Java Code Examples for org.springframework.util.concurrent.ListenableFuture#get()

The following examples show how to use org.springframework.util.concurrent.ListenableFuture#get() . 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: SpringMvcIntegrationTestBase.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void ableToPostWithHeader() throws Exception {
  Person person = new Person();
  person.setName("person name");

  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(APPLICATION_JSON);
  headers.add("prefix", "prefix  prefix");

  HttpEntity<Person> requestEntity = new HttpEntity<>(person, headers);
  ResponseEntity<String> responseEntity = restTemplate
      .postForEntity(codeFirstUrl + "saysomething", requestEntity, String.class);

  assertThat(jsonOf(responseEntity.getBody(), String.class), is("prefix  prefix person name"));

  ListenableFuture<ResponseEntity<String>> listenableFuture = asyncRestTemplate
      .postForEntity(codeFirstUrl + "saysomething", requestEntity, String.class);
  responseEntity = listenableFuture.get();
  assertThat(jsonOf(responseEntity.getBody(), String.class), is("prefix  prefix person name"));
}
 
Example 2
Source File: BigQueryTemplateIntegrationTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadBytes() throws ExecutionException, InterruptedException {
	byte[] byteArray =
			"CountyId,State,County\n1001,Alabama,Autauga County\n".getBytes();
	ByteArrayInputStream byteStream = new ByteArrayInputStream(byteArray);

	ListenableFuture<Job> bigQueryJobFuture =
			bigQueryTemplate.writeDataToTable(TABLE_NAME, byteStream, FormatOptions.csv());

	Job job = bigQueryJobFuture.get();
	assertThat(job.getStatus().getState()).isEqualTo(JobStatus.State.DONE);

	QueryJobConfiguration queryJobConfiguration = QueryJobConfiguration
			.newBuilder("SELECT * FROM test_dataset.template_test_table").build();
	TableResult result = this.bigQuery.query(queryJobConfiguration);

	assertThat(result.getTotalRows()).isEqualTo(1);
	assertThat(
			result.getValues().iterator().next().get("State").getStringValue()).isEqualTo("Alabama");
}
 
Example 3
Source File: PubSubSubscriberTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testPullAndAckAsync() throws InterruptedException, ExecutionException, TimeoutException {
	ListenableFuture<List<PubsubMessage>> asyncResult = this.pubSubSubscriberTemplate.pullAndAckAsync(
			"sub2", 1, true);

	List<PubsubMessage> result = asyncResult.get(10L, TimeUnit.SECONDS);
	assertThat(asyncResult.isDone()).isTrue();

	assertThat(result.size()).isEqualTo(1);

	PubsubMessage pubsubMessage = result.get(0);
	assertThat(pubsubMessage).isSameAs(this.pubsubMessage);

	verify(this.pubSubSubscriberTemplate, times(1)).ack(any());
}
 
Example 4
Source File: SpringMvcIntegrationTestBase.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void putsEndWithPathParam() throws Exception {
  ResponseEntity<String> responseEntity = restTemplate
      .exchange(codeFirstUrl + "sayhi/{name}", PUT, null, String.class, "world");

  assertThat(responseEntity.getStatusCode(), is(ACCEPTED));
  assertThat(jsonOf(responseEntity.getBody(), String.class), is("world sayhi"));

  ListenableFuture<ResponseEntity<String>> listenableFuture = asyncRestTemplate
      .exchange(codeFirstUrl + "sayhi/{name}", PUT, null, String.class, "world");
  ResponseEntity<String> futureResponse = listenableFuture.get();
  assertThat(futureResponse.getStatusCode(), is(ACCEPTED));
  assertThat(jsonOf(futureResponse.getBody(), String.class), is("world sayhi"));
}
 
Example 5
Source File: SpringMvcIntegrationTestBase.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void postsEndWithPathParam() throws Exception {
  String result = restTemplate.postForObject(
      controllerUrl + "sayhello/{name}",
      null,
      String.class,
      "world");

  assertThat(jsonOf(result, String.class), is("hello world"));

  List<HttpMessageConverter<?>> convertersOld = restTemplate.getMessageConverters();
  List<HttpMessageConverter<?>> converters = new ArrayList<>();
  converters.add(new MappingJackson2HttpMessageConverter());
  restTemplate.setMessageConverters(converters);
  result = restTemplate.postForObject(
      controllerUrl + "sayhello/{name}",
      null,
      String.class,
      "中 国");

  assertThat(result, is("hello 中 国"));
  restTemplate.setMessageConverters(convertersOld);

  ListenableFuture<ResponseEntity<String>> listenableFuture = asyncRestTemplate
      .postForEntity(controllerUrl + "sayhello/{name}",
          null,
          String.class,
          "world");
  ResponseEntity<String> futureResonse = listenableFuture.get();
  assertThat(jsonOf(futureResonse.getBody(), String.class), is("hello world"));
  asyncRestTemplate.setMessageConverters(converters);
  listenableFuture = asyncRestTemplate.postForEntity(controllerUrl + "sayhello/{name}",
      null,
      String.class,
      "中 国");
  futureResonse = listenableFuture.get();
  assertThat(futureResonse.getBody(), is("hello 中 国"));
  asyncRestTemplate.setMessageConverters(convertersOld);
}
 
