// JMSCommunicationThread
 @Override
 protected void closeProducersAndConsumers() throws Exception {
   timeout_timer.cancel();
   server_consumer.close();
   server_consumer = null;
   client_consumer.close();
   client_consumer = null;
   if (client_producer != null) {
     client_producer.close();
     client_producer = null;
   }
 }
 @Override
 public void run() {
   try {
     // Create a ConncetionFactory
     ActiveMQConnectionFactory connectionFactory =
         new ActiveMQConnectionFactory("tcp://MSPL-08-09-D158:61616");
     // Create a Connection
     Connection connection = connectionFactory.createConnection();
     connection.start();
     // Create a session
     Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
     // Create the destination (Topic or Queue)
     Destination destination = session.createQueue("HELLOWORLD.TESTQ");
     // Create a MessageProducer from the Session to the Topic or Queue
     MessageConsumer consumer = session.createConsumer(destination);
     Message message = consumer.receive(1000);
     if (message instanceof TextMessage) {
       TextMessage textMessage = (TextMessage) message;
       String text = textMessage.getText();
       System.out.println("Received : " + text);
     } else {
       System.out.println("Received : " + message);
     }
     consumer.close();
     session.close();
     connection.close();
   } catch (Exception e) {
     System.out.println("Error Occure : " + e);
     e.printStackTrace();
   }
 }
