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 Project: servicecomb-java-chassis   Author: apache   File: TestRestTemplateWrapper.java    License: 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 Project: spring-boot-demo   Author: xkcoding   File: AuthorizationServerInfo.java    License: 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 Project: riptide   Author: zalando   File: HttpOperationsTest.java    License: 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 Project: spring-analysis-note   Author: Vip-Augus   File: RestTemplateXhrTransportTests.java    License: 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 #5
Source Project: wecube-platform   Author: WeBankPartners   File: JwtSsoRestTemplate.java    License: 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 #6
Source Project: java-technology-stack   Author: codeEngraver   File: RestTemplateXhrTransportTests.java    License: 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 #7
Source Project: servicecomb-java-chassis   Author: apache   File: TestCseRequestCallback.java    License: 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 #8
Source Project: servicecomb-java-chassis   Author: apache   File: TestCseRequestCallback.java    License: 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 #9
Source Project: spring4-understanding   Author: langtianya   File: RestTemplateXhrTransportTests.java    License: 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 #10
Source Project: dhis2-core   Author: dhis2   File: DataValueSynchronization.java    License: 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 #11
Source Project: dhis2-core   Author: dhis2   File: TrackerSynchronization.java    License: 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 #12
Source Project: dhis2-core   Author: dhis2   File: EventSynchronization.java    License: 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 #13
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 #14
Source Project: spring-cloud-stream-app-starters   Author: spring-cloud   File: TwitterSourceIntegrationTests.java    License: 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 #15
Source Project: spring-cloud-stream-app-starters   Author: spring-cloud   File: TwitterTestConfiguration.java    License: 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 #16
Source Project: riptide   Author: zalando   File: HttpOperations.java    License: 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 #17
Source Project: riptide   Author: zalando   File: HttpOperations.java    License: 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 #18
Source Project: onetwo   Author: wayshall   File: ExtRestTemplate.java    License: 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 #19
Source Project: onetwo   Author: wayshall   File: ExtRestTemplate.java    License: 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 #20
Source Project: spring-cloud-sleuth   Author: spring-cloud   File: AssertingRestTemplate.java    License: 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 #21
Source Project: spring-cloud-sleuth   Author: spring-cloud   File: ZipkinRestTemplateSenderConfiguration.java    License: 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 #22
Source Project: expper   Author: Raysmond   File: BasicAuthRestTemplate.java    License: 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 #23
Source Project: tutorials   Author: eugenp   File: RestTemplateBasicLiveTest.java    License: 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 #24
Source Project: tutorials   Author: eugenp   File: RestTemplateBasicLiveTest.java    License: 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 #25
Source Project: spring-analysis-note   Author: Vip-Augus   File: RestTemplateXhrTransport.java    License: 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));
}
 
Example #26
Source Project: spring-analysis-note   Author: Vip-Augus   File: RestTemplateXhrTransport.java    License: 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 #27
Source Project: java-technology-stack   Author: codeEngraver   File: RestTemplateXhrTransport.java    License: 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));
}
 
Example #28
Source Project: java-technology-stack   Author: codeEngraver   File: RestTemplateXhrTransport.java    License: 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 #29
Source Project: n2o-framework   Author: i-novus-llc   File: SpringRestDataProviderEngine.java    License: Apache License 2.0 4 votes vote down vote up
private Object exchange(String query, HttpMethod method, HttpHeaders headers, Map<String, Object> args) {
    RequestCallback requestCallback = restTemplate.httpEntityCallback(new HttpEntity<>(headers), Object.class);
    return restTemplate.execute(query, method, requestCallback, responseExtractor, args);
}
 
Example #30
Source Project: n2o-framework   Author: i-novus-llc   File: SpringRestDataProviderEngine.java    License: Apache License 2.0 4 votes vote down vote up
private Object exchange(String query, HttpMethod method, Object body, HttpHeaders headers, Map<String, Object> args) {
    RequestCallback requestCallback = restTemplate.httpEntityCallback(new HttpEntity<>(body, headers), Object.class);
    return restTemplate.execute(query, method, requestCallback, responseExtractor, args);
}