Search in sources :

Example 26 with ClientHttpResponse

use of org.springframework.http.client.ClientHttpResponse in project uPortal by Jasig.

the class BasicAuthInterceptorTest method doInterceptorTest.

private void doInterceptorTest(PropertyResolver resolver, String id, String expectedAuthCode) throws Exception {
    final String url = "http://www.test.com/lrs";
    final String data = "test";
    final String expectedHeader = "Basic " + expectedAuthCode;
    // holder for the headers...
    HttpHeaders headers = new HttpHeaders();
    // Mock guts of RestTemplate so no need to actually hit the web...
    ClientHttpResponse resp = mock(ClientHttpResponse.class);
    when(resp.getStatusCode()).thenReturn(HttpStatus.ACCEPTED);
    when(resp.getHeaders()).thenReturn(new HttpHeaders());
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    ClientHttpRequest client = mock(ClientHttpRequest.class);
    when(client.getHeaders()).thenReturn(headers);
    when(client.getBody()).thenReturn(buffer);
    when(client.execute()).thenReturn(resp);
    ClientHttpRequestFactory factory = mock(ClientHttpRequestFactory.class);
    when(factory.createRequest(any(URI.class), any(HttpMethod.class))).thenReturn(client);
    // add the new interceptor...
    BasicAuthInterceptor interceptor = new BasicAuthInterceptor();
    interceptor.setPropertyResolver(resolver);
    interceptor.setId(id);
    List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
    interceptors.add(interceptor);
    RestTemplate rest = new RestTemplate(factory);
    rest.setInterceptors(interceptors);
    // do it...
    rest.postForLocation(url, data, Collections.emptyMap());
    // make sure auth header is correctly set...
    assertThat(headers, hasKey(Headers.Authorization.name()));
    assertThat(headers.get(Headers.Authorization.name()), contains(expectedHeader));
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ClientHttpRequestFactory(org.springframework.http.client.ClientHttpRequestFactory) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) URI(java.net.URI) ClientHttpRequestInterceptor(org.springframework.http.client.ClientHttpRequestInterceptor) RestTemplate(org.springframework.web.client.RestTemplate) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) HttpMethod(org.springframework.http.HttpMethod)

Example 27 with ClientHttpResponse

use of org.springframework.http.client.ClientHttpResponse in project uPortal by Jasig.

the class ZeroLeggedOAuthInterceptorTest method testInterceptor.

@Test
public void testInterceptor() throws Exception {
    final String url = "http://www.test.com/lrs?param1=val1&param2=val2";
    final String data = "test";
    final String id = "test";
    final String realm = "realm";
    final String consumerKey = "consumerKey";
    final String secretKey = "secretKey";
    PropertyResolver resolver = mock(PropertyResolver.class);
    when(resolver.getProperty(Matchers.eq("org.jasig.rest.interceptor.oauth." + id + ".realm"))).thenReturn(realm);
    when(resolver.getProperty(Matchers.eq("org.jasig.rest.interceptor.oauth." + id + ".consumerKey"))).thenReturn(consumerKey);
    when(resolver.getProperty(Matchers.eq("org.jasig.rest.interceptor.oauth." + id + ".secretKey"))).thenReturn(secretKey);
    // holder for the headers...
    HttpHeaders headers = new HttpHeaders();
    // Mock guts of RestTemplate so no need to actually hit the web...
    ClientHttpResponse resp = mock(ClientHttpResponse.class);
    when(resp.getStatusCode()).thenReturn(HttpStatus.ACCEPTED);
    when(resp.getHeaders()).thenReturn(new HttpHeaders());
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    ClientHttpRequest client = mock(ClientHttpRequest.class);
    when(client.getHeaders()).thenReturn(headers);
    when(client.getBody()).thenReturn(buffer);
    when(client.execute()).thenReturn(resp);
    ClientHttpRequestFactory factory = mock(ClientHttpRequestFactory.class);
    when(factory.createRequest(Matchers.any(URI.class), Matchers.any(HttpMethod.class))).thenReturn(client);
    // add the new interceptor...
    ZeroLeggedOAuthInterceptor interceptor = new ZeroLeggedOAuthInterceptor();
    interceptor.setPropertyResolver(resolver);
    interceptor.setId(id);
    List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
    interceptors.add(interceptor);
    RestTemplate rest = new RestTemplate(factory);
    rest.setInterceptors(interceptors);
    rest.postForLocation(url, data, Collections.emptyMap());
    // make sure auth header is correctly set...
    assertThat(headers, hasKey(Headers.Authorization.name()));
    String authHeader = headers.get(Headers.Authorization.name()).get(0);
    assertThat(authHeader, containsString("OAuth realm=\"" + realm + "\""));
    assertThat(authHeader, containsString("oauth_consumer_key=\"" + consumerKey + "\""));
    // for now, only supports HMAC-SHA1.  May have to fix later...
    assertThat(authHeader, containsString("oauth_signature_method=\"HMAC-SHA1\""));
    assertThat(authHeader, containsString("oauth_version=\"1.0\""));
    assertThat(authHeader, containsString("oauth_timestamp="));
    assertThat(authHeader, containsString("oauth_nonce="));
    assertThat(authHeader, containsString("oauth_signature="));
    // oauth lib will create 2 oauth_signature params if you call sign
    // multiple times.  Make sure only get 1.
    assertThat(StringUtils.countMatches(authHeader, "oauth_signature="), is(1));
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ClientHttpRequestFactory(org.springframework.http.client.ClientHttpRequestFactory) ArrayList(java.util.ArrayList) Matchers.containsString(org.hamcrest.Matchers.containsString) ByteArrayOutputStream(java.io.ByteArrayOutputStream) PropertyResolver(org.springframework.core.env.PropertyResolver) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) URI(java.net.URI) ClientHttpRequestInterceptor(org.springframework.http.client.ClientHttpRequestInterceptor) RestTemplate(org.springframework.web.client.RestTemplate) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) HttpMethod(org.springframework.http.HttpMethod) Test(org.junit.Test)