Example #3
0
 public Message receive(Scenario scenario) throws Exception {
   Connection connection = null;
   try {
     ConnectionFactory factory = new ActiveMQConnectionFactory(scenario.getBrokerUrl());
     connection = factory.createConnection();
     connection.start();
     Session session = null;
     try {
       session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge());
       ActiveMQQueue destination = new ActiveMQQueue(scenario.getOutputQueue());
       MessageConsumer consumer = null;
       try {
         consumer = session.createConsumer(destination);
         return scenario.receive(session, consumer);
       } finally {
         if (consumer != null) {
           consumer.close();
         }
       }
     } finally {
       if (session != null) {
         session.close();
       }
     }
   } finally {
     if (connection != null) {
       connection.close();
     }
   }
 }
  @Test
  public void testSendMessage() throws Exception {
    ConnectionFactory connFactory = lookup("ConnectionFactory", ConnectionFactory.class);
    Connection conn = connFactory.createConnection();
    conn.start();
    Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    TemporaryQueue replyQueue = session.createTemporaryQueue();
    TextMessage msg = session.createTextMessage("Hello world");
    msg.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);
    msg.setJMSReplyTo(replyQueue);
    Queue queue = lookup("java:jboss/" + queueName, Queue.class);
    MessageProducer producer = session.createProducer(queue);
    producer.send(msg);
    MessageConsumer consumer = session.createConsumer(replyQueue);
    Message replyMsg = consumer.receive(5000);
    Assert.assertNotNull(replyMsg);
    if (replyMsg instanceof ObjectMessage) {
      Exception e = (Exception) ((ObjectMessage) replyMsg).getObject();
      throw e;
    }
    Assert.assertTrue(replyMsg instanceof TextMessage);
    String actual = ((TextMessage) replyMsg).getText();
    Assert.assertEquals("SUCCESS", actual);

    consumer.close();
    producer.close();
    session.close();
    conn.stop();
  }
  public void testNoScheduledRedeliveryOfExpired() throws Exception {
    startBroker(true);
    ActiveMQConnection consumerConnection = (ActiveMQConnection) createConnection();
    consumerConnection.start();
    Session consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    MessageConsumer consumer = consumerSession.createConsumer(destination);
    sendMessage(1500);
    Message message = consumer.receive(1000);
    assertNotNull("got message", message);

    // ensure there is another consumer to redispatch to
    MessageConsumer redeliverConsumer = consumerSession.createConsumer(destination);

    // allow consumed to expire so it gets redelivered
    TimeUnit.SECONDS.sleep(2);
    consumer.close();

    // should go to dlq as it has expired
    // validate DLQ
    MessageConsumer dlqConsumer =
        consumerSession.createConsumer(
            new ActiveMQQueue(SharedDeadLetterStrategy.DEFAULT_DEAD_LETTER_QUEUE_NAME));
    Message dlqMessage = dlqConsumer.receive(2000);
    assertNotNull("Got message from dql", dlqMessage);
    assertEquals(
        "message matches", message.getStringProperty("data"), dlqMessage.getStringProperty("data"));
  }
 @Test
 public void testPublishBytesMessage()
     throws FileNotFoundException, JMSException, OpenJMSAdapterException {
   YamlConfigurationHolder holder =
       new YamlConfigurationHolder("C:/NetBeansProjects/openjmsadapter/test/yaml_config.yml");
   ActiveMQConnectionFactoryBuilder builder = new ActiveMQConnectionFactoryBuilder();
   OpenJMSAdapterConnection connection =
       new OpenJMSAdapterConnection(builder.getConnectionFactory(holder.getConfig()));
   connection.connect();
   connection.createQueuePublishingSession("test.queue");
   QueuePublishSession session =
       (QueuePublishSession) connection.getQueuePublishSession("test.queue");
   BytesMessage msg = session.createBytesMessage();
   msg.writeBytes("HELLO".getBytes());
   session.publish(msg);
   connection.disconnect();
   Connection conn = builder.getConnectionFactory(holder.getConfig()).createConnection();
   conn.start();
   Session receive_session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer consumer =
       receive_session.createConsumer(receive_session.createQueue("test.queue"));
   BytesMessage rx_msg = (BytesMessage) consumer.receive();
   assertNotNull(rx_msg);
   byte[] bytes = new byte[5];
   rx_msg.readBytes(bytes);
   assertTrue((new String(bytes)).equals("HELLO"));
   consumer.close();
   receive_session.close();
   conn.close();
 }
 @Test
 public void testPublishObjectMessage()
     throws FileNotFoundException, JMSException, OpenJMSAdapterException {
   YamlConfigurationHolder holder =
       new YamlConfigurationHolder("C:/NetBeansProjects/openjmsadapter/test/yaml_config.yml");
   ActiveMQConnectionFactoryBuilder builder = new ActiveMQConnectionFactoryBuilder();
   OpenJMSAdapterConnection connection =
       new OpenJMSAdapterConnection(builder.getConnectionFactory(holder.getConfig()));
   connection.connect();
   connection.createQueuePublishingSession("test.queue");
   QueuePublishSession session =
       (QueuePublishSession) connection.getQueuePublishSession("test.queue");
   ObjectMessage msg = session.createObjectMessage();
   msg.setObject(new Integer(1));
   session.publish(msg);
   connection.disconnect();
   Connection conn = builder.getConnectionFactory(holder.getConfig()).createConnection();
   conn.start();
   Session receive_session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer consumer =
       receive_session.createConsumer(receive_session.createQueue("test.queue"));
   ObjectMessage rx_msg = (ObjectMessage) consumer.receive();
   assertNotNull(rx_msg);
   assertTrue((Integer) (rx_msg.getObject()) == 1);
   consumer.close();
   receive_session.close();
   conn.close();
 }
  public void receiveMessage() {

    try {

      Connection connection = getConnection();

      connection.start();

      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Destination destination = getQueue(session);
      MessageConsumer consumer = session.createConsumer(destination);

      int i = 0;
      while (i < JMS_LOOP) {
        System.out.println("Waiting for queue message nr: " + i);
        Message message = consumer.receive();

        if (message instanceof TextMessage) {
          TextMessage textMessage = (TextMessage) message;
          String text = textMessage.getText();
          System.out.println("Queue message nr " + i + ": " + text);
        }

        i++;
      }

      consumer.close();
      session.close();
      connection.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 public void run() {
   MessageConsumer consumer = null;
   try {
     consumer =
         session.createConsumer(
             responseQueue,
             " " + TaskServiceConstants.SELECTOR_NAME + " like '" + selector + "%' ");
     ObjectMessage serverMessage = (ObjectMessage) consumer.receive();
     if (serverMessage != null) {
       ((JMSTaskClientHandler) handler)
           .messageReceived(session, readMessage(serverMessage), responseQueue, selector);
     }
   } catch (JMSException e) {
     if (!"102".equals(e.getErrorCode())) {
       throw new RuntimeException("No se pudo recibir respuesta JMS", e);
     }
     logger.info(e.getMessage());
     return;
   } catch (Exception e) {
     throw new RuntimeException("Error inesperado recibiendo respuesta JMS", e);
   } finally {
     if (consumer != null) {
       try {
         consumer.close();
       } catch (Exception e) {
         logger.info("No se pudo cerrar el consumer: " + e.getMessage());
       }
     }
   }
 }
  @Override
  public void close() throws MessengingException {
    try {
      if (producer == null) {
        synchronized (this) {
          if (producer == null) {
            producer.close();
          }
        }
      }

      if (consumer != null) {
        synchronized (this) {
          if (consumer != null) {
            consumer.close();
          }
        }
      }

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

    } catch (JMSException e) {
      throw new MessengingException(e);
    }
  }
Example #11
0
 @Override
 public void stop() {
   try {
     messageConsumer.close();
   } catch (final JMSException ignored) {
   }
   jmsManager.release();
 }
 @Override
 public void tearDown() throws Exception {
   consumer.close();
   producer.close();
   session.close();
   connection.close();
   brokerService.stop();
 }
Example #13
0
 @Override
 public void stop() {
   try {
     messageConsumer.close();
     connection.stop();
   } catch (JMSException e) {
     e.printStackTrace();
   }
 }
Example #14
0
  public void terminate() {
    try {
      consumer.close();
      session.close();
      connection.close();
    } catch (JMSException e) {

    }
  }
Example #15
0
 public static void silentClose(final MessageConsumer consumer) {
   if (consumer != null) {
     try {
       consumer.close();
     } catch (final JMSException e) {
       // Swallow this exception.
     }
   }
 }
Example #16
0
 public static void safeClose(final MessageConsumer consumer) {
   if (consumer != null) {
     try {
       consumer.close();
     } catch (final JMSException e) {
       // Propagate exception as unchecked fault up to the fault barrier.
       ThreadContext.throwFault(e);
     }
   }
 }
 protected void closeConsumer() throws Exception {
   if (consumer != null) {
     consumer.close();
     consumer = null;
     session.close();
     session = null;
     connection.close();
     connection = null;
   }
 }
  /**
   * Send some messages. Receive them in a transacted session. Commit the receiving session Close
   * the connection Create a new connection, session and consumer - verify messages are not
   * redelivered
   */
  @Test
  public void testAckCommitQueue() throws Exception {
    Connection conn = null;

    try {
      conn = createConnection();

      Session producerSess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = producerSess.createProducer(queue1);

      Session consumerSess = conn.createSession(true, Session.SESSION_TRANSACTED);
      MessageConsumer consumer = consumerSess.createConsumer(queue1);
      conn.start();

      final int NUM_MESSAGES = 10;

      // Send some messages
      for (int i = 0; i < NUM_MESSAGES; i++) {
        Message m = producerSess.createMessage();
        producer.send(m);
      }

      int count = 0;
      while (true) {
        Message m = consumer.receive(500);
        if (m == null) {
          break;
        }
        count++;
      }

      ProxyAssertSupport.assertEquals(NUM_MESSAGES, count);

      consumerSess.commit();

      conn.stop();
      consumer.close();

      conn.close();

      conn = createConnection();

      consumerSess = conn.createSession(true, Session.CLIENT_ACKNOWLEDGE);
      consumer = consumerSess.createConsumer(queue1);
      conn.start();

      Message m = consumer.receive(500);

      ProxyAssertSupport.assertNull(m);
    } finally {
      if (conn != null) {
        conn.close();
      }
    }
  }
  public static void main(String args[]) {
    Connection connection = null;

    try {
      // JNDI lookup of JMS Connection Factory and JMS Destination
      Context context = new InitialContext();
      ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME);
      Destination destination = (Destination) context.lookup(DESTINATION_NAME);

      connection = factory.createConnection();
      connection.start();

      Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
      MessageConsumer consumer = session.createConsumer(destination);

      LOG.info(
          "Start consuming messages from "
              + destination.toString()
              + " with "
              + MESSAGE_TIMEOUT_MILLISECONDS
              + "ms timeout");

      // Synchronous message consumer
      int i = 1;
      while (true) {
        Message message = consumer.receive(MESSAGE_TIMEOUT_MILLISECONDS);
        if (message != null) {
          if (message instanceof TextMessage) {
            String text = ((TextMessage) message).getText();
            LOG.info("Got " + (i++) + ". message: " + text);
          }
        } else {
          break;
        }
      }

      consumer.close();
      session.close();
    } catch (Throwable t) {
      LOG.error("Error receiving message", t);
    } finally {
      // Cleanup code
      // In general, you should always close producers, consumers,
      // sessions, and connections in reverse order of creation.
      // For this simple example, a JMS connection.close will
      // clean up all other resources.
      if (connection != null) {
        try {
          connection.close();
        } catch (JMSException e) {
          LOG.error("Error closing connection", e);
        }
      }
    }
  }
 private void consumeVerifyOrder(Session session, final int num) throws Exception {
   MessageConsumer messageConsumer = session.createConsumer(dest);
   for (int i = 0; i < num; ) {
     Message message = messageConsumer.receive(4000);
     if (message != null) {
       assertEquals(i, message.getIntProperty("Order"));
       i++;
     }
   }
   messageConsumer.close();
 }
 private String receive(Session session) throws Exception {
   MessageConsumer consumer = session.createConsumer(destination);
   String result = null;
   TextMessage message = (TextMessage) consumer.receive(5000);
   if (message != null) {
     LOG.info("got message: " + message);
     result = message.getText();
   }
   consumer.close();
   return result;
 }
 public void stop() throws JMSException {
   if (consumer != null) {
     consumer.close();
   }
   if (session != null) {
     session.close();
   }
   if (connection != null) {
     connection.close();
   }
 }
Example #23
0
  public void setUp() throws Exception, JMSException {
    super.setUp();
    _con = getConnection();
    _con.start();
    _session = _con.createSession(true, Session.SESSION_TRANSACTED);
    _destination = _session.createQueue(getTestQueueName());
    _consumer = _session.createConsumer(_destination);
    _consumer.close();

    sendMessage(_session, _destination, NUM_MESSAGES);
    _session.commit();
  }
 private int drainQueue(int max) throws Exception {
   Connection connection = cf.createConnection();
   connection.start();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer consumer = session.createConsumer(destination);
   int count = 0;
   while (count < max && consumer.receive(5000) != null) {
     count++;
   }
   consumer.close();
   connection.close();
   return count;
 }
  public void receiveMessage() {
    Properties prop = new Properties();
    prop.put(InitialContext.INITIAL_CONTEXT_FACTORY, "org.exolab.jms.jndi.InitialContextFactory");
    prop.put(InitialContext.PROVIDER_URL, "tcp://192.168.122.1:3035/");

    try {
      context = new InitialContext(prop);
      factory = (ConnectionFactory) context.lookup("ConnectionFactory");
      destination = (Destination) context.lookup("queue1");

      connection = factory.createConnection();
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      consumer = session.createConsumer(destination);
      connection.start();

      Message message = consumer.receive();
      if (message instanceof ObjectMessage) {
        ObjectMessage object = (ObjectMessage) message;
        System.out.println("Received: " + object.getObject());
      }

    } catch (NamingException e) {
      e.printStackTrace();
    } catch (JMSException e) {
      e.printStackTrace();
    }

    try {
      if (consumer != null) consumer.close();
    } catch (JMSException e) {
      e.printStackTrace();
    }

    try {
      if (session != null) session.close();
    } catch (JMSException e) {
      e.printStackTrace();
    }

    try {
      if (connection != null) connection.close();
    } catch (JMSException e) {
      e.printStackTrace();
    }

    try {
      if (context != null) context.close();
    } catch (NamingException e) {
      e.printStackTrace();
    }
  }
  /*
   * 确保资源正确关闭并释放
   */
  public synchronized void shutdownGracefully() {
    try {
      consumer.close();
      session.close();
      connection.close();
      consumer = null;
      session = null;
      destination = null;
      connection = null;
      factory = null;
    } catch (JMSException e) {

    }
  }
Example #27
0
  public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
      url = args[0].trim();
    }
    System.out.println(
        "\nWaiting to receive messages... will timeout after " + TIMEOUT / 1000 + "s");
    ActiveMQConnectionFactory connectionFactory =
        new ActiveMQConnectionFactory("admin", "password", url);
    Connection connection = null;

    try {

      connection = connectionFactory.createConnection();
      connection.start();

      Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
      Queue destination = session.createQueue("test-queue?consumer.exclusive=true");
      MessageConsumer consumer = session.createConsumer(destination);

      int i = 0;
      while (true) {
        Message message = consumer.receive(TIMEOUT);

        if (message != null) {
          if (message instanceof TextMessage) {
            String text = ((TextMessage) message).getText();
            System.out.println("Got " + i++ + ". message: " + text);
          }
        } else {
          break;
        }
      }

      consumer.close();
      session.close();

    } catch (Exception e) {
      System.out.println("Caught exception!");
    } finally {
      if (connection != null) {
        try {
          connection.close();
        } catch (JMSException e) {
          System.out.println("Could not close an open connection...");
        }
      }
    }
  }
