org.springframework.util.concurrent.ListenableFuture Java Examples

The following examples show how to use org.springframework.util.concurrent.ListenableFuture. 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: AsyncRestTemplateIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void exchangePostCallback() throws Exception {
	HttpHeaders requestHeaders = new HttpHeaders();
	requestHeaders.set("MyHeader", "MyValue");
	requestHeaders.setContentType(MediaType.TEXT_PLAIN);
	HttpEntity<String> requestEntity = new HttpEntity<>(helloWorld, requestHeaders);
	ListenableFuture<ResponseEntity<Void>> resultFuture =
			template.exchange(baseUrl + "/{method}", HttpMethod.POST, requestEntity, Void.class, "post");
	final URI expected =new URI(baseUrl + "/post/1");
	resultFuture.addCallback(new ListenableFutureCallback<ResponseEntity<Void>>() {
		@Override
		public void onSuccess(ResponseEntity<Void> result) {
			assertEquals("Invalid location", expected, result.getHeaders().getLocation());
			assertFalse(result.hasBody());
		}
		@Override
		public void onFailure(Throwable ex) {
			fail(ex.getMessage());
		}
	});
	waitTillDone(resultFuture);
}
 
Example #2
Source File: KafkaDriverPublisher.java    From stateful-functions with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(InboundDriverMessage driver) {
  byte[] keyBytes = driver.getDriverId().getBytes(StandardCharsets.UTF_8);
  ListenableFuture<SendResult<Object, Object>> future =
      kafkaTemplate.send(topic, keyBytes, driver.toByteArray());

  future.addCallback(
      new ListenableFutureCallback<SendResult<Object, Object>>() {
        @Override
        public void onFailure(Throwable throwable) {
          log.warn("Failed sending an event to kafka", throwable);
        }

        @Override
        public void onSuccess(SendResult<Object, Object> objectObjectSendResult) {}
      });
}
 
Example #3
Source File: SpringMvcIntegrationTestBase.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void getsEndWithRequestVariables() throws Exception {
  int result = restTemplate.getForObject(
      controllerUrl + "add?a={a}&b={b}",
      Integer.class,
      3,
      4);

  assertThat(result, is(7));
  ListenableFuture<ResponseEntity<Integer>> listenableFuture = asyncRestTemplate
      .getForEntity(controllerUrl + "add?a={a}&b={b}",
          Integer.class,
          3,
          4);
  ResponseEntity<Integer> futureResponse = listenableFuture.get();
  assertThat(futureResponse.getBody(), is(7));
}
 
Example #4
Source File: InterceptingAsyncClientHttpRequest.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public ListenableFuture<ClientHttpResponse> executeAsync(HttpRequest request, byte[] body)
		throws IOException {

	if (this.iterator.hasNext()) {
		AsyncClientHttpRequestInterceptor interceptor = this.iterator.next();
		return interceptor.intercept(request, body, this);
	}
	else {
		URI uri = request.getURI();
		HttpMethod method = request.getMethod();
		HttpHeaders headers = request.getHeaders();

		AsyncClientHttpRequest delegate = requestFactory.createAsyncRequest(uri, method);
		delegate.getHeaders().putAll(headers);
		if (body.length > 0) {
			StreamUtils.copy(body, delegate.getBody());
		}

		return delegate.executeAsync();
	}
}
 
Example #5
Source File: AsyncResultTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void asyncResultWithCallbackAndValue() throws Exception {
	String value = "val";
	final Set<String> values = new HashSet<>(1);
	ListenableFuture<String> future = AsyncResult.forValue(value);
	future.addCallback(new ListenableFutureCallback<String>() {
		@Override
		public void onSuccess(String result) {
			values.add(result);
		}
		@Override
		public void onFailure(Throwable ex) {
			fail("Failure callback not expected: " + ex);
		}
	});
	assertSame(value, values.iterator().next());
	assertSame(value, future.get());
	assertSame(value, future.completable().get());
	future.completable().thenAccept(v -> assertSame(value, v));
}
 
Example #6
Source File: SampleAsyncTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void performGet() throws Exception {

	String responseBody = "{\"name\" : \"Ludwig van Beethoven\", \"someDouble\" : \"1.6035\"}";

	this.mockServer.expect(requestTo("/composers/42")).andExpect(method(HttpMethod.GET))
		.andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON));

	@SuppressWarnings("unused")
	ListenableFuture<ResponseEntity<Person>> ludwig =
			this.restTemplate.getForEntity("/composers/{id}", Person.class, 42);

	// We are only validating the request. The response is mocked out.
	// person.getName().equals("Ludwig van Beethoven")
	// person.getDouble().equals(1.6035)

	this.mockServer.verify();
}
 
