Search in sources :

Example 16 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 17 with ClientHttpRequest

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

the class OAuthClientHttpRequestFactory method createRequest.

public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
    OAuthSecurityContext context = OAuthSecurityContextHolder.getContext();
    if (context == null) {
        context = new OAuthSecurityContextImpl();
    }
    Map<String, OAuthConsumerToken> accessTokens = context.getAccessTokens();
    OAuthConsumerToken accessToken = accessTokens == null ? null : accessTokens.get(this.resource.getId());
    boolean useAuthHeader = this.resource.isAcceptsAuthorizationHeader();
    if (!useAuthHeader) {
        String queryString = this.support.getOAuthQueryString(this.resource, accessToken, uri.toURL(), httpMethod.name(), this.additionalOAuthParameters);
        String uriValue = String.valueOf(uri);
        uri = URI.create((uriValue.contains("?") ? uriValue.substring(0, uriValue.indexOf('?')) : uriValue) + "?" + queryString);
    }
    ClientHttpRequest req = delegate.createRequest(uri, httpMethod);
    if (useAuthHeader) {
        String authHeader = this.support.getAuthorizationHeader(this.resource, accessToken, uri.toURL(), httpMethod.name(), this.additionalOAuthParameters);
        req.getHeaders().add("Authorization", authHeader);
    }
    Map<String, String> additionalHeaders = this.resource.getAdditionalRequestHeaders();
    if (additionalHeaders != null) {
        for (Map.Entry<String, String> header : additionalHeaders.entrySet()) {
            req.getHeaders().add(header.getKey(), header.getValue());
        }
    }
    return req;
}
Also used : OAuthSecurityContextImpl(org.springframework.security.oauth.consumer.OAuthSecurityContextImpl) OAuthSecurityContext(org.springframework.security.oauth.consumer.OAuthSecurityContext) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) Map(java.util.Map) OAuthConsumerToken(org.springframework.security.oauth.consumer.OAuthConsumerToken)

Example 18 with ClientHttpRequest

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

the class OAuth2RestTemplate method createRequest.

@Override
protected ClientHttpRequest createRequest(URI uri, HttpMethod method) throws IOException {
    OAuth2AccessToken accessToken = getAccessToken();
    AuthenticationScheme authenticationScheme = resource.getAuthenticationScheme();
    if (AuthenticationScheme.query.equals(authenticationScheme) || AuthenticationScheme.form.equals(authenticationScheme)) {
        uri = appendQueryParameter(uri, accessToken);
    }
    ClientHttpRequest req = super.createRequest(uri, method);
    if (AuthenticationScheme.header.equals(authenticationScheme)) {
        authenticator.authenticate(resource, getOAuth2ClientContext(), req);
    }
    return req;
}
Also used : AuthenticationScheme(org.springframework.security.oauth2.common.AuthenticationScheme) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest)

Example 19 with ClientHttpRequest

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

the class OAuth2RestTemplateTests method testNoRetryAccessDeniedExceptionForNoExistingToken.

@Test(expected = AccessTokenRequiredException.class)
public void testNoRetryAccessDeniedExceptionForNoExistingToken() throws Exception {
    restTemplate.setAccessTokenProvider(new StubAccessTokenProvider());
    restTemplate.setRequestFactory(new ClientHttpRequestFactory() {

        public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
            throw new AccessTokenRequiredException(resource);
        }
    });
    restTemplate.doExecute(new URI("http://foo"), HttpMethod.GET, new NullRequestCallback(), new SimpleResponseExtractor());
}
Also used : ClientHttpRequestFactory(org.springframework.http.client.ClientHttpRequestFactory) AccessTokenRequiredException(org.springframework.security.oauth2.client.http.AccessTokenRequiredException) IOException(java.io.IOException) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) URI(java.net.URI) HttpMethod(org.springframework.http.HttpMethod) Test(org.junit.Test)

Example 20 with ClientHttpRequest

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

the class OAuth2RestTemplateTests method testCustomAuthenticator.

@Test
public void testCustomAuthenticator() throws Exception {
    DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken("12345");
    token.setTokenType("MINE");
    restTemplate.setAuthenticator(new OAuth2RequestAuthenticator() {

        @Override
        public void authenticate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext clientContext, ClientHttpRequest req) {
            req.getHeaders().set("X-Authorization", clientContext.getAccessToken().getTokenType() + " " + "Nah-nah-na-nah-nah");
        }
    });
    restTemplate.getOAuth2ClientContext().setAccessToken(token);
    ClientHttpRequest http = restTemplate.createRequest(URI.create("https://nowhere.com/api/crap"), HttpMethod.GET);
    String auth = http.getHeaders().getFirst("X-Authorization");
    assertEquals("MINE Nah-nah-na-nah-nah", auth);
}
Also used : BaseOAuth2ProtectedResourceDetails(org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails) OAuth2ProtectedResourceDetails(org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) Test(org.junit.Test)

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