Search in sources :

Example 1 with SettableListenableFuture

use of org.springframework.util.concurrent.SettableListenableFuture in project spring-framework by spring-projects.

the class DeferredResultReturnValueHandlerTests method completableFuture.

@Test
public void completableFuture() throws Exception {
    MethodParameter returnType = returnType("handleCompletableFuture");
    SettableListenableFuture<String> future = new SettableListenableFuture<>();
    handleReturnValue(future, returnType);
    assertTrue(this.request.isAsyncStarted());
    assertFalse(WebAsyncUtils.getAsyncManager(this.webRequest).hasConcurrentResult());
    future.set("foo");
    assertTrue(WebAsyncUtils.getAsyncManager(this.webRequest).hasConcurrentResult());
    assertEquals("foo", WebAsyncUtils.getAsyncManager(this.webRequest).getConcurrentResult());
}
Also used : SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) MethodParameter(org.springframework.core.MethodParameter) Test(org.junit.Test)

Example 2 with SettableListenableFuture

use of org.springframework.util.concurrent.SettableListenableFuture in project spring-framework by spring-projects.

the class DeferredResultReturnValueHandlerTests method listenableFutureWithError.

@Test
public void listenableFutureWithError() throws Exception {
    MethodParameter returnType = returnType("handleListenableFuture");
    SettableListenableFuture<String> future = new SettableListenableFuture<>();
    handleReturnValue(future, returnType);
    assertTrue(this.request.isAsyncStarted());
    assertFalse(WebAsyncUtils.getAsyncManager(this.webRequest).hasConcurrentResult());
    IllegalStateException ex = new IllegalStateException();
    future.setException(ex);
    assertTrue(WebAsyncUtils.getAsyncManager(this.webRequest).hasConcurrentResult());
    assertSame(ex, WebAsyncUtils.getAsyncManager(this.webRequest).getConcurrentResult());
}
Also used : SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) MethodParameter(org.springframework.core.MethodParameter) Test(org.junit.Test)

Example 3 with SettableListenableFuture

use of org.springframework.util.concurrent.SettableListenableFuture in project webofneeds by researchstudio-sat.

the class SecurityBotTests method runBot.

private void runBot(Class botClass) throws ExecutionException, InterruptedException {
    IntegrationtestBot bot = null;
    // create a bot instance and auto-wire it
    AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();
    bot = (IntegrationtestBot) beanFactory.autowire(botClass, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
    Object botBean = beanFactory.initializeBean(bot, "theBot");
    bot = (IntegrationtestBot) botBean;
    // the bot also needs a trigger so its act() method is called regularly.
    // (there is no trigger bean in the context)
    PeriodicTrigger trigger = new PeriodicTrigger(500, TimeUnit.MILLISECONDS);
    trigger.setInitialDelay(100);
    ((TriggeredBot) bot).setTrigger(trigger);
    // adding the bot to the bot manager will cause it to be initialized.
    // at that point, the trigger starts.
    botManager.addBot(bot);
    final SettableListenableFuture<TestFinishedEvent> futureTestResult = new SettableListenableFuture();
    final EventListenerContext ctx = bot.getExposedEventListenerContext();
    // action for setting the future when we get a test result
    EventBotAction setFutureAction = new SetFutureAction(ctx, futureTestResult);
    // action for setting the future when an error occurs
    EventBotAction setFutureFromErrorAction = new SetFutureFromErrorEventAction(ctx, futureTestResult, bot);
    // add a listener for test success
    ctx.getEventBus().subscribe(TestPassedEvent.class, new ActionOnEventListener(ctx, setFutureAction));
    // add a listener for test failure
    ctx.getEventBus().subscribe(TestFailedEvent.class, new ActionOnEventListener(ctx, setFutureAction));
    // add a listener for errors
    ctx.getEventBus().subscribe(ErrorEvent.class, new ActionOnEventListener(ctx, setFutureFromErrorAction));
    // wait for the result
    TestFinishedEvent result = futureTestResult.get();
    if (result instanceof TestFailedEvent) {
        Assert.fail(((TestFailedEvent) result).getMessage());
    }
}
Also used : EventListenerContext(won.bot.framework.eventbot.EventListenerContext) SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) IntegrationtestBot(won.bot.IntegrationtestBot) AutowireCapableBeanFactory(org.springframework.beans.factory.config.AutowireCapableBeanFactory) TriggeredBot(won.bot.framework.bot.base.TriggeredBot) PeriodicTrigger(org.springframework.scheduling.support.PeriodicTrigger) TestFailedEvent(won.bot.framework.eventbot.event.impl.test.TestFailedEvent) TestFinishedEvent(won.bot.framework.eventbot.event.impl.test.TestFinishedEvent) ActionOnEventListener(won.bot.framework.eventbot.listener.impl.ActionOnEventListener) EventBotAction(won.bot.framework.eventbot.action.EventBotAction) BaseEventBotAction(won.bot.framework.eventbot.action.BaseEventBotAction)

Example 4 with SettableListenableFuture

use of org.springframework.util.concurrent.SettableListenableFuture in project spring-integration by spring-projects.

the class AsyncHandlerTests method setup.

