Java 类org.springframework.web.client.RestClientException 实例源码

项目:Settings    文件:ApplicationsApi.java   
/**
 * 
 * 
 * <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);
}
项目:xm-gate    文件:GatewayResource.java   
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;
}
项目:bxbot-ui-server    文件:MarketConfigRepositoryRestClient.java   
@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;
    }
}
项目:cfsummiteu2017    文件:HAProxyService.java   
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;
}
项目:mensa-api    文件:WebUtils.java   
/**
 * 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;
}
项目:oneops    文件:CMSClient.java   
/**
 * 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;
    }
}
项目:bxbot-ui-server    文件:MarketConfigRepositoryRestClient.java   
@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;
    }
}
项目:bxbot-ui-server    文件:StrategyConfigRepositoryRestClient.java   
@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;
    }
}
项目:Settings    文件:EnvironmentsApi.java   
/**
 * 
 * 
 * <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);
}
项目:oneops    文件:FlexStateProcessor.java   
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);
    }
}
项目:Settings    文件:AuthorizationApi.java   
/**
 * 
 * 
 * <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);
}
项目:Settings    文件:ApiClient.java   
/**
 * 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");
    }
}
项目:cfsummiteu2017    文件:OpenIdAuthenticationUtils.java   
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;
}
项目:openssp    文件:JsonDataProviderConnector.java   
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());
    }
}
项目:MicroServiceDemo    文件:RestTemplate.java   
@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);
}
项目:mtgo-best-bot    文件:BotCameraService.java   
public PlayerBot registerOrLoadSelf(PlayerBot playerBot) {
    ResponseEntity<PlayerBot> resp;

    try {
        resp = restTemplate.getForEntity(apiUrl + BotController.ENDPOINT_ROOT + "/name/" + playerBot.getName(), PlayerBot.class);
    } catch (RestClientException e) {
        log.error("Failed to log in!");
        log.error(e.getMessage());
        throw new RuntimeException(e);
    }


    if(resp.getStatusCode() != HttpStatus.OK) {
        throw new RuntimeException("PlayerBot is not registered");
    }

    return resp.getBody();
}
项目:open-kilda    文件:SwitchServiceImpl.java   
@Override
public List<SwitchDto> getSwitches() {
    LOGGER.debug("Get switch request received");

    SwitchInfoData[] switches;
    try {
        switches = restTemplate.exchange(switchesUrl, HttpMethod.GET, new HttpEntity<>(headers),
                SwitchInfoData[].class).getBody();
        LOGGER.debug("Returned {} links", switches.length);
    } catch (RestClientException e) {
        LOGGER.error("Exception during getting switches from TPE", e);
        throw e;
    }

    return Arrays.stream(switches)
            .map(switchMapper::toSwitchDto)
            .collect(Collectors.toList());
}
项目:bxbot-ui-server    文件:MarketConfigRepositoryRestClient.java   
@Override
public MarketConfig save(BotConfig botConfig, MarketConfig marketConfig) {

    LOG.info(() -> "Saving MarketConfig: " + marketConfig + " 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;
        LOG.info(() -> "Sending MarketConfig to: " + endpointUrl);

        final HttpEntity<MarketConfig> requestUpdate = new HttpEntity<>(marketConfig);
        final ResponseEntity<MarketConfig> savedConfig = restTemplate.exchange(
                endpointUrl, HttpMethod.PUT, requestUpdate, MarketConfig.class);

        LOG.info(() -> REMOTE_RESPONSE_RECEIVED_LOG_MSG + savedConfig.getBody());
        return savedConfig.getBody();

    } catch (RestClientException e) {
        LOG.error(FAILED_TO_INVOKE_REMOTE_BOT_LOG_MSG + e.getMessage(), e);
        return null;
    }
}
项目:oneops    文件:CMSClientTest.java   
@SuppressWarnings("unchecked")
@Test
public void checkDeploymentTestWithRestTemplateThrowExceptionShouldSucced() throws Exception{
    DelegateExecution delegateExecution = mock(DelegateExecution.class);
    CmsDeployment cmsDeployment = new CmsDeployment();
    cmsDeployment.setCreatedBy("created-by-mock");
    when(delegateExecution.getVariable("dpmt")).thenReturn(cmsDeployment);

    RestTemplate restTemplate = mock(RestTemplate.class);
    //when(restTemplate.getForObject(anyString(), any(Class.class) , anyLong())).thenThrow(new RestClientException("test")).thenReturn(cmsDeployment);
    when(restTemplate.getForObject(anyString(), any(Class.class), anyLong())).thenThrow(new RestClientException("test")).thenThrow(new RestClientException("test")).thenReturn(cmsDeployment);
    cc.setRestTemplate(restTemplate);
    try {
        cc.setRetryTemplate(cc.getRetryTemplate(3,2000,1000));
        cc.checkDpmt(delegateExecution);
        CmsDeployment cmsDeploymentPost = (CmsDeployment) delegateExecution.getVariable("dpmt");
        assertEquals(cmsDeploymentPost.getCreatedBy(), "created-by-mock", "object mutated unexpectedly");

    } catch (GeneralSecurityException e) {
        logger.warn("unexpected to catch here",e) ;
        throw e;
    }
}
项目:bxbot-ui-server    文件:StrategyConfigRepositoryRestClient.java   
@Override
public boolean delete(BotConfig botConfig, String strategyId) {

    LOG.info(() -> "Deleting StrategyConfig for strategyId: " + strategyId + " for botId: " + botConfig.getId());

    try {
        restTemplate.getInterceptors().clear();
        restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor(
                botConfig.getUsername(), botConfig.getPassword()));

        final String endpointUrl = botConfig.getBaseUrl() + STRATEGY_RESOURCE_PATH + '/' + strategyId;
        LOG.info(() -> "Deleting StrategyConfig from: " + endpointUrl);

        restTemplate.delete(endpointUrl);
        return true;

    } catch (RestClientException e) {
        LOG.error(FAILED_TO_INVOKE_REMOTE_BOT_LOG_MSG + e.getMessage(), e);
        return false;
    }
}
项目:sentry    文件:SubscriberService.java   
public void publish(String outputChannel, String id, DatadogEvent message) {
    log.debug("Publishing an event message ({}) to output channel : {}", id, outputChannel);
    subscriberRepository.findByChannelAndType(outputChannel, "DatadogEvent").stream()
        .filter(sub -> timeFrameService.included(sub.getId()))
        .filter(sub -> checkDuplicate(sub, id))
        .forEach(sub -> {
            String apiKey = (String) sub.getVariables().get("api_key");
            if (apiKey == null) {
                log.warn("Subscriber did not define a Datadog API Key: {}", sub);
            } else {
                try {
                    ResponseEntity<Map<String, ?>> responseEntity = publishEvent(message, apiKey);
                    log.debug("[{}] Response: {}", outputChannel, responseEntity);
                } catch (RestClientException e) {
                    log.warn("Could not publish event", e);
                }
            }
        });
}
项目:xitikit-blue    文件:SimpleB2CAuthenticationService.java   
/**
 * Attempts to get an RSAPublicKey for the given policy.
 *
 * @param keyId the key ID to fetch
 * @param policy the policy the key belongs to
 *
 * @return the key or null if it could not be fetched
 */
