org.springframework.util.concurrent.ListenableFutureCallback Java Examples

The following examples show how to use org.springframework.util.concurrent.ListenableFutureCallback. 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: KafkaProducer.java    From cubeai with Apache License 2.0 12 votes vote down vote up
public void send(String topic, String message) {
    // the KafkaTemplate provides asynchronous send methods returning a Future
    ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(topic, message);

    // register a callback with the listener to receive the result of the send asynchronously
    future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {

        @Override
        public void onSuccess(SendResult<String, String> result) {
            log.info("Kafka sent message='{}' with offset={}", message,
                result.getRecordMetadata().offset());
        }

        @Override
        public void onFailure(Throwable ex) {
            log.error("Kafka unable to send message='{}'", message, ex);
        }
    });

    // or, to block the sending thread to await the result, invoke the future's get() method
}
 
Example #2
Source File: WebSocketTransport.java    From java-technology-stack with MIT License 7 votes vote down vote up
@Override
public ListenableFuture<WebSocketSession> connect(TransportRequest request, WebSocketHandler handler) {
	final SettableListenableFuture<WebSocketSession> future = new SettableListenableFuture<>();
	WebSocketClientSockJsSession session = new WebSocketClientSockJsSession(request, handler, future);
	handler = new ClientSockJsWebSocketHandler(session);
	request.addTimeoutTask(session.getTimeoutTask());

	URI url = request.getTransportUrl();
	WebSocketHttpHeaders headers = new WebSocketHttpHeaders(request.getHandshakeHeaders());
	if (logger.isDebugEnabled()) {
		logger.debug("Starting WebSocket session on " + url);
	}
	this.webSocketClient.doHandshake(handler, headers, url).addCallback(
			new ListenableFutureCallback<WebSocketSession>() {
				@Override
				public void onSuccess(@Nullable WebSocketSession webSocketSession) {
					// WebSocket session ready, SockJS Session not yet
				}
				@Override
				public void onFailure(Throwable ex) {
					future.setException(ex);
				}
			});
	return future;
}
 
Example #3
Source File: AsyncRestTemplateIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void deleteCallback() throws Exception  {
	ListenableFuture<?> deletedFuture = template.delete(new URI(baseUrl + "/delete"));
	deletedFuture.addCallback(new ListenableFutureCallback<Object>() {
		@Override
		public void onSuccess(Object result) {
			assertNull(result);
		}
		@Override
		public void onFailure(Throwable ex) {
			fail(ex.getMessage());
		}
	});
	while (!deletedFuture.isDone()) {
	}
}
 
Example #4
Source File: ListenableFutureReturnValueHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	final DeferredResult<Object> deferredResult = new DeferredResult<Object>();
	WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult, mavContainer);

	ListenableFuture<?> future = (ListenableFuture<?>) returnValue;
	future.addCallback(new ListenableFutureCallback<Object>() {
		@Override
		public void onSuccess(Object result) {
			deferredResult.setResult(result);
		}
		@Override
		public void onFailure(Throwable ex) {
			deferredResult.setErrorResult(ex);
		}
	});
}
 
Example #5
Source File: AsyncRestTemplateIntegrationTests.java    From spring4-understanding with Apache License 2.0 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<String>(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());
		}
	});
	while (!resultFuture.isDone()) {
	}
}
 
Example #6
Source File: RestTemplateXhrTransportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void connectFailure() throws Exception {
	final HttpServerErrorException expected = new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR);
	RestOperations restTemplate = mock(RestOperations.class);
	given(restTemplate.execute((URI) any(), eq(HttpMethod.POST), any(), any())).willThrow(expected);

	final CountDownLatch latch = new CountDownLatch(1);
	connect(restTemplate).addCallback(
			new ListenableFutureCallback<WebSocketSession>() {
				@Override
				public void onSuccess(WebSocketSession result) {
				}
				@Override
				public void onFailure(Throwable ex) {
					if (ex == expected) {
						latch.countDown();
					}
				}
			}
	);
	verifyNoMoreInteractions(this.webSocketHandler);
}
 