Example 28 with ClientHttpResponse

use of org.springframework.http.client.ClientHttpResponse in project midpoint by Evolveum.

the class SimpleSmsTransport method send.

@Override
public void send(Message message, String transportName, Event event, Task task, OperationResult parentResult) {
    OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
    result.addCollectionOfSerializablesAsParam("message recipient(s)", message.getTo());
    result.addParam("message subject", message.getSubject());
    SystemConfigurationType systemConfiguration = NotificationFunctionsImpl.getSystemConfiguration(cacheRepositoryService, new OperationResult("dummy"));
    if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null) {
        String msg = "No notifications are configured. SMS notification to " + message.getTo() + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }
    // after "sms:"
    String smsConfigName = transportName.length() > NAME.length() ? transportName.substring(NAME.length() + 1) : null;
    SmsConfigurationType found = null;
    for (SmsConfigurationType smsConfigurationType : systemConfiguration.getNotificationConfiguration().getSms()) {
        if ((smsConfigName == null && smsConfigurationType.getName() == null) || (smsConfigName != null && smsConfigName.equals(smsConfigurationType.getName()))) {
            found = smsConfigurationType;
            break;
        }
    }
    if (found == null) {
        String msg = "SMS configuration '" + smsConfigName + "' not found. SMS notification to " + message.getTo() + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }
    SmsConfigurationType smsConfigurationType = found;
    String file = smsConfigurationType.getRedirectToFile();
    if (file != null) {
        writeToFile(message, file, null, result);
        return;
    }
    if (smsConfigurationType.getGateway().isEmpty()) {
        String msg = "SMS gateway(s) are not defined, notification to " + message.getTo() + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }
    String from = smsConfigurationType.getDefaultFrom() != null ? smsConfigurationType.getDefaultFrom() : "";
    if (message.getTo().isEmpty()) {
        String msg = "There is no recipient to send the notification to.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }
    String to = message.getTo().get(0);
    if (message.getTo().size() > 1) {
        String msg = "Currently it is possible to send the SMS to one recipient only. Among " + message.getTo() + " the chosen one is " + to + " (the first one).";
        LOGGER.warn(msg);
    }
    for (SmsGatewayConfigurationType smsGatewayConfigurationType : smsConfigurationType.getGateway()) {
        OperationResult resultForGateway = result.createSubresult(DOT_CLASS + "send.forGateway");
        resultForGateway.addContext("gateway name", smsGatewayConfigurationType.getName());
        try {
            String url = evaluateExpressionChecked(smsGatewayConfigurationType.getUrl(), getDefaultVariables(from, to, message), "sms gateway url", task, result);
            LOGGER.debug("Sending SMS to URL " + url);
            if (smsGatewayConfigurationType.getRedirectToFile() != null) {
                writeToFile(message, smsGatewayConfigurationType.getRedirectToFile(), url, resultForGateway);
                result.computeStatus();
                return;
            } else {
                SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
                ClientHttpRequest request = requestFactory.createRequest(new URI(url), HttpMethod.GET);
                ClientHttpResponse response = request.execute();
                LOGGER.debug("Result: " + response.getStatusCode() + "/" + response.getStatusText());
                if (response.getStatusCode().series() != HttpStatus.Series.SUCCESSFUL) {
                    throw new SystemException("SMS gateway communication failed: " + response.getStatusCode() + ": " + response.getStatusText());
                }
                LOGGER.info("Message sent successfully to " + message.getTo() + " via gateway " + smsGatewayConfigurationType.getName() + ".");
                resultForGateway.recordSuccess();
                result.recordSuccess();
                return;
            }
        } catch (Throwable t) {
            String msg = "Couldn't send SMS to " + message.getTo() + " via " + smsGatewayConfigurationType.getName() + ", trying another gateway, if there is any";
            LoggingUtils.logException(LOGGER, msg, t);
            resultForGateway.recordFatalError(msg, t);
        }
    }
    LOGGER.warn("No more SMS gateways to try, notification to " + message.getTo() + " will not be sent.");
    result.recordWarning("Notification to " + message.getTo() + " could not be sent.");
}
Also used : SimpleClientHttpRequestFactory(org.springframework.http.client.SimpleClientHttpRequestFactory) SystemException(com.evolveum.midpoint.util.exception.SystemException) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) URI(java.net.URI) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse)