@Nullable
private RSAPublicKey rsaPublicKey(
  @Nonnull final String keyId,
  @Nonnull final String policy){

    try{
        JsonNode kidNode = kidForKeyId(
          keysForPolicy(policy),
          keyId
        );
        return parseKey(
          modulus(kidNode),
          exponent(kidNode)
        );

    }catch(RestClientException | NullPointerException x){
        log.error("Error retrieving RSA keys for policy [" + policy + "]: " + x.getMessage(), x);
    }
    return null;
}
项目:oneops    文件:CMSClient.java   
/**
 * Commit and deploy release.
 *
 * @param exec the exec
 * @throws GeneralSecurityException the general security exception
 */
public void commitAndDeployRelease(DelegateExecution exec) throws GeneralSecurityException {
    CmsRelease release = (CmsRelease) exec.getVariable("release");
    CmsCISimple env = (CmsCISimple) exec.getVariable("env");
    logger.info("Committing and deploying manifest release with id = " + release.getReleaseId());
    Map<String, String> descMap = new HashMap<String, String>();
    descMap.put("description", "oneops autodeploy");
    try {
        @SuppressWarnings("unchecked")
        Map<String, Long> bomDpmtMap = retryTemplate.execute(retryContext -> restTemplate.postForObject(transUrl + "environments/{envId}/deployments/deploy", descMap, Map.class, env.getCiId()));
        logger.info("BOM deployment id = " + bomDpmtMap.get("deploymentId"));
    } catch (RestClientException e) {
        //should
        logger.error("DeploymentExecution of manifest release " + release.getReleaseId() + " failed with error:\n" + e.getMessage());
    }

}
项目:graphium    文件:GraphVersionImportHttpNotifierImpl.java   
@Override
public boolean notifyRegisteredServersOfActivating(String graphName, String version, String groupName, Integer segmentsCount) {
    boolean ok = true;

    // activate graph version on all registered graph servers
    try {
        List<ISubscription> subscriptions = subscriptionDao.getSubscriptionsForGraph(graphName, groupName);
        if (subscriptions != null && !subscriptions.isEmpty()) {
            for (ISubscription subscription : subscriptions) {
                log.info("Updating graph version " + graphName + "_" + version + " on Server " + subscription.getServerName() + " at " + subscription.getUrl()
                        + " to state " + State.ACTIVATING.toString());
                updateGraphVersionState(subscription.getUrl(), subscription.getViewName(), version, State.ACTIVATING, segmentsCount);
            }
        }
    } catch (RestClientException e) {
        log.error("Activating graph version failed!", e);
        ok = false;
    }

    return ok;
}
项目:bxbot-ui-server    文件:StrategyConfigRepositoryRestClient.java   
@Override
public List<StrategyConfig> findAll(BotConfig botConfig) {

    try {
        restTemplate.getInterceptors().clear();
        restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor(
                botConfig.getUsername(), botConfig.getPassword()));

        final String endpointUrl = botConfig.getBaseUrl() + STRATEGY_RESOURCE_PATH;
        LOG.info(() -> "Fetching all StrategyConfig from: " + endpointUrl);

        @SuppressWarnings("unchecked") final List<StrategyConfig> allTheStrategyConfig = restTemplate.getForObject(endpointUrl, List.class);

        LOG.info(() -> REMOTE_RESPONSE_RECEIVED_LOG_MSG + allTheStrategyConfig);
        return allTheStrategyConfig;

    } catch (RestClientException e) {
        LOG.error(FAILED_TO_INVOKE_REMOTE_BOT_LOG_MSG + e.getMessage(), e);
        return new ArrayList<>();
    }
}
项目:bxbot-ui-server    文件:EmailAlertsConfigRepositoryRestClient.java   
@Override
public EmailAlertsConfig get(BotConfig botConfig) {

    try {
        restTemplate.getInterceptors().clear();
        restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor(
                botConfig.getUsername(), botConfig.getPassword()));

        final String endpointUrl = botConfig.getBaseUrl() + EMAIL_ALERTS_RESOURCE_PATH;
        LOG.info(() -> "Fetching EmailAlertsConfig from: " + endpointUrl);

        final EmailAlertsConfig config = restTemplate.getForObject(endpointUrl, EmailAlertsConfig.class);

        LOG.info(() -> REMOTE_RESPONSE_RECEIVED_LOG_MSG + config);
        config.setId(botConfig.getId());
        return config;

    } catch (RestClientException e) {
        LOG.error(FAILED_TO_INVOKE_REMOTE_BOT_LOG_MSG + e.getMessage(), e);
        return null;
    }
}
项目:bxbot-ui-server    文件:BotStatusRepositoryRestClient.java   
@Override
public BotStatus getBotStatus(BotConfig botConfig) {

    try {
        restTemplate.getInterceptors().clear();
        restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor(
                botConfig.getUsername(), botConfig.getPassword()));

        final String endpointUrl = botConfig.getBaseUrl() + STATUS_RESOURCE_PATH;
        LOG.info(() -> "Fetching BotStatus from: " + endpointUrl);

        final BotStatus botStatus = restTemplate.getForObject(endpointUrl, BotStatus.class);

        LOG.info(() -> REMOTE_RESPONSE_RECEIVED_LOG_MSG + botStatus);
        return botStatus;

    } catch (RestClientException e) {
        LOG.error(FAILED_TO_INVOKE_REMOTE_BOT_LOG_MSG + e.getMessage(), e);
        return null;
    }
}
项目:mot-automated-testsuite    文件:DataServerManager.java   
/**
 * Stops the data server, gracefully if possible (using the /shutdown endpoint) otherwise forcibly.
 */
