コード例 #1
0
ファイル: JmsContextTest.java プロジェクト: ravib777/hornetq
  @Test
  public void testDelay() throws Exception {
    JMSProducer producer = context.createProducer();

    JMSConsumer consumer = context.createConsumer(queue1);

    producer.setDeliveryDelay(500);

    long timeStart = System.currentTimeMillis();

    String strRandom = newXID().toString();

    producer.send(queue1, context.createTextMessage(strRandom));

    TextMessage msg = (TextMessage) consumer.receive(2500);

    assertNotNull(msg);

    long actualDelay = System.currentTimeMillis() - timeStart;
    assertTrue(
        "delay is not working, actualDelay=" + actualDelay,
        actualDelay >= 500 && actualDelay < 2000);

    assertEquals(strRandom, msg.getText());
  }
コード例 #2
0
ファイル: JmsContextTest.java プロジェクト: ravib777/hornetq
 @Test
 public void testSendStreamMessage() throws JMSException, InterruptedException {
   JmsProducerCompletionListenerTest.CountingCompletionListener cl =
       new JmsProducerCompletionListenerTest.CountingCompletionListener(1);
   JMSProducer producer = context.createProducer();
   producer.setAsync(cl);
   StreamMessage msg = context.createStreamMessage();
   msg.setStringProperty("name", name.getMethodName());
   String bprop = "booleanProp";
   String iprop = "intProp";
   msg.setBooleanProperty(bprop, true);
   msg.setIntProperty(iprop, 42);
   msg.writeBoolean(true);
   msg.writeInt(67);
   producer.send(queue1, msg);
   JMSConsumer consumer = context.createConsumer(queue1);
   Message msg2 = consumer.receive(100);
   Assert.assertNotNull(msg2);
   Assert.assertTrue(cl.completionLatch.await(1, TimeUnit.SECONDS));
   StreamMessage sm = (StreamMessage) cl.lastMessage;
   Assert.assertEquals(true, sm.getBooleanProperty(bprop));
   Assert.assertEquals(42, sm.getIntProperty(iprop));
   Assert.assertEquals(true, sm.readBoolean());
   Assert.assertEquals(67, sm.readInt());
 }
コード例 #3
0
ファイル: JmsContextTest.java プロジェクト: ravib777/hornetq
  @Test
  public void testRollbackTest() {
    JMSContext ctx = addContext(cf.createContext(JMSContext.SESSION_TRANSACTED));

    JMSProducer producer = ctx.createProducer();
    JMSConsumer cons = ctx.createConsumer(queue1);

    producer.send(queue1, context.createTextMessage("hello"));

    ctx.rollback();

    assertNull(cons.receiveNoWait());

    producer.send(queue1, context.createTextMessage("hello"));

    ctx.commit();

    assertNotNull(cons.receiveNoWait());

    ctx.commit();

    ctx.rollback();

    assertNull(cons.receiveNoWait());

    cons.close();
  }
コード例 #4
0
 public void onMetricsServiceReady(@Observes @ServiceReady ServiceReadyEvent event) {
   context = connectionFactory.createContext();
   gaugesConsumer = context.createConsumer(gaugesQueue);
   gaugesConsumer.setMessageListener(
       new BasicMessageListener<MetricDataMessage>() {
         @Override
         protected void onBasicMessage(MetricDataMessage basicMessage) {
           onGaugeData(basicMessage.getMetricData());
         }
       });
   countersConsumer = context.createConsumer(countersQueue);
   countersConsumer.setMessageListener(
       new BasicMessageListener<MetricDataMessage>() {
         @Override
         protected void onBasicMessage(MetricDataMessage basicMessage) {
           onCounterData(basicMessage.getMetricData());
         }
       });
   availabilityConsumer = context.createConsumer(availabilityQueue);
   availabilityConsumer.setMessageListener(
       new BasicMessageListener<AvailDataMessage>() {
         @Override
         protected void onBasicMessage(AvailDataMessage basicMessage) {
           onAvailData(basicMessage.getAvailData());
         }
       });
 }
コード例 #5
0
 public String receiveMessage() {
   try (JMSConsumer consumer = context.createConsumer(pointsQueue)) {
     String message = consumer.receiveBody(String.class);
     Logger.getLogger(ReceivePointsBean.class.getName())
         .log(Level.INFO, "Received message: " + message);
     return message;
   }
 }
コード例 #6
0
  protected static void receiveMessage(Context ctx, String destinationLookup, String expectedText)
      throws NamingException {
    ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/RemoteConnectionFactory");
    assertNotNull(cf);
    Destination destination = (Destination) ctx.lookup(destinationLookup);
    assertNotNull(destination);

    try (JMSContext context = cf.createContext("guest", "guest")) {
      JMSConsumer consumer = context.createConsumer(destination);
      String text = consumer.receiveBody(String.class, 5000);
      assertNotNull(text);
      assertEquals(expectedText, text);
    }
  }
