org.springframework.web.client.RequestCallback Java Examples

The following examples show how to use org.springframework.web.client.RequestCallback. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestRestTemplateWrapper.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void executeWithUnderlyingRestTemplate() {
  RequestCallback requestCallback = clientHttpRequest -> {
  };
  ResponseExtractor<ResponseEntity<String>> responseExtractor = clientHttpResponse -> responseEntity;

  ResponseEntity<String> actual;

  for (HttpMethod method : httpMethods) {
    when(underlying.execute(url, method, requestCallback, responseExtractor, param1, param2))
        .thenReturn(responseEntity);
    actual = wrapper.execute(url, method, requestCallback, responseExtractor, param1, param2);
    assertThat(actual, is(responseEntity));
    verify(underlying).execute(url, method, requestCallback, responseExtractor, param1, param2);

    when(underlying.execute(url, method, requestCallback, responseExtractor, paramsMap)).thenReturn(responseEntity);
    actual = wrapper.execute(url, method, requestCallback, responseExtractor, paramsMap);
    assertThat(actual, is(responseEntity));
    verify(underlying).execute(url, method, requestCallback, responseExtractor, paramsMap);

    when(underlying.execute(uri, method, requestCallback, responseExtractor)).thenReturn(responseEntity);
    actual = wrapper.execute(uri, method, requestCallback, responseExtractor);
    assertThat(actual, is(responseEntity));
    verify(underlying).execute(uri, method, requestCallback, responseExtractor);
  }
}
 
Example #2
Source File: AuthorizationServerInfo.java    From spring-boot-demo with MIT License 6 votes vote down vote up
public HttpHeaders postForHeaders(String path, MultiValueMap<String, String> formData, final HttpHeaders headers) {
    RequestCallback requestCallback = new NullRequestCallback();
    if (headers != null) {
        requestCallback = request -> request.getHeaders().putAll(headers);
    }
    StringBuilder builder = new StringBuilder(getUrl(path));
    if (!path.contains("?")) {
        builder.append("?");
    } else {
        builder.append("&");
    }
    for (String key : formData.keySet()) {
        for (String value : formData.get(key)) {
            builder.append(key).append("=").append(value);
            builder.append("&");
        }
    }
    builder.deleteCharAt(builder.length() - 1);

    return client.execute(builder.toString(), HttpMethod.POST, requestCallback,
        HttpMessage::getHeaders);
}
 
Example #3
Source File: HttpOperationsTest.java    From riptide with MIT License 6 votes vote down vote up
static Iterable<Function<RestOperations, User>> execute() {
    final ObjectMapper mapper = new ObjectMapper();

    final RequestCallback callback = request -> {
        request.getHeaders().add("Test", "true");
        request.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        mapper.writeValue(request.getBody(), new User("D. Fault", "1984-09-13"));
    };

    final ResponseExtractor<User> extractor = response ->
            mapper.readValue(response.getBody(), User.class);

    return Arrays.asList(
            unit -> unit.execute("/departments/{id}/users", POST, callback, extractor, 1),
            unit -> unit.execute("/departments/{id}/users", POST, callback, extractor, singletonMap("id", 1)),
            unit -> unit.execute(URI.create("/departments/1/users"), POST, callback, extractor)
    );
}
 
Example #4
Source File: HttpOperations.java    From riptide with MIT License 5 votes vote down vote up
@Nullable
private Entity toEntity(@Nullable final RequestCallback callback) {
    if (callback == null) {
        return null;
    }

    return message ->
            callback.doWithRequest(new HttpOutputMessageClientHttpRequestAdapter(message));
}
 
Example #5
Source File: RestTemplateXhrTransportTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T execute(URI url, HttpMethod method, RequestCallback callback, ResponseExtractor<T> extractor) throws RestClientException {
	try {
		extractor.extractData(this.responses.remove());
	}
	catch (Throwable t) {
		throw new RestClientException("Failed to invoke extractor", t);
	}
	return null;
}
 
Example #6
Source File: TrackerSynchronization.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean sendSyncRequest( List<TrackedEntityInstance> dtoTeis )
{
    TrackedEntityInstances teis = new TrackedEntityInstances();
    teis.setTrackedEntityInstances( dtoTeis );

    final RequestCallback requestCallback = request ->
    {
        request.getHeaders().setContentType( MediaType.APPLICATION_JSON );
        request.getHeaders().add( SyncUtils.HEADER_AUTHORIZATION, CodecUtils.getBasicAuthString( instance.getUsername(), instance.getPassword() ) );
        renderService.toJson( request.getBody(), teis );
    };

    return SyncUtils.sendSyncRequest( systemSettingManager, restTemplate, requestCallback, instance, SyncEndpoint.TRACKED_ENTITY_INSTANCES );
}
 
