org.springframework.web.client.ResponseExtractor Java Examples

The following examples show how to use org.springframework.web.client.ResponseExtractor. 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: IHealthShim.java    From shimmer with Apache License 2.0 6 votes vote down vote up
@Override
protected ResponseExtractor<OAuth2AccessToken> getResponseExtractor() {

    return new ResponseExtractor<OAuth2AccessToken>() {

        @Override
        public OAuth2AccessToken extractData(ClientHttpResponse response) throws IOException {

            JsonNode node = new ObjectMapper().readTree(response.getBody());
            String token = Preconditions
                    .checkNotNull(node.path("AccessToken").textValue(), "Missing access token: %s", node);
            String refreshToken = Preconditions
                    .checkNotNull(node.path("RefreshToken").textValue(), "Missing refresh token: %s" + node);
            String userId =
                    Preconditions.checkNotNull(node.path("UserID").textValue(), "Missing UserID: %s", node);
            long expiresIn = node.path("Expires").longValue() * 1000;
            Preconditions.checkArgument(expiresIn > 0, "Missing Expires: %s", node);

            DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(token);
            accessToken.setExpiration(new Date(System.currentTimeMillis() + expiresIn));
            accessToken.setRefreshToken(new DefaultOAuth2RefreshToken(refreshToken));
            accessToken.setAdditionalInformation(ImmutableMap.<String, Object>of("UserID", userId));
            return accessToken;
        }
    };
}
 