コード例 #7
0
ファイル: JmsContextTest.java プロジェクト: ravib777/hornetq
  @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());
    }
  }
コード例 #8
0
 public static void main(String[] args) throws NamingException {
   final InitialContext ic = new InitialContext();
   ConnectionFactory factory = (ConnectionFactory) ic.lookup("jms/RemoteConnectionFactory");
   Queue queue = (Queue) ic.lookup("jms/FILA.GERADOR");
   try (JMSContext context = factory.createContext("jms", "jms2")) {
     JMSConsumer consumer = context.createConsumer(queue);
     consumer.setMessageListener(new TratadorDeMensagem());
     context.start();
     Scanner teclado = new Scanner(System.in);
     System.out.println("Tratador esperando as mensagens na fila JMS");
     teclado.nextLine();
     teclado.close();
     context.stop();
   }
 }
コード例 #9
0
ファイル: JmsContextTest.java プロジェクト: ravib777/hornetq
  @Test
  public void testContextStopAndCloseFromMessageListeners() throws Exception {
    final JMSContext context1 = context.createContext(Session.AUTO_ACKNOWLEDGE);
    JMSConsumer consumer1 = context1.createConsumer(queue1);

    final CountDownLatch latch1 = new CountDownLatch(1);

    InvalidMessageListener listener1 = new InvalidMessageListener(context1, latch1, 1);

    consumer1.setMessageListener(listener1);

    JMSProducer producer = context1.createProducer();
    Message msg = context1.createTextMessage("first message");
    producer.send(queue1, msg);

    latch1.await();

    Throwable error1 = listener1.getError();

    assertNotNull(error1);

    assertTrue(error1 instanceof IllegalStateRuntimeException);

    context1.close();

    final JMSContext context2 = context.createContext(Session.AUTO_ACKNOWLEDGE);
    JMSConsumer consumer2 = context2.createConsumer(queue1);

    final CountDownLatch latch2 = new CountDownLatch(1);

    InvalidMessageListener listener2 = new InvalidMessageListener(context2, latch2, 2);

    consumer2.setMessageListener(listener2);

    JMSProducer producer2 = context2.createProducer();
    Message msg2 = context2.createTextMessage("second message");
    producer2.send(queue1, msg2);

    latch2.await();

    Throwable error2 = listener2.getError();

    assertNotNull(error2);

    assertTrue(error2 instanceof IllegalStateRuntimeException);

    context2.close();
  }
コード例 #10
0
ファイル: JmsContextTest.java プロジェクト: ravib777/hornetq
  @Test
  public void testReceiveText() throws Exception {
    JMSProducer producer = context.createProducer();

    JMSConsumer consumer = context.createConsumer(queue1);

    String randomStr = newXID().toString();

    System.out.println("RandomStr:" + randomStr);

    TextMessage sendMsg = context.createTextMessage(randomStr);
    producer.send(queue1, sendMsg);

    TextMessage receiveMsg = (TextMessage) consumer.receiveNoWait();

    assertEquals(randomStr, receiveMsg.getText());
  }
コード例 #11
0
 private void closeQuietly(JMSConsumer jmsConsumer) {
   if (jmsConsumer != null) {
     try {
       jmsConsumer.close();
     } catch (JMSRuntimeException ignored) {
     }
   }
 }
コード例 #12
0
ファイル: JmsContextTest.java プロジェクト: ravib777/hornetq
  @Test
  public void testDeliveryMode() throws Exception {
    JMSProducer producer = context.createProducer();

    JMSConsumer consumer = context.createConsumer(queue1);

    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

    String strRandom = newXID().toString();

    producer.send(queue1, context.createTextMessage(strRandom));

    TextMessage msg = (TextMessage) consumer.receiveNoWait();

    assertNotNull(msg);

    assertEquals(DeliveryMode.NON_PERSISTENT, msg.getJMSDeliveryMode());
  }
コード例 #13
0
ファイル: JmsContextTest.java プロジェクト: ravib777/hornetq
  @Test
  public void testExpire() throws Exception {
    JMSProducer producer = context.createProducer();

    producer.setTimeToLive(500);

    String strRandom = newXID().toString();

    producer.send(queue1, context.createTextMessage(strRandom));

    Thread.sleep(700);

    // Create consumer after message is expired, making it to expire at the server's
    JMSConsumer consumer = context.createConsumer(queue1);

    TextMessage msg = (TextMessage) consumer.receiveNoWait();

    // Time to live kicked in, so it's supposed to return null
    assertNull(msg);

    strRandom = newXID().toString();

    producer.send(queue1, context.createTextMessage(strRandom));

    Thread.sleep(700);

    // Receive second message, expiring on client
    msg = (TextMessage) consumer.receiveNoWait();

    assertNull(msg);

    strRandom = newXID().toString();

    producer.send(queue1, context.createTextMessage(strRandom));

    // will receive a message that's not expired now
    msg = (TextMessage) consumer.receiveNoWait();

    assertNotNull(msg);

    assertEquals(strRandom, msg.getText());
  }
