@Test(invocationCount = 5, successPercentage = 19)
  public void topicConduit() throws Exception {
    String topicName =
        "JmsByteArrayTransportTest-topicConduit-"
            + System.getProperty("user.name")
            + "-"
            + System.currentTimeMillis();
    ConnectionFactory cf = ActiveMQTestUtils.createTestConnectionFactory();
    JmsTemplate jmsTemplate = new JmsTemplate();
    jmsTemplate.setConnectionFactory(cf);
    jmsTemplate.setPubSubDomain(true);

    JmsByteArrayMessageSender messageSender = new JmsByteArrayMessageSender(topicName, jmsTemplate);
    CollectingByteArrayMessageReceiver collectingReceiver =
        new CollectingByteArrayMessageReceiver();
    JmsByteArrayMessageDispatcher messageDispatcher =
        new JmsByteArrayMessageDispatcher(collectingReceiver);

    DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
    container.setConnectionFactory(cf);
    container.setMessageListener(messageDispatcher);
    container.setDestinationName(topicName);
    container.setPubSubDomain(true);
    container.afterPropertiesSet();
    container.start();

    Random random = new Random();
    byte[] randomBytes = new byte[1024];
    random.nextBytes(randomBytes);

    while (!container.isRunning()) {
      Thread.sleep(10l);
    }
    // TODO: this is a hack.  The context doesn't seem to have always set up the consumer completely
    // yet
    Thread.sleep(500l);

    messageSender.send(randomBytes);
    long startTime = System.currentTimeMillis();
    while (collectingReceiver.getMessages().isEmpty()) {
      Thread.sleep(10l);
      if ((System.currentTimeMillis() - startTime) > TIMEOUT) {
        fail("Did not receive a message in " + (TIMEOUT / 1000) + " seconds.");
      }
    }
    s_logger.debug(
        "topicConduit message received {}ms before timeout limit",
        TIMEOUT - (System.currentTimeMillis() - startTime));
    assertEquals(1, collectingReceiver.getMessages().size());
    byte[] receivedBytes = collectingReceiver.getMessages().get(0);
    assertEquals(randomBytes.length, receivedBytes.length);
    for (int i = 0; i < randomBytes.length; i++) {
      assertEquals(randomBytes[i], receivedBytes[i]);
    }

    container.stop();
    container.destroy();
  }
  /**
   * Creates a {@link org.springframework.jms.core.JmsOperations} object used for one way messaging
   */
  public JmsOperations createInOnlyTemplate(
      JmsEndpoint endpoint, boolean pubSubDomain, String destination) {
    if (jmsOperations != null) {
      return jmsOperations;
    }

    ConnectionFactory factory = getTemplateConnectionFactory();
    JmsTemplate template = new CamelJmsTemplate(this, factory);

    template.setPubSubDomain(pubSubDomain);
    if (destinationResolver != null) {
      template.setDestinationResolver(destinationResolver);
      if (endpoint instanceof DestinationEndpoint) {
        LOG.debug(
            "You are overloading the destinationResolver property on a DestinationEndpoint; are you sure you want to do that?");
      }
    } else if (endpoint instanceof DestinationEndpoint) {
      DestinationEndpoint destinationEndpoint = (DestinationEndpoint) endpoint;
      template.setDestinationResolver(createDestinationResolver(destinationEndpoint));
    }
    template.setDefaultDestinationName(destination);

    template.setExplicitQosEnabled(isExplicitQosEnabled());
    template.setDeliveryPersistent(deliveryPersistent);
    if (messageConverter != null) {
      template.setMessageConverter(messageConverter);
    }
    template.setMessageIdEnabled(messageIdEnabled);
    template.setMessageTimestampEnabled(messageTimestampEnabled);
    if (priority >= 0) {
      template.setPriority(priority);
    }
    template.setPubSubNoLocal(pubSubNoLocal);
    if (receiveTimeout >= 0) {
      template.setReceiveTimeout(receiveTimeout);
    }
    // only set TTL if we have a positive value and it has not been disabled
    if (timeToLive >= 0 && !isDisableTimeToLive()) {
      template.setTimeToLive(timeToLive);
    }

    template.setSessionTransacted(transacted);
    if (transacted) {
      template.setSessionAcknowledgeMode(Session.SESSION_TRANSACTED);
    } else {
      // This is here for completeness, but the template should not get
      // used for receiving messages.
      if (acknowledgementMode >= 0) {
        template.setSessionAcknowledgeMode(acknowledgementMode);
      } else if (acknowledgementModeName != null) {
        template.setSessionAcknowledgeModeName(acknowledgementModeName);
      }
    }
    return template;
  }
 @Override
 public Object postProcessAfterInitialization(Object bean, String beanName)
     throws BeansException {
   if (bean.getClass().isAssignableFrom(JmsTemplate.class)) {
     JmsTemplate jmsTemplate = (JmsTemplate) bean;
     jmsTemplate.setPubSubDomain(true);
   }
   return bean;
 }
 @Override
 public void sendMessage(Notify notify) {
   jmsTemplate.setMessageConverter(messageConverter);
   jmsTemplate.setPubSubDomain(false);
   jmsTemplate.convertAndSend(testQueue, notify);
 }