Example 6
Source File: SpringMvcIntegrationTestBase.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void ableToUploadFileFromConsumer() throws Exception {
  String file1Content = "hello world";
  String file2Content = "bonjour";
  String username = "mike";

  Map<String, Object> map = new HashMap<>();
  map.put("file1", new FileSystemResource(newFile(file1Content).getAbsolutePath()));
  map.put("someFile", new FileSystemResource(newFile(file2Content).getAbsolutePath()));
  map.put("name", username);

  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.MULTIPART_FORM_DATA);
  String result = RestTemplateBuilder.create().postForObject(
      "cse://springmvc-tests/codeFirstSpringmvc/upload",
      new HttpEntity<>(map, headers),
      String.class);

  assertThat(result, is(file1Content + file2Content + username));
  org.springframework.web.client.AsyncRestTemplate cseAsyncRestTemplate = new CseAsyncRestTemplate();
  ListenableFuture<ResponseEntity<String>> listenableFuture = cseAsyncRestTemplate
      .postForEntity("cse://springmvc-tests/codeFirstSpringmvc/upload",
          new HttpEntity<>(map, headers),
          String.class);
  ResponseEntity<String> responseEntity = listenableFuture.get();
  assertThat(responseEntity.getBody(), is(file1Content + file2Content + username));
}
 
Example 7
Source File: BigQueryFileMessageHandlerIntegrationTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadFile() throws InterruptedException, ExecutionException {
	HashMap<String, Object> messageHeaders = new HashMap<>();
	this.messageHandler.setTableName(TABLE_NAME);
	this.messageHandler.setFormatOptions(FormatOptions.csv());

	Message<File> message = MessageBuilder.createMessage(
			new File("src/test/resources/data.csv"),
			new MessageHeaders(messageHeaders));

	ListenableFuture<Job> jobFuture =
			(ListenableFuture<Job>) this.messageHandler.handleRequestMessage(message);

	// Assert that a BigQuery polling task is scheduled successfully.
	await().atMost(Duration.FIVE_SECONDS)
			.untilAsserted(
					() -> assertThat(
							this.taskScheduler.getScheduledThreadPoolExecutor().getQueue()).hasSize(1));
	jobFuture.get();

	QueryJobConfiguration queryJobConfiguration = QueryJobConfiguration
			.newBuilder("SELECT * FROM test_dataset.test_table").build();
	TableResult result = this.bigquery.query(queryJobConfiguration);

	assertThat(result.getTotalRows()).isEqualTo(1);
	assertThat(
			result.getValues().iterator().next().get("State").getStringValue()).isEqualTo("Alabama");

	// This asserts that the BigQuery job polling task is no longer in the scheduler.
	assertThat(this.taskScheduler.getScheduledThreadPoolExecutor().getQueue()).hasSize(0);
}
 
Example 8
Source File: SpringMvcIntegrationTestBase.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void ableToPostMap() throws Exception {
  Map<String, User> users = new HashMap<>();
  users.put("user1", userOfNames("name11", "name12"));
  users.put("user2", userOfNames("name21", "name22"));

  ParameterizedTypeReference<Map<String, User>> reference = new ParameterizedTypeReference<Map<String, User>>() {
  };
  ResponseEntity<Map<String, User>> responseEntity = restTemplate.exchange(codeFirstUrl + "testUserMap",
      POST,
      jsonRequest(users),
      reference);

  assertThat(responseEntity.getStatusCode(), is(OK));

  Map<String, User> body = responseEntity.getBody();
  assertArrayEquals(body.get("user1").getNames(), new String[] {"name11", "name12"});
  assertArrayEquals(body.get("user2").getNames(), new String[] {"name21", "name22"});

  ListenableFuture<ResponseEntity<Map<String, User>>> listenableFuture = asyncRestTemplate
      .exchange(codeFirstUrl + "testUserMap",
          POST,
          jsonRequest(users),
          reference);
  ResponseEntity<Map<String, User>> futureResponse = listenableFuture.get();
  assertThat(futureResponse.getStatusCode(), is(OK));
  body = futureResponse.getBody();
  assertArrayEquals(body.get("user1").getNames(), new String[] {"name11", "name12"});
  assertArrayEquals(body.get("user2").getNames(), new String[] {"name21", "name22"});
}
 
