@Test
  public void testStateEvents() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
    assertTrue(ctx.containsBean(StateMachineSystemConstants.DEFAULT_ID_STATEMACHINE));
    @SuppressWarnings("unchecked")
    EnumStateMachine<TestStates, TestEvents> machine =
        ctx.getBean(StateMachineSystemConstants.DEFAULT_ID_STATEMACHINE, EnumStateMachine.class);

    TestStateMachineListener listener = new TestStateMachineListener();
    machine.addStateListener(listener);

    assertThat(machine, notNullValue());
    machine.sendEvent(MessageBuilder.withPayload(TestEvents.E1).setHeader("foo", "jee1").build());
    assertThat(listener.states.size(), is(1));
    assertThat(listener.states.get(0).from.getId(), is(TestStates.S1));
    assertThat(listener.states.get(0).to.getId(), is(TestStates.S2));
    machine.sendEvent(MessageBuilder.withPayload(TestEvents.E2).setHeader("foo", "jee2").build());
    assertThat(listener.states.size(), is(2));
    assertThat(listener.states.get(1).from.getId(), is(TestStates.S2));
    assertThat(listener.states.get(1).to.getId(), is(TestStates.S3));
    machine.sendEvent(MessageBuilder.withPayload(TestEvents.E4).setHeader("foo", "jee2").build());
    assertThat(listener.states.size(), is(2));

    ctx.close();
  }
  @Test
  public void handleMessageToClientConnectAck() {

    StompHeaderAccessor connectHeaders = StompHeaderAccessor.create(StompCommand.CONNECT);
    connectHeaders.setHeartbeat(10000, 10000);
    connectHeaders.setNativeHeader(StompHeaderAccessor.STOMP_ACCEPT_VERSION_HEADER, "1.0,1.1");
    Message<?> connectMessage =
        MessageBuilder.withPayload(new byte[0]).setHeaders(connectHeaders).build();

    SimpMessageHeaderAccessor connectAckHeaders =
        SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT_ACK);
    connectAckHeaders.setHeader(SimpMessageHeaderAccessor.CONNECT_MESSAGE_HEADER, connectMessage);
    Message<byte[]> connectAckMessage =
        MessageBuilder.withPayload(new byte[0]).setHeaders(connectAckHeaders).build();

    this.protocolHandler.handleMessageToClient(this.session, connectAckMessage);

    verifyNoMoreInteractions(this.channel);

    // Check CONNECTED reply

    assertEquals(1, this.session.getSentMessages().size());
    TextMessage textMessage = (TextMessage) this.session.getSentMessages().get(0);
    Message<?> message =
        new StompDecoder().decode(ByteBuffer.wrap(textMessage.getPayload().getBytes()));
    StompHeaderAccessor replyHeaders = StompHeaderAccessor.wrap(message);

    assertEquals(StompCommand.CONNECTED, replyHeaders.getCommand());
    assertEquals("1.1", replyHeaders.getVersion());
    assertArrayEquals(new long[] {0, 0}, replyHeaders.getHeartbeat());
    assertEquals("joe", replyHeaders.getNativeHeader("user-name").get(0));
  }
 @Test
 public void testSubscribersNotInterrupted() throws Exception {
   ConfigurableApplicationContext context =
       SpringApplication.run(TestTimeWindows.class, "--server.port=0");
   Sink sink = context.getBean(Sink.class);
   TestTimeWindows testTimeWindows = context.getBean(TestTimeWindows.class);
   sink.input().send(MessageBuilder.withPayload("hello1").build());
   sink.input().send(MessageBuilder.withPayload("hello2").build());
   sink.input().send(MessageBuilder.withPayload("hello3").build());
   assertThat(testTimeWindows.latch.await(5, TimeUnit.SECONDS)).isTrue();
   assertThat(testTimeWindows.interruptionState).isNotNull();
   assertThat(testTimeWindows.interruptionState).isFalse();
   context.close();
 }
 @Test
 @SuppressWarnings({"unchecked", "rawtypes"})
 public void testProducerListenerSet() throws Exception {
   KafkaProducerContext producerContext = new KafkaProducerContext();
   Serializer serializer = Mockito.mock(Serializer.class);
   ProducerMetadata<Object, Object> producerMetadata =
       new ProducerMetadata<>("default", Object.class, Object.class, serializer, serializer);
   Producer producer = Mockito.mock(Producer.class);
   ProducerConfiguration<Object, Object> producerConfiguration =
       new ProducerConfiguration<>(producerMetadata, producer);
   ProducerListener producerListener = mock(ProducerListener.class);
   producerConfiguration.setProducerListener(producerListener);
   Map<String, ProducerConfiguration<?, ?>> producerConfigurations =
       Collections.<String, ProducerConfiguration<?, ?>>singletonMap(
           "default", producerConfiguration);
   producerContext.setProducerConfigurations(producerConfigurations);
   KafkaProducerMessageHandler handler = new KafkaProducerMessageHandler(producerContext);
   handler.handleMessage(
       MessageBuilder.withPayload("somePayload")
           .setHeader(KafkaHeaders.PARTITION_ID, 2)
           .setHeader(KafkaHeaders.MESSAGE_KEY, "someKey")
           .build());
   final ArgumentCaptor<Callback> argument = ArgumentCaptor.forClass(Callback.class);
   verify(producer).send(any(ProducerRecord.class), argument.capture());
   Callback callback = argument.getValue();
   assertThat(callback, CoreMatchers.instanceOf(ProducerListenerInvokingCallback.class));
   DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(callback);
   assertEquals(fieldAccessor.getPropertyValue("topic"), "default");
   assertEquals(fieldAccessor.getPropertyValue("partition"), 2);
   assertEquals(fieldAccessor.getPropertyValue("key"), "someKey");
   assertEquals(fieldAccessor.getPropertyValue("payload"), "somePayload");
   assertSame(fieldAccessor.getPropertyValue("producerListener"), producerListener);
   verifyNoMoreInteractions(producer);
 }
  @Test
  public void testWithReply() throws Exception {
    QueueChannel replies = new QueueChannel();
    this.gateway1.setOutputChannel(replies);
    this.gateway1.start();
    this.gateway1.handleMessage(
        MessageBuilder.withPayload("foo")
            .setHeader(
                JmsHeaders.CORRELATION_ID,
                "baz") // make sure it's restored in case we're from an upstream gw
            .build());
    JmsTemplate template = new JmsTemplate(this.ccf);
    template.setReceiveTimeout(10000);
    final Message received = template.receive("asyncTest1");
    assertNotNull(received);
    template.send(
        received.getJMSReplyTo(),
        new MessageCreator() {

          @Override
          public Message createMessage(Session session) throws JMSException {
            TextMessage textMessage = session.createTextMessage("bar");
            textMessage.setJMSCorrelationID(received.getJMSCorrelationID());
            return textMessage;
          }
        });
    org.springframework.messaging.Message<?> reply = replies.receive(10000);
    assertNotNull(reply);
    assertEquals("bar", reply.getPayload());
    assertEquals("baz", reply.getHeaders().get(JmsHeaders.CORRELATION_ID));
    this.gateway1.stop();
  }
  @Bean
  public IntegrationFlow webSocketFlow(EchoService echoService) {
    return (IntegrationFlowDefinition<?> integrationFlowDefinition) -> {
      Function<String, Object> splitter =
          (String messagePayload) -> {

            // convert the payload
            String echoValue = echoService.echo(messagePayload);

            // for each of the active WS sessions,
            // build a Message destined for that session containing the
            // input message
            return serverWebSocketContainer()
                .getSessions()
                .keySet()
                .stream()
                .map(
                    s ->
                        MessageBuilder.withPayload(echoValue)
                            .setHeader(SimpMessageHeaderAccessor.SESSION_ID_HEADER, s)
                            .build())
                .collect(Collectors.toList());
          };

      integrationFlowDefinition
          .split(String.class, splitter)
          .channel(c -> c.executor(Executors.newCachedThreadPool()))
          .handle(webSocketOutboundAdapter());
    };
  }