Example #7
Source File: SpringMvcIntegrationTestBase.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void ableToConsumeTextPlain() throws Exception {
  String body = "a=1";
  String result = restTemplate.postForObject(
      codeFirstUrl + "textPlain",
      body,
      String.class);

  assertThat(jsonOf(result, String.class), is(body));

  HttpEntity<?> entity = new HttpEntity<>(body);
  ListenableFuture<ResponseEntity<String>> listenableFuture = asyncRestTemplate
      .postForEntity(codeFirstUrl + "textPlain", entity, String.class);
  ResponseEntity<String> responseEntity = listenableFuture.get();
  assertThat(jsonOf(responseEntity.getBody(), String.class), is(body));
}
 
Example #8
Source File: SpringConvertedFutureTestHelper.java    From future-converter with Apache License 2.0 6 votes vote down vote up
@Override
public void waitForCalculationToFinish(ListenableFuture<String> convertedFuture) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    convertedFuture.addCallback(new ListenableFutureCallback<String>() {
        @Override
        public void onSuccess(String result) {
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            latch.countDown();
        }
    });
    latch.await(1, TimeUnit.SECONDS);
}
 
Example #9
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 #10
Source File: AsyncLoadBalancerInterceptor.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<ClientHttpResponse> intercept(final HttpRequest request,
		final byte[] body, final AsyncClientHttpRequestExecution execution)
		throws IOException {
	final URI originalUri = request.getURI();
	String serviceName = originalUri.getHost();
	return this.loadBalancer.execute(serviceName,
			new LoadBalancerRequest<ListenableFuture<ClientHttpResponse>>() {
				@Override
				public ListenableFuture<ClientHttpResponse> apply(
						final ServiceInstance instance) throws Exception {
					HttpRequest serviceRequest = new ServiceRequestWrapper(request,
							instance, AsyncLoadBalancerInterceptor.this.loadBalancer);
					return execution.executeAsync(serviceRequest, body);
				}

			});
}
 
Example #11
Source File: WebSocketConnectionManager.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected void openConnection() {
	if (logger.isInfoEnabled()) {
		logger.info("Connecting to WebSocket at " + getUri());
	}

	ListenableFuture<WebSocketSession> future =
			this.client.doHandshake(this.webSocketHandler, this.headers, getUri());

	future.addCallback(new ListenableFutureCallback<WebSocketSession>() {
		@Override
		public void onSuccess(WebSocketSession result) {
			webSocketSession = result;
			logger.info("Successfully connected");
		}
		@Override
		public void onFailure(Throwable ex) {
			logger.error("Failed to connect", ex);
		}
	});
}
 
Example #12
Source File: CassandraOperationsIntegrationTests.java    From spring-data-examples with Apache License 2.0 6 votes vote down vote up
/**
 * Asynchronous query execution using callbacks.
 */
@Test
public void insertAsynchronously() throws InterruptedException {

	User user = new User();
	user.setId(42L);
	user.setUsername("heisenberg");
	user.setFirstname("Walter");
	user.setLastname("White");

	final CountDownLatch countDownLatch = new CountDownLatch(1);

	AsyncCassandraTemplate asyncTemplate = new AsyncCassandraTemplate(session);

	ListenableFuture<User> future = asyncTemplate.insert(user);

	future.addCallback(it -> countDownLatch.countDown(), throwable -> countDownLatch.countDown());

	countDownLatch.await(5, TimeUnit.SECONDS);

	User loaded = template.selectOneById(user.getId(), User.class);
	assertThat(loaded).isEqualTo(user);
}
 
Example #13
Source File: AbstractXhrTransport.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public ListenableFuture<WebSocketSession> connect(TransportRequest request, WebSocketHandler handler) {
	SettableListenableFuture<WebSocketSession> connectFuture = new SettableListenableFuture<WebSocketSession>();
	XhrClientSockJsSession session = new XhrClientSockJsSession(request, handler, this, connectFuture);
	request.addTimeoutTask(session.getTimeoutTask());

	URI receiveUrl = request.getTransportUrl();
	if (logger.isDebugEnabled()) {
		logger.debug("Starting XHR " +
				(isXhrStreamingDisabled() ? "Polling" : "Streaming") + "session url=" + receiveUrl);
	}

	HttpHeaders handshakeHeaders = new HttpHeaders();
	handshakeHeaders.putAll(getRequestHeaders());
	handshakeHeaders.putAll(request.getHandshakeHeaders());

	connectInternal(request, handler, receiveUrl, handshakeHeaders, session, connectFuture);
	return connectFuture;
}
 