Example #7
Source File: PrefetchingDatabaseProvider.java    From embedded-database-spring-test with Apache License 2.0 6 votes vote down vote up
private ListenableFutureTask<DataSource> prepareDatabase(PipelineKey key, int priority) {
    PrefetchingTask task = new PrefetchingTask(key.provider, key.preparer, priority);
    DatabasePipeline pipeline = pipelines.get(key);

    task.addCallback(new ListenableFutureCallback<DataSource>() {
        @Override
        public void onSuccess(DataSource result) {
            pipeline.tasks.remove(task);
            pipeline.results.offer(PreparedResult.success(result));
        }

        @Override
        public void onFailure(Throwable error) {
            pipeline.tasks.remove(task);
            if (!(error instanceof CancellationException)) {
                pipeline.results.offer(PreparedResult.failure(error));
            }
        }
    });

    pipeline.tasks.add(task);
    taskExecutor.execute(task);
    return task;
}
 
Example #8
Source File: ListenableFutureCallbackWithTracingTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@Before
public void beforeMethod() {
    listenableFutureCallbackMock = mock(ListenableFutureCallback.class);

    successInObj = new Object();
    failureInObj = new Exception("kaboom");
    throwExceptionDuringCall = false;
    currentSpanStackWhenListenableFutureCallbackWasCalled = new ArrayList<>();
    currentMdcInfoWhenListenableFutureCallbackWasCalled = new ArrayList<>();
    doAnswer(invocation -> {
        currentSpanStackWhenListenableFutureCallbackWasCalled.add(Tracer.getInstance().getCurrentSpanStackCopy());
        currentMdcInfoWhenListenableFutureCallbackWasCalled.add(MDC.getCopyOfContextMap());
        if (throwExceptionDuringCall)
            throw new RuntimeException("kaboom");
        return null;
    }).when(listenableFutureCallbackMock).onSuccess(successInObj);
    doAnswer(invocation -> {
        currentSpanStackWhenListenableFutureCallbackWasCalled.add(Tracer.getInstance().getCurrentSpanStackCopy());
        currentMdcInfoWhenListenableFutureCallbackWasCalled.add(MDC.getCopyOfContextMap());
        if (throwExceptionDuringCall)
            throw new RuntimeException("kaboom");
        return null;
    }).when(listenableFutureCallbackMock).onFailure(failureInObj);

    resetTracing();
}
 
Example #9
Source File: SenderConfiguration.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Bean
@ServiceActivator(inputChannel = "pubSubOutputChannel")
public MessageHandler messageSender(PubSubTemplate pubSubTemplate) {
	PubSubMessageHandler adapter = new PubSubMessageHandler(pubSubTemplate, TOPIC_NAME);
	adapter.setPublishCallback(new ListenableFutureCallback<String>() {
		@Override
		public void onFailure(Throwable ex) {
			LOGGER.info("There was an error sending the message.");
		}

		@Override
		public void onSuccess(String result) {
			LOGGER.info("Message was sent successfully.");
		}
	});

	return adapter;
}
 
Example #10
Source File: AbstractSockJsIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void infoRequestFailure() throws Exception {
	TestClientHandler handler = new TestClientHandler();
	this.testFilter.sendErrorMap.put("/info", 500);
	CountDownLatch latch = new CountDownLatch(1);
	initSockJsClient(createWebSocketTransport());
	this.sockJsClient.doHandshake(handler, this.baseUrl + "/echo").addCallback(
			new ListenableFutureCallback<WebSocketSession>() {
				@Override
				public void onSuccess(WebSocketSession result) {
				}

				@Override
				public void onFailure(Throwable ex) {
					latch.countDown();
				}
			}
	);
	assertTrue(latch.await(5000, TimeUnit.MILLISECONDS));
}
 
Example #11
Source File: KafkaSender.java    From java-tutorial with MIT License 6 votes vote down vote up
/**
 * kafka 发送消息
 *
 * @param obj 消息对象
 */
