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;
}
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;
}
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;
}
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());
}
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);
}
Aggregations