Example 9
Source File: WebController.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private ModelAndView getResponse(ListenableFuture<Job> loadJob, String tableName) {
	String message;
	try {
		Job job = loadJob.get();
		message = "Successfully loaded data file to " + tableName;
	}
	catch (Exception e) {
		e.printStackTrace();
		message = "Error: " + e.getMessage();
	}

	return new ModelAndView("index")
			.addObject("datasetName", this.datasetName)
			.addObject("message", message);
}
 
Example 10
Source File: StompBrokerRelayMessageHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public ListenableFuture<Void> forward(Message<?> message, StompHeaderAccessor accessor) {
	try {
		ListenableFuture<Void> future = super.forward(message, accessor);
		if (message.getHeaders().get(SimpMessageHeaderAccessor.IGNORE_ERROR) == null) {
			future.get();
		}
		return future;
	}
	catch (Throwable ex) {
		throw new MessageDeliveryException(message, ex);
	}
}
 
Example 11
Source File: WebSocketSessionContext.java    From artemis with Apache License 2.0 5 votes vote down vote up
protected void connect() {
    if (_isConnecting.compareAndSet(false, true)) {
        try {
            if (rateLimiter.isRateLimited("connect")) {
                _logger.error("WebSocketSessionContext reconnect times exceed expected value for a period time");
                return;
            }
            final AddressContext context = _addressManager.getContext();
            if (!context.isAavailable()) {
                return;
            }
            ListenableFuture<WebSocketSession> future = _wsClient.doHandshake(_handler, context.getWebSocketEndPoint());
            future.addCallback(new WebSocketSessionCallback(this, context));
            try {
                WebSocketSession session = future.get(_connectTimeout.typedValue(), TimeUnit.MILLISECONDS);
                final WebSocketSession oldSession = _session.getAndSet(session);
                _lastUpdatedTime = System.currentTimeMillis();
                _addressContext.set(context);
                disconnect(oldSession);
                WebSocketSessionContext.this.afterConnectionEstablished(session);
                _logger.info("WebSocketSessionContext connected to: " + context.getWebSocketEndPoint());
            } catch (Throwable ex) {
                context.markUnavailable();
                _logger.warn("get WebSocketSession failed within the time specified", ex);
            }
        } catch (final Throwable e) {
            _addressContext.get().markUnavailable();
            _logger.warn("connect to websocket endpoint failed", e);
        } finally {
            _isConnecting.set(false);
        }
    }
}
 
Example 12
Source File: SpringMvcIntegrationTestBase.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void ensureServerWorksFine() throws Exception {
  String result = restTemplate.getForObject(
      controllerUrl + "sayhi?name=world",
      String.class);

  assertThat(jsonOf(result, String.class), is("hi world [world]"));
  ListenableFuture<ResponseEntity<String>> listenableFuture = asyncRestTemplate
      .getForEntity(controllerUrl + "sayhi?name=world",
          String.class);
  ResponseEntity<String> futureResponse = listenableFuture.get();
  assertThat(jsonOf(futureResponse.getBody(), String.class), is("hi world [world]"));
}
 
Example 13
Source File: WebController.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@GetMapping("/multipull")
public RedirectView multipull(
		@RequestParam("subscription1") String subscriptionName1,
		@RequestParam("subscription2") String subscriptionName2) {

	Set<AcknowledgeablePubsubMessage> mixedSubscriptionMessages = new HashSet<>();
	mixedSubscriptionMessages.addAll(this.pubSubTemplate.pull(subscriptionName1, 1000, true));
	mixedSubscriptionMessages.addAll(this.pubSubTemplate.pull(subscriptionName2, 1000, true));

	if (mixedSubscriptionMessages.isEmpty()) {
		return buildStatusView("No messages available for retrieval.");
	}

	RedirectView returnView;
	try {
		ListenableFuture<Void> ackFuture = this.pubSubTemplate.ack(mixedSubscriptionMessages);
		ackFuture.get();
		returnView = buildStatusView(
				String.format("Pulled and acked %s message(s)", mixedSubscriptionMessages.size()));
	}
	catch (Exception ex) {
		LOGGER.warn("Acking failed.", ex);
		returnView = buildStatusView("Acking failed");
	}

	return returnView;
}
 
