Search in sources :

Example 1 with StompSession

use of org.springframework.messaging.simp.stomp.StompSession in project spring-integration by spring-projects.

the class StompSessionManagerTests method testDoConnectFailure.

@Test
public void testDoConnectFailure() throws Exception {
    StompClientSupport stompClient = mock(StompClientSupport.class);
    stompClient.setTaskScheduler(new ConcurrentTaskScheduler());
    AbstractStompSessionManager sessionManager = new AbstractStompSessionManager(stompClient) {

        private final AtomicBoolean thrown = new AtomicBoolean();

        @Override
        protected ListenableFuture<StompSession> doConnect(StompSessionHandler handler) {
            if (!this.thrown.getAndSet(true)) {
                throw new RuntimeException("intentional");
            } else {
                SettableListenableFuture<StompSession> future = new SettableListenableFuture<StompSession>();
                StompSession stompSession = mock(StompSession.class);
                future.set(stompSession);
                handler.afterConnected(stompSession, getConnectHeaders());
                return future;
            }
        }
    };
    sessionManager.start();
    final SettableListenableFuture<StompSession> stompSessionFuture = new SettableListenableFuture<StompSession>();
    sessionManager.connect(new StompSessionHandlerAdapter() {

        @Override
        public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
            stompSessionFuture.set(session);
        }
    });
    assertNotNull(stompSessionFuture.get(10, TimeUnit.SECONDS));
    sessionManager.stop();
}
Also used : ConcurrentTaskScheduler(org.springframework.scheduling.concurrent.ConcurrentTaskScheduler) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) StompClientSupport(org.springframework.messaging.simp.stomp.StompClientSupport) StompSession(org.springframework.messaging.simp.stomp.StompSession) StompSessionHandler(org.springframework.messaging.simp.stomp.StompSessionHandler) StompHeaders(org.springframework.messaging.simp.stomp.StompHeaders) StompSessionHandlerAdapter(org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter) Test(org.junit.Test)

Example 2 with StompSession

use of org.springframework.messaging.simp.stomp.StompSession in project elastest-torm by elastest.

the class StompTestUtils method connectToRabbitMQ.

public static StompSession connectToRabbitMQ(int serverPort) throws InterruptedException, ExecutionException, TimeoutException {
    WebSocketContainer cont = ContainerProvider.getWebSocketContainer();
    cont.setDefaultMaxTextMessageBufferSize(65500);
    WebSocketClient webSocketClient = new StandardWebSocketClient(cont);
    WebSocketStompClient stompClient = new WebSocketStompClient(webSocketClient);
    stompClient.setMessageConverter(new StringMessageConverter());
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.initialize();
    // for heartbeats
    stompClient.setTaskScheduler(taskScheduler);
    stompClient.setDefaultHeartbeat(new long[] { 10000, 10000 });
    String url = "ws://localhost:" + serverPort + "/rabbitMq";
    StompSessionHandler sessionHandler = new LogConnectedSessionHandler();
    final int MAX_RETRIES = 5;
    int retry = 0;
    while (true) {
        try {
            StompSession stompSession = stompClient.connect(url, sessionHandler).get(10, TimeUnit.SECONDS);
            log.info("Test connected to RabbitMQ in URL '{}'", url);
            return stompSession;
        } catch (Exception e) {
            if (retry < MAX_RETRIES) {
                retry++;
                log.warn("Exception trying to connect to RabbitMQ: {}:{}", e.getClass().getName(), e.getMessage());
                log.info("Retrying {}/{} in 5 second", retry, MAX_RETRIES);
                Thread.sleep(5000);
            } else {
                throw e;
            }
        }
    }
}
Also used : StringMessageConverter(org.springframework.messaging.converter.StringMessageConverter) WebSocketContainer(javax.websocket.WebSocketContainer) StompSession(org.springframework.messaging.simp.stomp.StompSession) StompSessionHandler(org.springframework.messaging.simp.stomp.StompSessionHandler) WebSocketStompClient(org.springframework.web.socket.messaging.WebSocketStompClient) StandardWebSocketClient(org.springframework.web.socket.client.standard.StandardWebSocketClient) StandardWebSocketClient(org.springframework.web.socket.client.standard.StandardWebSocketClient) WebSocketClient(org.springframework.web.socket.client.WebSocketClient) TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler)

Example 3 with StompSession

use of org.springframework.messaging.simp.stomp.StompSession in project spring-boot by spring-projects.

the class WebSocketMessagingAutoConfigurationTests method performStompSubscription.

