Search in sources :

Example 26 with RestClientException

use of org.springframework.web.client.RestClientException in project portal by ixinportal.

the class WeixinUtil method getJsApiTicketFromWeixin.

public void getJsApiTicketFromWeixin() {
    synchronized (jsapitLock) {
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={accToken}&type=jsapi";
        try {
            Long nowDate = System.currentTimeMillis();
            if (JS_API_TICKET != null && new Date(nowDate + inDateTime).before(JS_API_TICKET.getInDate()))
                return;
            if (ACCESS_TOKEN == null || new Date(nowDate + inDateTime).after(ACCESS_TOKEN.getInDate()))
                getAccTokenFromWeixin();
            ByteArrayResource retRes = restTemplate.getForObject(tokenUrl, ByteArrayResource.class, ACCESS_TOKEN.accessToken);
            Map<String, Object> ticketMap = jsonTool.readValue(new String(retRes.getByteArray()), Map.class);
            if (ticketMap == null || ticketMap.isEmpty()) {
                log.error("微信获取ticket失败,返回为空");
                return;
            }
            Integer ei = (Integer) ticketMap.get("expires_in");
            Date inDate = new Date(nowDate + ei * 1000);
            JsApiTicket TICKET_TMP = new JsApiTicket((String) ticketMap.get("ticket"), inDate);
            JS_API_TICKET = TICKET_TMP;
        } catch (RestClientException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Also used : JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) RestClientException(org.springframework.web.client.RestClientException) ByteArrayResource(org.springframework.core.io.ByteArrayResource) IOException(java.io.IOException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) Date(java.util.Date)

Example 27 with RestClientException

use of org.springframework.web.client.RestClientException in project oncotree by cBioPortal.

the class TopBraidRepository method query.

private List<T> query(String query, ParameterizedTypeReference<List<T>> parameterizedType, boolean refreshSessionOnFailure) throws TopBraidException {
    String sessionId = topBraidSessionConfiguration.getSessionId();
    logger.debug("query() -- sessionId: " + sessionId);
    RestTemplate restTemplate = new RestTemplate();
    // the default supported types for MappingJackson2HttpMessageConverter are:
    // application/json and application/*+json
    // our response content type is application/sparql-results+json-simple
    // NOTE: if the response content type was one of the default types we
    // would not have to add the message converter to the rest template
    MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
    messageConverter.setSupportedMediaTypes(Collections.singletonList(new MediaType("application", "sparql-results+json-simple")));
    restTemplate.getMessageConverters().add(messageConverter);
    // set our JSESSIONID cookie and our params
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cookie", "JSESSIONID=" + sessionId);
    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("format", "json-simple");
    map.add("query", query);
    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
    // See: http://stackoverflow.com/questions/21987295/using-spring-resttemplate-in-generic-method-with-generic-parameter
    try {
        ResponseEntity<List<T>> response = restTemplate.exchange(topBraidURL, HttpMethod.POST, request, parameterizedType);
        logger.debug("query() -- response.getBody(): '" + response.getBody() + "'");
        return response.getBody();
    } catch (RestClientException e) {
        logger.debug("query() -- caught RestClientException");
        // see if we should try again, maybe the session expired
        if (refreshSessionOnFailure == true) {
            // force refresh of the session id
            sessionId = topBraidSessionConfiguration.getFreshSessionId();
            // do not make a second attempt
            return query(query, parameterizedType, false);
        }
        throw new TopBraidException("Failed to connect to TopBraid", e);
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) HttpEntity(org.springframework.http.HttpEntity) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) RestTemplate(org.springframework.web.client.RestTemplate) RestClientException(org.springframework.web.client.RestClientException) MediaType(org.springframework.http.MediaType) ArrayList(java.util.ArrayList) List(java.util.List) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Example 28 with RestClientException

use of org.springframework.web.client.RestClientException in project mots by motech-implementations.

the class IvrService method sendVotoRequest.

private <T> T sendVotoRequest(String url, MultiValueMap<String, String> params, ParameterizedTypeReference<T> responseType, HttpMethod method) throws IvrException {
    params.add(API_KEY, ivrApiKey);
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).queryParams(params);
    HttpEntity<?> request = new HttpEntity<>(headers);
    try {
        ResponseEntity<T> responseEntity = restTemplate.exchange(builder.build().toString(), method, request, responseType);
        return responseEntity.getBody();
    } catch (RestClientResponseException ex) {
        String responseBodyJson = ex.getResponseBodyAsString();
        String responseMessage = responseBodyJson;
        String clearVotoInfo = "";
        try {
            VotoResponseDto<String> votoResponse = mapper.readValue(responseBodyJson, new TypeReference<VotoResponseDto<String>>() {
            });
            if (votoResponse.getMessage() != null) {
                responseMessage = votoResponse.getMessage();
                clearVotoInfo = "Invalid IVR service response: " + responseMessage;
            }
        } catch (IOException e) {
            responseMessage = responseBodyJson;
        }
        String message = "Invalid IVR service response: " + ex.getRawStatusCode() + " " + ex.getStatusText() + ", Response body: " + responseMessage;
        throw new IvrException(message, ex, clearVotoInfo);
    } catch (RestClientException ex) {
        String message = "Error occurred when sending request to IVR service: " + ex.getMessage();
        throw new IvrException(message, ex);
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) IvrException(org.motechproject.mots.exception.IvrException) HttpEntity(org.springframework.http.HttpEntity) VotoResponseDto(org.motechproject.mots.dto.VotoResponseDto) IOException(java.io.IOException) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) RestClientException(org.springframework.web.client.RestClientException) RestClientResponseException(org.springframework.web.client.RestClientResponseException) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) TypeReference(com.fasterxml.jackson.core.type.TypeReference)