Example 14
Source File: PubSubSubscriberTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testPullAndAckAsync_NoMessages() throws InterruptedException, ExecutionException, TimeoutException {
	when(this.pullApiFuture.get()).thenReturn(PullResponse.newBuilder().build());

	ListenableFuture<List<PubsubMessage>> asyncResult = this.pubSubSubscriberTemplate.pullAndAckAsync(
			"sub2", 1, true);

	List<PubsubMessage> result = asyncResult.get(10L, TimeUnit.SECONDS);
	assertThat(asyncResult.isDone()).isTrue();

	assertThat(result.size()).isEqualTo(0);

	verify(this.pubSubSubscriberTemplate, never()).ack(any());
}
 
Example 15
Source File: SpringMvcIntegrationTestBase.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void ableToExchangeCookie() throws Exception {
  Map<String, String> params = new HashMap<>();
  params.put("a", "5");

  HttpHeaders headers = new HttpHeaders();
  headers.add(HttpHeaders.COOKIE, "b=3");

  HttpEntity<?> requestEntity = new HttpEntity<>(headers);
  ResponseEntity<Integer> result = restTemplate.exchange(
      codeFirstUrl + "reduce?a={a}",
      GET,
      requestEntity,
      Integer.class,
      params);

  assertThat(result.getBody(), is(2));

  ListenableFuture<ResponseEntity<Integer>> listenableFuture = asyncRestTemplate
      .exchange(codeFirstUrl + "reduce?a={a}",
          GET,
          requestEntity,
          Integer.class,
          params);
  result = listenableFuture.get();
  assertThat(result.getBody(), is(2));
}
 
Example 16
Source File: StompBrokerRelayMessageHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<Void> forward(Message<?> message, StompHeaderAccessor accessor) {
	try {
		ListenableFuture<Void> future = super.forward(message, accessor);
		if (message.getHeaders().get(SimpMessageHeaderAccessor.IGNORE_ERROR) == null) {
			future.get();
		}
		return future;
	}
	catch (Throwable ex) {
		throw new MessageDeliveryException(message, ex);
	}
}
 
Example 17
Source File: PubSubSubscriberTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Test
public void testSubscribe_AndManualAck() throws InterruptedException, ExecutionException, TimeoutException {
	this.pubSubSubscriberTemplate.subscribe("sub1", this.consumer);

	verify(this.subscriber).startAsync();
	verify(this.consumer).accept(this.message.capture());

	TestListenableFutureCallback testListenableFutureCallback = new TestListenableFutureCallback();

	ListenableFuture<Void> listenableFuture = this.message.getValue().ack();

	assertThat(listenableFuture).isNotNull();

	listenableFuture.addCallback(testListenableFutureCallback);
	listenableFuture.get(10L, TimeUnit.SECONDS);

	assertThat(listenableFuture.isDone()).isTrue();

	verify(this.ackReplyConsumer).ack();

	assertThat(testListenableFutureCallback.getThrowable()).isNull();
}
 
Example 18
Source File: SpringmvcHelloClient.java    From servicecomb-samples with Apache License 2.0 4 votes vote down vote up
public void run() throws Exception {
  Person person = new Person();
  person.setName("ServiceComb/Java Chassis");

  // RestTemplate Consumer or POJO Consumer. You can choose whatever you like
  // RestTemplate Consumer
  String sayHiResult =
      restTemplate.postForObject("cse://springmvc/springmvchello/sayhi?name=Java Chassis", null, String.class);
  Assertion.assertEquals("Hello Java Chassis", sayHiResult);

  String sayHiDefaultResult =
      restTemplate.postForObject("cse://springmvc/springmvchello/sayhi", null, String.class);
  Assertion.assertEquals("Hello test", sayHiDefaultResult);

  String sayHelloResult = restTemplate.postForObject("cse://springmvc/springmvchello/sayhello", person, String.class);
  Assertion.assertEquals("Hello person ServiceComb/Java Chassis", sayHelloResult);

  System.out.println("RestTemplate Consumer or POJO Consumer.  You can choose whatever you like.");
  System.out.println("RestTemplate consumer sayhi services: " + sayHiResult);
  System.out.println("RestTemplate consumer sayHiDefault services: " + sayHiDefaultResult);
  System.out.println("RestTemplate consumer sayhello services: " + sayHelloResult);

  // POJO Consumer
  String pojoSayHi = hello.sayHi("Java Chassis");
  Assertion.assertEquals("Hello Java Chassis", pojoSayHi);
  String pojoSayHello = hello.sayHello(person);
  Assertion.assertEquals("Hello person ServiceComb/Java Chassis", pojoSayHello);

  System.out.println("POJO consumer sayhi services: " + pojoSayHi);
  System.out.println("POJO consumer sayhello services: " + pojoSayHello);

  //AsyncRestTemplate Consumer
  // NOTICE: since 2.0.0, spring deprecated AsyncRestTemplate, user's can use CompletableFuture of RPC instead
  CseAsyncRestTemplate cseAsyncRestTemplate = new CseAsyncRestTemplate();
  ListenableFuture<ResponseEntity<String>> responseEntityListenableFuture = cseAsyncRestTemplate
      .postForEntity("cse://springmvc/springmvchello/sayhi?name=Java Chassis", null, String.class);
  ResponseEntity<String> responseEntity = responseEntityListenableFuture.get();
  Assertion.assertEquals("Hello Java Chassis", responseEntity.getBody());
  System.out.println("AsyncRestTemplate Consumer sayHi services: " + responseEntity.getBody());

  HttpEntity<Person> entity = new HttpEntity<>(person);
  ListenableFuture<ResponseEntity<String>> listenableFuture = cseAsyncRestTemplate
      .exchange("cse://springmvc/springmvchello/sayhello", HttpMethod.POST, entity, String.class);

  listenableFuture.addCallback(
      new ListenableFutureCallback<ResponseEntity<String>>() {
        @Override
        public void onFailure(Throwable ex) {
          LOG.error("AsyncResTemplate Consumer catched exception when sayHello, ", ex);
        }

        @Override
        public void onSuccess(ResponseEntity<String> result) {
          System.out.println("AsyncRestTemplate Consumer sayHello services: " + result.getBody());
        }
      });
}
 