Example #7
Source File: EventSynchronization.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean sendSyncRequest( Events events )
{
    final RequestCallback requestCallback = request ->
    {
        request.getHeaders().setContentType( MediaType.APPLICATION_JSON );
        request.getHeaders().add( SyncUtils.HEADER_AUTHORIZATION, CodecUtils.getBasicAuthString( instance.getUsername(), instance.getPassword() ) );
        renderService.toJson( request.getBody(), events );
    };

    return SyncUtils.sendSyncRequest( systemSettingManager, restTemplate, requestCallback, instance, SyncEndpoint.EVENTS );
}
 
Example #8
Source File: CompleteDataSetRegistrationSynchronization.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean sendSyncRequest()
{
    final RequestCallback requestCallback = request -> {
        request.getHeaders().setContentType( MediaType.APPLICATION_JSON );
        request.getHeaders().add( SyncUtils.HEADER_AUTHORIZATION,
            CodecUtils.getBasicAuthString( instance.getUsername(), instance.getPassword() ) );

        completeDataSetRegistrationExchangeService
            .writeCompleteDataSetRegistrationsJson( lastUpdatedAfter, request.getBody(), new IdSchemes() );
    };

    return SyncUtils.sendSyncRequest( systemSettingManager, restTemplate, requestCallback, instance, SyncEndpoint.COMPLETE_DATA_SET_REGISTRATIONS );
}
 
Example #9
Source File: TwitterSourceIntegrationTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Bean
public TwitterTemplate twitterTemplate() {
	TwitterTemplate mockTemplate = mock(TwitterTemplate.class);
	RestTemplate restTemplate = mock(RestTemplate.class);
	final ClientHttpResponse response = mock(ClientHttpResponse.class);
	ByteArrayInputStream bais = new ByteArrayInputStream("foo".getBytes());
	try {
		when(response.getBody()).thenReturn(bais);
	}
	catch (IOException e) {
	}
	doAnswer(new Answer<Void>() {

		@Override
		public Void answer(InvocationOnMock invocation) throws Throwable {
			uri().set(invocation.getArgumentAt(0, URI.class));
			ResponseExtractor<?> extractor = invocation.getArgumentAt(3, ResponseExtractor.class);
			extractor.extractData(response);
			return null;
		}

	}).when(restTemplate).execute(any(URI.class), any(HttpMethod.class), any(RequestCallback.class),
			any(ResponseExtractor.class));
	when(mockTemplate.getRestTemplate()).thenReturn(restTemplate);
	return mockTemplate;
}
 
Example #10
Source File: TwitterTestConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Bean
@ConditionalOnClass(TwitterTemplate.class)
public TwitterTemplate twitterTemplate() {
	TwitterTemplate mockTemplate = mock(TwitterTemplate.class);
	RestTemplate restTemplate = mock(RestTemplate.class);
	final ClientHttpResponse response = mock(ClientHttpResponse.class);
	ByteArrayInputStream bais = new ByteArrayInputStream("foo".getBytes());
	try {
		when(response.getBody()).thenReturn(bais);
	}
	catch (IOException e) {
	}
	doAnswer(new Answer<Void>() {

		@Override
		public Void answer(InvocationOnMock invocation) throws Throwable {
			ResponseExtractor<?> extractor = invocation.getArgumentAt(3, ResponseExtractor.class);
			extractor.extractData(response);
			return null;
		}

	}).when(restTemplate).execute(any(URI.class), any(HttpMethod.class), any(RequestCallback.class),
			any(ResponseExtractor.class));
	when(mockTemplate.getRestTemplate()).thenReturn(restTemplate);
	return mockTemplate;
}
 
Example #11
Source File: HttpOperations.java    From riptide with MIT License 5 votes vote down vote up
@Override
public <T> T execute(final String url, final HttpMethod method, @Nullable final RequestCallback callback,
        @Nullable final ResponseExtractor<T> extractor, final Map<String, ?> uriVariables) {
    final Capture<T> capture = Capture.empty();
    return execute(url, method, toEntity(callback), ExtractRoute.extractTo(extractor, capture), capture,
            extract(url, uriVariables));
}
 
Example #12
Source File: DataValueSynchronization.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean sendSyncRequest( int syncPageSize, int page )
{
    final RequestCallback requestCallback = request ->
    {
        request.getHeaders().setContentType( MediaType.APPLICATION_JSON );
        request.getHeaders().add( SyncUtils.HEADER_AUTHORIZATION,
            CodecUtils.getBasicAuthString( instance.getUsername(), instance.getPassword() ) );

        dataValueSetService.writeDataValueSetJson( lastUpdatedAfter, request.getBody(), new IdSchemes(),
            syncPageSize, page );
    };

    return SyncUtils.sendSyncRequest( systemSettingManager, restTemplate, requestCallback, instance, SyncEndpoint.DATA_VALUE_SETS );
}
 