public void send(T obj) {
    String jsonObj = JSON.toJSONString(obj);
    logger.info("------------ message = {}", jsonObj);

    String topic = "jwell-opt-log";
    //发送消息
    ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(topic, jsonObj);
    future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
        @Override
        public void onFailure(Throwable throwable) {
            logger.info("Produce: The message failed to be sent:" + throwable.getMessage());
        }

        @Override
        public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
            //TODO 业务处理
            logger.info("Produce: The message was sent successfully:");
            logger.info("Produce: _+_+_+_+_+_+_+ result: " + stringObjectSendResult.toString());
        }
    });
}
 
Example #12
Source File: SendKafkaMessageService.java    From enode with MIT License 6 votes vote down vote up
@Override
public CompletableFuture<Void> sendMessageAsync(QueueMessage queueMessage) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    ProducerRecord<String, String> message = KafkaTool.covertToProducerRecord(queueMessage);
    producer.send(message).addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
        @Override
        public void onFailure(Throwable throwable) {
            logger.error("Enode message async send has exception, message: {}", message, throwable);
            future.completeExceptionally(new IORuntimeException(throwable));
        }

        @Override
        public void onSuccess(SendResult<String, String> result) {
            if (logger.isDebugEnabled()) {
                logger.debug("Enode message async send success, sendResult: {}, message: {}", result, message);
            }
            future.complete(null);
        }
    });
    return future;
}
 
Example #13
Source File: ListenableFutureReturnValueHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	final DeferredResult<Object> deferredResult = new DeferredResult<Object>();
	WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult, mavContainer);

	ListenableFuture<?> future = (ListenableFuture<?>) returnValue;
	future.addCallback(new ListenableFutureCallback<Object>() {
		@Override
		public void onSuccess(Object result) {
			deferredResult.setResult(result);
		}
		@Override
		public void onFailure(Throwable ex) {
			deferredResult.setErrorResult(ex);
		}
	});
}
 
Example #14
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 #15
Source File: KafkaPassengerPublisher.java    From stateful-functions with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(InboundPassengerMessage passenger) {
  byte[] bytes = passenger.getPassengerId().getBytes(StandardCharsets.UTF_8);
  kafkaTemplate
      .send(topic, bytes, passenger.toByteArray())
      .addCallback(
          new ListenableFutureCallback<SendResult<Object, Object>>() {
            @Override
            public void onFailure(@NonNull Throwable throwable) {
              log.warn("couldn't send passenger data.", throwable);
            }

            @Override
            public void onSuccess(SendResult<Object, Object> objectObjectSendResult) {
              log.info("Sent passenger data");
            }
          });
}
 
Example #16
Source File: AsyncRestTemplateIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void notFoundCallback() throws Exception {
	ListenableFuture<?> future = template.execute(baseUrl + "/status/notfound", HttpMethod.GET, null, null);
	future.addCallback(new ListenableFutureCallback<Object>() {
		@Override
		public void onSuccess(Object result) {
			fail("onSuccess not expected");
		}
		@Override
		public void onFailure(Throwable t) {
			assertTrue(t instanceof HttpClientErrorException);
			HttpClientErrorException ex = (HttpClientErrorException) t;
			assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
			assertNotNull(ex.getStatusText());
			assertNotNull(ex.getResponseBodyAsString());
		}
	});
	while (!future.isDone()) {
	}
}
 
Example #17
Source File: RestTemplateXhrTransportTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void connectFailure() throws Exception {
	final HttpServerErrorException expected = new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR);
	RestOperations restTemplate = mock(RestOperations.class);
	given(restTemplate.execute((URI) any(), eq(HttpMethod.POST), any(), any())).willThrow(expected);

	final CountDownLatch latch = new CountDownLatch(1);
	connect(restTemplate).addCallback(
			new ListenableFutureCallback<WebSocketSession>() {
				@Override
				public void onSuccess(WebSocketSession result) {
				}
				@Override
				public void onFailure(Throwable ex) {
					if (ex == expected) {
						latch.countDown();
					}
				}
			}
	);
	verifyNoMoreInteractions(this.webSocketHandler);
}
 