private Object performStompSubscription(String topic) throws Throwable {
    TestPropertyValues.of("server.port:0", "spring.jackson.serialization.indent-output:true").applyTo(this.context);
    this.context.register(WebSocketMessagingConfiguration.class);
    new ServerPortInfoApplicationContextInitializer().initialize(this.context);
    this.context.refresh();
    WebSocketStompClient stompClient = new WebSocketStompClient(this.sockJsClient);
    final AtomicReference<Throwable> failure = new AtomicReference<>();
    final AtomicReference<Object> result = new AtomicReference<>();
    final CountDownLatch latch = new CountDownLatch(1);
    StompSessionHandler handler = new StompSessionHandlerAdapter() {

        @Override
        public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
            session.subscribe(topic, new StompFrameHandler() {

                @Override
                public void handleFrame(StompHeaders headers, Object payload) {
                    result.set(payload);
                    latch.countDown();
                }

                @Override
                public Type getPayloadType(StompHeaders headers) {
                    return Object.class;
                }
            });
        }

        @Override
        public void handleFrame(StompHeaders headers, Object payload) {
            latch.countDown();
        }

        @Override
        public void handleException(StompSession session, StompCommand command, StompHeaders headers, byte[] payload, Throwable exception) {
            failure.set(exception);
            latch.countDown();
        }

        @Override
        public void handleTransportError(StompSession session, Throwable exception) {
            failure.set(exception);
            latch.countDown();
        }
    };
    stompClient.setMessageConverter(new SimpleMessageConverter());
    stompClient.connect("ws://localhost:{port}/messaging", handler, this.context.getEnvironment().getProperty("local.server.port"));
    if (!latch.await(30, TimeUnit.SECONDS)) {
        if (failure.get() != null) {
            throw failure.get();
        }
        fail("Response was not received within 30 seconds");
    }
    return result.get();
}
Also used : ServerPortInfoApplicationContextInitializer(org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer) StompFrameHandler(org.springframework.messaging.simp.stomp.StompFrameHandler) StompSession(org.springframework.messaging.simp.stomp.StompSession) StompSessionHandler(org.springframework.messaging.simp.stomp.StompSessionHandler) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) StompHeaders(org.springframework.messaging.simp.stomp.StompHeaders) StompCommand(org.springframework.messaging.simp.stomp.StompCommand) Type(java.lang.reflect.Type) WebSocketStompClient(org.springframework.web.socket.messaging.WebSocketStompClient) SimpleMessageConverter(org.springframework.messaging.converter.SimpleMessageConverter) StompSessionHandlerAdapter(org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter)

Example 4 with StompSession

use of org.springframework.messaging.simp.stomp.StompSession in project spring-boot by spring-projects.

the class WebSocketMessagingAutoConfigurationTests method performStompSubscription.

private Object performStompSubscription(final String topic) throws Throwable {
    EnvironmentTestUtils.addEnvironment(this.context, "server.port:0", "spring.jackson.serialization.indent-output:true");
    this.context.register(WebSocketMessagingConfiguration.class);
    new ServerPortInfoApplicationContextInitializer().initialize(this.context);
    this.context.refresh();
    WebSocketStompClient stompClient = new WebSocketStompClient(this.sockJsClient);
    final AtomicReference<Throwable> failure = new AtomicReference<>();
    final AtomicReference<Object> result = new AtomicReference<>();
    final CountDownLatch latch = new CountDownLatch(1);
    StompSessionHandler handler = new StompSessionHandlerAdapter() {

        @Override
        public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
            session.subscribe(topic, new StompFrameHandler() {

                @Override
                public void handleFrame(StompHeaders headers, Object payload) {
                    result.set(payload);
                    latch.countDown();
                }

                @Override
                public Type getPayloadType(StompHeaders headers) {
                    return Object.class;
                }
            });
        }

        @Override
        public void handleFrame(StompHeaders headers, Object payload) {
            latch.countDown();
        }

        @Override
        public void handleException(StompSession session, StompCommand command, StompHeaders headers, byte[] payload, Throwable exception) {
            failure.set(exception);
            latch.countDown();
        }

        @Override
        public void handleTransportError(StompSession session, Throwable exception) {
            failure.set(exception);
            latch.countDown();
        }
    };
    stompClient.setMessageConverter(new SimpleMessageConverter());
    stompClient.connect("ws://localhost:{port}/messaging", handler, this.context.getEnvironment().getProperty("local.server.port"));
    if (!latch.await(30000, TimeUnit.SECONDS)) {
        if (failure.get() != null) {
            throw failure.get();
        }
        fail("Response was not received within 30 seconds");
    }
    return result.get();
}
Also used : ServerPortInfoApplicationContextInitializer(org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer) StompFrameHandler(org.springframework.messaging.simp.stomp.StompFrameHandler) StompSession(org.springframework.messaging.simp.stomp.StompSession) StompSessionHandler(org.springframework.messaging.simp.stomp.StompSessionHandler) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) StompHeaders(org.springframework.messaging.simp.stomp.StompHeaders) StompCommand(org.springframework.messaging.simp.stomp.StompCommand) Type(java.lang.reflect.Type) WebSocketStompClient(org.springframework.web.socket.messaging.WebSocketStompClient) SimpleMessageConverter(org.springframework.messaging.converter.SimpleMessageConverter) StompSessionHandlerAdapter(org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter)

