本文整理匯總了Java中org.springframework.web.client.RestClientException類的典型用法代碼示例。如果您正苦於以下問題:Java RestClientException類的具體用法?Java RestClientException怎麽用?Java RestClientException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
RestClientException類屬於org.springframework.web.client包,在下文中一共展示了RestClientException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: receiveServiceStatus
import org.springframework.web.client.RestClientException; //導入依賴的package包/類
private Map<String, String> receiveServiceStatus(List<ServiceInstance> instances) {
if (CollectionUtils.isEmpty(instances)) {
return Collections.emptyMap();
}
Map<String, String> instancesStatus = new HashMap<>();
instances.stream()
.filter(serviceInstance -> serviceInstance.getUri() != null)
.forEach(instance -> {
String uri = instance.getUri().toString();
String status;
try {
Map body = restTemplate.exchange(
String.format("%s/management/health", uri),
HttpMethod.GET, null, Map.class).getBody();
status = (String) body.get(STATUS);
} catch (RestClientException e) {
log.error("Error occurred while getting status of the microservice by URI {}",
uri, e);
status = "DOWN";
}
instancesStatus.put(uri, status);
});
return instancesStatus;
}
示例2: apiApplicationsByApplicationNameGet
import org.springframework.web.client.RestClientException; //導入依賴的package包/類
/**
*
*
* <p><b>200</b> - Success
* @param applicationName The applicationName parameter
* @return HierarchicalModel
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public HierarchicalModel apiApplicationsByApplicationNameGet(String applicationName) throws RestClientException {
Object postBody = null;
// verify the required parameter 'applicationName' is set
if (applicationName == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'applicationName' when calling apiApplicationsByApplicationNameGet");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("applicationName", applicationName);
String path = UriComponentsBuilder.fromPath("/api/applications/{applicationName}").buildAndExpand(uriVariables).toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
final String[] accepts = {
"text/plain", "application/json", "text/json"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { };
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<HierarchicalModel> returnType = new ParameterizedTypeReference<HierarchicalModel>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
示例3: findById
import org.springframework.web.client.RestClientException; //導入依賴的package包/類
@Override
public MarketConfig findById(BotConfig botConfig, String marketId) {
try {
restTemplate.getInterceptors().clear();
restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor(
botConfig.getUsername(), botConfig.getPassword()));
final String endpointUrl = botConfig.getBaseUrl() + MARKET_RESOURCE_PATH + '/' + marketId;
LOG.info(() -> "Fetching MarketConfig from: " + endpointUrl);
@SuppressWarnings("unchecked") final MarketConfig marketConfig = restTemplate.getForObject(endpointUrl, MarketConfig.class);
LOG.info(() -> REMOTE_RESPONSE_RECEIVED_LOG_MSG + marketConfig);
return marketConfig;
} catch (RestClientException e) {
LOG.error(FAILED_TO_INVOKE_REMOTE_BOT_LOG_MSG + e.getMessage(), e);
return null;
}
}
示例4: appendSingleAgent
import org.springframework.web.client.RestClientException; //導入依賴的package包/類
private ServerAddress appendSingleAgent(HAProxyServerAddress internalAddress, String bindingId, String instanceId) {
HAProxyServerAddress bindingAddress = new HAProxyServerAddress(internalAddress, bindingId);
HttpEntity<HAProxyServerAddress> entity = new HttpEntity<>(bindingAddress, headers);
try {
HABackendResponse response = restTemplate.exchange(haProxy, HttpMethod.PUT, entity, HABackendResponse.class)
.getBody();
log.info("Called: " + haProxy);
log.info("Response is: " + response);
if (response != null) {
ServerAddress serverAddress = new ServerAddress(internalAddress.getName(), response.getIp(), response.getPort());
return serverAddress;
}
} catch (RestClientException e) {
e.printStackTrace();
}
return null;
}
示例5: getDocumentAsString
import org.springframework.web.client.RestClientException; //導入依賴的package包/類
/**
* Get content of a website as a string
* @param url of the website
* @return the content if available, empty otherwise
*/
public Optional<String> getDocumentAsString(String url) {
Optional<String> result = Optional.empty();
try {
ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
if (entity.getStatusCode().is2xxSuccessful()) {
String body = entity.getBody();
if (StringUtils.isBlank(body)) {
logger.error("Empty response for {}", url);
} else {
result = Optional.of(body);
}
} else {
logger.error("Failed to get {}. Response error: {}", url, entity.getStatusCode());
}
} catch (RestClientException e) {
logger.error("Failed to get {} due to error: {}", url, e.getMessage());
}
return result;
}
示例6: getCloudCi
import org.springframework.web.client.RestClientException; //導入依賴的package包/類
/**
* Gets the cloud ci.
*
* @param ns the ns
* @param ciName the ci name
* @return the cloud ci
*/
public CmsCISimple getCloudCi(String ns, String ciName) {
try {
CmsCISimple[] mgmtClouds = restTemplate.getForObject(serviceUrl + "cm/simple/cis?nsPath={nsPath}&ciClassName={mgmtCloud}&ciName={ciName}", new CmsCISimple[0].getClass(), ns, mgmtCloud, ciName);
if (mgmtClouds.length > 0) {
return mgmtClouds[0];
}
CmsCISimple[] acctClouds = restTemplate.getForObject(serviceUrl + "cm/simple/cis?nsPath={nsPath}&ciClassName={acctCloud}&ciName={ciName}", new CmsCISimple[0].getClass(), ns, acctCloud, ciName);
if (acctClouds.length > 0) {
return acctClouds[0];
}
return null;
} catch (RestClientException ce) {
logger.error("Broker can not connect to cms api to authenticate the user:" + ce.getMessage());
throw ce;
}
}
示例7: delete
import org.springframework.web.client.RestClientException; //導入依賴的package包/類
@Override
public boolean delete(BotConfig botConfig, String marketId) {
LOG.info(() -> "Deleting MarketConfig for marketId: " + marketId + " for botId: " + botConfig.getId());
try {
restTemplate.getInterceptors().clear();
restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor(
botConfig.getUsername(), botConfig.getPassword()));
final String endpointUrl = botConfig.getBaseUrl() + MARKET_RESOURCE_PATH + '/' + marketId;
LOG.info(() -> "Deleting MarketConfig from: " + endpointUrl);
restTemplate.delete(endpointUrl);
return true;
} catch (RestClientException e) {
LOG.error(FAILED_TO_INVOKE_REMOTE_BOT_LOG_MSG + e.getMessage(), e);
return false;
}
}
示例8: findById
import org.springframework.web.client.RestClientException; //導入依賴的package包/類
@Override
public StrategyConfig findById(BotConfig botConfig, String strategyId) {
try {
restTemplate.getInterceptors().clear();
restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor(
botConfig.getUsername(), botConfig.getPassword()));
final String endpointUrl = botConfig.getBaseUrl() + STRATEGY_RESOURCE_PATH + '/' + strategyId;
LOG.info(() -> "Fetching StrategyConfig from: " + endpointUrl);
@SuppressWarnings("unchecked") final StrategyConfig strategyConfig = restTemplate.getForObject(endpointUrl, StrategyConfig.class);
LOG.info(() -> REMOTE_RESPONSE_RECEIVED_LOG_MSG + strategyConfig);
return strategyConfig;
} catch (RestClientException e) {
LOG.error(FAILED_TO_INVOKE_REMOTE_BOT_LOG_MSG + e.getMessage(), e);
return null;
}
}
示例9: apiEnvironmentsGet
import org.springframework.web.client.RestClientException; //導入依賴的package包/類
/**
*
*
* <p><b>200</b> - Success
* @return HierarchicalModel
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public HierarchicalModel apiEnvironmentsGet() throws RestClientException {
Object postBody = null;
String path = UriComponentsBuilder.fromPath("/api/environments").build().toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
final String[] accepts = {
"text/plain", "application/json", "text/json"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { };
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<HierarchicalModel> returnType = new ParameterizedTypeReference<HierarchicalModel>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
示例10: processFlexRelation
import org.springframework.web.client.RestClientException; //導入依賴的package包/類
private void processFlexRelation(CmsCIRelation flexRel, CmsCI env, int step, boolean scaleUp) throws OpampException {
try {
//now we need to call transistor and create deployment;
Map<String,String> params = new HashMap<>();
params.put("envId", String.valueOf(env.getCiId()));
params.put("relId", String.valueOf(flexRel.getCiRelationId()));
params.put("step", String.valueOf(step));
params.put("scaleUp", String.valueOf(scaleUp));
Long bomReleaseId = restTemplate.getForObject(transistorUrl + "flex?envId={envId}&relId={relId}&step={step}&scaleUp={scaleUp}", Long.class, params);
logger.info("created new bom release - " + bomReleaseId);
} catch (RestClientException e) {
logger.error("RestClientException in processFlexRelation", e);
throw new OpampException(e);
}
}
示例11: apiAuthorizationLoginPost
import org.springframework.web.client.RestClientException; //導入依賴的package包/類
/**
*
*
* <p><b>200</b> - Success
* @param model The model parameter
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public void apiAuthorizationLoginPost(LoginModel model) throws RestClientException {
Object postBody = model;
String path = UriComponentsBuilder.fromPath("/api/authorization/login").build().toUriString();
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
final String[] accepts = { };
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json-patch+json", "application/json", "text/json", "application/_*+json"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
示例12: invokeAPI
import org.springframework.web.client.RestClientException; //導入依賴的package包/類
/**
* Invoke API by sending HTTP request with the given options.
*
* @param <T> the return type to use
* @param path The sub-path of the HTTP URL
* @param method The request method
* @param queryParams The query parameters
* @param body The request body object
* @param headerParams The header parameters
* @param formParams The form parameters
* @param accept The request's Accept header
* @param contentType The request's Content-Type header
* @param authNames The authentications to apply
* @param returnType The return type into which to deserialize the response
* @return The response body in chosen type
*/
public <T> T invokeAPI(String path, HttpMethod method, MultiValueMap<String, String> queryParams, Object body, HttpHeaders headerParams, MultiValueMap<String, Object> formParams, List<MediaType> accept, MediaType contentType, String[] authNames, ParameterizedTypeReference<T> returnType) throws RestClientException {
updateParamsForAuth(authNames, queryParams, headerParams);
final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(basePath).path(path);
if (queryParams != null) {
builder.queryParams(queryParams);
}
final BodyBuilder requestBuilder = RequestEntity.method(method, builder.build().toUri());
if(accept != null) {
requestBuilder.accept(accept.toArray(new MediaType[accept.size()]));
}
if(contentType != null) {
requestBuilder.contentType(contentType);
}
addHeadersToRequest(headerParams, requestBuilder);
addHeadersToRequest(defaultHeaders, requestBuilder);
RequestEntity<Object> requestEntity = requestBuilder.body(selectBody(body, formParams, contentType));
ResponseEntity<T> responseEntity = restTemplate.exchange(requestEntity, returnType);
statusCode = responseEntity.getStatusCode();
responseHeaders = responseEntity.getHeaders();
if (responseEntity.getStatusCode() == HttpStatus.NO_CONTENT) {
return null;
} else if (responseEntity.getStatusCode().is2xxSuccessful()) {
if (returnType == null) {
return null;
}
return responseEntity.getBody();
} else {
// The error handler built into the RestTemplate should handle 400 and 500 series errors.
throw new RestClientException("API returned " + statusCode + " and it wasn't handled by the RestTemplate error handler");
}
}
示例13: getAccessAndRefreshToken
import org.springframework.web.client.RestClientException; //導入依賴的package包/類
public static CompositeAccessToken getAccessAndRefreshToken(String oauthEndpoint, String code, DashboardClient dashboardClient,
String redirectUri) throws RestClientException {
String clientBasicAuth = getClientBasicAuthHeader(dashboardClient.getId(), dashboardClient.getSecret());
RestTemplate template = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, clientBasicAuth);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String,String> form = new LinkedMultiValueMap<>();
form.add("response_type", "token");
form.add("grant_type", "authorization_code");
form.add("client_id", dashboardClient.getId());
form.add("client_secret", dashboardClient.getSecret());
form.add("redirect_uri", redirectUri);
form.add("code", code);
ResponseEntity<CompositeAccessToken> token = template.exchange(oauthEndpoint + "/token",
HttpMethod.POST, new HttpEntity<>(form, headers), CompositeAccessToken.class);
if (token != null)
return token.getBody();
else
return null;
}
示例14: doConnection
import org.springframework.web.client.RestClientException; //導入依賴的package包/類
private T doConnection(final PathBuilder config, int attempts) throws RestException {
if (StringUtils.isEmpty(RestfulContext.getToken())) {
RestfulContext.setToken(LoginService.loginDataProvider(config));
}
try {
return connect(config);
} catch (final RestClientException e) {
final HttpStatus status = evaluateStatusCode(e.getMessage());
if (status == HttpStatus.UNAUTHORIZED) {
if (attempts > 0) {
attempts--;
LOGGER.info(" retrying connect " + attempts);
RestfulContext.setToken(null);
return doConnection(config, attempts);
}
}
LOGGER.warn("" + status);
throw new RestException(LocalDateTime.now(ZoneId.of("Europe/Berlin")).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) + " " + dtoType.getSimpleName()
+ " is empty " + e.getMessage());
}
}
示例15: doExecute
import org.springframework.web.client.RestClientException; //導入依賴的package包/類
@Override
@Nullable
protected <T> T doExecute(URI url, @Nullable HttpMethod method, @Nullable RequestCallback requestCallback,
@Nullable ResponseExtractor<T> responseExtractor) throws RestClientException {
String from = name;
String to = url.
toString().
replace("http://", "").
replace("http:// www.", "").
replace("www.", "").
replace("/", "%20").
toLowerCase();
System.out.println(from);
System.out.println(to);
try {
restTemplate.postForObject("http://trace-callback-service/" + from + "/" + to, null, Object.class);
} catch (Exception exception) {
}
return super.doExecute(url, method, requestCallback, responseExtractor);
}