Example #18
Source File: AsyncRestTemplateIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void postForEntityCallback() throws Exception  {
	HttpEntity<String> requestEntity = new HttpEntity<>(helloWorld);
	ListenableFuture<ResponseEntity<String>> responseEntityFuture =
			template.postForEntity(baseUrl + "/{method}", requestEntity, String.class, "post");
	responseEntityFuture.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
		@Override
		public void onSuccess(ResponseEntity<String> result) {
			assertEquals("Invalid content", helloWorld, result.getBody());
		}
		@Override
		public void onFailure(Throwable ex) {
			fail(ex.getMessage());
		}
	});
	while (!responseEntityFuture.isDone()) {
	}
}
 
Example #19
Source File: AsyncRestTemplateIntegrationTests.java    From java-technology-stack 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 #20
Source File: WebSocketConnectionManager.java    From java-technology-stack with MIT License 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(@Nullable WebSocketSession result) {
			webSocketSession = result;
			logger.info("Successfully connected");
		}
		@Override
		public void onFailure(Throwable ex) {
			logger.error("Failed to connect", ex);
		}
	});
}
 
Example #21
Source File: AsyncRestTemplateIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void exchangeGetCallback() throws Exception {
	HttpHeaders requestHeaders = new HttpHeaders();
	requestHeaders.set("MyHeader", "MyValue");
	HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
	ListenableFuture<ResponseEntity<String>> responseFuture =
			template.exchange(baseUrl + "/{method}", HttpMethod.GET, requestEntity, String.class, "get");
	responseFuture.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
		@Override
		public void onSuccess(ResponseEntity<String> result) {
			assertEquals("Invalid content", helloWorld, result.getBody());
		}
		@Override
		public void onFailure(Throwable ex) {
			fail(ex.getMessage());
		}
	});
	waitTillDone(responseFuture);
}
 
Example #22
Source File: AsyncRestTemplateIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void optionsForAllowCallback() throws Exception {
	ListenableFuture<Set<HttpMethod>> allowedFuture = template.optionsForAllow(new URI(baseUrl + "/get"));
	allowedFuture.addCallback(new ListenableFutureCallback<Set<HttpMethod>>() {
		@Override
		public void onSuccess(Set<HttpMethod> result) {
			assertEquals("Invalid response", EnumSet.of(HttpMethod.GET, HttpMethod.OPTIONS,
					HttpMethod.HEAD, HttpMethod.TRACE), result);
		}
		@Override
		public void onFailure(Throwable ex) {
			fail(ex.getMessage());
		}
	});
	waitTillDone(allowedFuture);
}
 
Example #23
Source File: AsyncRestTemplateIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void serverErrorCallback() throws Exception {
	ListenableFuture<Void> future = template.execute(baseUrl + "/status/server", HttpMethod.GET, null, null);
	future.addCallback(new ListenableFutureCallback<Void>() {
		@Override
		public void onSuccess(Void result) {
			fail("onSuccess not expected");
		}
		@Override
		public void onFailure(Throwable ex) {
			assertTrue(ex instanceof HttpServerErrorException);
			HttpServerErrorException hsex = (HttpServerErrorException) ex;
			assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, hsex.getStatusCode());
			assertNotNull(hsex.getStatusText());
			assertNotNull(hsex.getResponseBodyAsString());
		}
	});
	waitTillDone(future);
}
 
Example #24
Source File: AsyncRestTemplateIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void notFoundCallback() throws Exception {
	ListenableFuture<?> future = template.execute(baseUrl + "/status/notfound", HttpMethod.GET, null, null);
	future.addCallback(new ListenableFutureCallback<Object>() {
		@Override
		public void onSuccess(Object result) {
			fail("onSuccess not expected");
		}
		@Override
		public void onFailure(Throwable t) {
			assertTrue(t instanceof HttpClientErrorException);
			HttpClientErrorException ex = (HttpClientErrorException) t;
			assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
			assertNotNull(ex.getStatusText());
			assertNotNull(ex.getResponseBodyAsString());
		}
	});
	waitTillDone(future);
}
 