Example #28
0
 public void close() {
   try {
     if (consumer != null) consumer.close();
     if (producer != null) producer.close();
     if (session != null) session.close();
   } catch (JMSException ex) {
   } finally {
     if (connection != null) {
       try {
         connection.close();
       } catch (JMSException ex) {
       }
     }
   }
 }
    @Override
    public void run() {

      try {
        startSignal.await();
        log.info(workerName);
        Session sess = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        MessageConsumer consumer = sess.createConsumer(queueName);
        workerStarted.countDown();

        while (true) {
          if (counters[0] == 0 && counters[1] == 0 && counters[2] == 0) {
            doneSignal.countDown();
            log.info(workerName + " done...");
            break;
          }

          Message msg = consumer.receive(500);
          if (msg == null) continue;

          msg.acknowledge();

          String group = msg.getStringProperty("JMSXGroupID");
          msg.getBooleanProperty("JMSXGroupFirstForConsumer");

          if ("A".equals(group)) {
            --counters[0];
            update(group);
          } else if ("B".equals(group)) {
            --counters[1];
            update(group);
          } else if ("C".equals(group)) {
            --counters[2];
            update(group);
          } else {
            log.warn(workerName + ", unknown group");
          }
          if (counters[0] != 0 || counters[1] != 0 || counters[2] != 0) {
            msg.acknowledge();
          }
        }
        consumer.close();
        sess.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
Example #30
0
      public void close() {

        try {
          mc.close();
        } catch (Exception e) {
        }

        try {
          session.close();
        } catch (Exception e) {
        }

        try {
          qc.close();
        } catch (Exception e) {

        }
      }