Example 29 with RestClientException

use of org.springframework.web.client.RestClientException in project elastest-torm by elastest.

the class ElasticsearchService method putCall.

public ResponseEntity<String> putCall(String url, String body) throws IndexAlreadyExistException, RestClientException {
    RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory(5000, 5000));
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> request = new HttpEntity<String>(body, headers);
    try {
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, request, String.class);
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (!HttpStatus.OK.equals(statusCode)) {
            throw new IndexAlreadyExistException();
        }
        return responseEntity;
    } catch (RestClientException e) {
        throw e;
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity) HttpStatus(org.springframework.http.HttpStatus) RestTemplate(org.springframework.web.client.RestTemplate) RestClientException(org.springframework.web.client.RestClientException)

Example 30 with RestClientException

use of org.springframework.web.client.RestClientException in project spring-integration by spring-projects.

the class HttpRequestExecutingMessageHandler method exchange.

@Override
protected Object exchange(Supplier<URI> uriSupplier, HttpMethod httpMethod, HttpEntity<?> httpRequest, Object expectedResponseType, Message<?> requestMessage) {
    URI uri = uriSupplier.get();
    ResponseEntity<?> httpResponse;
    try {
        if (expectedResponseType instanceof ParameterizedTypeReference<?>) {
            httpResponse = this.restTemplate.exchange(uri, httpMethod, httpRequest, (ParameterizedTypeReference<?>) expectedResponseType);
        } else {
            httpResponse = this.restTemplate.exchange(uri, httpMethod, httpRequest, (Class<?>) expectedResponseType);
        }
        return getReply(httpResponse);
    } catch (RestClientException e) {
        throw new MessageHandlingException(requestMessage, "HTTP request execution failed for URI [" + uri + "]", e);
    }
}
Also used : ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) RestClientException(org.springframework.web.client.RestClientException) URI(java.net.URI) MessageHandlingException(org.springframework.messaging.MessageHandlingException)

Aggregations

RestClientException (org.springframework.web.client.RestClientException)43 HttpHeaders (org.springframework.http.HttpHeaders)12 HttpEntity (org.springframework.http.HttpEntity)11 IOException (java.io.IOException)9 RestTemplate (org.springframework.web.client.RestTemplate)9 HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)8 Test (org.junit.Test)5 JsonParseException (com.fasterxml.jackson.core.JsonParseException)4 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)4 HttpServerErrorException (org.springframework.web.client.HttpServerErrorException)4 UriComponentsBuilder (org.springframework.web.util.UriComponentsBuilder)4 URI (java.net.URI)3 List (java.util.List)3 Test (org.junit.jupiter.api.Test)3 JSONObject (com.alibaba.fastjson.JSONObject)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2 RealNameAuthentication (com.itrus.portal.db.RealNameAuthentication)2 RealNameAuthenticationExample (com.itrus.portal.db.RealNameAuthenticationExample)2 GitHubDTO (com.nixmash.blog.jpa.dto.GitHubDTO)2