Example #2
Source File: AsyncHttpOperationsTest.java    From riptide with MIT License 6 votes vote down vote up
static Iterable<Function<AsyncRestOperations, ListenableFuture<User>>> execute() {
    final ObjectMapper mapper = new ObjectMapper();

    final AsyncRequestCallback 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 #3
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 #4
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 #5
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 #6
Source File: AsyncHttpOperations.java    From riptide with MIT License 5 votes vote down vote up
@Override
public <T> ListenableFuture<T> execute(final String url, final HttpMethod method,
        @Nullable final AsyncRequestCallback callback, @Nullable final ResponseExtractor<T> extractor,
        final Object... uriVariables) {

    final Capture<T> capture = Capture.empty();
    return execute(url, method, toEntity(callback), route(extractTo(extractor, capture)), capture, uriVariables);
}
 
Example #7
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 #8
Source File: AsyncHttpOperations.java    From riptide with MIT License 5 votes vote down vote up
@Nonnull
@Override
public <T> ListenableFuture<T> execute(final URI url, final HttpMethod method,
        @Nullable final AsyncRequestCallback callback, @Nullable final ResponseExtractor<T> extractor) {

    final Capture<T> capture = Capture.empty();
    return execute(url, method, toEntity(callback), route(extractTo(extractor, capture)), capture);
}
 
Example #9
Source File: AsyncHttpOperationsTest.java    From riptide with MIT License 5 votes vote down vote up
@Test
void shouldExecuteWithoutCallbackOrExtractor() throws ExecutionException, InterruptedException {
    driver.addExpectation(onRequestTo("/departments/1/users")
                    .withMethod(Method.POST),
            giveEmptyResponse());

    final AsyncRestOperations unit = new AsyncHttpOperations(http);
    @Nullable final User user = unit.execute("/departments/{id}/users", POST, null,
            (ResponseExtractor<User>) null, 1).get();

    assertNull(user);
}
 
Example #10
Source File: NIORestClient.java    From micro-server with Apache License 2.0 5 votes vote down vote up
public <T> CompletableFuture<T> execute(String url, HttpMethod method,
		AsyncRequestCallback requestCallback,
		ResponseExtractor<T> responseExtractor, Object... urlVariables)
		throws RestClientException {
	return toCompletableFuture(template.execute(url, method,
			requestCallback, responseExtractor, urlVariables));
}
 
Example #11
Source File: NIORestClient.java    From micro-server with Apache License 2.0 5 votes vote down vote up
public <T> CompletableFuture<T> execute(String url, HttpMethod method,
		AsyncRequestCallback requestCallback,
		ResponseExtractor<T> responseExtractor, Map<String, ?> urlVariables)
		throws RestClientException {
	return toCompletableFuture(template.execute(url, method,
			requestCallback, responseExtractor, urlVariables));
}
 
Example #12
Source File: AsyncHttpOperations.java    From riptide with MIT License 5 votes vote down vote up
@Nonnull
@Override
public <T> ListenableFuture<T> execute(final String url, final HttpMethod method,
        @Nullable final AsyncRequestCallback callback, @Nullable final ResponseExtractor<T> extractor,
        final Map<String, ?> uriVariables) {
    return execute(url, method, callback, extractor, extract(url, uriVariables));
}
 
Example #13
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 #14
Source File: ExtRestTemplate.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public void handleError(ClientHttpResponse response) throws IOException {
	ResponseExtractor<ResponseEntity<Object>> responseExtractor = null;
	if(extErrorResultType!=null){
		responseExtractor = responseEntityExtractor(extErrorResultType);
	}
	if (responseExtractor != null) {
		ResponseEntity<?> errorData = responseExtractor.extractData(response);
		extErrorHandler.onError(errorData.getBody());
	}else{
		super.handleError(response);
	}
}
 
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: HttpFileTransferImpl.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void getFile(
    @NotBlank(message = "Source file path cannot be empty.") final String srcRemotePath,
    @NotBlank(message = "Destination local path cannot be empty") final String dstLocalPath
) throws GenieException {
    final long start = System.nanoTime();
    final Set<Tag> tags = Sets.newHashSet();
    log.debug("Called with src path {} and destination path {}", srcRemotePath, dstLocalPath);

    try {
        final File outputFile = new File(dstLocalPath);
        if (!this.isValid(srcRemotePath)) {
            throw new GenieServerException("Unable to download " + srcRemotePath + " not a valid URL");
        }
        this.restTemplate.execute(
            srcRemotePath,
            HttpMethod.GET,
            requestEntity -> requestEntity.getHeaders().setAccept(Lists.newArrayList(MediaType.ALL)),
            (ResponseExtractor<Void>) response -> {
                // Documentation I could find pointed to the HttpEntity reading the bytes off
                // the stream so this should resolve memory problems if the file returned is large
                FileUtils.copyInputStreamToFile(response.getBody(), outputFile);
                return null;
            }
        );
        MetricsUtils.addSuccessTags(tags);
    } catch (final GenieException | RuntimeException e) {
        MetricsUtils.addFailureTagsWithException(tags, e);
        throw e;
    } finally {
        this.registry.timer(DOWNLOAD_TIMER_NAME, tags).record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
    }
}
 
Example #19
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
protected ResponseExtractor<ResponseEntity<Void>> getAuthorizationResponseExtractor() {
    return new ResponseExtractor<ResponseEntity<Void>>() {
        public ResponseEntity<Void> extractData(ClientHttpResponse response) throws IOException {
            return new ResponseEntity(response.getHeaders(), response.getStatusCode());
        }
    };
}
 
Example #20
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 #21
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 #22
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
protected OAuth2AccessToken retrieveToken(final AccessTokenRequest request,
                                          OAuth2ProtectedResourceDetails resource,
                                          MultiValueMap<String, String> form,
                                          HttpHeaders headers) throws OAuth2AccessDeniedException {
    try {
        this.authenticationHandler.authenticateTokenRequest(resource, form, headers);
        this.tokenRequestEnhancer.enhance(request, resource, form, headers);
        final ResponseExtractor<OAuth2AccessToken> delegate = this.getResponseExtractor();

        ResponseExtractor<OAuth2AccessToken> extractor = new ResponseExtractor<OAuth2AccessToken>() {
            public OAuth2AccessToken extractData(ClientHttpResponse response) throws IOException {
                if(response.getHeaders().containsKey("Set-Cookie")) {
                    request.setCookie(response.getHeaders().getFirst("Set-Cookie"));
                }

                return (OAuth2AccessToken)delegate.extractData(response);
            }
        };
        System.out.println("URI == " + this.getAccessTokenUri(resource, form));
        return (OAuth2AccessToken)this.getRestTemplate().execute(this.getAccessTokenUri(resource, form),
                this.getHttpMethod(),
                this.getRequestCallback(resource, form, headers),
                extractor,
                form.toSingleValueMap());
    } catch (OAuth2Exception var8) {
        System.out.println(var8.toString());
        throw new OAuth2AccessDeniedException("Access token denied.", resource, var8);
    } catch (RestClientException var9) {
        System.out.println(var9.toString());
        throw new OAuth2AccessDeniedException("Error requesting access token.", resource, var9);
    }
}
 
Example #23
Source File: HttpArtifactoryRepository.java    From artifactory-resource with Apache License 2.0 5 votes vote down vote up
private ResponseExtractor<Void> getResponseExtractor(String path, File destination) {
	return (response) -> {
		Path fullPath = destination.toPath().resolve(path);
		Files.createDirectories(fullPath.getParent());
		Files.copy(response.getBody(), fullPath);
		return null;
	};
}
 
Example #24
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 #25
Source File: RestClient.java    From spring-boot-cookbook with Apache License 2.0 5 votes vote down vote up
public File downFileToLocal(String url, String suffix) throws IOException {
    String actualSuffix;
    if (StringUtils.isNotBlank(suffix)) {
        actualSuffix = suffix.startsWith(".") ? suffix : DOT + suffix;
    } else {
        String extension = FilenameUtils.getExtension(url);
        if (StringUtils.isNotBlank(extension)) {
            actualSuffix = DOT + extension;
        } else {
            actualSuffix = "";
        }
    }
    ResponseExtractor<ResponseEntity<File>> responseExtractor = new ResponseExtractor<ResponseEntity<File>>() {
        @Override
        public ResponseEntity<File> extractData(ClientHttpResponse response) throws IOException {
            File downFile = File.createTempFile("download", actualSuffix);
            log.info("down {} to local:{}", url, downFile.getPath());
            FileCopyUtils.copy(response.getBody(), new FileOutputStream(downFile));
            return ResponseEntity.status(response.getStatusCode()).headers(response.getHeaders()).body(downFile);
        }
    };
    ResponseEntity<File> responseEntity = restTemplate.execute(url, HttpMethod.GET, null, responseExtractor);
    if (responseEntity != null) {
        return responseEntity.getBody();
    }
    log.error("fail to downFileToLocal {} ", url);
    throw new IOException("fail to downFileToLocal");
}
 
Example #26
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 #27
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 #28
Source File: ExtractRoute.java    From riptide with MIT License 5 votes vote down vote up
static <T> Route extractTo(@Nullable final ResponseExtractor<T> extractor, final Capture<T> capture) {
    return (response, reader) ->
            tryWith(response, ignored -> {
                if (extractor == null) {
                    capture.capture(null);
                } else {
                    capture.capture(extractor.extractData(response));
                }
            });
}
 
Example #29
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 #30
Source File: NIORestClient.java    From micro-server with Apache License 2.0 4 votes vote down vote up
public <T> CompletableFuture<T> execute(URI url, HttpMethod method,
		AsyncRequestCallback requestCallback,
		ResponseExtractor<T> responseExtractor) throws RestClientException {
	return toCompletableFuture(template.execute(url, method,
			requestCallback, responseExtractor));
}