/**
   * Send a command via JMS.
   *
   * <p>Note: Opens and closes the connection per invocation of this method which, when run outside
   * a JavaEE container, is not very efficient.
   *
   * @param command
   * @throws JMSException
   */
  public void sendCommandMessage(Command command) throws JMSException {
    Connection connection = null;
    Session session = null;
    try {
      connection = connectionFactory.createConnection();
      session = connection.createSession(TRANSACTIONAL, Session.AUTO_ACKNOWLEDGE);

      // Construct a JMS "TextMessage"
      final TextMessage newMessage = session.createTextMessage();
      newMessage.setStringProperty("issuer", command.getIssuer());
      newMessage.setStringProperty("type", command.getType());
      newMessage.setText(command.getPayload());

      // Send the message
      final MessageProducer producer = session.createProducer(this.commandQueue);
      producer.send(newMessage);

      if (TRANSACTIONAL) {
        // JavaEE containers would manage this
        session.commit();
      }
    } finally {
      if (connection != null) {
        try {
          if (session != null) {
            session.close();
          }
          connection.stop();
          connection.close();
        } catch (JMSException e) {
          e.printStackTrace();
        }
      }
    }
  }
  /**
   * test messages are acknowledged and recovered properly
   *
   * @throws Exception
   */
  public void testClientAcknowledge() throws Exception {
    Destination destination = createDestination(getClass().getName());
    Connection connection = createConnection();
    connection.setClientID(idGen.generateId());
    connection.start();
    Session consumerSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    MessageConsumer consumer = consumerSession.createConsumer(destination);
    Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = producerSession.createProducer(destination);
    producer.setDeliveryMode(deliveryMode);

    // send some messages

    TextMessage sent1 = producerSession.createTextMessage();
    sent1.setText("msg1");
    sent1.setStringProperty("str", "1");
    producer.send(sent1);

    TextMessage sent2 = producerSession.createTextMessage();
    sent2.setText("msg2");
    sent2.setStringProperty("str", "2");
    producer.send(sent2);

    TextMessage sent3 = producerSession.createTextMessage();
    sent2.setText("msg3");
    sent2.setStringProperty("str", "3");
    producer.send(sent3);

    TextMessage msgTest = (TextMessage) consumer.receive(RECEIVE_TIMEOUT);
    System.out.println("msgTest::" + msgTest + " // " + msgTest.getText());
    TextMessage rec2 = (TextMessage) consumer.receive(RECEIVE_TIMEOUT);
    System.out.println("msgTest::" + rec2 + " // " + rec2.getText());
    assertNull(consumer.receiveNoWait());

    // ack rec2
    rec2.acknowledge();

    TextMessage sent4 = producerSession.createTextMessage();
    sent4.setText("msg4");
    producer.send(sent4);

    TextMessage rec4 = (TextMessage) consumer.receive(RECEIVE_TIMEOUT);
    assertTrue(rec4.equals(sent4));
    consumerSession.recover();
    rec4 = (TextMessage) consumer.receive(RECEIVE_TIMEOUT);
    assertTrue(rec4.equals(sent4));
    assertTrue(rec4.getJMSRedelivered());
    rec4.acknowledge();
    connection.close();
  }
예제 #3
0
 public void sendMessage(String msg, String propertyName, String propertyValue)
     throws JMSException {
   MessageProducer producer = session.createProducer(queue);
   TextMessage message = session.createTextMessage(msg);
   message.setStringProperty(propertyName, propertyValue);
   producer.send(message);
 }
예제 #4
0
  public static void main(String[] args) {
    try {
      Parameters parameters = new Parameters(args);

      ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(parameters.url);
      Connection connection = connectionFactory.createConnection();
      connection.start();

      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      Topic destination = session.createTopic(parameters.topic);

      MessageProducer producer = session.createProducer(destination);
      producer.setDeliveryMode(DeliveryMode.PERSISTENT);

      String messageBody = IOUtils.toString(new FileReader(parameters.message));

      TextMessage message = session.createTextMessage(messageBody);
      message.setStringProperty("Channel", parameters.channel);
      message.setJMSExpiration(parameters.expiration);

      LOG.info("Sent message: {}", message);
      producer.send(message);

      session.close();
      connection.close();
    } catch (Exception e) {
      LOG.error("Producing interrupted", e);
    }
  }
예제 #5
0
  public void testSubscribeWithMessageSentWithProperties() throws Exception {

    String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL;
    sendFrame(frame);

    frame = receiveFrame(100000);
    Assert.assertTrue(frame.startsWith("CONNECTED"));

    frame =
        "SUBSCRIBE\n" + "destination:/queue/" + getQueueName() + "\n" + "ack:auto\n\n" + Stomp.NULL;
    sendFrame(frame);

    MessageProducer producer = session.createProducer(queue);
    TextMessage message = session.createTextMessage("Hello World");
    message.setStringProperty("s", "value");
    message.setBooleanProperty("n", false);
    message.setByteProperty("byte", (byte) 9);
    message.setDoubleProperty("d", 2.0);
    message.setFloatProperty("f", (float) 6.0);
    message.setIntProperty("i", 10);
    message.setLongProperty("l", 121);
    message.setShortProperty("s", (short) 12);
    producer.send(message);

    frame = receiveFrame(10000);
    Assert.assertTrue(frame.startsWith("MESSAGE"));

    //        System.out.println("out: "+frame);

    frame = "DISCONNECT\n" + "\n\n" + Stomp.NULL;
    sendFrame(frame);
  }