Example #14
Source File: AsyncRestTemplate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public <T> ListenableFuture<T> execute(String url, HttpMethod method, AsyncRequestCallback requestCallback,
		ResponseExtractor<T> responseExtractor, Object... uriVariables) throws RestClientException {

	URI expanded = getUriTemplateHandler().expand(url, uriVariables);
	return doExecute(expanded, method, requestCallback, responseExtractor);
}
 
Example #15
Source File: AsyncRestTemplate.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public <T> ListenableFuture<ResponseEntity<T>> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity,
		ParameterizedTypeReference<T> responseType, Object... uriVariables) throws RestClientException {

	Type type = responseType.getType();
	AsyncRequestCallback requestCallback = httpEntityCallback(requestEntity, type);
	ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(type);
	return execute(url, method, requestCallback, responseExtractor, uriVariables);
}
 
Example #16
Source File: AsyncRestTemplate.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public <T> ListenableFuture<ResponseEntity<T>> exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity,
		Class<T> responseType) throws RestClientException {

	AsyncRequestCallback requestCallback = httpEntityCallback(requestEntity, responseType);
	ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
	return execute(url, method, requestCallback, responseExtractor);
}
 
Example #17
Source File: TaskExecutorAdapter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public <T> ListenableFuture<T> submitListenable(Callable<T> task) {
	try {
		ListenableFutureTask<T> future = new ListenableFutureTask<>(task);
		doExecute(this.concurrentExecutor, this.taskDecorator, future);
		return future;
	}
	catch (RejectedExecutionException ex) {
		throw new TaskRejectedException(
				"Executor [" + this.concurrentExecutor + "] did not accept task: " + task, ex);
	}
}
 
Example #18
Source File: AsyncRestTemplate.java    From java-technology-stack with MIT License 5 votes vote down vote up
private static ListenableFuture<Set<HttpMethod>> adaptToAllowHeader(ListenableFuture<HttpHeaders> future) {
	return new ListenableFutureAdapter<Set<HttpMethod>, HttpHeaders>(future) {
		@Override
		protected Set<HttpMethod> adapt(HttpHeaders headers) throws ExecutionException {
			return headers.getAllow();
		}
	};
}
 
Example #19
Source File: JpaRolloutManagement.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Async
public ListenableFuture<RolloutGroupsValidation> validateTargetsInGroups(final List<RolloutGroupCreate> groups,
        final String targetFilter, final Long createdAt) {

    final String baseFilter = RolloutHelper.getTargetFilterQuery(targetFilter, createdAt);
    final long totalTargets = targetManagement.countByRsql(baseFilter);
    if (totalTargets == 0) {
        throw new ConstraintDeclarationException("Rollout target filter does not match any targets");
    }

    return new AsyncResult<>(validateTargetsInGroups(
            groups.stream().map(RolloutGroupCreate::build).collect(Collectors.toList()), baseFilter, totalTargets));
}
 
Example #20
Source File: AsyncRestTemplate.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public <T> ListenableFuture<ResponseEntity<T>> postForEntity(String url, @Nullable HttpEntity<?> request,
		Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {

	AsyncRequestCallback requestCallback = httpEntityCallback(request, responseType);
	ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
	return execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables);
}
 
Example #21
Source File: ThreadPoolTaskScheduler.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected void cancelRemainingTask(Runnable task) {
	super.cancelRemainingTask(task);
	// Cancel associated user-level ListenableFuture handle as well
	ListenableFuture<?> listenableFuture = this.listenableFutureMap.get(task);
	if (listenableFuture != null) {
		listenableFuture.cancel(true);
	}
}
 
Example #22
Source File: ThreadPoolTaskScheduler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<?> submitListenable(Runnable task) {
	ExecutorService executor = getScheduledExecutor();
	try {
		ListenableFutureTask<Object> future = new ListenableFutureTask<Object>(task, null);
		executor.execute(errorHandlingTask(future, false));
		return future;
	}
	catch (RejectedExecutionException ex) {
		throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex);
	}
}
 
Example #23
Source File: SockJsClient.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public ListenableFuture<WebSocketSession> doHandshake(
		WebSocketHandler handler, String uriTemplate, Object... uriVars) {

	Assert.notNull(uriTemplate, "uriTemplate must not be null");
	URI uri = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(uriVars).encode().toUri();
	return doHandshake(handler, null, uri);
}
 