@Before
public void setup() {
    this.executor = Executors.newSingleThreadExecutor();
    this.handler = new AbstractReplyProducingMessageHandler() {

        @Override
        protected Object handleRequestMessage(Message<?> requestMessage) {
            final SettableListenableFuture<String> future = new SettableListenableFuture<String>();
            AsyncHandlerTests.this.executor.execute(() -> {
                try {
                    latch.await(10, TimeUnit.SECONDS);
                    switch(whichTest) {
                        case 0:
                            future.set("reply");
                            break;
                        case 1:
                            future.setException(new RuntimeException("foo"));
                            break;
                        case 2:
                            future.setException(new MessagingException(requestMessage));
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
            return future;
        }
    };
    this.handler.setAsync(true);
    this.handler.setOutputChannel(this.output);
    this.handler.setBeanFactory(mock(BeanFactory.class));
    this.latch = new CountDownLatch(1);
    Log logger = spy(TestUtils.getPropertyValue(this.handler, "logger", Log.class));
    new DirectFieldAccessor(this.handler).setPropertyValue("logger", logger);
    doAnswer(invocation -> {
        failedCallbackMessage = invocation.getArgument(0);
        failedCallbackException = invocation.getArgument(1);
        exceptionLatch.countDown();
        return null;
    }).when(logger).error(anyString(), any(Throwable.class));
}
Also used : SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) MessagingException(org.springframework.messaging.MessagingException) Log(org.apache.commons.logging.Log) Matchers.containsString(org.hamcrest.Matchers.containsString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) CountDownLatch(java.util.concurrent.CountDownLatch) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) BeanFactory(org.springframework.beans.factory.BeanFactory) Before(org.junit.Before)

Example 5 with SettableListenableFuture

use of org.springframework.util.concurrent.SettableListenableFuture in project spring-integration by spring-projects.

the class SimpleWebServiceOutboundGatewayTests method testDomPoxMessageFactory.

@Test
public void testDomPoxMessageFactory() throws Exception {
    String uri = "http://www.example.org";
    SimpleWebServiceOutboundGateway gateway = new SimpleWebServiceOutboundGateway(uri);
    gateway.setBeanFactory(mock(BeanFactory.class));
    final SettableListenableFuture<WebServiceMessage> requestFuture = new SettableListenableFuture<>();
    ClientInterceptorAdapter interceptorAdapter = new ClientInterceptorAdapter() {

        @Override
        public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
            requestFuture.set(messageContext.getRequest());
            return super.handleRequest(messageContext);
        }
    };
    gateway.setInterceptors(interceptorAdapter);
    gateway.setMessageFactory(new DomPoxMessageFactory());
    gateway.afterPropertiesSet();
    String request = "<test>foo</test>";
    try {
        gateway.handleMessage(new GenericMessage<>(request));
        fail("Expected MessageHandlingException");
    } catch (MessageHandlingException e) {
    // expected
    }
    WebServiceMessage requestMessage = requestFuture.get(10, TimeUnit.SECONDS);
    assertNotNull(requestMessage);
    assertThat(requestMessage, instanceOf(PoxMessage.class));
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringResult stringResult = new StringResult();
    transformer.transform(requestMessage.getPayloadSource(), stringResult);
    assertEquals(request, stringResult.toString());
}
Also used : SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) DomPoxMessageFactory(org.springframework.ws.pox.dom.DomPoxMessageFactory) ClientInterceptorAdapter(org.springframework.ws.client.support.interceptor.ClientInterceptorAdapter) MessageHandlingException(org.springframework.messaging.MessageHandlingException) WebServiceMessage(org.springframework.ws.WebServiceMessage) BeanFactory(org.springframework.beans.factory.BeanFactory) MessageContext(org.springframework.ws.context.MessageContext) StringResult(org.springframework.xml.transform.StringResult) PoxMessage(org.springframework.ws.pox.PoxMessage) Test(org.junit.Test)

Aggregations

SettableListenableFuture (org.springframework.util.concurrent.SettableListenableFuture)18 Test (org.junit.Test)8 BeanFactory (org.springframework.beans.factory.BeanFactory)3 MessagingException (org.springframework.messaging.MessagingException)3 URI (java.net.URI)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 Transformer (javax.xml.transform.Transformer)2 TransformerFactory (javax.xml.transform.TransformerFactory)2 Log (org.apache.commons.logging.Log)2 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)2 MethodParameter (org.springframework.core.MethodParameter)2 Message (org.springframework.messaging.Message)2 MessageHandlingException (org.springframework.messaging.MessageHandlingException)2 ErrorMessage (org.springframework.messaging.support.ErrorMessage)2 WebSocketSession (org.springframework.web.socket.WebSocketSession)2 WebServiceMessage (org.springframework.ws.WebServiceMessage)2 ClientInterceptorAdapter (org.springframework.ws.client.support.interceptor.ClientInterceptorAdapter)2 MessageContext (org.springframework.ws.context.MessageContext)2 StringResult (org.springframework.xml.transform.StringResult)2 ClientApplicationRegisteredEvent (de.codecentric.boot.admin.event.ClientApplicationRegisteredEvent)1