public static void stopServer() {
    logger.info("In DataServerManager.stopServer");

    try {
        // POST to Spring Boot shutdown handler to trigger a clean shutdown...
        // (it returns a short JSON reply message)
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.postForObject(
                "http://localhost:9999/shutdown", null, String.class);
        logger.info("Server shutdown triggered, received {}", result);

    } catch (RestClientException ex) {
        String message = "Failed to post server shutdown message: " + ex.getMessage();
        logger.error(message, ex);

        if (serverProcess != null) {
            // attempt to kill the server process as a last resort...
            // not possible if using Courgette runner (as start and stop is in different processes)
            serverProcess.destroy();
            logger.info("Server process killed");
        }

        // swallow exception
    }
}
项目:spring-cloud-dashboard    文件:ConfigCommandTests.java   
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    final CommandLine commandLine = Mockito.mock(CommandLine.class);

    when(commandLine.getArgs()).thenReturn(null);

    final List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
    messageConverters.add(new  MappingJackson2HttpMessageConverter());

    when(restTemplate.getMessageConverters()).thenReturn(messageConverters);
    final Exception e = new RestClientException("FooBar");
    when(restTemplate.getForObject(Mockito.any(URI.class), Mockito.eq(ResourceSupport.class))).thenThrow(e);

    configCommands.setTargetHolder(new TargetHolder());
    configCommands.setRestTemplate(restTemplate);
    configCommands.setDataFlowShell(dataFlowShell);
    configCommands.setServerUri("http://localhost:9393");
    configCommands.onApplicationEvent(null);
}
项目:Persephone    文件:LogsService.java   
public boolean endpointAvailable(Application app) {

        String url = app.endpoints().logfile();

        try {
            LOGGER.debug("HEAD {}", url);
            restTemplates.get(app).headForHeaders(new URI(url));
            return true;
        } catch (RestClientException | URISyntaxException e) {
            LOGGER.warn("Application {} endpoint {} not reachable: {}", app.getId(), url, e.getMessage());
            return false;
        }
    }
