Java Code Examples for org.springframework.web.client.AsyncRequestCallback

Following code examples demonstrate how to use org.springframework.web.client.AsyncRequestCallbackfrom spring-framework. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use org.springframework.web.client.AsyncRequestCallbackand various code implementation of this class.

	public void doWithRequest(AsyncClientHttpRequest request) throws IOException {

		for (AsyncRequestCallback callback : callbacks) {
			callback.doWithRequest(request);
		}
	} 


	public CompositeAsyncRequestCallback add(AsyncRequestCallback callback) {
		if (callback != null) {
			callbacks.add(callback);
		}

		return this;
	} 

    public static void method1() {
        AsyncRestTemplate asycTemp = new AsyncRestTemplate();
        HttpMethod method = HttpMethod.GET;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        AsyncRequestCallback requestCallback = new AsyncRequestCallback (){
                    @Override
                    public void doWithRequest(AsyncClientHttpRequest arg0)
                            throws IOException {
                        System.out.println(arg0.getURI());
                    }
                };
                
        ResponseExtractor<String> responseExtractor = new ResponseExtractor<String>(){
            @Override
            public String extractData(ClientHttpResponse arg0)
                    throws IOException {
                return arg0.getStatusText();
            }
        };
        Map<String,String> urlVariable = new HashMap<String, String>();
        urlVariable.put("q", "Concretepage");
        ListenableFuture<String> future = asycTemp.execute(url, method, requestCallback, responseExtractor, urlVariable);
        try {
            String result = future.get();
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    } 

    public ResponseEntity<String> getResultForExternalService() {
        AsyncRestTemplate asycTemp = new AsyncRestTemplate();

        AsyncRequestCallback requestCallback = arg0 -> {
            LOGGER.info("Execute AsyncRequestCallback");
            LOGGER.info("Execute AsyncRequestCallback. URL of Request: " + arg0.getURI());
        };

        ResponseExtractor<String> responseExtractor = arg0 -> {
            LOGGER.info("Execute ResponseExtractor");
            String text;
            try (Scanner scanner = new Scanner(arg0.getBody(), StandardCharsets.UTF_8.name())) {
                text = scanner.useDelimiter("\\A").next();
            }
            LOGGER.info("Execute ResponseExtractor. Bodey: " + text);
            return text;
        };


        for (int i = 0; i < 10; i++) {
                    requestCallback, responseExtractor);

            future1.addCallback(new ListenableFutureCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    LOGGER.info("Success: " + result);
                }

                @Override
                public void onFailure(Throwable t) {
                    LOGGER.info("Failure: " + t.getMessage());
                }
            });
        }

        


        return ResponseEntity.ok("Revisa los logs");
    } 

    protected <T> ListenableFuture<T> doExecute(URI url, HttpMethod method, AsyncRequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException {
        ListenableFuture<ResponseEntity<String>> future = restTemplate.exchange(CURRENCY_URL, HttpMethod.GET, null, String.class);
        SettableListenableFuture<T> settable = new SettableListenableFuture<>();
        log.info("OAuth: {}", StateHolder.getState());

        future.addCallback(response -> {
            try {
                log.info("OAuth Callback: {}", StateHolder.getState());
                AsyncRequestCallback newRequestCallback = requestCallback;
                if (response.getStatusCode().is2xxSuccessful()) {
                    newRequestCallback = request -> {
                        request.getHeaders().set("Currency", response.getBody());
                        requestCallback.doWithRequest(request);
                        log.info("Headers: {}", request.getHeaders());
                    };
                }
                super.doExecute(url, method, newRequestCallback, responseExtractor).addCallback(response2 -> {
                    settable.set(response2);
                }, error -> {
                    log.error("Got error on original request");
                    settable.setException(error);
                });
            } catch (Throwable t) {
                log.error("Got error chaining requests", t);
                settable.setException(t);
            }
        }, error -> {
            log.error("Got error on currency request");
            settable.setException(error);
        });
        return settable;
    } 

	public void test() {

		AsyncRestTemplate asycTemp = new AsyncRestTemplate();


		HttpMethod method = HttpMethod.GET;
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);

		AsyncRequestCallback requestCallback = new AsyncRequestCallback() {
			@Override
			public void doWithRequest(AsyncClientHttpRequest request) throws IOException {
				System.out.println(request.getURI());
			}
		};

		ResponseExtractor<String> responseExtractor = new ResponseExtractor<String>() {
			@Override
			public String extractData(ClientHttpResponse response) throws IOException {
				StringWriter writer = new StringWriter(2048);
				IOUtils.copy(response.getBody(), writer, Charset.forName("utf-8"));
				return new String(writer.getBuffer());
			}
		};


		ListenableFuture<String> future = asycTemp.execute(url, method, requestCallback, responseExtractor);
		try {
			String result = future.get();
			System.out.println(result);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	} 

	public <T> ListenableFuture<ResponseEntity<T>> getForEntity(String url, Class<T> responseType,
                                                                AsyncHcGetRequestCallback getRequestCallback,
                                                                Object... uriVariables) {

		AsyncRequestCallback acceptHeaderRequestCallback = acceptHeaderRequestCallback(responseType);
		ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);

		AsyncRequestCallback requestCallback = acceptHeaderRequestCallback;
		if (getRequestCallback != null) {
			requestCallback = CompositeAsyncRequestCallback.create().add(acceptHeaderRequestCallback)
					.add(getRequestCallback.adapt());
		}

		return execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables);
	} 

Advertisement
Javadoc
Callback interface for code that operates on an org.springframework.http.client.AsyncClientHttpReque

st. Allows to manipulate the request headers, and write to the request body.

Used internally by the AsyncRestTemplate, but also useful for application code. @author Arjen Poutsma @see org.springframework.web.client.AsyncRestTemplate#execute @since 4.0 @deprecated as of Spring 5.0, in favor of org.springframework.web.reactive.function.client.ExchangeFilterFunction

Read More
Advertisement