Example #25
Source File: RestTemplateXhrTransportTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void connectFailure() throws Exception {
	final HttpServerErrorException expected = new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR);
	RestOperations restTemplate = mock(RestOperations.class);
	given(restTemplate.execute((URI) any(), eq(HttpMethod.POST), any(), any())).willThrow(expected);

	final CountDownLatch latch = new CountDownLatch(1);
	connect(restTemplate).addCallback(
			new ListenableFutureCallback<WebSocketSession>() {
				@Override
				public void onSuccess(WebSocketSession result) {
				}
				@Override
				public void onFailure(Throwable ex) {
					if (ex == expected) {
						latch.countDown();
					}
				}
			}
	);
	verifyNoMoreInteractions(this.webSocketHandler);
}
 
Example #26
Source File: AsyncRestTemplateIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void postForLocationCallback() throws Exception  {
	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(new MediaType("text", "plain", Charset.forName("ISO-8859-15")));
	HttpEntity<String> entity = new HttpEntity<String>(helloWorld, entityHeaders);
	final URI expected = new URI(baseUrl + "/post/1");
	ListenableFuture<URI> locationFuture = template.postForLocation(baseUrl + "/{method}", entity, "post");
	locationFuture.addCallback(new ListenableFutureCallback<URI>() {
		@Override
		public void onSuccess(URI result) {
			assertEquals("Invalid location", expected, result);
		}
		@Override
		public void onFailure(Throwable ex) {
			fail(ex.getMessage());
		}
	});
	while (!locationFuture.isDone()) {
	}
}
 
Example #27
Source File: AsyncRestTemplateIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void exchangeGetCallback() throws Exception {
	HttpHeaders requestHeaders = new HttpHeaders();
	requestHeaders.set("MyHeader", "MyValue");
	HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
	ListenableFuture<ResponseEntity<String>> responseFuture =
			template.exchange(baseUrl + "/{method}", HttpMethod.GET, requestEntity, String.class, "get");
	responseFuture.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
		@Override
		public void onSuccess(ResponseEntity<String> result) {
			assertEquals("Invalid content", helloWorld, result.getBody());
		}
		@Override
		public void onFailure(Throwable ex) {
			fail(ex.getMessage());
		}
	});
	while (!responseFuture.isDone()) {
	}
}
 
Example #28
Source File: MessageSendingCallback.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public ListenableFutureCallback<OutboundMessageResponseSummary> getBatchCallBack()
{
    return new ListenableFutureCallback<OutboundMessageResponseSummary>()
    {
        @Override
        public void onFailure( Throwable ex )
        {
            log.error( "Message sending failed", ex );
        }

        @Override
        public void onSuccess( OutboundMessageResponseSummary result )
        {
            int successful = result.getSent();
            int failed = result.getFailed();

            log.info( String.format( "%s Message sending status: Successful: %d Failed: %d", result.getChannel().name(), successful, failed ) );
        }
    };
}
 
Example #29
Source File: AsyncRestTemplateIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void serverErrorCallback() throws Exception {
	ListenableFuture<Void> future = template.execute(baseUrl + "/status/server", HttpMethod.GET, null, null);
	future.addCallback(new ListenableFutureCallback<Void>() {
		@Override
		public void onSuccess(Void result) {
			fail("onSuccess not expected");
		}
		@Override
		public void onFailure(Throwable ex) {
			assertTrue(ex instanceof HttpServerErrorException);
			HttpServerErrorException hsex = (HttpServerErrorException) ex;
			assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, hsex.getStatusCode());
			assertNotNull(hsex.getStatusText());
			assertNotNull(hsex.getResponseBodyAsString());
		}
	});
	while (!future.isDone()) {
	}
}
 
Example #30
Source File: AsyncRestTemplateIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void postForLocationCallback() throws Exception  {
	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(new MediaType("text", "plain", StandardCharsets.ISO_8859_1));
	HttpEntity<String> entity = new HttpEntity<>(helloWorld, entityHeaders);
	final URI expected = new URI(baseUrl + "/post/1");
	ListenableFuture<URI> locationFuture = template.postForLocation(baseUrl + "/{method}", entity, "post");
	locationFuture.addCallback(new ListenableFutureCallback<URI>() {
		@Override
		public void onSuccess(URI result) {
			assertEquals("Invalid location", expected, result);
		}
		@Override
		public void onFailure(Throwable ex) {
			fail(ex.getMessage());
		}
	});
	waitTillDone(locationFuture);
}