Example #13
Source File: ExtRestTemplate.java    From onetwo with Apache License 2.0 5 votes vote down vote up
protected <T> ResponseEntity<T> doExecute(RequestContextData context) {
		RequestCallback rc = null;
		HttpMethod method = context.getHttpMethod();
		ResponseExtractor<ResponseEntity<T>> responseExtractor = null;
		HttpHeaders headers = context.getHeaders();
		HttpEntity<?> requestEntity = null;
		
		if(method==HttpMethod.GET) {
//				rc = super.acceptHeaderRequestCallback(context.getResponseType());
//				responseExtractor = responseEntityExtractor(context.getResponseType());
			//根据consumers 设置header,以指定messageConvertor
//			headers = new HttpHeaders();
//			context.acceptHeaderCallback(headers);
			requestEntity = new HttpEntity<>(headers);
			
			rc = super.httpEntityCallback(requestEntity, context.getResponseType());
			responseExtractor = responseEntityExtractor(context.getResponseType());
		}else if(RestUtils.isRequestBodySupportedMethod(method)){
//			headers = new HttpHeaders();
			//根据consumers 设置header,以指定messageConvertor
//			context.acceptHeaderCallback(headers);
			
//			Object requestBody = context.getRequestBodySupplier().get();
//			Object requestBody = context.getRequestBodySupplier().getRequestBody(context);
			Object requestBody = context.getRequestBody();
			logData(requestBody);
			requestEntity = new HttpEntity<>(requestBody, headers);
			
			rc = super.httpEntityCallback(requestEntity, context.getResponseType());
			responseExtractor = responseEntityExtractor(context.getResponseType());
		}else{
			throw new RestClientException("unsupported method: " + method);
		}
		if(context.hasHeaderCallback()){
			rc = wrapRequestCallback(context, rc);
		}
		return execute(context.getRequestUrl(), method, rc, responseExtractor, context.getUriVariables());
	}
 
Example #14
Source File: ExtRestTemplate.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException {
	RequestContextData ctx = RestExecuteThreadLocal.get();
	if(ctx!=null && logger.isDebugEnabled()){
		logger.debug("rest requestId[{}] : {} - {}", ctx.getRequestId(), method, url);
	}
	return super.doExecute(url, method, requestCallback, responseExtractor);
}
 
Example #15
Source File: AssertingRestTemplate.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Override
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback,
		ResponseExtractor<T> responseExtractor) throws RestClientException {
	try {
		return super.doExecute(url, method, requestCallback, responseExtractor);
	}
	catch (Exception e) {
		log.error("Exception occurred while sending the message to uri [" + url
				+ "]. Exception [" + e.getCause() + "]");
		throw new AssertionError(e);
	}
}
 
Example #16
Source File: ZipkinRestTemplateSenderConfiguration.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Override
protected <T> T doExecute(URI originalUrl, HttpMethod method,
		RequestCallback requestCallback, ResponseExtractor<T> responseExtractor)
		throws RestClientException {
	URI uri = this.extractor.zipkinUrl(this.zipkinProperties);
	URI newUri = resolvedZipkinUri(originalUrl, uri);
	return super.doExecute(newUri, method, requestCallback, responseExtractor);
}
 
Example #17
Source File: BasicAuthRestTemplate.java    From expper with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected <T> T doExecute(URI url, HttpMethod method,
                          RequestCallback requestCallback,
                          ResponseExtractor<T> responseExtractor) throws RestClientException {

    RequestCallbackDecorator requestCallbackDecorator = new RequestCallbackDecorator(
        requestCallback);

    return super.doExecute(url, method, requestCallbackDecorator,
        responseExtractor);
}
 
Example #18
Source File: RestTemplateBasicLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
private RequestCallback requestCallback(final Foo updatedInstance) {
    return clientHttpRequest -> {
        final ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(clientHttpRequest.getBody(), updatedInstance);
        clientHttpRequest.getHeaders()
            .add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        clientHttpRequest.getHeaders()
            .add(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass());
    };
}
 
Example #19
Source File: RestTemplateBasicLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
private RequestCallback requestCallback(final Foo updatedInstance) {
    return clientHttpRequest -> {
        final ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(clientHttpRequest.getBody(), updatedInstance);
        clientHttpRequest.getHeaders()
            .add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        clientHttpRequest.getHeaders()
            .add(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass());
    };
}
 
