Search in sources :

Example 31 with ParameterizedTypeReference

use of org.springframework.core.ParameterizedTypeReference 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 32 with ParameterizedTypeReference

use of org.springframework.core.ParameterizedTypeReference 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)

Example 33 with ParameterizedTypeReference

use of org.springframework.core.ParameterizedTypeReference in project spring-integration by spring-projects.

the class HttpRequestExecutingMessageHandlerTests method testHttpOutboundGatewayWithinChain.

// INT-1029
@Test
public void testHttpOutboundGatewayWithinChain() throws IOException, URISyntaxException {
    ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("HttpOutboundWithinChainTests-context.xml", this.getClass());
    MessageChannel channel = ctx.getBean("httpOutboundGatewayWithinChain", MessageChannel.class);
    RestTemplate restTemplate = ctx.getBean("restTemplate", RestTemplate.class);
    channel.send(MessageBuilder.withPayload("test").build());
    PollableChannel output = ctx.getBean("replyChannel", PollableChannel.class);
    Message<?> receive = output.receive();
    assertEquals(HttpStatus.OK, ((ResponseEntity<?>) receive.getPayload()).getStatusCode());
    Mockito.verify(restTemplate).exchange(Mockito.eq(new URI("http://localhost:51235/%2f/testApps?param=http+Outbound+Gateway+Within+Chain")), Mockito.eq(HttpMethod.POST), Mockito.any(HttpEntity.class), Mockito.eq(new ParameterizedTypeReference<List<String>>() {
    }));
    ctx.close();
}
Also used : ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) MessageChannel(org.springframework.messaging.MessageChannel) HttpEntity(org.springframework.http.HttpEntity) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) RestTemplate(org.springframework.web.client.RestTemplate) PollableChannel(org.springframework.messaging.PollableChannel) URI(java.net.URI) Test(org.junit.Test)

Example 34 with ParameterizedTypeReference

use of org.springframework.core.ParameterizedTypeReference in project tutorials by eugenp.

the class PetApi method updatePetWithForm.

/**
 * Updates a pet in the store with form data
 *
 * <p><b>405</b> - Invalid input
 * @param petId ID of pet that needs to be updated
 * @param name Updated name of the pet
 * @param status Updated status of the pet
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public void updatePetWithForm(Long petId, String name, String status) throws RestClientException {
    Object postBody = null;
    // verify the required parameter 'petId' is set
    if (petId == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling updatePetWithForm");
    }
    // create path and map variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("petId", petId);
    String path = UriComponentsBuilder.fromPath("/pet/{petId}").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>();
    if (name != null)
        formParams.add("name", name);
    if (status != null)
        formParams.add("status", status);
    final String[] accepts = { "application/xml", "application/json" };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { "application/x-www-form-urlencoded" };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
    String[] authNames = new String[] { "petstore_auth" };
    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {
    };
    apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HashMap(java.util.HashMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) MediaType(org.springframework.http.MediaType)

Example 35 with ParameterizedTypeReference

use of org.springframework.core.ParameterizedTypeReference in project tutorials by eugenp.

the class PetApi method updatePet.

/**
 * Update an existing pet
 *
 * <p><b>400</b> - Invalid ID supplied
 * <p><b>404</b> - Pet not found
 * <p><b>405</b> - Validation exception
 * @param body Pet object that needs to be added to the store
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public void updatePet(Pet body) throws RestClientException {
    Object postBody = body;
    // verify the required parameter 'body' is set
    if (body == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling updatePet");
    }
    String path = UriComponentsBuilder.fromPath("/pet").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 = { "application/xml", "application/json" };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { "application/json", "application/xml" };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
    String[] authNames = new String[] { "petstore_auth" };
    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {
    };
    apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) MediaType(org.springframework.http.MediaType)

Aggregations

ParameterizedTypeReference (org.springframework.core.ParameterizedTypeReference)57 MediaType (org.springframework.http.MediaType)29 HttpHeaders (org.springframework.http.HttpHeaders)25 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)22 List (java.util.List)20 HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)18 Test (org.junit.jupiter.api.Test)16 ArrayList (java.util.ArrayList)15 HashMap (java.util.HashMap)12 URI (java.net.URI)11 Test (org.junit.Test)10 MockHttpInputMessage (org.springframework.http.MockHttpInputMessage)8 URISyntaxException (java.net.URISyntaxException)7 MockHttpOutputMessage (org.springframework.http.MockHttpOutputMessage)7 DataBuffer (org.springframework.core.io.buffer.DataBuffer)6 HttpEntity (org.springframework.http.HttpEntity)6 Resources (org.springframework.hateoas.Resources)5 Traverson (org.springframework.hateoas.client.Traverson)5 IOException (java.io.IOException)4 DefaultDataBuffer (org.springframework.core.io.buffer.DefaultDataBuffer)4