Example 29 with ClientHttpResponse

use of org.springframework.http.client.ClientHttpResponse in project sic by belluccifranco.

the class FacturacionIntegrationTest method setup.

@Before
public void setup() {
    String md5Test = "098f6bcd4621d373cade4e832627b4f6";
    usuarioRepository.save(new UsuarioBuilder().withNombre("test").withPassword(md5Test).build());
    // Interceptor de RestTemplate para JWT
    List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
    interceptors.add((ClientHttpRequestInterceptor) (HttpRequest request, byte[] body, ClientHttpRequestExecution execution) -> {
        request.getHeaders().set("Authorization", "Bearer " + token);
        return execution.execute(request, body);
    });
    restTemplate.getRestTemplate().setInterceptors(interceptors);
    // ErrorHandler para RestTemplate        
    restTemplate.getRestTemplate().setErrorHandler(new ResponseErrorHandler() {

        @Override
        public boolean hasError(ClientHttpResponse response) throws IOException {
            HttpStatus.Series series = response.getStatusCode().series();
            return (HttpStatus.Series.CLIENT_ERROR.equals(series) || HttpStatus.Series.SERVER_ERROR.equals(series));
        }

        @Override
        public void handleError(ClientHttpResponse response) throws IOException {
            String mensaje = IOUtils.toString(response.getBody());
            throw new RestClientResponseException(mensaje, response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), null, Charset.defaultCharset());
        }
    });
}
Also used : HttpRequest(org.springframework.http.HttpRequest) ResponseErrorHandler(org.springframework.web.client.ResponseErrorHandler) ArrayList(java.util.ArrayList) ClientHttpRequestExecution(org.springframework.http.client.ClientHttpRequestExecution) IOException(java.io.IOException) ClientHttpRequestInterceptor(org.springframework.http.client.ClientHttpRequestInterceptor) UsuarioBuilder(sic.builder.UsuarioBuilder) RestClientResponseException(org.springframework.web.client.RestClientResponseException) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) Before(org.junit.Before)

Example 30 with ClientHttpResponse

use of org.springframework.http.client.ClientHttpResponse in project spring-framework by spring-projects.

the class RestTemplateXhrTransportTests method response.

private ClientHttpResponse response(HttpStatus status, String body) throws IOException {
    ClientHttpResponse response = mock(ClientHttpResponse.class);
    InputStream inputStream = getInputStream(body);
    given(response.getStatusCode()).willReturn(status);
    given(response.getBody()).willReturn(inputStream);
    return response;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse)

Aggregations

ClientHttpResponse (org.springframework.http.client.ClientHttpResponse)70 Test (org.junit.Test)35 IOException (java.io.IOException)25 ResponseErrorHandler (org.springframework.web.client.ResponseErrorHandler)21 URI (java.net.URI)17 HttpHeaders (org.springframework.http.HttpHeaders)17 DefaultResponseErrorHandler (org.springframework.web.client.DefaultResponseErrorHandler)15 ClientHttpRequest (org.springframework.http.client.ClientHttpRequest)14 HttpComponentsClientHttpRequestFactory (org.springframework.http.client.HttpComponentsClientHttpRequestFactory)11 RestTemplate (org.springframework.web.client.RestTemplate)11 ResponseExtractor (org.springframework.web.client.ResponseExtractor)10 ByteArrayInputStream (java.io.ByteArrayInputStream)7 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)7 ServiceError (com.kixeye.chassis.transport.dto.ServiceError)6 SerDeHttpMessageConverter (com.kixeye.chassis.transport.http.SerDeHttpMessageConverter)6 MessageSerDe (com.kixeye.chassis.transport.serde.MessageSerDe)6 JsonJacksonMessageSerDe (com.kixeye.chassis.transport.serde.converter.JsonJacksonMessageSerDe)6 ProtobufMessageSerDe (com.kixeye.chassis.transport.serde.converter.ProtobufMessageSerDe)6 XmlMessageSerDe (com.kixeye.chassis.transport.serde.converter.XmlMessageSerDe)6 YamlJacksonMessageSerDe (com.kixeye.chassis.transport.serde.converter.YamlJacksonMessageSerDe)6