Search in sources :

Example 11 with ClientHttpRequest

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

the class ContentRequestMatchers method string.

/**
	 * Get the body of the request as a UTF-8 string and appply the given {@link Matcher}.
	 */
public RequestMatcher string(final Matcher<? super String> matcher) {
    return new RequestMatcher() {

        @Override
        public void match(ClientHttpRequest request) throws IOException, AssertionError {
            MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
            assertThat("Request content", mockRequest.getBodyAsString(), matcher);
        }
    };
}
Also used : RequestMatcher(org.springframework.test.web.client.RequestMatcher) MockClientHttpRequest(org.springframework.mock.http.client.MockClientHttpRequest) MockClientHttpRequest(org.springframework.mock.http.client.MockClientHttpRequest) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest)

Example 12 with ClientHttpRequest

use of org.springframework.http.client.ClientHttpRequest in project spring-boot by spring-projects.

the class ServletWebServerMvcIntegrationTests method doTest.

private void doTest(AnnotationConfigServletWebServerApplicationContext context, String resourcePath) throws Exception {
    SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
    ClientHttpRequest request = clientHttpRequestFactory.createRequest(new URI("http://localhost:" + context.getWebServer().getPort() + resourcePath), HttpMethod.GET);
    ClientHttpResponse response = request.execute();
    try {
        String actual = StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8"));
        assertThat(actual).isEqualTo("Hello World");
    } finally {
        response.close();
    }
}
Also used : SimpleClientHttpRequestFactory(org.springframework.http.client.SimpleClientHttpRequestFactory) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) URI(java.net.URI) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse)

Example 13 with ClientHttpRequest

use of org.springframework.http.client.ClientHttpRequest 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 14 with ClientHttpRequest

use of org.springframework.http.client.ClientHttpRequest in project dhis2-core by dhis2.

the class DefaultSynchronizationManager method executeEventPush.

@Override
public ImportSummaries executeEventPush() throws WebMessageParseException {
    AvailabilityStatus availability = isRemoteServerAvailable();
    if (!availability.isAvailable()) {
        log.info("Aborting synch, server not available");
        return null;
    }
    // ---------------------------------------------------------------------
    // Set time for last success to start of process to make data saved
    // subsequently part of next synch process without being ignored
    // ---------------------------------------------------------------------
    final Date startTime = new Date();
    final Date lastSuccessTime = getLastEventSynchSuccessFallback();
    int lastUpdatedEventsCount = eventService.getAnonymousEventValuesCountLastUpdatedAfter(lastSuccessTime);
    log.info("Events: " + lastUpdatedEventsCount + " since last synch success: " + lastSuccessTime);
    if (lastUpdatedEventsCount == 0) {
        log.info("Skipping synch, no new or updated data values for events");
        return null;
    }
    String url = systemSettingManager.getSystemSetting(SettingKey.REMOTE_INSTANCE_URL) + "/api/events";
    log.info("Remote server events POST URL: " + url);
    final String username = (String) systemSettingManager.getSystemSetting(SettingKey.REMOTE_INSTANCE_USERNAME);
    final String password = (String) systemSettingManager.getSystemSetting(SettingKey.REMOTE_INSTANCE_PASSWORD);
    final RequestCallback requestCallback = new RequestCallback() {

        @Override
        public void doWithRequest(ClientHttpRequest request) throws IOException {
            request.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            request.getHeaders().add(HEADER_AUTHORIZATION, CodecUtils.getBasicAuthString(username, password));
            Events result = eventService.getAnonymousEventValuesLastUpdatedAfter(lastSuccessTime);
            renderService.toJson(request.getBody(), result);
        }
    };
    ResponseExtractor<ImportSummaries> responseExtractor = new ImportSummariesResponseExtractor();
    ImportSummaries summaries = null;
    try {
        summaries = restTemplate.execute(url, HttpMethod.POST, requestCallback, responseExtractor);
    } catch (HttpClientErrorException ex) {
        String responseBody = ex.getResponseBodyAsString();
        summaries = WebMessageParseUtils.fromWebMessageResponse(responseBody, ImportSummaries.class);
    } catch (HttpServerErrorException ex) {
        String responseBody = ex.getResponseBodyAsString();
        log.error("Internal error happened during event data push: " + responseBody, ex);
        throw ex;
    } catch (ResourceAccessException ex) {
        log.error("Exception during event data push: " + ex.getMessage(), ex);
        throw ex;
    }
    log.info("Event synch summary: " + summaries);
    boolean isError = false;
    if (summaries != null) {
        for (ImportSummary summary : summaries.getImportSummaries()) {
            if (ImportStatus.ERROR.equals(summary.getStatus()) || ImportStatus.WARNING.equals(summary.getStatus())) {
                isError = true;
                log.debug("Sync failed: " + summaries);
                break;
            }
        }
    }
    if (!isError) {
        setLastEventSynchSuccess(startTime);
        log.info("Synch successful, setting last success time: " + startTime);
    }
    return summaries;
}
Also used : ImportSummariesResponseExtractor(org.hisp.dhis.dxf2.common.ImportSummariesResponseExtractor) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) Date(java.util.Date) ResourceAccessException(org.springframework.web.client.ResourceAccessException) RequestCallback(org.springframework.web.client.RequestCallback) Events(org.hisp.dhis.dxf2.events.event.Events) ImportSummaries(org.hisp.dhis.dxf2.importsummary.ImportSummaries)

Example 15 with ClientHttpRequest

use of org.springframework.http.client.ClientHttpRequest 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)

Aggregations

ClientHttpRequest (org.springframework.http.client.ClientHttpRequest)36 URI (java.net.URI)19 Test (org.junit.Test)13 ClientHttpResponse (org.springframework.http.client.ClientHttpResponse)13 IOException (java.io.IOException)11 HttpMethod (org.springframework.http.HttpMethod)9 ClientHttpRequestFactory (org.springframework.http.client.ClientHttpRequestFactory)9 HttpHeaders (org.springframework.http.HttpHeaders)6 MockClientHttpRequest (org.springframework.mock.http.client.MockClientHttpRequest)6 RequestMatcher (org.springframework.test.web.client.RequestMatcher)6 SimpleClientHttpRequestFactory (org.springframework.http.client.SimpleClientHttpRequestFactory)4 AccessTokenRequest (org.springframework.security.oauth2.client.token.AccessTokenRequest)4 DefaultAccessTokenRequest (org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest)4 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 ArrayList (java.util.ArrayList)2 ObjectMapper (org.codehaus.jackson.map.ObjectMapper)2 MediaType (org.springframework.http.MediaType)2 ClientHttpRequestInterceptor (org.springframework.http.client.ClientHttpRequestInterceptor)2 HttpComponentsClientHttpRequestFactory (org.springframework.http.client.HttpComponentsClientHttpRequestFactory)2