Esempio n. 5
0
  @Test
  public void testUINotifyAppender() throws Exception {
    DummyFrameAction act = DummyFrameAction.INSTANCE;

    // setup JMS topic/connection/session
    String brokerURL =
        "vm://hmp-test?waitForStart=1000&broker.persistent=false&broker.deleteAllMessagesOnStartup=true";
    ConnectionFactory fact = new ActiveMQConnectionFactory(brokerURL);
    Connection conn = fact.createConnection();
    conn.start();
    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    // setup a JMS template
    JmsTemplate tpl = new JmsTemplate(fact);
    tpl.setPubSubDomain(true);
    tpl.setDefaultDestinationName("ui.notify");
    tpl.setReceiveTimeout(JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT);
    Topic dest = sess.createTopic("ui.notify");
    MessageConsumer consumer = sess.createConsumer(dest);
    assertNull(tpl.receive());

    // configure the runner
    runner.setTimeoutMS(60000); // 1m
    runner.addResource(tpl);

    // create a viewdef with a nested UINotifier viewdef that should be done in 100ms
    // the rest of the time (10x100ms) should run in parallel and be done in 200ms;
    ((DataGeneratorQuery) vd.getPrimaryQuery()).setDelay(100);
    ViewDef view = new TestViewDef();
    DataGeneratorQuery q1 = view.addQuery(new DataGeneratorQuery("id", "1st", 10, 5).setDelay(150));
    UINotifyQueryMapper q2 = view.addQuery(new UINotifyQueryMapper("subview", vd));

    // query should be done in ~150ms, rest will take another 200ms
    long start = System.currentTimeMillis();
    FrameTask task = runner.exec(view);
    RenderTask q = task.getAction(ViewRenderAction.class).getResults();
    assertTrue(task.getTotalTimeMS() <= 200); // generous fudge factor
    assertEquals(task.getTotalTimeMS(), (System.currentTimeMillis() - start), 50);

    // should return 10 placeholder values
    assertEquals(10, q.size());
    assertEquals(1, q1.execCount);
    List<String> uuids = new ArrayList<String>();
    for (int i = 0; i < q.size(); i++) {
      Object subview = q.getCellIdx(i, "subview");
      assertTrue(subview instanceof String);
      uuids.add(subview.toString());
    }

    // expecting the main task to have a single subtask (RenderTask)
    assertEquals(1, task.getSubTasks().size());
    assertTrue(task.getSubTasks().get(0) instanceof RenderTask);
    assertSame(q, task.getSubTasks().get(0));
    assertEquals(1, q.getSubTasks().size());

    // main render task has one empty subtask for the UINotifyQueryMapper
    RenderTask task2 = (RenderTask) q.getSubTasks().get(0);
    assertSame(q2, task2.getQuery());
    assertEquals(0, task2.getSubTasks().size());

    // check that the JMS topic has 10 items on it, with the corresponding UUIDs
    for (int i = 0; i < 10; i++) {
      Message msg = consumer.receive(500);
      assertNotNull(msg);
      String uuid = msg.getStringProperty("uid");
      uuids.remove(uuid);
    }
    assertNull(consumer.receiveNoWait()); // nothing left

    // vd should have been executed 10x and found all UUIDs
    DataGeneratorQuery q3 = (DataGeneratorQuery) vd.getPrimaryQuery();
    assertEquals(10, q3.execCount);
    assertEquals(0, uuids.size());
  }
  @Test(invocationCount = 5, successPercentage = 19)
  public void requestConduit() throws Exception {
    String topicName =
        "JmsByteArrayTransportTest-requestConduit-"
            + System.getProperty("user.name")
            + "-"
            + System.currentTimeMillis();
    ConnectionFactory cf = ActiveMQTestUtils.createTestConnectionFactory();
    JmsTemplate jmsTemplate = new JmsTemplate();
    jmsTemplate.setConnectionFactory(cf);
    jmsTemplate.setPubSubDomain(true);
    jmsTemplate.setReceiveTimeout(5000l);

    final Random random = new Random();
    final byte[] responseBytes = new byte[512];
    random.nextBytes(responseBytes);

    JmsByteArrayRequestSender requestSender = new JmsByteArrayRequestSender(topicName, jmsTemplate);
    JmsByteArrayRequestDispatcher requestDispatcher =
        new JmsByteArrayRequestDispatcher(
            new ByteArrayRequestReceiver() {
              @Override
              public byte[] requestReceived(byte[] message) {
                return responseBytes;
              }
            });

    DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
    container.setConnectionFactory(cf);
    container.setMessageListener(requestDispatcher);
    container.setDestinationName(topicName);
    container.setPubSubDomain(true);
    container.afterPropertiesSet();
    container.start();

    byte[] randomBytes = new byte[1024];
    random.nextBytes(randomBytes);

    while (!container.isRunning()) {
      Thread.sleep(10l);
    }

    CollectingByteArrayMessageReceiver collectingReceiver =
        new CollectingByteArrayMessageReceiver();
    requestSender.sendRequest(randomBytes, collectingReceiver);
    long startTime = System.currentTimeMillis();
    while (collectingReceiver.getMessages().isEmpty()) {
      Thread.sleep(10l);
      if ((System.currentTimeMillis() - startTime) > TIMEOUT) {
        fail("Did not receive a response in " + (TIMEOUT / 1000) + " seconds.");
      }
    }
    s_logger.debug(
        "requestConduit message received {}ms before timeout limit",
        TIMEOUT - (System.currentTimeMillis() - startTime));
    assertEquals(1, collectingReceiver.getMessages().size());
    byte[] receivedBytes = collectingReceiver.getMessages().get(0);
    assertEquals(responseBytes.length, receivedBytes.length);
    for (int i = 0; i < responseBytes.length; i++) {
      assertEquals(responseBytes[i], receivedBytes[i]);
    }

    container.stop();
    container.destroy();
  }