Example 5 with StompSession

use of org.springframework.messaging.simp.stomp.StompSession in project elastest-torm by elastest.

the class TJobExecutionApiItTest method testExecuteTJob.

private void testExecuteTJob(boolean withSut) throws InterruptedException, ExecutionException, TimeoutException, MultipleFailuresError {
    log.info("Start the test testExecuteTJob " + (withSut ? "with" : "without") + " SuT");
    TJob tJob;
    if (withSut) {
        Long sutId = createSut(projectId).getId();
        tJob = createTJob(projectId, sutId);
    } else {
        tJob = createTJob(projectId);
    }
    StompSession stompSession = connectToRabbitMQ(serverPort);
    log.info("POST /api/tjob/{tjobId}/exec");
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    String body = "{\"tJobParams\" : [{\"Param1\":\"NewValue1\"}], \"sutParams\" : [{\"Param1\":\"NewValue1\"}]}";
    HttpEntity<String> entity = new HttpEntity<>(body, headers);
    Map<String, Object> urlParams = new HashMap<>();
    urlParams.put("tjobId", tJob.getId());
    ResponseEntity<TJobExecution> response = httpClient.postForEntity("/api/tjob/{tjobId}/exec", entity, TJobExecution.class, urlParams);
    TJobExecution exec = response.getBody();
    log.info("TJobExecution creation response: " + response);
    if (withSut) {
        String queueToSuscribe = "/topic/" + "sut.default_log." + exec.getId() + ".log";
        log.info("Sut log queue '" + queueToSuscribe + "'");
        WaitForMessagesHandler handler = new WaitForMessagesHandler();
        stompSession.subscribe(queueToSuscribe, handler);
        handler.waitForCompletion(5, TimeUnit.SECONDS);
        log.info("Sut log queue received a message");
    }
    String queueToSuscribe = "/topic/" + "test.default_log." + exec.getId() + ".log";
    log.info("TJob log queue '" + queueToSuscribe + "'");
    WaitForMessagesHandler handler = new WaitForMessagesHandler(msg -> msg.contains("BUILD SUCCESS") || msg.contains("BUILD FAILURE"));
    stompSession.subscribe(queueToSuscribe, handler);
    handler.waitForCompletion(180, TimeUnit.SECONDS);
    assertAll("Validating TJobExecution Properties", () -> assertNotNull(response.getBody()), () -> assertNotNull(response.getBody().getId()), () -> assertTrue(response.getBody().getTjob().getId().equals(urlParams.get("tjobId"))));
    while (true) {
        exec = getTJobExecutionById(exec.getId(), tJob.getId()).getBody();
        log.info("TJobExecution: " + exec);
        if (exec.getResult() != ResultEnum.IN_PROGRESS) {
            log.info("Test results:" + exec.getTestSuites());
            break;
        }
        sleep(500);
    }
    deleteTJobExecution(exec.getId(), tJob.getId());
    deleteTJob(tJob.getId());
    log.info("Finished.");
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) StompSession(org.springframework.messaging.simp.stomp.StompSession) HttpEntity(org.springframework.http.HttpEntity) HashMap(java.util.HashMap) TJobExecution(io.elastest.etm.model.TJobExecution) TJob(io.elastest.etm.model.TJob) WaitForMessagesHandler(io.elastest.etm.test.util.StompTestUtils.WaitForMessagesHandler)

Aggregations

StompSession (org.springframework.messaging.simp.stomp.StompSession)10 StompHeaders (org.springframework.messaging.simp.stomp.StompHeaders)6 StompSessionHandler (org.springframework.messaging.simp.stomp.StompSessionHandler)4 Type (java.lang.reflect.Type)3 StompFrameHandler (org.springframework.messaging.simp.stomp.StompFrameHandler)3 StompSessionHandlerAdapter (org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter)3 WebSocketStompClient (org.springframework.web.socket.messaging.WebSocketStompClient)3 WaitForMessagesHandler (io.elastest.etm.test.util.StompTestUtils.WaitForMessagesHandler)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 ExecutionException (java.util.concurrent.ExecutionException)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Test (org.junit.Test)2 ServerPortInfoApplicationContextInitializer (org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer)2 ApplicationEventPublisher (org.springframework.context.ApplicationEventPublisher)2 StompReceiptEvent (org.springframework.integration.stomp.event.StompReceiptEvent)2 SimpleMessageConverter (org.springframework.messaging.converter.SimpleMessageConverter)2 StompCommand (org.springframework.messaging.simp.stomp.StompCommand)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 TJob (io.elastest.etm.model.TJob)1 TJobExecution (io.elastest.etm.model.TJobExecution)1