コード例 #14
0
ファイル: JmsContextTest.java プロジェクト: ravib777/hornetq
  @Test
  public void testCloseSecondContextConnectionRemainsOpen() throws JMSException {
    JMSContext localContext = context.createContext(JMSContext.CLIENT_ACKNOWLEDGE);
    Assert.assertEquals("client_ack", JMSContext.CLIENT_ACKNOWLEDGE, localContext.getSessionMode());
    JMSProducer producer = localContext.createProducer();
    JMSConsumer consumer = localContext.createConsumer(queue1);

    final int pass = 1;
    for (int idx = 0; idx < 2; idx++) {
      Message m = localContext.createMessage();
      int intProperty = random.nextInt();
      m.setIntProperty("random", intProperty);
      Assert.assertNotNull(m);
      producer.send(queue1, m);
      m = null;
      Message msg = consumer.receive(100);
      Assert.assertNotNull("must have a msg", msg);
      Assert.assertEquals(intProperty, msg.getIntProperty("random"));
      /* In the second pass we close the connection before ack'ing */
      if (idx == pass) {
        localContext.close();
      }
      /**
       * From {@code JMSContext.close()}'s javadoc:<br>
       * Invoking the {@code acknowledge} method of a received message from a closed connection's
       * session must throw an {@code IllegalStateRuntimeException}. Closing a closed connection
       * must NOT throw an exception.
       */
      try {
        msg.acknowledge();
        Assert.assertEquals("connection should be open on pass 0. It is " + pass, 0, idx);
      }
      // HORNETQ-1209 "JMS 2.0" XXX JMSContext javadoc says we must expect a
      // IllegalStateRuntimeException here. But Message.ack...() says it must throws the
      // non-runtime variant.
      catch (javax.jms.IllegalStateException expected) {
        Assert.assertEquals("we only close the connection on pass " + pass, pass, idx);
      }
    }
  }
コード例 #15
0
ファイル: JmsContextTest.java プロジェクト: ravib777/hornetq
  @Test
  public void testReceiveBytes() throws Exception {
    JMSProducer producer = context.createProducer();

    JMSConsumer consumer = context.createConsumer(queue1);

    BytesMessage bytesSend = context.createBytesMessage();
    bytesSend.writeByte((byte) 1);
    bytesSend.writeLong(2l);
    producer.send(queue1, bytesSend);

    BytesMessage msgReceived = (BytesMessage) consumer.receiveNoWait();

    byte[] bytesArray = msgReceived.getBody(byte[].class);

    assertEquals((byte) 1, msgReceived.readByte());
    assertEquals(2l, msgReceived.readLong());

    DataInputStream dataInputStream = new DataInputStream(new ByteArrayInputStream(bytesArray));

    assertEquals((byte) 1, dataInputStream.readByte());
    assertEquals(2l, dataInputStream.readLong());
  }
コード例 #16
0
 protected final void receiveMessages(
     JMSConsumer consumer, final int start, final int msgCount, final boolean ack) {
   try {
     for (int i = start; i < msgCount; i++) {
       Message message = consumer.receive(100);
       Assert.assertNotNull("Expecting a message " + i, message);
       final int actual = message.getIntProperty("counter");
       Assert.assertEquals("expected=" + i + ". Got: property['counter']=" + actual, i, actual);
       if (ack) message.acknowledge();
     }
   } catch (JMSException cause) {
     throw new JMSRuntimeException(cause.getMessage(), cause.getErrorCode(), cause);
   }
 }
コード例 #17
0
ファイル: JmsContextTest.java プロジェクト: ravib777/hornetq
 @Test
 public void testCreateConsumerWithSelector() throws JMSException {
   final String filterName = "magicIndexMessage";
   final int total = 5;
   JMSProducer producer = context.createProducer();
   JMSConsumer consumerNoSelect = context.createConsumer(queue1);
   JMSConsumer consumer = context.createConsumer(queue1, filterName + "=TRUE");
   for (int i = 0; i < total; i++) {
     Message msg = context.createTextMessage("message " + i);
     msg.setBooleanProperty(filterName, i == 3);
     producer.send(queue1, msg);
   }
   Message msg0 = consumer.receive(500);
   Assert.assertNotNull(msg0);
   msg0.acknowledge();
   Assert.assertNull("no more messages", consumer.receiveNoWait());
   for (int i = 0; i < total - 1; i++) {
     Message msg = consumerNoSelect.receive(100);
     Assert.assertNotNull(msg);
     msg.acknowledge();
   }
   Assert.assertNull("no more messages", consumerNoSelect.receiveNoWait());
 }