Exemplo n.º 7
0
 /** {@inheritDoc} */
 @Override
 protected Message<String> launchAnalysisFlowHelp() {
   String mstr =
       "\nBabraham FastQC plugin: launch the analysis flow with given FileGroup Id.\n"
           + "wasp -T fastqc -t launchAnalysisFlowHelp -m \'{id:\"1\"}\'\n";
   return MessageBuilder.withPayload(mstr).build();
 }
  @Test
  public void resolveNonAnnotatedParameter() throws Exception {
    PublishMessage notEmptyMessage = new PublishMessage("pub", "ABC");
    assertEquals("ABC", this.resolver.resolveArgument(this.paramNotAnnotated, notEmptyMessage));

    Message<?> emptyStringMessage = MessageBuilder.withPayload("").build();
    this.thrown.expect(MethodArgumentNotValidException.class);
    this.resolver.resolveArgument(this.paramValidated, emptyStringMessage);
  }
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {

      StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT);
      headers.setAcceptVersion("1.1,1.2");
      headers.setHeartbeat(0, 0);
      Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();

      TextMessage textMessage = new TextMessage(new String(this.encoder.encode(message), UTF_8));
      session.sendMessage(textMessage);
    }
 @Test
 public void testIncrement() throws InterruptedException {
   assertNotNull(this.sink.input());
   Message<String> message = MessageBuilder.withPayload("...").build();
   sink.input().send(message);
   Thread.sleep(sleepTime);
   // Note: If the name of the counter does not start with 'counter' or 'metric' the
   // 'counter.' prefix is added
   // by the DefaultCounterService
   assertEquals(
       1, this.redisMetricRepository.findOne("counter.simpleCounter").getValue().longValue());
 }
 @Override
 public void handleException(
     StompSession session,
     StompCommand command,
     StompHeaders headers,
     byte[] payload,
     Throwable exception) {
   Message<byte[]> message =
       MessageBuilder.createMessage(
           payload, StompHeaderAccessor.create(command, headers).getMessageHeaders());
   logger.error(
       "The exception for session [" + session + "] on message [" + message + "]", exception);
 }
 @Test
 @DirtiesContext
 public void testWithTimeoutNoReplyRequired() throws Exception {
   QueueChannel errors = new QueueChannel();
   this.gateway2.setOutputChannel(errors);
   this.gateway2.setRequiresReply(false);
   this.gateway2.start();
   this.gateway2.handleMessage(MessageBuilder.withPayload("foo").setErrorChannel(errors).build());
   JmsTemplate template = new JmsTemplate(this.ccf);
   final Message received = template.receive("asyncTest3");
   assertNotNull(received);
   org.springframework.messaging.Message<?> error = errors.receive(1000);
   assertNull(error);
   this.gateway1.stop();
 }