Example 19
Source File: PubSubSubscriberTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 3 votes vote down vote up
@Test
public void testPull_AndManualAck() throws InterruptedException, ExecutionException, TimeoutException {

	List<AcknowledgeablePubsubMessage> result = this.pubSubSubscriberTemplate.pull(
			"sub2", 1, true);

	assertThat(result.size()).isEqualTo(1);
	assertThat(result.get(0).getPubsubMessage()).isSameAs(this.pubsubMessage);
	assertThat(result.get(0).getProjectSubscriptionName().getProject()).isEqualTo("testProject");
	assertThat(result.get(0).getProjectSubscriptionName().getSubscription()).isEqualTo("sub2");

	AcknowledgeablePubsubMessage acknowledgeablePubsubMessage = result.get(0);
	assertThat(acknowledgeablePubsubMessage.getAckId()).isNotNull();

	TestListenableFutureCallback testListenableFutureCallback = new TestListenableFutureCallback();

	ListenableFuture<Void> listenableFuture = this.pubSubSubscriberTemplate.ack(result);

	assertThat(listenableFuture).isNotNull();

	listenableFuture.addCallback(testListenableFutureCallback);
	listenableFuture.get(10L, TimeUnit.SECONDS);

	assertThat(listenableFuture.isDone()).isTrue();

	assertThat(testListenableFutureCallback.getThrowable()).isNull();
}
 
Example 20
Source File: PubSubSubscriberTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 3 votes vote down vote up
@Test
public void testPullAsync_AndManualAck() throws InterruptedException, ExecutionException, TimeoutException {

	ListenableFuture<List<AcknowledgeablePubsubMessage>> asyncResult = this.pubSubSubscriberTemplate
			.pullAsync("sub", 1, true);

	List<AcknowledgeablePubsubMessage> result = asyncResult.get(10L, TimeUnit.SECONDS);

	assertThat(asyncResult.isDone()).isTrue();

	assertThat(result.size()).isEqualTo(1);
	assertThat(result.get(0).getPubsubMessage()).isSameAs(this.pubsubMessage);
	assertThat(result.get(0).getProjectSubscriptionName().getProject()).isEqualTo("testProject");
	assertThat(result.get(0).getProjectSubscriptionName().getSubscription()).isEqualTo("sub");

	AcknowledgeablePubsubMessage acknowledgeablePubsubMessage = result.get(0);
	assertThat(acknowledgeablePubsubMessage.getAckId()).isNotNull();

	TestListenableFutureCallback ackTestListenableFutureCallback = new TestListenableFutureCallback();

	ListenableFuture<Void> ackListenableFuture = this.pubSubSubscriberTemplate.ack(result);

	assertThat(ackListenableFuture).isNotNull();

	ackListenableFuture.addCallback(ackTestListenableFutureCallback);
	ackListenableFuture.get(10L, TimeUnit.SECONDS);

	assertThat(ackListenableFuture.isDone()).isTrue();

	assertThat(ackTestListenableFutureCallback.getThrowable()).isNull();
}