Example #24
Source File: IMWebrtcHandlerImpl.java    From sctalk with Apache License 2.0 5 votes vote down vote up
@Override
    public void initiateReq(IMHeader header, MessageLite body, ChannelHandlerContext ctx) {
        IMAVCallInitiateReq msg = (IMAVCallInitiateReq)body;
        long fromId = msg.getFromId();
        long toId = msg.getToId();
//        // long callId = msg.getCallId();
//        // FIXME: ?sdp msg.getAttachData()
//        
//        // IMBaseDefine.ClientType nType = msg.getCallerClientType();
//        // logger.debug("webrtc initiate request {} {} {} {}", fromId, toId, callId, nType);
//
//        ClientUser toClientUser = ClientUserManager.getUserById(toId);
//        if (toClientUser != null ){
//            IMHeader hdRequest = header.clone();
//            hdRequest.setSeqnum(0);
//            IMProtoMessage<MessageLite>  msgCancel = new IMProtoMessage<MessageLite>(hdRequest, body);
//            toClientUser.broadcast(msgCancel, ctx);
//        }
// 
//        messageServerCluster.send(header, body);
        ListenableFuture<?> future = messageServerCluster.webrtcInitateCallReq(fromId, toId, super.getHandleId(ctx));
        future.addCallback((result) -> {
            messageServerCluster.sendToUser(toId, header, body);
        }, (throwable) -> {
            // TODO 发起失败
        });
    }
 
Example #25
Source File: OkHttp3AsyncClientHttpRequest.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers, byte[] content)
		throws IOException {

	Request request = OkHttp3ClientHttpRequestFactory.buildRequest(headers, content, this.uri, this.method);
	return new OkHttpListenableFuture(this.client.newCall(request));
}
 
Example #26
Source File: TaskExecutorAdapter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public ListenableFuture<?> submitListenable(Runnable task) {
	try {
		ListenableFutureTask<Object> future = new ListenableFutureTask<>(task, null);
		doExecute(this.concurrentExecutor, this.taskDecorator, future);
		return future;
	}
	catch (RejectedExecutionException ex) {
		throw new TaskRejectedException(
				"Executor [" + this.concurrentExecutor + "] did not accept task: " + task, ex);
	}
}
 
Example #27
Source File: KafkaStructuredEventHandlerTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void checkEventTypeBasedTopicDistribution() throws ExecutionException, InterruptedException {
    StructuredRestCallEvent structuredEvent = createDummyStructuredRestEvent();
    Event<StructuredEvent> event = new Event<>(structuredEvent);
    ListenableFuture<SendResult<String, String>> futures = generateMockFutureWrappers();
    when(kafkaTemplate.send(eq("cbStructuredRestCallEvent"), anyString())).thenReturn(futures);

    classIntest.accept(event);

    verify(kafkaTemplate).send(eq("cbStructuredRestCallEvent"), anyString());
}
 
Example #28
Source File: AsyncRestTemplateIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void headForHeadersCallbackWithLambdas() throws Exception {
	ListenableFuture<HttpHeaders> headersFuture = template.headForHeaders(baseUrl + "/get");
	headersFuture.addCallback(result -> assertTrue("No Content-Type header",
			result.containsKey("Content-Type")), ex -> fail(ex.getMessage()));
	waitTillDone(headersFuture);
}
 
Example #29
Source File: AsyncRestTemplateIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void headForHeadersCallbackWithLambdas() throws Exception {
	ListenableFuture<HttpHeaders> headersFuture = template.headForHeaders(baseUrl + "/get");
	headersFuture.addCallback(result -> assertTrue("No Content-Type header",
			result.containsKey("Content-Type")), ex -> fail(ex.getMessage()));
	waitTillDone(headersFuture);
}
 
Example #30
Source File: DockerServiceImpl.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
@Override
public ServiceCallResult getContainerLog(GetLogContainerArg arg) {

    ServiceCallResult callResult = new ServiceCallResult();

    final Consumer<ProcessEvent> watcher = firstNonNull(arg.getWatcher(), Consumers.<ProcessEvent>nop());
    boolean stderr = arg.isStderr();
    boolean stdout = arg.isStdout();
    if (!stderr && !stdout) {
        // we need at least one stream (but usually need both )
        stderr = stdout = true;
    }
    URI url = getUrlContainer(arg.getId(), "logs")
            .queryParam("stderr", stderr)
            .queryParam("stdout", stdout)
            .queryParam("follow", arg.isFollow())
            .queryParam("since", arg.getSince())
            .queryParam("tail", arg.getTail())
            .queryParam("timestamps", arg.isTimestamps()).build().toUri();
    try {
        ListenableFuture<Object> future = restTemplate.execute(url, HttpMethod.GET, null, response -> {
            StreamContext<ProcessEvent> context = new StreamContext<>(response.getBody(), watcher);
            context.getInterrupter().setFuture(arg.getInterrupter());
            frameStreamProcessor.processResponseStream(context);
            return null;
        });
        waitFuture(callResult, future);
    } catch (HttpStatusCodeException e) {
        processStatusCodeException(e, callResult, url);
    }
    return callResult;
}