Example #20
Source File: TestCseRequestCallback.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testNormal(@Mocked RequestCallback callback) throws IOException {
  CseClientHttpRequest request = new CseClientHttpRequest();
  CseRequestCallback cb = new CseRequestCallback(null, callback, null);
  cb.doWithRequest(request);

  Assert.assertEquals(null, request.getContext());
}
 
Example #21
Source File: TestCseRequestCallback.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testCseEntity(@Injectable CseHttpEntity<?> entity,
    @Mocked RequestCallback callback) throws IOException {
  CseClientHttpRequest request = new CseClientHttpRequest();

  entity.addContext("c1", "c2");
  CseRequestCallback cb = new CseRequestCallback(entity, callback, null);
  cb.doWithRequest(request);

  Assert.assertEquals(entity.getContext(), request.getContext());
}
 
Example #22
Source File: RestTemplateXhrTransportTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public <T> T execute(URI url, HttpMethod method, @Nullable RequestCallback callback,
		@Nullable ResponseExtractor<T> extractor) throws RestClientException {

	try {
		extractor.extractData(this.responses.remove());
	}
	catch (Throwable t) {
		throw new RestClientException("Failed to invoke extractor", t);
	}
	return null;
}
 
Example #23
Source File: JwtSsoRestTemplate.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
@Override
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback,
        ResponseExtractor<T> responseExtractor) throws RestClientException {
    try {
        return super.doExecute(url, method, requestCallback, responseExtractor);
    } catch (JwtSsoAccessTokenRequiredException e) {
        if (log.isInfoEnabled()) {
            log.info("access token is invalid and try again.");
        }
        jwtSsoClientContext.refreshToken();
        return super.doExecute(url, method, requestCallback, responseExtractor);
    }
}
 
Example #24
Source File: RestTemplateXhrTransportTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public <T> T execute(URI url, HttpMethod method, @Nullable RequestCallback callback,
		@Nullable ResponseExtractor<T> extractor) throws RestClientException {

	try {
		extractor.extractData(this.responses.remove());
	}
	catch (Throwable t) {
		throw new RestClientException("Failed to invoke extractor", t);
	}
	return null;
}
 
Example #25
Source File: RestTemplateXhrTransport.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public ResponseEntity<String> executeSendRequestInternal(URI url, HttpHeaders headers, TextMessage message) {
	RequestCallback requestCallback = new XhrRequestCallback(headers, message.getPayload());
	return nonNull(this.restTemplate.execute(url, HttpMethod.POST, requestCallback, textResponseExtractor));
}
 
Example #26
Source File: RestClientTemplate.java    From sinavi-jfw with Apache License 2.0 4 votes vote down vote up
/**
 * このメソッドは {@link RestOperations#execute(java.net.URI, org.springframework.http.HttpMethod, org.springframework.web.client.RequestCallback, org.springframework.web.client.ResponseExtractor)} への単純な委譲です。
 * {@inheritDoc}
 */
@Override
public <T> T execute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException {
    return delegate.execute(url, method, requestCallback, responseExtractor);
}
 
Example #27
Source File: RestClientTemplate.java    From sinavi-jfw with Apache License 2.0 4 votes vote down vote up
/**
 * このメソッドは {@link RestOperations#execute(String, org.springframework.http.HttpMethod, org.springframework.web.client.RequestCallback, org.springframework.web.client.ResponseExtractor, java.util.Map)} への単純な委譲です。
 * {@inheritDoc}
 */
@Override
public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor, Map<String, ?> uriVariables) throws RestClientException {
    return delegate.execute(url, method, requestCallback, responseExtractor, uriVariables);
}
 
Example #28
Source File: RestClientTemplate.java    From sinavi-jfw with Apache License 2.0 4 votes vote down vote up
/**
 * このメソッドは {@link RestOperations#execute(String, org.springframework.http.HttpMethod, org.springframework.web.client.RequestCallback, org.springframework.web.client.ResponseExtractor, Object...)} への単純な委譲です。
 * {@inheritDoc}
 */
@Override
public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor, Object... uriVariables) throws RestClientException {
    return delegate.execute(url, method, requestCallback, responseExtractor, uriVariables);
}
 
Example #29
Source File: BasicAuthRestTemplate.java    From expper with GNU General Public License v3.0 4 votes vote down vote up
public RequestCallbackDecorator(RequestCallback targetRequestCallback) {
    this.targetRequestCallback = targetRequestCallback;
}
 
Example #30
Source File: RestTemplateXhrTransport.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
protected ResponseEntity<String> executeInfoRequestInternal(URI infoUrl, HttpHeaders headers) {
	RequestCallback requestCallback = new XhrRequestCallback(headers);
	return nonNull(this.restTemplate.execute(infoUrl, HttpMethod.GET, requestCallback, textResponseExtractor));
}