Exemplo n.º 13
0
 @SuppressWarnings({"unchecked"})
 @Test
 public void testTriggerlessTransitionInRegions() throws Exception {
   context.register(BaseConfig.class, Config6.class);
   context.refresh();
   assertTrue(context.containsBean(StateMachineSystemConstants.DEFAULT_ID_STATEMACHINE));
   ObjectStateMachine<TestStates, TestEvents> machine =
       context.getBean(
           StateMachineSystemConstants.DEFAULT_ID_STATEMACHINE, ObjectStateMachine.class);
   machine.start();
   assertThat(machine.getState().getIds(), contains(TestStates.S1));
   machine.sendEvent(MessageBuilder.withPayload(TestEvents.E1).build());
   assertThat(
       machine.getState().getIds(),
       containsInAnyOrder(TestStates.S2, TestStates.S201, TestStates.S211));
 }
  @Test
  public void handleMessageToClientConnected() {

    UserSessionRegistry registry = new DefaultUserSessionRegistry();
    this.protocolHandler.setUserSessionRegistry(registry);

    StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECTED);
    Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
    this.protocolHandler.handleMessageToClient(this.session, message);

    assertEquals(1, this.session.getSentMessages().size());
    WebSocketMessage<?> textMessage = this.session.getSentMessages().get(0);
    assertEquals("CONNECTED\n" + "user-name:joe\n" + "\n" + "\u0000", textMessage.getPayload());

    assertEquals(Collections.singleton("s1"), registry.getSessionIds("joe"));
  }
  @Test
  @SuppressWarnings("unchecked")
  public void testReactiveMessageChannel() throws InterruptedException {
    QueueChannel replyChannel = new QueueChannel();

    for (int i = 0; i < 10; i++) {
      this.reactiveChannel.send(
          MessageBuilder.withPayload(i).setReplyChannel(replyChannel).build());
    }

    for (int i = 0; i < 10; i++) {
      Message<?> receive = replyChannel.receive(10000);
      assertNotNull(receive);
      assertThat(receive.getPayload(), isOneOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"));
    }
  }
Exemplo n.º 16
0
  /*
   * 上传完成时动作:通过spring容器发送事件消息
   *
   * @see
   * org.apache.ftpserver.ftplet.DefaultFtplet#onUploadEnd(org.apache.ftpserver
   * .ftplet.FtpSession, org.apache.ftpserver.ftplet.FtpRequest)
   */
  @Override
  public FtpletResult onUploadEnd(FtpSession session, FtpRequest request) {
    String username = session.getUser().getName();
    String input = session.getUser().getHomeDirectory() + "/" + request.getArgument();
    String homeDirectory = session.getUser().getHomeDirectory();
    /** 发送spring事件 */
    HashMap<String, String> map = new HashMap<String, String>();
    map.put("username", username);
    map.put("homeDirectory", homeDirectory);
    map.put("input", input);
    logger.debug(map);

    Message<String> message = MessageBuilder.withPayload("").copyHeaders(map).build();

    filePathChannel.send(message);

    return FtpletResult.DEFAULT;
  }
 @Test
 public void testWithTimeout() throws Exception {
   QueueChannel errors = new QueueChannel();
   this.gateway2.setOutputChannel(errors);
   this.gateway2.start();
   this.gateway2.handleMessage(MessageBuilder.withPayload("foo").setErrorChannel(errors).build());
   JmsTemplate template = new JmsTemplate(this.ccf);
   final Message received = template.receive("asyncTest3");
   assertNotNull(received);
   org.springframework.messaging.Message<?> error = errors.receive(10000);
   assertNotNull(error);
   assertThat(error, instanceOf(ErrorMessage.class));
   assertThat(error.getPayload(), instanceOf(MessagingException.class));
   assertThat(
       ((MessagingException) error.getPayload()).getCause(),
       instanceOf(JmsTimeoutException.class));
   assertEquals("foo", ((MessagingException) error.getPayload()).getFailedMessage().getPayload());
   this.gateway1.stop();
 }
 @Test
 @SuppressWarnings({"unchecked", "rawtypes"})
 public void testProducerListenerNotSet() throws Exception {
   KafkaProducerContext producerContext = new KafkaProducerContext();
   Serializer serializer = Mockito.mock(Serializer.class);
   ProducerMetadata<Object, Object> producerMetadata =
       new ProducerMetadata<>("default", Object.class, Object.class, serializer, serializer);
   Producer producer = Mockito.mock(Producer.class);
   ProducerConfiguration<Object, Object> producerConfiguration =
       new ProducerConfiguration<>(producerMetadata, producer);
   Map<String, ProducerConfiguration<?, ?>> producerConfigurations =
       Collections.<String, ProducerConfiguration<?, ?>>singletonMap(
           "default", producerConfiguration);
   producerContext.setProducerConfigurations(producerConfigurations);
   KafkaProducerMessageHandler handler = new KafkaProducerMessageHandler(producerContext);
   handler.handleMessage(MessageBuilder.withPayload("somePayload").build());
   verify(producer).send(any(ProducerRecord.class));
   verifyNoMoreInteractions(producer);
 }
 @Override
 @SuppressWarnings("unchecked")
 protected Object handleRequestMessage(Message<?> requestMessage) {
   if (Mode.embeddedHeaders.equals(mode)) {
     MessageValues messageValues;
     try {
       messageValues =
           embeddedHeadersMessageConverter.extractHeaders(
               (Message<byte[]>) requestMessage, true);
     } catch (Exception e) {
       logger.error(EmbeddedHeadersMessageConverter.decodeExceptionMessage(requestMessage), e);
       messageValues = new MessageValues(requestMessage);
     }
     messageValues = deserializePayloadIfNecessary(messageValues);
     return MessageBuilder.createMessage(
         messageValues.getPayload(), new KafkaBinderHeaders(messageValues));
   } else {
     return requestMessage;
   }
 }
  @Override
  protected void doSend(String destination, Message<?> message) {
    Assert.notNull(destination, "Destination must not be null");

    SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
    headers.setDestination(destination);
    headers.setMessageTypeIfNotSet(SimpMessageType.MESSAGE);
    message = MessageBuilder.withPayload(message.getPayload()).setHeaders(headers).build();

    long timeout = this.sendTimeout;
    boolean sent =
        (timeout >= 0)
            ? this.messageChannel.send(message, timeout)
            : this.messageChannel.send(message);

    if (!sent) {
      throw new MessageDeliveryException(
          message,
          "failed to send message to destination '" + destination + "' within timeout: " + timeout);
    }
  }
Exemplo n.º 21
0
  public Message<String> execute(Message<String> message) {

    /** 获取参数 */
    MessageHeaders headers = message.getHeaders();
    String outputPathAndOutputFileMainName =
        (String) headers.get("outputPathAndOutputFileMainName");
    String outputFileMainName = (String) headers.get("outputFileMainName");
    String username = (String) headers.get("username");
    int captureTimes = (int) headers.get("captureTimes");
    String lengthString = (String) headers.get("ID_LENGTH");
    double length = Double.parseDouble(lengthString);

    /** 处理命令行 */
    commandLine =
        parameterLine
            .replaceAll(":command:", command)
            .replaceAll(":outputPathAndOutputFileMainName:", outputPathAndOutputFileMainName)
            .replaceAll(":outputFileMainName:", outputFileMainName)
            .replaceAll(":pictureOutputPath:", pictureOutputPath)
            .replaceAll(":username:"******"";
    for (int i = 0; i < captureTimes; ++i) {
      String currentCommandLine = commandLine.replaceAll(":i:", String.valueOf(i));
      double time = i * length / captureTimes;
      currentCommandLine = currentCommandLine.replaceAll(":time:", round_half_up(time));
      newCommandLine = newCommandLine + currentCommandLine + "\n";
    }

    /** 生成新消息 */
    String payload = message.getPayload();
    Message<String> result =
        MessageBuilder.withPayload(payload + newCommandLine + "\n")
            .copyHeaders(message.getHeaders())
            .setHeader("captureTimes", captureTimes)
            .build();

    return result;
  }
Exemplo n.º 22
0
  @SuppressWarnings({"unchecked"})
  @Test
  public void testTriggerlessTransition() throws Exception {
    context.register(BaseConfig.class, Config1.class);
    context.refresh();

    assertTrue(context.containsBean(StateMachineSystemConstants.DEFAULT_ID_STATEMACHINE));
    ObjectStateMachine<TestStates, TestEvents> machine =
        context.getBean(
            StateMachineSystemConstants.DEFAULT_ID_STATEMACHINE, ObjectStateMachine.class);

    TestListener listener = new TestListener();
    machine.addStateListener(listener);

    machine.start();
    assertThat(machine.getState().getIds(), contains(TestStates.S1));

    listener.reset(2);
    machine.sendEvent(MessageBuilder.withPayload(TestEvents.E1).build());
    assertThat(listener.stateChangedLatch.await(2, TimeUnit.SECONDS), is(true));
    assertThat(listener.stateChangedCount, is(2));
    assertThat(machine.getState().getIds(), contains(TestStates.S3));
  }
Exemplo n.º 23
0
 /** {@inheritDoc} */
 @Override
 protected Message<String> helloWorldHelp() {
   String mstr = "\nBabraham FastQC plugin: hello world!\n" + "wasp -T fastqc -t helloWorld\n";
   return MessageBuilder.withPayload(mstr).build();
 }
 @RequestMapping("/echo")
 public void send(@RequestParam String name) {
   requestChannel().send(MessageBuilder.withPayload(name).build());
 }
Exemplo n.º 25
0
  /** Decode a single STOMP frame from the given {@code buffer} into a {@link Message}. */
  private Message<byte[]> decodeMessage(ByteBuffer buffer, MultiValueMap<String, String> headers) {

    Message<byte[]> decodedMessage = null;
    skipLeadingEol(buffer);
    buffer.mark();

    String command = readCommand(buffer);
    if (command.length() > 0) {

      StompHeaderAccessor headerAccessor = null;
      byte[] payload = null;

      if (buffer.remaining() > 0) {
        StompCommand stompCommand = StompCommand.valueOf(command);
        headerAccessor = StompHeaderAccessor.create(stompCommand);
        initHeaders(headerAccessor);

        readHeaders(buffer, headerAccessor);
        payload = readPayload(buffer, headerAccessor);
      }

      if (payload != null) {
        if ((payload.length > 0) && (!headerAccessor.getCommand().isBodyAllowed())) {
          throw new StompConversionException(
              headerAccessor.getCommand()
                  + " shouldn't have a payload: length="
                  + payload.length
                  + ", headers="
                  + headers);
        }
        headerAccessor.updateSimpMessageHeadersFromStompHeaders();
        headerAccessor.setLeaveMutable(true);
        decodedMessage = MessageBuilder.createMessage(payload, headerAccessor.getMessageHeaders());
        if (logger.isDebugEnabled()) {
          logger.debug("Decoded " + decodedMessage);
        }
      } else {
        if (logger.isTraceEnabled()) {
          logger.trace("Received incomplete frame. Resetting buffer.");
        }
        if (headers != null && headerAccessor != null) {
          String name = NativeMessageHeaderAccessor.NATIVE_HEADERS;
          @SuppressWarnings("unchecked")
          MultiValueMap<String, String> map =
              (MultiValueMap<String, String>) headerAccessor.getHeader(name);
          if (map != null) {
            headers.putAll(map);
          }
        }
        buffer.reset();
      }
    } else {
      if (logger.isTraceEnabled()) {
        logger.trace("Decoded heartbeat");
      }
      StompHeaderAccessor headerAccessor = StompHeaderAccessor.createForHeartbeat();
      initHeaders(headerAccessor);
      headerAccessor.setLeaveMutable(true);
      decodedMessage =
          MessageBuilder.createMessage(HEARTBEAT_PAYLOAD, headerAccessor.getMessageHeaders());
    }
    return decodedMessage;
  }