当前位置: 首页>>代码示例>>Java>>正文


Java RestClientException类代码示例

本文整理汇总了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;
}
 
开发者ID:xm-online,项目名称:xm-gate,代码行数:26,代码来源:GatewayResource.java

示例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);
}
 
开发者ID:jopache,项目名称:Settings,代码行数:38,代码来源:ApplicationsApi.java

示例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;
    }
}
 
开发者ID:gazbert,项目名称:bxbot-ui-server,代码行数:22,代码来源:MarketConfigRepositoryRestClient.java

示例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;
}
 
开发者ID:evoila,项目名称:cfsummiteu2017,代码行数:23,代码来源:HAProxyService.java

示例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;
}
 
开发者ID:xabgesagtx,项目名称:mensa-api,代码行数:25,代码来源:WebUtils.java

示例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;
	}
}
 
开发者ID:oneops,项目名称:oneops,代码行数:26,代码来源:CMSClient.java

示例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;
    }
}
 
开发者ID:gazbert,项目名称:bxbot-ui-server,代码行数:22,代码来源:MarketConfigRepositoryRestClient.java

示例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;
    }
}
 
开发者ID:gazbert,项目名称:bxbot-ui-server,代码行数:22,代码来源:StrategyConfigRepositoryRestClient.java

示例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);
}
 
开发者ID:jopache,项目名称:Settings,代码行数:29,代码来源:EnvironmentsApi.java

示例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);
	}
}
 
开发者ID:oneops,项目名称:oneops,代码行数:17,代码来源:FlexStateProcessor.java

示例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);
}
 
开发者ID:jopache,项目名称:Settings,代码行数:29,代码来源:AuthorizationApi.java

示例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");
    }
}
 
开发者ID:jopache,项目名称:Settings,代码行数:55,代码来源:ApiClient.java

示例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;
}
 
开发者ID:evoila,项目名称:cfsummiteu2017,代码行数:26,代码来源:OpenIdAuthenticationUtils.java

示例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());
	}
}
 
开发者ID:ad-tech-group,项目名称:openssp,代码行数:22,代码来源:JsonDataProviderConnector.java

示例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);
}
 
开发者ID:Clcanny,项目名称:MicroServiceDemo,代码行数:24,代码来源:RestTemplate.java


注:本文中的org.springframework.web.client.RestClientException类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。