예제 #6
0
  private void writeMessage(String s) throws JMSException {

    TextMessage message = session.createTextMessage();
    message.setStringProperty("language", "java");
    message.setText(s);
    System.out.println("sending text message " + message);
    pub.publish(message);
  }
 private TextMessage createStartStreamMessage() throws JMSException {
   String streamId = UUID.randomUUID().toString();
   MDC.put(Constants.STREAM_ID, streamId);
   TextMessage message = createMessage(Constants.START_STREAM);
   message.setStringProperty(Constants.STREAM_URI, (String) MDC.get(Constants.START_STREAM));
   MDC.remove(Constants.START_STREAM);
   return message;
 }
 private void sendMessage(String jndiName) throws Exception {
   JMSManager jmsManager = new JMSManager(properties);
   TextMessage message = jmsManager.createTextMessage(jndiName, messageText);
   message.setStringProperty(propertyName, propertyValue);
   jmsManager.send(jndiName, message);
   jmsManager.stop(jndiName);
   jmsManager.close();
 }
 private TextMessage createEventMessage(LoggingEvent event, String service, String environment)
     throws JMSException {
   TextMessage message = createMessage(this.layout.format(event));
   message.setStringProperty(Constants.LEVEL, event.getLevel().toString());
   message.setLongProperty(Constants.TIME_STAMP, event.getTimeStamp());
   message.setStringProperty(
       Constants.EXCEPTION, StringUtils.join(event.getThrowableStrRep(), "\n"));
   message.setStringProperty(Constants.SERVICE, service);
   message.setStringProperty(Constants.ENVIRONMENT, environment);
   @SuppressWarnings("unchecked")
   Map<String, Object> context = MDC.getContext();
   if (context != null) {
     for (String key : context.keySet()) {
       message.setStringProperty("context." + key, MDC.get(key).toString());
     }
   }
   return message;
 }
    @Override
    protected Message createMessage(int i) throws Exception {
      TextMessage msg = createTextMessage(this.session, "Message-" + i);
      if (selectors.size() > 0) {
        String value = getRandomKey();
        msg.setStringProperty("SYMBOL", value);
        AtomicInteger currentCount = selectorCounts.get(value);
        currentCount.incrementAndGet();
      }

      return msg;
    }
  private void sendMessages(
      final Session session,
      final MessageProducer producer,
      final int numMessages,
      final boolean killServer)
      throws Exception {
    // We send half of messages
    for (int i = 0; i < numMessages / 2; i++) {
      TextMessage message = session.createTextMessage("This is text message " + i);

      // We set the duplicate detection header - so the server will ignore the same message
      // if sent again after failover

      message.setStringProperty(Message.HDR_DUPLICATE_DETECTION_ID.toString(), "uniqueid" + i);

      producer.send(message);

      System.out.println("Sent message: " + message.getText());
    }

    if (killServer) {
      Thread.sleep(2000);

      killServer(0);
    }

    // We send the remaining half of messages
    for (int i = numMessages / 2; i < numMessages; i++) {
      TextMessage message = session.createTextMessage("This is text message " + i);

      // We set the duplicate detection header - so the server will ignore the same message
      // if sent again after failover

      message.setStringProperty(Message.HDR_DUPLICATE_DETECTION_ID.toString(), "uniqueid" + i);

      producer.send(message);

      System.out.println("Sent message: " + message.getText());
    }
  }
 /**
  * Test that the <code>Message.clearProperties()</code> method deletes all the properties of the
  * Message.
  */
 @Test
 public void testClearProperties_1() {
   try {
     TextMessage message = senderSession.createTextMessage();
     message.setStringProperty("prop", "foo");
     message.clearProperties();
     Assert.assertEquals(
         "sec. 3.5.7 A message's properties are deleted by the clearProperties method.\n",
         null,
         message.getStringProperty("prop"));
   } catch (JMSException e) {
     fail(e);
   }
 }