项目:keti    文件:UaaHealthIndicatorTest.java   
@DataProvider
public Object[][] statuses() {
    return new Object[][] {
            new Object[] { mockRestWithUp(), Status.UP, AcsMonitoringUtilities.HealthCode.AVAILABLE },

            { mockRestWithException(new RestClientException("")), Status.DOWN,
                    AcsMonitoringUtilities.HealthCode.UNREACHABLE },

            { mockRestWithException(new RuntimeException()), Status.DOWN,
                    AcsMonitoringUtilities.HealthCode.ERROR }, };
}
项目:Persephone    文件:LoggersService.java   
public Loggers getLoggers(Application app) {

        String url = app.endpoints().loggers();

        LOGGER.debug("GET {}", url);

        try {
            return restTemplates.get(app).getForObject(url, Loggers.class);
        } catch(RestClientException e) {
            throw RestTemplateErrorHandler.handle(app, url, e);
        }
    }
项目:Persephone    文件:HealthService.java   
public Health getHealth(Application app) {
    String url = app.endpoints().health();

    try {
        LOGGER.debug("GET {}", url);
        return restTemplates.get(app).getForObject(url, Health.class);
    } catch(RestClientException rce) {
        return new Health(Status.DOWN);
    }
}
项目:spring-boot-readiness    文件:MockRestTemplateAnswer.java   
@Override
public HealthResponse answer(InvocationOnMock invocation) {
    URI uri = invocation.getArgumentAt(0, URI.class);
    List<String> pathSegments = UriComponentsBuilder.fromUri(uri).build().getPathSegments();
    String status = Iterables.getLast(pathSegments);
    if ("EXCEPTION".equals(status)) {
        throw new RestClientException("simulated exception");
    }
    return HealthResponse.builder().status(new Status(status)).build();
}
项目:spring-boot-readiness    文件:HealthClient.java   
private HealthResponseBuilder doGetHealth(URI uri) {
    try {
        log.debug("Checking health at '{}'", uri);
        // TODO let Jackson directly deserialize into HealthResponseBuilder
        return restTemplate.getForObject(uri, HealthResponse.class).toBuilder();
    } catch (RestClientException e) {
        Status status = new Status(DOWN.getCode(), getRootCause(e).getMessage());
        return HealthResponse.builder().status(status);
    }
}
项目:cfsummiteu2017    文件:HAProxyService.java   
private void removeSingleAgent(ServerAddress internalAddress, String bindingId) throws ServiceBrokerException {
    ServerAddress bindingAddress = new ServerAddress(bindingId, internalAddress.getIp(), internalAddress.getPort());
    HttpEntity<ServerAddress> entity = new HttpEntity<>(bindingAddress, headers);
    try {
        HttpStatus statusCode = restTemplate.exchange(haProxy, HttpMethod.DELETE, entity, Object.class)
                .getStatusCode();
        if (!statusCode.equals(HttpStatus.NO_CONTENT))
            throw new ServiceBrokerException("Could not remove external IP " + internalAddress.getName() + " - "
                    + internalAddress.getIp() + ":" + internalAddress.getPort());
    } catch (RestClientException e) {
        e.printStackTrace();
        throw new ServiceBrokerException("Could not remove external IP " + internalAddress.getName() + " - "
                + internalAddress.getIp() + ":" + internalAddress.getPort());
    }
}
项目:ServiceComb-Company-WorkShop    文件:FixedUrlRestTemplate.java   
@Override
public <T> ResponseEntity<T> postForEntity(
    String url,
    Object request,
    Class<T> responseType,
    Object... uriVariables) throws RestClientException {

  logger.info("Received POST request to address {} -> {}", url, this.url);
  return super.postForEntity(
      this.url,
      request,
      responseType,
      uriVariables);
}
项目:Settings    文件:SettingsApi.java   
/**
 * 
 * 
 * <p><b>200</b> - Success
 * @param applicationName The applicationName parameter
 * @param environmentName The environmentName parameter
 * @return List&lt;SettingReadModel&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public List<SettingReadModel> apiSettingsByApplicationNameByEnvironmentNameGet(String applicationName, String environmentName) 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 apiSettingsByApplicationNameByEnvironmentNameGet");
    }

    // verify the required parameter 'environmentName' is set
    if (environmentName == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'environmentName' when calling apiSettingsByApplicationNameByEnvironmentNameGet");
    }

    // create path and map variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("applicationName", applicationName);
    uriVariables.put("environmentName", environmentName);
    String path = UriComponentsBuilder.fromPath("/api/settings/{applicationName}/{environmentName}").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<List<SettingReadModel>> returnType = new ParameterizedTypeReference<List<SettingReadModel>>() {};
    return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
项目:Settings    文件:SettingsApi.java   
/**
 * 
 * 
 * <p><b>200</b> - Success
 * @param applicationName The applicationName parameter
 * @param environmentName The environmentName parameter
 * @param settings The settings parameter
 * @return Boolean
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public Boolean apiSettingsCreateUpdateByApplicationNameByEnvironmentNamePost(String applicationName, String environmentName, SettingsWriteModel settings) throws RestClientException {
    Object postBody = settings;

    // verify the required parameter 'applicationName' is set
    if (applicationName == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'applicationName' when calling apiSettingsCreateUpdateByApplicationNameByEnvironmentNamePost");
    }

    // verify the required parameter 'environmentName' is set
    if (environmentName == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'environmentName' when calling apiSettingsCreateUpdateByApplicationNameByEnvironmentNamePost");
    }

    // create path and map variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("applicationName", applicationName);
    uriVariables.put("environmentName", environmentName);
    String path = UriComponentsBuilder.fromPath("/api/settings/create-update/{applicationName}/{environmentName}").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 = { 
        "application/json-patch+json", "application/json", "text/json", "application/_*+json"
    };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

    String[] authNames = new String[] {  };

    ParameterizedTypeReference<Boolean> returnType = new ParameterizedTypeReference<Boolean>() {};
    return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
项目:Persephone    文件:EnvironmentService.java   
public Environment getEnvironmentV1(Application app) {

        String url = app.endpoints().env();

        try {
            LOGGER.debug("GET {}", url);
            ResponseEntity<String> response = restTemplates.get(app).getForEntity(url, String.class);

            String json = response.getBody();

            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
            JsonNode rootNode = mapper.readTree(json);

            List<PropertyItem> properties = new ArrayList<>();

            Iterator<Entry<String, JsonNode>> iterator = rootNode.fields();

            // Get properties
            while (iterator.hasNext()) {
                Entry<String, JsonNode> current = iterator.next();

                current.getValue().fields().forEachRemaining(
                        // current.getKey ==> origin of the property : system,
                        // application.properties, etc
                        p -> properties.add(new PropertyItem(p.getKey(), p.getValue().asText(), current.getKey())));
            }

            return new Environment(properties);
        } catch (RestClientException ex) {
            throw RestTemplateErrorHandler.handle(app, url, ex);
        } catch (IOException e) {
            throw RestTemplateErrorHandler.handle(app, e);
        }
    }