コード例 #18
0
  /**
   * Main method.
   *
   * @param args the destination name and type used by the example
   */
  public static void main(String[] args) {
    String destType;
    Destination dest = null;
    JMSConsumer consumer;

    if (args.length != 1) {
      System.err.println("Program takes one argument: <dest_type>");
      System.exit(1);
    }

    destType = args[0];
    System.out.println("Destination type is " + destType);

    if (!(destType.equals("queue") || destType.equals("topic"))) {
      System.err.println("Argument must be \"queue\" or \"topic\"");
      System.exit(1);
    }

    try {
      if (destType.equals("queue")) {
        dest = (Destination) queue;
      } else {
        dest = (Destination) topic;
      }
    } catch (JMSRuntimeException e) {
      System.err.println("Error setting destination: " + e.toString());
      System.exit(1);
    }

    /*
     * In a try-with-resources block, create context.
     * Create consumer.
     * Receive all text messages from destination until
     * a non-text message is received indicating end of
     * message stream.
     */
    try (JMSContext context = connectionFactory.createContext(); ) {
      consumer = context.createConsumer(dest);
      int count = 0;

      while (true) {
        Message m = consumer.receive(1000);

        if (m != null) {
          if (m instanceof TextMessage) {
            // Comment out the following two lines to receive
            // a large volume of messages
            System.out.println("Reading message: " + m.getBody(String.class));
            count += 1;
          } else {
            break;
          }
        }
      }
      System.out.println("Messages received: " + count);
    } catch (JMSException e) {
      System.err.println("Exception occurred: " + e.toString());
      System.exit(1);
    }
    System.exit(0);
  }
コード例 #19
0
 protected static void receiveMessage(JMSConsumer consumer, String expectedText)
     throws NamingException {
   String text = consumer.receiveBody(String.class, 5000);
   assertNotNull(text);
   assertEquals(expectedText, text);
 }
コード例 #20
0
ファイル: Retailer.java プロジェクト: PlamenStilyianov/JEE
  public static void main(String[] args) {
    MapMessage outMessage;
    JMSConsumer orderConfirmReceiver;
    MapMessage inMessage;

    if (args.length != 1) {
      System.out.println("Error: Program takes numerical argument.");
      System.exit(1);
    }

    quantity = (new Integer(args[0])).intValue();
    System.out.println("Retailer: Quantity to be ordered is " + quantity);
    /*
     * Create non-transacted context and sender for
     * vendor order queue.
     * Create message to vendor, setting item and
     * quantity values.
     * Send message.
     * Create receiver for retailer confirmation queue.
     * Get message and report result.
     * Send an end-of-message-stream message so vendor
     * will stop processing orders.
     */
    try (JMSContext context = connectionFactory.createContext(); ) {
      outMessage = context.createMapMessage();
      outMessage.setString("Item", "Computer(s)");
      outMessage.setInt("Quantity", quantity);
      outMessage.setJMSReplyTo(retailerConfirmQueue);
      context.createProducer().send(vendorOrderQueue, outMessage);
      System.out.println("Retailer: Ordered " + quantity + " computer(s)");

      orderConfirmReceiver = context.createConsumer(retailerConfirmQueue);
      inMessage = (MapMessage) orderConfirmReceiver.receive();

      if (inMessage.getBoolean("OrderAccepted") == true) {
        System.out.println("Retailer: Order filled");
      } else {
        System.out.println("Retailer: Order not filled");
      }

      System.out.println("Retailer: Placing another order");
      outMessage.setInt("Quantity", quantity * 2);
      context.createProducer().send(vendorOrderQueue, outMessage);
      System.out.println("Retailer: Ordered " + outMessage.getInt("Quantity") + " computer(s)");
      inMessage = (MapMessage) orderConfirmReceiver.receive();

      if (inMessage.getBoolean("OrderAccepted") == true) {
        System.out.println("Retailer: Order filled");
      } else {
        System.out.println("Retailer: Order not filled");
      }

      /*
       * Send a non-text control message indicating end
       * of messages.
       */
      context.createProducer().send(vendorOrderQueue, context.createMessage());
    } catch (JMSException e) {
      System.err.println("Retailer: Exception occurred: " + e.toString());
    }
  }
コード例 #21
0
 public String readMessage() throws JMSException {
   JMSConsumer jmsConsumer = jmsContext.createConsumer(queue);
   Message message = jmsConsumer.receive(5000);
   return message.getBody(String.class);
 }