예제 #13
0
  @Test
  public void recoverAckTest() throws Exception {
    // Create JMSContext with CLIENT_ACKNOWLEDGE

    try (JMSContext context = cf.createContext(JMSContext.CLIENT_ACKNOWLEDGE)) {
      int numMessages = 10;

      TextMessage textMessage = null;

      // Create JMSConsumer from JMSContext
      JMSConsumer consumer = context.createConsumer(queue1);

      // Create JMSProducer from JMSContext
      JMSProducer producer = context.createProducer();

      // send messages
      for (int i = 0; i < numMessages; i++) {
        String message = "text message " + i;
        textMessage = context.createTextMessage(message);
        textMessage.setStringProperty("COM_SUN_JMS_TESTNAME", "recoverAckTest" + i);
        producer.send(queue1, textMessage);
      }

      // receive messages but do not acknowledge
      for (int i = 0; i < numMessages; i++) {
        textMessage = (TextMessage) consumer.receive(5000);
        assertNotNull(textMessage);
      }

      context.recover();

      // receive messages a second time followed by acknowledge
      for (int i = 0; i < numMessages; i++) {
        textMessage = (TextMessage) consumer.receive(5000);
        assertNotNull(textMessage);
      }

      // Acknowledge all messages
      context.acknowledge();
    }

    // doing this check with another context / consumer to make sure it was acked.
    try (JMSContext context = cf.createContext(JMSContext.CLIENT_ACKNOWLEDGE)) {
      // Create JMSConsumer from JMSContext
      JMSConsumer consumer = context.createConsumer(queue1);

      assertNull(consumer.receiveNoWait());
    }
  }
 @Override
 public boolean offer(T event) throws FalconException {
   Session session;
   try {
     session = getSession();
     TextMessage msg = session.createTextMessage(event.toString());
     msg.setLongProperty(
         ScheduledMessage.AMQ_SCHEDULED_DELAY, event.getDelay(TimeUnit.MILLISECONDS));
     msg.setStringProperty("TYPE", event.getType().name());
     producer.send(msg);
     LOG.debug(
         "Enqueued Message: {} with delay {} milli sec",
         event.toString(),
         event.getDelay(TimeUnit.MILLISECONDS));
     return true;
   } catch (Exception e) {
     LOG.error("Unable to offer event: {} to ActiveMQ", event, e);
     throw new FalconException("Unable to offer event:" + event + " to ActiveMQ", e);
   }
 }
예제 #15
0
      @Override
      public void run() {

        try {

          // Loop until we've published enough messages
          while (count-- > 0) {

            TextMessage tm = session.createTextMessage(getMessageText());
            String id = UUID.randomUUID().toString();
            tm.setStringProperty("KEY", id);
            ids.add(id); // keep track of the key to compare against consumer

            mp.send(tm);
            session.commit();
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
예제 #16
0
  /**
   * Sends a command into a queue for processing
   *
   * @param queueName name of queue
   * @param command command to process
   * @param deliveryMode delivery mode: {@link javax.jms.DeliveryMode}.
   * @param priority priority of the message. Correct values are from 0 to 9, with higher number
   *     denoting a higher priority.
   * @param timeToLive the message's lifetime (in milliseconds, where 0 is to never expire)
   */
  public void send(
      String queueName, Command command, int deliveryMode, int priority, int timeToLive) {
    try {
      checkRange(deliveryMode, 1, 2, "delivery mode");
      checkRange(priority, 0, 9, "priority");
      if (timeToLive < 0) throw new HornetNestException("time to live cannot be negative");

      Queue queue = (Queue) jmsServer.lookup("/queue/" + queueName);
      if (queue == null) throw new HornetNestException("Failed to find queue: " + queueName);

      Session session = producerConnection.createSession();
      TextMessage msg = session.createTextMessage(command.toString());
      msg.setStringProperty("command_class", command.getClass().getName());
      MessageProducer p = session.createProducer(queue);
      p.send(msg, deliveryMode, priority, timeToLive);
    } catch (HornetNestException e) {
      throw e;
    } catch (Exception e) {
      throw new HornetNestException("Failed to send message", e);
    }
  }
예제 #17
0
  @Test(timeout = 60000)
  public void testSubscribeWithMessageSentWithEncodedProperties() throws Exception {

    String frame =
        "CONNECT\n"
            + "login:system\n"
            + "passcode:manager\n"
            + "accept-version:1.1"
            + "\n\n"
            + Stomp.NULL;
    stompConnection.sendFrame(frame);

    frame = stompConnection.receiveFrame();
    assertTrue(frame.startsWith("CONNECTED"));

    frame =
        "SUBSCRIBE\n"
            + "destination:/queue/"
            + getQueueName()
            + "\n"
            + "id:12345\n"
            + "ack:auto\n\n"
            + Stomp.NULL;
    stompConnection.sendFrame(frame);

    MessageProducer producer = session.createProducer(queue);
    TextMessage message = session.createTextMessage("Hello World");
    message.setStringProperty("s", "\\value:");
    producer.send(message);

    frame = stompConnection.receiveFrame();
    assertTrue("" + frame, frame.startsWith("MESSAGE"));

    int start = frame.indexOf("\ns:") + 3;
    final String expectedEncoded = "\\\\value\\c";
    final String headerVal = frame.substring(start, start + expectedEncoded.length());
    assertEquals("" + frame, expectedEncoded, headerVal);
  }
예제 #18
0
  // @Test
  public void testFetchGraphSimple() {
    try {

      String neId = "21100799";
      String group = "bw"; // interesting for the BW

      String titleX = "Bandwidth";
      String titleY = "bps";
      int timespan = 0; // Daily

      /*
      String neId = "1005255";
      String group = "cpu";    // interesting for the CPU

      String titleX = "CPU Utilization";
      String titleY = "Utilization";
      int timespan = 0;   // Daily
                */
      FetchGraphSimpleCommandMessage message =
          CommandMessageFactory.createRRDGraphSimpleCommandMessage(
              neId, group, timespan, titleX, titleY);

      MessageProducer producer = null;
      MessageConsumer consumer = null;

      try {
        // time to send the JMS request
        TextMessage reqMsg;
        Message replyMsg;

        producer = session.createProducer(new HornetQQueue(SERVICE_QUEUE));

        // this will uniquelly identify the request
        String UIID = UUID.randomUUID().toString();

        reqMsg = session.createTextMessage();
        reqMsg.setStringProperty("ServiceRRD_msg_type", "fetchGraphSimple");
        reqMsg.setStringProperty("ServiceRRD_correlation_id", UIID);

        String body = JsonUtil.getInstance().toJSON(message);

        reqMsg.setText(body);

        logger.info("SEND:\n" + body);

        producer.send(reqMsg);

        consumer =
            session.createConsumer(
                new HornetQQueue(SERVICE_REPLY_QUEUE),
                "ServiceRRD_correlation_id = '" + UIID + "'");

        replyMsg = consumer.receive(30000);

        if (replyMsg == null) {
          logger.info("ServiceRRD timeout on receive()");
        } else {
          if (replyMsg instanceof BytesMessage) {

            BytesMessage graphStream = (BytesMessage) replyMsg;

            byte[] graph = new byte[(int) graphStream.getBodyLength()];
            graphStream.readBytes(graph);

            FileOutputStream image =
                new FileOutputStream(
                    "/Users/cvasilak/Temp/svc-rrd-images/"
                        + neId
                        + "_"
                        + group
                        + "_"
                        + timespan
                        + ".png");

            image.write(graph);
            image.close();

            logger.info("image retrieved and saved!");

          } else if (replyMsg instanceof TextMessage) { // the server responded with an error
            logger.info(((TextMessage) replyMsg).getText());
          }
        }

      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        try {
          if (producer != null) producer.close();
          if (consumer != null) consumer.close();
        } catch (JMSException e) {
        }
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
예제 #19
0
  private void propertiesPreserved(boolean persistent, boolean messageIDInHeader) throws Exception {
    BridgeImpl bridge = null;

    Connection connSource = null;

    Connection connTarget = null;

    try {
      final int NUM_MESSAGES = 10;

      bridge =
          new BridgeImpl(
              cff0,
              cff1,
              sourceQueueFactory,
              targetQueueFactory,
              null,
              null,
              null,
              null,
              null,
              5000,
              10,
              QualityOfServiceMode.AT_MOST_ONCE,
              1,
              -1,
              null,
              null,
              messageIDInHeader);

      bridge.start();

      connSource = cf0.createConnection();

      connTarget = cf1.createConnection();

      log.trace("Sending " + NUM_MESSAGES + " messages");

      Session sessSource = connSource.createSession(false, Session.AUTO_ACKNOWLEDGE);

      Session sessTarget = connTarget.createSession(false, Session.AUTO_ACKNOWLEDGE);

      MessageConsumer cons = sessTarget.createConsumer(targetQueue);

      connTarget.start();

      MessageProducer prod = sessSource.createProducer(sourceQueue);

      prod.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);

      TextMessage tm = sessSource.createTextMessage("blahmessage");

      prod.setPriority(7);

      prod.setTimeToLive(1 * 60 * 60 * 1000);

      prod.send(tm);

      long expiration = tm.getJMSExpiration();

      assertEquals(
          persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT,
          tm.getJMSDeliveryMode());

      tm = (TextMessage) cons.receive(1000);

      assertNotNull(tm);

      assertEquals("blahmessage", tm.getText());

      assertEquals(
          persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT,
          tm.getJMSDeliveryMode());

      assertEquals(7, tm.getJMSPriority());

      assertTrue(Math.abs(expiration - tm.getJMSExpiration()) < 100);

      Message m = cons.receive(5000);

      assertNull(m);

      // Now do one with expiration = 0

      tm = sessSource.createTextMessage("blahmessage2");

      prod.setPriority(7);

      prod.setTimeToLive(0);

      prod.send(tm);

      assertEquals(
          persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT,
          tm.getJMSDeliveryMode());

      tm = (TextMessage) cons.receive(1000);

      assertNotNull(tm);

      assertEquals("blahmessage2", tm.getText());

      assertEquals(
          persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT,
          tm.getJMSDeliveryMode());

      assertEquals(7, tm.getJMSPriority());

      assertEquals(0, tm.getJMSExpiration());

      m = cons.receive(5000);

      assertNull(m);

      tm = sessSource.createTextMessage("blahmessage3");

      final boolean myBool = false;
      final byte myByte = (byte) 23;
      final double myDouble = 17625765d;
      final float myFloat = 87127.23f;
      final int myInt = 123;
      final long myLong = 81728712;
      final short myShort = (short) 88;
      final String myString = "ojweodewj";
      final String myJMSX = "aardvark";

      tm.setBooleanProperty("mybool", myBool);
      tm.setByteProperty("mybyte", myByte);
      tm.setDoubleProperty("mydouble", myDouble);
      tm.setFloatProperty("myfloat", myFloat);
      tm.setIntProperty("myint", myInt);
      tm.setLongProperty("mylong", myLong);
      tm.setShortProperty("myshort", myShort);
      tm.setStringProperty("mystring", myString);

      tm.setStringProperty("JMSXMyNaughtyJMSXProperty", myJMSX);

      prod.send(tm);

      tm = (TextMessage) cons.receive(1000);

      assertNotNull(tm);

      assertEquals("blahmessage3", tm.getText());

      assertEquals(myBool, tm.getBooleanProperty("mybool"));
      assertEquals(myByte, tm.getByteProperty("mybyte"));
      assertEquals(myDouble, tm.getDoubleProperty("mydouble"));
      assertEquals(myFloat, tm.getFloatProperty("myfloat"));
      assertEquals(myInt, tm.getIntProperty("myint"));
      assertEquals(myLong, tm.getLongProperty("mylong"));
      assertEquals(myShort, tm.getShortProperty("myshort"));
      assertEquals(myString, tm.getStringProperty("mystring"));
      assertEquals(myJMSX, tm.getStringProperty("JMSXMyNaughtyJMSXProperty"));

      m = cons.receive(5000);

    } finally {
      if (bridge != null) {
        bridge.stop();
      }

      if (connSource != null) {
        connSource.close();
      }

      if (connTarget != null) {
        connTarget.close();
      }
    }
  }
예제 #20
0
  private void messageIDInHeader(boolean on) throws Exception {
    BridgeImpl bridge = null;

    Connection connSource = null;

    Connection connTarget = null;

    try {
      final int NUM_MESSAGES = 10;

      bridge =
          new BridgeImpl(
              cff0,
              cff1,
              sourceQueueFactory,
              targetQueueFactory,
              null,
              null,
              null,
              null,
              null,
              5000,
              10,
              QualityOfServiceMode.AT_MOST_ONCE,
              1,
              -1,
              null,
              null,
              on);

      bridge.start();

      connSource = cf0.createConnection();

      connTarget = cf1.createConnection();

      log.trace("Sending " + NUM_MESSAGES + " messages");

      List ids1 = new ArrayList();

      Session sessSource = connSource.createSession(false, Session.AUTO_ACKNOWLEDGE);

      MessageProducer prod = sessSource.createProducer(sourceQueue);

      for (int i = 0; i < NUM_MESSAGES; i++) {
        TextMessage tm = sessSource.createTextMessage("message" + i);

        // We add some headers to make sure they get passed through ok
        tm.setStringProperty("wib", "uhuh");
        tm.setBooleanProperty("cheese", true);
        tm.setIntProperty("Sausages", 23);

        // We add some JMSX ones too

        tm.setStringProperty("JMSXGroupID", "mygroup543");
        tm.setIntProperty("JMSXGroupSeq", 777);

        prod.send(tm);

        ids1.add(tm.getJMSMessageID());
      }

      log.trace("Sent the first messages");

      Session sessTarget = connTarget.createSession(false, Session.AUTO_ACKNOWLEDGE);

      MessageConsumer cons = sessTarget.createConsumer(targetQueue);

      connTarget.start();

      List msgs = new ArrayList();

      for (int i = 0; i < NUM_MESSAGES; i++) {
        TextMessage tm = (TextMessage) cons.receive(5000);

        assertNotNull(tm);

        assertEquals("message" + i, tm.getText());

        assertEquals("uhuh", tm.getStringProperty("wib"));
        assertTrue(tm.getBooleanProperty("cheese"));
        assertEquals(23, tm.getIntProperty("Sausages"));

        assertEquals("mygroup543", tm.getStringProperty("JMSXGroupID"));
        assertEquals(777, tm.getIntProperty("JMSXGroupSeq"));

        if (on) {
          String header = tm.getStringProperty(JBossMessage.JBOSS_MESSAGING_BRIDGE_MESSAGE_ID_LIST);

          assertNotNull(header);

          assertEquals(ids1.get(i), header);

          msgs.add(tm);
        }
      }

      if (on) {
        // Now we send them again back to the source

        Iterator iter = msgs.iterator();

        List ids2 = new ArrayList();

        while (iter.hasNext()) {
          Message msg = (Message) iter.next();

          prod.send(msg);

          ids2.add(msg.getJMSMessageID());
        }

        // And consume them again

        for (int i = 0; i < NUM_MESSAGES; i++) {
          TextMessage tm = (TextMessage) cons.receive(5000);

          assertNotNull(tm);

          assertEquals("message" + i, tm.getText());

          assertEquals("uhuh", tm.getStringProperty("wib"));
          assertTrue(tm.getBooleanProperty("cheese"));
          assertEquals(23, tm.getIntProperty("Sausages"));

          assertEquals("mygroup543", tm.getStringProperty("JMSXGroupID"));
          assertEquals(777, tm.getIntProperty("JMSXGroupSeq"));

          String header = tm.getStringProperty(JBossMessage.JBOSS_MESSAGING_BRIDGE_MESSAGE_ID_LIST);

          assertNotNull(header);

          assertEquals(ids1.get(i) + "," + ids2.get(i), header);
        }
      }

    } finally {
      if (bridge != null) {
        bridge.stop();
      }

      if (connSource != null) {
        connSource.close();
      }

      if (connTarget != null) {
        connTarget.close();
      }
    }
  }
예제 #21
0
  public void testSelector() throws Exception {
    BridgeImpl bridge = null;

    Connection connSource = null;

    Connection connTarget = null;

    try {
      final int NUM_MESSAGES = 10;

      String selector = "vegetable='radish'";

      bridge =
          new BridgeImpl(
              cff0,
              cff1,
              sourceQueueFactory,
              targetQueueFactory,
              null,
              null,
              null,
              null,
              selector,
              5000,
              10,
              QualityOfServiceMode.AT_MOST_ONCE,
              1,
              -1,
              null,
              null,
              false);

      bridge.start();

      connSource = cf0.createConnection();

      Session sessSend = connSource.createSession(false, Session.AUTO_ACKNOWLEDGE);

      MessageProducer prod = sessSend.createProducer(sourceQueue);

      for (int i = 0; i < NUM_MESSAGES; i++) {
        TextMessage tm = sessSend.createTextMessage("message" + i);

        if (i >= NUM_MESSAGES / 2) {
          tm.setStringProperty("vegetable", "radish");
        } else {
          tm.setStringProperty("vegetable", "cauliflower");
        }

        prod.send(tm);
      }

      connTarget = cf1.createConnection();

      Session sessRec = connTarget.createSession(false, Session.AUTO_ACKNOWLEDGE);

      MessageConsumer cons = sessRec.createConsumer(targetQueue);

      connTarget.start();

      for (int i = NUM_MESSAGES / 2; i < NUM_MESSAGES; i++) {
        TextMessage tm = (TextMessage) cons.receive(1000);

        assertNotNull(tm);

        assertEquals("message" + i, tm.getText());
      }

      Message m = cons.receive(1000);

      assertNull(m);

    } finally {
      if (connSource != null) {
        connSource.close();
      }

      if (connTarget != null) {
        connTarget.close();
      }

      if (bridge != null) {
        bridge.stop();
      }

      removeAllMessages(sourceQueue.getQueueName(), true, 0);
    }
  }
예제 #22
0
  @Test
  public void testFetchLast() {
    try {

      String neId =
          "1005255"; // KLNNMS02(cpuusage=YES cpu1min=YES memutil=YES) KLNNMS05(cpuusage=YES
                     // bususage=YES)
      // String neId = "1006119";    // KLNNMS02(cpuusage=YES cpu1min=YES memutil=YES
      // KLNNMS05(cpuusage=NO bususage=NO)

      Set<String> rras = new HashSet<String>();
      // klnnms02
      rras.add("cpu5sec");
      rras.add("cpu1min");
      rras.add("memutil");

      // klnnms05
      rras.add("cpuusage");
      rras.add("bususage");

      FetchLastCommandMessage message =
          CommandMessageFactory.createRRDLastCommandMessage(neId, "AVERAGE", 0, 0, null, rras);

      MessageProducer producer = null;
      MessageConsumer consumer = null;

      // time to send the JMS request
      try {
        TextMessage reqMsg, replyMsg;

        producer = session.createProducer(new HornetQQueue(SERVICE_QUEUE));

        // this will uniquelly identify the request
        String UIID = UUID.randomUUID().toString();

        reqMsg = session.createTextMessage();
        reqMsg.setStringProperty("ServiceRRD_msg_type", "fetchLast");
        reqMsg.setStringProperty("ServiceRRD_correlation_id", UIID);

        String body = JsonUtil.getInstance().toJSON(message);

        reqMsg.setText(body);

        logger.info("SEND:\n" + body);

        producer.send(reqMsg);

        consumer =
            session.createConsumer(
                new HornetQQueue(SERVICE_REPLY_QUEUE),
                "ServiceRRD_correlation_id = '" + UIID + "'");

        replyMsg = (TextMessage) consumer.receive(30000);

        if (replyMsg == null) {
          logger.info("ServiceRRD timeout on receive()");
        } else {
          logger.info("REPLY:\n" + replyMsg.getText());
        }

      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        try {
          if (producer != null) producer.close();
          if (consumer != null) consumer.close();
        } catch (JMSException e) {
        }
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
예제 #23
0
  /** Create JMS client for publishing and subscribing to messages. */
  private void chatter(String broker, String username, String password, String selection) {

    // Create a connection.
    try {
      javax.jms.ConnectionFactory factory;
      factory = new ActiveMQConnectionFactory(username, password, broker);
      connect = factory.createConnection(username, password);
      pubSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
      subSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
    } catch (javax.jms.JMSException jmse) {
      System.err.println("error: Cannot connect to Broker - " + broker);
      jmse.printStackTrace();
      System.exit(1);
    }

    // Create Publisher and Subscriber to 'chat' topics

    try {
      javax.jms.Topic topic = pubSession.createTopic(APP_TOPIC);
      // NOTE: The subscriber's message selector will now be set:
      javax.jms.MessageConsumer subscriber =
          subSession.createConsumer(topic, PROPERTY_NAME + " = \'" + selection + "\'", false);
      subscriber.setMessageListener(this);
      publisher = pubSession.createProducer(topic);
      // Now that setup is complete, start the Connection
      connect.start();
    } catch (javax.jms.JMSException jmse) {
      jmse.printStackTrace();
      System.exit(1);
    }

    try {
      // Read all standard input and send it as a message.

      java.io.BufferedReader stdin =
          new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
      System.out.println(
          "\nSelectorChat application:\n"
              + "===========================\n"
              + "The application user "
              + username
              + " connects to the broker at "
              + DEFAULT_BROKER_NAME
              + ".\n"
              + "The application will publish messages with "
              + PROPERTY_NAME
              + " set to "
              + selection
              + " to the "
              + APP_TOPIC
              + " topic .\n"
              + "The application also subscribes to that topic, selecting only messages where "
              + PROPERTY_NAME
              + " is "
              + selection
              + ".\n"
              + "Type some text, and then press Enter to publish it as a TextMesssage from "
              + username
              + ".\n");

      while (true) {
        String s = stdin.readLine();

        if (s == null) exit();
        else if (s.length() > 0) {
          javax.jms.TextMessage msg = pubSession.createTextMessage();
          msg.setText(username + ": " + s);
          // NOTE: here we set a property on messages to be published:
          msg.setStringProperty(PROPERTY_NAME, selection);
          publisher.send(msg);
        }
      }
    } catch (java.io.IOException ioe) {
      ioe.printStackTrace();
    } catch (javax.jms.JMSException jmse) {
      jmse.printStackTrace();
    }
  }
예제 #24
0
  /**
   * This method establishes a connection to the ESB and also Instantiates a producer which can
   * deliver messages to the "ctms-caaers.inputQueue".
   */
  public static void main(String[] args) {

    // Required fields
    ConnectionFactory connectionFactory = null;
    Connection connection = null;
    Session session = null;
    MessageProducer producer = null;
    StringBuilder contents = new StringBuilder();
    BufferedReader input = null;
    File xmlFile = null;

    ActiveMQConnectionFactory mqConnectionFactory = new ActiveMQConnectionFactory();
    // Queue Instantiated with the Queue name from the ESB.
    ActiveMQQueue sendQueue = new ActiveMQQueue("ctms-caaers.inputQueue");

    try {
      // Connection to the ESB.
      mqConnectionFactory.setBrokerURL("tcp://localhost:61616");
      connectionFactory = mqConnectionFactory;
      connection = connectionFactory.createConnection();

      // Obtaining a Session.
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      // Instance of producer configured to deliver JMS Messages to the ""ctms-caaers.inputQueue"
      // Queue
      producer = session.createProducer(sendQueue);

      // For testing purpose the Study/Participant Xml is read from the file system.
      // In reality the Local Ctms System generates this Study/Participant Xml Message.
      xmlFile =
          getResources("classpath*:gov/nih/nci/cabig/caaers/impl/studydata/CreateStudyTest.xml")[0]
              .getFile();

      // Reading the File Contents into Memory.
      input = new BufferedReader(new FileReader(xmlFile));
      String line = null;
      while ((line = input.readLine()) != null) {
        contents.append(line);
      }

      // Create anew JMS TextMessage
      TextMessage message = session.createTextMessage();

      // Here a sample ID is used. In reality the Local Ctms System has to have a
      // process to generate unique ID's.
      message.setJMSCorrelationID("103");

      // Since this sample dealing with creating a Study in caaers the MESSAGE_TYPE is CREATE_STUDY.
      // If we need to update an existing Study in caaers then we have to set the MESSAGE_TYPE to
      // UPDATE_STUDY.
      message.setStringProperty("MESSAGE_TYPE", "CREATE_STUDY");

      /*
      message.setStringProperty("MESSAGE_TYPE", "UPDATE_STUDY");
      message.setStringProperty("MESSAGE_TYPE", "CREATE_PARTICIPANT");
      message.setStringProperty("MESSAGE_TYPE", "UPDATE_PARTICIPANT");
      message.setStringProperty("MESSAGE_TYPE", "CREATE_INVESTIGATOR");
      message.setStringProperty("MESSAGE_TYPE", "UPDATE_INVESTIGATOR");
      message.setStringProperty("MESSAGE_TYPE", "CREATE_RESEARCHSTAFF");
      message.setStringProperty("MESSAGE_TYPE", "UPDATE_RESEARCHSTAFF");
      */

      // Setting the File Contents in memory as the PayLoad of the JMS TextMessage.
      message.setText(contents.toString());

      // Call to deliver the JMS Message to the Queue.
      producer.send(message);

      // Close
      producer.close();

    } catch (Exception e) {
      System.out.println(e.getMessage());
    } finally {
      try {
        if (input != null) {
          input.close();
        }
        if (connection != null) {
          connection.close();
        }

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
예제 #25
0
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {

    res.setContentType("text/html");
    java.io.PrintWriter out = res.getWriter();
    // use a stringbuffer to avoid concatenation of Strings
    StringBuffer output = new StringBuffer(100);
    output.append(
        "<html><head><title>PingServlet2MDBQueue</title></head>"
            + "<body><HR><FONT size=\"+2\" color=\"#000066\">PingServlet2MDBQueue<BR></FONT>"
            + "<FONT size=\"-1\" color=\"#000066\">"
            + "Tests the basic operation of a servlet posting a message to an EJB MDB through a JMS Queue.<BR>"
            + "<FONT color=\"red\"><B>Note:</B> Not intended for performance testing.</FONT>");

    try {
      if (queueConnectionFactory == null) {
        queueConnectionFactory =
            (ConnectionFactory) new InitialContext().lookup("ConnectionFactory");
      }
      Connection conn = queueConnectionFactory.createConnection();

      if (tradeBrokerQueue == null) {
        tradeBrokerQueue =
            (Queue) new InitialContext().lookup("java:comp/env/jms/TradeBrokerQueue");
      }

      try {
        TextMessage message = null;
        int iter = TradeConfig.getPrimIterations();
        for (int ii = 0; ii < iter; ii++) {
          Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
          try {
            MessageProducer producer = sess.createProducer(tradeBrokerQueue);

            message = sess.createTextMessage();

            String command = "ping";
            message.setStringProperty("command", command);
            message.setLongProperty("publishTime", System.currentTimeMillis());
            message.setText(
                "Ping message for queue java:comp/env/jms/TradeBrokerQueue sent from PingServlet2MDBQueue at "
                    + new java.util.Date());
            producer.send(message);
          } finally {
            sess.close();
          }
        }

        // write out the output
        output.append("<HR>initTime: ").append(initTime);
        output.append("<BR>Hit Count: ").append(hitCount++);
        output.append("<HR>Posted Text message to java:comp/env/jms/TradeBrokerQueue destination");
        output.append("<BR>Message: ").append(message);
        output.append("<BR><BR>Message text: ").append(message.getText());
        output.append("<BR><HR></FONT></BODY></HTML>");
        out.println(output.toString());

      } catch (Exception e) {
        Log.error(
            "PingServlet2MDBQueue.doGet(...):exception posting message to TradeBrokerQueue destination ");
        throw e;
      } finally {
        conn.close();
      }
    } // this is where I actually handle the exceptions
    catch (Exception e) {
      Log.error(e, "PingServlet2MDBQueue.doGet(...): error");
      res.sendError(500, "PingServlet2MDBQueue.doGet(...): error, " + e.toString());
    }
  }
예제 #26
0
  public void testNoMessageIDInHeader() throws Exception {
    BridgeImpl bridge = null;

    Connection connSource = null;

    Connection connTarget = null;

    try {
      final int NUM_MESSAGES = 10;

      bridge =
          new BridgeImpl(
              cff0,
              cff1,
              sourceQueueFactory,
              targetQueueFactory,
              null,
              null,
              null,
              null,
              null,
              5000,
              10,
              QualityOfServiceMode.AT_MOST_ONCE,
              1,
              -1,
              null,
              null,
              false);

      bridge.start();

      connSource = cf0.createConnection();

      connTarget = cf1.createConnection();

      log.trace("Sending " + NUM_MESSAGES + " messages");

      Session sessSource = connSource.createSession(false, Session.AUTO_ACKNOWLEDGE);

      MessageProducer prod = sessSource.createProducer(sourceQueue);

      for (int i = 0; i < NUM_MESSAGES; i++) {
        TextMessage tm = sessSource.createTextMessage("message" + i);

        // We add some headers to make sure they get passed through ok
        tm.setStringProperty("wib", "uhuh");
        tm.setBooleanProperty("cheese", true);
        tm.setIntProperty("Sausages", 23);

        prod.send(tm);
      }

      log.trace("Sent the first messages");

      Session sessTarget = connTarget.createSession(false, Session.AUTO_ACKNOWLEDGE);

      MessageConsumer cons = sessTarget.createConsumer(targetQueue);

      connTarget.start();

      for (int i = 0; i < NUM_MESSAGES; i++) {
        TextMessage tm = (TextMessage) cons.receive(5000);

        assertNotNull(tm);

        assertEquals("message" + i, tm.getText());

        assertEquals("uhuh", tm.getStringProperty("wib"));
        assertTrue(tm.getBooleanProperty("cheese"));
        assertEquals(23, tm.getIntProperty("Sausages"));

        String header = tm.getStringProperty(JBossMessage.JBOSS_MESSAGING_BRIDGE_MESSAGE_ID_LIST);

        assertNull(header);
      }
    } finally {
      if (bridge != null) {
        bridge.stop();
      }

      if (connSource != null) {
        connSource.close();
      }

      if (connTarget != null) {
        connTarget.close();
      }
    }
  }