public void testWithConnectionFactoryAndExceptionListenerAndReconnectOnException()
      throws JMSException {
    MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
    ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
    TestConnection con = new TestConnection();

    TestExceptionListener listener = new TestExceptionListener();
    cf.createConnection();
    cfControl.setReturnValue(con, 2);
    cfControl.replay();

    SingleConnectionFactory scf = new SingleConnectionFactory(cf);
    scf.setExceptionListener(listener);
    scf.setReconnectOnException(true);
    Connection con1 = scf.createConnection();
    assertSame(listener, con1.getExceptionListener());
    con1.start();
    con.getExceptionListener().onException(new JMSException(""));
    Connection con2 = scf.createConnection();
    con2.start();
    scf.destroy(); // should trigger actual close

    cfControl.verify();
    assertEquals(2, con.getStartCount());
    assertEquals(2, con.getCloseCount());
    assertEquals(1, listener.getCount());
  }
  public void testWithConnection() throws JMSException {
    MockControl conControl = MockControl.createControl(Connection.class);
    Connection con = (Connection) conControl.getMock();

    con.start();
    conControl.setVoidCallable(1);
    con.stop();
    conControl.setVoidCallable(1);
    con.close();
    conControl.setVoidCallable(1);

    conControl.replay();

    SingleConnectionFactory scf = new SingleConnectionFactory(con);
    Connection con1 = scf.createConnection();
    con1.start();
    con1.stop(); // should be ignored
    con1.close(); // should be ignored
    Connection con2 = scf.createConnection();
    con2.start(); // should be ignored
    con2.stop(); // should be ignored
    con2.close(); // should be ignored
    scf.destroy(); // should trigger actual close

    conControl.verify();
  }
  public void testWithConnectionFactoryAndClientId() throws JMSException {
    MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
    ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
    MockControl conControl = MockControl.createControl(Connection.class);
    Connection con = (Connection) conControl.getMock();

    cf.createConnection();
    cfControl.setReturnValue(con, 1);
    con.setClientID("myId");
    conControl.setVoidCallable(1);
    con.start();
    conControl.setVoidCallable(1);
    con.stop();
    conControl.setVoidCallable(1);
    con.close();
    conControl.setVoidCallable(1);

    cfControl.replay();
    conControl.replay();

    SingleConnectionFactory scf = new SingleConnectionFactory(cf);
    scf.setClientId("myId");
    Connection con1 = scf.createConnection();
    con1.start();
    con1.close(); // should be ignored
    Connection con2 = scf.createConnection();
    con2.start();
    con2.close(); // should be ignored
    scf.destroy(); // should trigger actual close

    cfControl.verify();
    conControl.verify();
  }
Ejemplo n.º 4
0
  protected void setUp() throws Exception {
    super.setUp();

    // Create Client
    _clientConnection = getConnection("guest", "guest");

    _clientConnection.start();

    Session clientSession = _clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    Queue queue = clientSession.createQueue("message-listener-test-queue");

    _consumer = clientSession.createConsumer(queue);

    // Create Producer

    Connection producerConnection = getConnection("guest", "guest");

    producerConnection.start();

    Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    MessageProducer producer = producerSession.createProducer(queue);

    for (int msg = 0; msg < MSG_COUNT; msg++) {
      producer.send(producerSession.createTextMessage("Message " + msg));
    }

    producerConnection.close();
  }
  public void testRun() {

    // http://pookey.co.uk/wordpress/archives/74-playing-with-activemq-using-maven
    // http://java.sun.com/developer/technicalArticles/Ecommerce/jms/index.html

    String brokerURL = "tcp://localhost:61616";

    ConnectionFactory factory;
    Connection connection;
    Session session;
    MessageProducer producer;

    final String fedoraAppEmailQueue = FedoraAppConstants.JMS_ECTD_RESULTS_Q;

    String string_1 =
        "/home/chet/batch_space/codu/ectd/logs/codu.ectd.april-08-2011_17:15:36-297.txt"; // ingest
    // report
    String string_2 =
        "/home/chet/batch_space/codu/ectd/logs/codu.ectd.april-08-2011_17:15:36-297.csv"; // pid
    // report

    try {
      factory = new ActiveMQConnectionFactory(brokerURL);

      connection = factory.createConnection();
      connection.start();
      session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

      System.out.println("\n\n** session transactions is set to :" + session.getTransacted());

      // send message

      Destination destination = session.createQueue(fedoraAppEmailQueue);
      producer = session.createProducer(destination);

      System.out.println("Creating Message ");
      Message message = session.createTextMessage(string_1 + "\n" + string_2 + "\n");
      producer.send(message);
      connection.close();

      // consume message
      connection = factory.createConnection();
      connection.start();
      session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
      destination = session.createQueue(fedoraAppEmailQueue);
      MessageConsumer consumer = session.createConsumer(destination);
      consumer.setMessageListener(null);
      consumer.setMessageListener(new ActiveMQListener());

      for (int i = 1; i < 10000000; i++) {
        System.out.println("looping");
      }
    } catch (Exception e) {
      System.out.println("Exception: " + e.getMessage());
    }
  } // testRun
  @Test
  public void testSendnReceiveAuthorization() throws Exception {
    Connection sendingConn = null;
    Connection receivingConn = null;

    // Sender
    try {
      Destination dest = new ActiveMQQueue(queueName);

      receivingConn = factory.createConnection("openwireReceiver", "ReCeIvEr");
      receivingConn.start();

      sendingConn = factory.createConnection("openwireSender", "SeNdEr");
      sendingConn.start();

      Session sendingSession = sendingConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Session receivingSession = receivingConn.createSession(false, Session.AUTO_ACKNOWLEDGE);

      TextMessage message = sendingSession.createTextMessage("Hello World");

      MessageProducer producer = null;

      producer = receivingSession.createProducer(dest);

      try {
        producer.send(message);
      } catch (JMSSecurityException e) {
        // expected
        producer.close();
      }

      producer = sendingSession.createProducer(dest);
      producer.send(message);

      MessageConsumer consumer = null;
      try {
        consumer = sendingSession.createConsumer(dest);
      } catch (JMSSecurityException e) {
        // expected
      }

      consumer = receivingSession.createConsumer(dest);
      TextMessage received = (TextMessage) consumer.receive();

      assertNotNull(received);
      assertEquals("Hello World", received.getText());
    } finally {
      if (sendingConn != null) {
        sendingConn.close();
      }

      if (receivingConn != null) {
        receivingConn.close();
      }
    }
  }
  /**
   * 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();
      }
    }
  }
Ejemplo n.º 8
0
  public void testNoLocalNotQueued() throws Exception {
    if (!isBrokerStorePersistent()) {
      fail("This test requires a broker with a persistent store");
    }

    Connection connection = getConnection();
    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    Topic topic = session.createTopic(MY_TOPIC_SUBSCRIPTION_NAME);

    TopicSubscriber noLocalSubscriber =
        session.createDurableSubscriber(topic, MY_TOPIC_SUBSCRIPTION_NAME + "-NoLocal", null, true);

    TopicSubscriber normalSubscriber =
        session.createDurableSubscriber(topic, MY_TOPIC_SUBSCRIPTION_NAME + "-Normal", null, false);

    sendMessage(session, topic, SEND_COUNT);

    // Check messages can be received as expected.
    connection.start();

    // As the no-local subscriber was on the same connection the messages were
    // published on, tit will receive no messages as they will be discarded on the broker
    List<Message> received = receiveMessage(noLocalSubscriber, SEND_COUNT);
    assertEquals("No Local Subscriber Received messages", 0, received.size());

    received = receiveMessage(normalSubscriber, SEND_COUNT);
    assertEquals("Normal Subscriber Received no messages", SEND_COUNT, received.size());
    session.commit();

    normalSubscriber.close();
    connection.close();

    // Ensure the no-local subscribers messages were discarded by restarting the broker
    // and reconnecting to the subscription to ensure they were not recovered.
    restartBroker();

    Connection connection2 = getConnection();
    connection2.start();

    Session session2 = connection2.createSession(true, Session.SESSION_TRANSACTED);
    Topic topic2 = session2.createTopic(MY_TOPIC_SUBSCRIPTION_NAME);

    TopicSubscriber noLocalSubscriber2 =
        session2.createDurableSubscriber(
            topic2, MY_TOPIC_SUBSCRIPTION_NAME + "-NoLocal", null, true);

    // The NO-local subscriber should not get any messages
    received = receiveMessage(noLocalSubscriber2, SEND_COUNT);
    session2.commit();
    assertEquals("No Local Subscriber Received messages", 0, received.size());

    noLocalSubscriber2.close();
  }
Ejemplo n.º 9
0
  public void testNonNoLocalQueued() throws Exception {
    if (!isBrokerStorePersistent()) {
      fail("This test requires a broker with a persistent store");
    }

    Connection connection = getConnection();
    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    Topic topic = session.createTopic(MY_TOPIC_SUBSCRIPTION_NAME);

    TopicSubscriber noLocalSubscriber =
        session.createDurableSubscriber(topic, MY_TOPIC_SUBSCRIPTION_NAME + "-NoLocal", null, true);

    sendMessage(session, topic, SEND_COUNT);

    // Check messages can be received as expected.
    connection.start();

    List<Message> received = receiveMessage(noLocalSubscriber, SEND_COUNT);
    assertEquals("No Local Subscriber Received messages", 0, received.size());

    session.commit();

    Connection connection3 = getConnection();
    Session session3 = connection3.createSession(true, Session.SESSION_TRANSACTED);
    sendMessage(session3, topic, SEND_COUNT);

    connection.close();

    // We didn't receive the messages on the durable queue for the no-local subscriber
    // so they are still on the broker. Restart the broker, prompting their recovery.
    restartBroker();

    Connection connection2 = getConnection();
    connection2.start();

    Session session2 = connection2.createSession(true, Session.SESSION_TRANSACTED);
    Topic topic2 = session2.createTopic(MY_TOPIC_SUBSCRIPTION_NAME);

    TopicSubscriber noLocalSubscriber2 =
        session2.createDurableSubscriber(
            topic2, MY_TOPIC_SUBSCRIPTION_NAME + "-NoLocal", null, true);

    // The NO-local subscriber should receive messages sent from connection3
    received = receiveMessage(noLocalSubscriber2, SEND_COUNT);
    session2.commit();
    assertEquals(
        "No Local Subscriber did not receive expected messages", SEND_COUNT, received.size());

    noLocalSubscriber2.close();
  }
Ejemplo n.º 10
0
  public static void main(String[] args) throws JMSException {
    AsyncSimpleConsumer asyncConsumer = new AsyncSimpleConsumer();

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

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

    Destination destination = session.createQueue(subject);

    MessageConsumer consumer = session.createConsumer(destination);

    consumer.setMessageListener(asyncConsumer);
    connection.setExceptionListener(asyncConsumer);

    try {
      while (true) {
        if (AsyncSimpleConsumer.catchExit) {
          break;
        }
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
      System.out.println("Sleep interrupted");
    }
    connection.close();
  }
Ejemplo n.º 11
0
  private void startSource() throws JMSException {
    // start the source connection

    sourceConn.start();

    started = true;

    if (maxBatchTime != -1) {
      if (JMSBridgeImpl.trace) {
        HornetQJMSServerLogger.LOGGER.trace("Starting time checker thread");
      }

      timeChecker = new BatchTimeChecker();

      executor.execute(timeChecker);
      batchExpiryTime = System.currentTimeMillis() + maxBatchTime;

      if (JMSBridgeImpl.trace) {
        HornetQJMSServerLogger.LOGGER.trace("Started time checker thread");
      }
    }

    executor.execute(new SourceReceiver());

    if (JMSBridgeImpl.trace) {
      HornetQJMSServerLogger.LOGGER.trace("Started " + this);
    }
  }
Ejemplo n.º 12
0
  public Mail receiveMail() {
    ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616");
    Destination destination = new ActiveMQQueue("mail.queue");
    Connection conn = null;
    try {
      conn = cf.createConnection();
      Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageConsumer consumer = session.createConsumer(destination);

      conn.start();
      MapMessage message = (MapMessage) consumer.receive();
      Mail mail = new Mail();
      mail.setFrom(message.getString("from"));
      mail.setTo(message.getString("to"));
      mail.setSubject(message.getString("subject"));
      mail.setContent(message.getString("content"));
      mail.setDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(message.getString("date")));
      session.close();
      return mail;
    } catch (JMSException e) {
      throw new RuntimeException(e);
    } catch (ParseException e) {
      throw new RuntimeException(e);
    } finally {
      if (conn != null) {
        try {
          conn.close();
        } catch (JMSException e) {

        }
      }
    }
  }
  /**
   * Check a session is rollbacked on a Session close();
   *
   * @throws Exception
   */
  public void xtestTransactionRollbackOnSessionClose() throws Exception {
    Destination destination = createDestination(getClass().getName());
    Connection connection = createConnection();
    connection.setClientID(idGen.generateId());
    connection.start();
    Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
    MessageConsumer consumer = null;
    if (topic) {
      consumer = consumerSession.createDurableSubscriber((Topic) destination, "TESTRED");
    } else {
      consumer = consumerSession.createConsumer(destination);
    }
    Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = producerSession.createProducer(destination);
    producer.setDeliveryMode(deliveryMode);

    TextMessage sentMsg = producerSession.createTextMessage();
    sentMsg.setText("msg1");
    producer.send(sentMsg);

    producerSession.commit();

    Message recMsg = consumer.receive(RECEIVE_TIMEOUT);
    assertFalse(recMsg.getJMSRedelivered());
    consumerSession.close();
    consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
    consumer = consumerSession.createConsumer(destination);

    recMsg = consumer.receive(RECEIVE_TIMEOUT);
    consumerSession.commit();
    assertTrue(recMsg.equals(sentMsg));
    connection.close();
  }
Ejemplo n.º 14
0
  /**
   * Initializes the qpid connection with a jndiName of cow, and a host and port taken from the
   * cow-server.properties file.
   */
  public void init() {
    String connectionFactorylocation =
        "amqp://*****:*****@clientid/test?brokerlist='tcp://" + host + ":" + port + "'";
    String destinationType = "topic";
    String jndiName = "cow";
    String destinationName = "myTopic";

    try {
      properties = new Properties();
      properties.setProperty(
          Context.INITIAL_CONTEXT_FACTORY,
          "org.apache.qpid.jndi.PropertiesFileInitialContextFactory");
      properties.setProperty("connectionfactory.amqpConnectionFactory", connectionFactorylocation);
      properties.setProperty(destinationType + "." + jndiName, destinationName);

      context = new InitialContext(properties);
      ConnectionFactory connectionFactory =
          (ConnectionFactory) context.lookup("amqpConnectionFactory");
      Connection connection = connectionFactory.createConnection();
      connection.start();

      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Destination destination = (Destination) context.lookup(jndiName);

      messageProducer = session.createProducer(destination);
      initialized = true;
    } catch (Exception e) {
      log.debug(e.getMessage());
      initialized = false;
    }
  }
Ejemplo n.º 15
0
  @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 start() throws JMSException {
    String selector = "next = '" + myId + "'";

    try {
      ConnectionFactory factory = template.getConnectionFactory();
      final Connection c = connection = factory.createConnection();

      // we might be a reusable connection in spring
      // so lets only set the client ID once if its not set
      synchronized (c) {
        if (c.getClientID() == null) {
          c.setClientID(myId);
        }
      }

      connection.start();

      session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
      consumer = session.createConsumer(destination, selector, false);
      consumer.setMessageListener(this);
    } catch (JMSException ex) {
      LOG.error("", ex);
      throw ex;
    }
  }
  @Override
  @Test(timeout = 30000)
  public void testMessageSizeOneDurablePartialConsumption() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = new ActiveMQConnectionFactory(brokerConnectURI).createConnection();
    connection.setClientID("clientId");
    connection.start();

    SubscriptionKey subKey = new SubscriptionKey("clientId", "sub1");
    org.apache.activemq.broker.region.Topic dest =
        publishTestMessagesDurable(
            connection, new String[] {"sub1"}, 200, publishedMessageSize, DeliveryMode.PERSISTENT);

    // verify the count and size - durable is offline so all 200 should be pending since none are in
    // prefetch
    verifyPendingStats(dest, subKey, 200, publishedMessageSize.get());

    // The expected value is only 100 because for durables a LRUCache is being used
    // with a max size of 100
    verifyStoreStats(dest, 100, publishedMessageSize.get());

    // consume all messages
    consumeDurableTestMessages(connection, "sub1", 50, publishedMessageSize);

    // All messages should now be gone
    verifyPendingStats(dest, subKey, 150, publishedMessageSize.get());

    // The expected value is only 100 because for durables a LRUCache is being used
    // with a max size of 100
    // verify the size is at least as big as 100 messages times the minimum of 100 size
    verifyStoreStats(dest, 100, 100 * 100);

    connection.close();
  }
Ejemplo n.º 18
0
  public void sendMessage(Order order) {
    ConnectionFactory factory = new ActiveMQConnectionFactory("failover://tcp://localhost:61616");
    Queue queue = new ActiveMQQueue("sequence");
    Connection conn = null;
    Session sen = null;
    MessageProducer producer = null;
    TextMessage msg = null;
    JSONMapper mapper = new JSONMapper();

    Destination des = null;
    try {
      conn = factory.createConnection();
      sen = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      producer = sen.createProducer(queue);
      conn.start();
      String str = mapper.writeObjectAsString(order);
      System.out.println(str);
      msg = sen.createTextMessage(str);
      producer.send(msg);
      producer.close();
      sen.close();
      conn.close();
    } catch (JMSException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Ejemplo n.º 19
0
  public void produceMsg(String text) throws Exception {
    // Create a ConnectionFactory
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");

    // Create a Connection
    Connection connection = connectionFactory.createConnection();
    connection.start();

    // Create a Session
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

    // Create the destination (Topic or Queue)
    Destination destination = session.createQueue("TEST.FOO");

    // Create a MessageProducer from the Session to the Topic or Queue
    MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

    // Create a messages
    TextMessage message = session.createTextMessage(text);
    producer.send(message);

    // Clean up
    session.close();
    connection.close();
  }
Ejemplo n.º 20
0
  public static void main(String[] args) throws JMSException {
    // Getting JMS connection from the server
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
    Connection connection = connectionFactory.createConnection();
    connection.start();

    // Creating session for seding messages
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    // Getting the queue 'JMSBEGINQUEUE'
    Destination destination = session.createQueue(subject);

    // MessageConsumer is used for receiving (consuming) messages
    MessageConsumer consumer = session.createConsumer(destination);

    // Here we receive the message.
    // By default this call is blocking, which means it will wait
    // for a message to arrive on the queue.
    Message message = consumer.receive();

    // There are many types of Message and TextMessage
    // is just one of them. Producer sent us a TextMessage
    // so we must cast to it to get access to its .getText()
    // method.
    if (message instanceof TextMessage) {
      TextMessage textMessage = (TextMessage) message;
      System.out.println("Received message '" + textMessage.getText() + "'");
    }
    connection.close();
  }
  @Override
  @Test(timeout = 30000)
  public void testMessageSizeTwoDurables() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = new ActiveMQConnectionFactory(brokerConnectURI).createConnection();
    connection.setClientID("clientId");
    connection.start();

    org.apache.activemq.broker.region.Topic dest =
        publishTestMessagesDurable(
            connection,
            new String[] {"sub1", "sub2"},
            200,
            publishedMessageSize,
            DeliveryMode.PERSISTENT);

    // verify the count and size
    SubscriptionKey subKey = new SubscriptionKey("clientId", "sub1");
    verifyPendingStats(dest, subKey, 200, publishedMessageSize.get());

    // consume messages just for sub1
    consumeDurableTestMessages(connection, "sub1", 200, publishedMessageSize);

    // There is still a durable that hasn't consumed so the messages should exist
    SubscriptionKey subKey2 = new SubscriptionKey("clientId", "sub2");
    verifyPendingStats(dest, subKey, 0, 0);
    verifyPendingStats(dest, subKey2, 200, publishedMessageSize.get());

    // The expected value is only 100 because for durables a LRUCache is being used
    // with a max size of 100
    verifyStoreStats(dest, 100, publishedMessageSize.get());

    connection.stop();
  }
  @Override
  @Test(timeout = 30000)
  public void testMessageSizeOneDurable() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();
    Connection connection = new ActiveMQConnectionFactory(brokerConnectURI).createConnection();
    connection.setClientID("clientId");
    connection.start();

    SubscriptionKey subKey = new SubscriptionKey("clientId", "sub1");
    org.apache.activemq.broker.region.Topic dest =
        publishTestMessagesDurable(
            connection, new String[] {"sub1"}, 200, publishedMessageSize, DeliveryMode.PERSISTENT);

    verifyPendingStats(dest, subKey, 200, publishedMessageSize.get());

    // The expected value is only 100 because for durables a LRUCache is being used
    // with a max size of 100
    verifyStoreStats(dest, 100, publishedMessageSize.get());

    // consume 100 messages
    consumeDurableTestMessages(connection, "sub1", 100, publishedMessageSize);

    // 100 should be left
    verifyPendingStats(dest, subKey, 100, publishedMessageSize.get());
    verifyStoreStats(dest, 100, publishedMessageSize.get());

    connection.close();
  }
Ejemplo n.º 23
0
  public void testConnectionFactory() throws Exception {
    final ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(connectionUri);
    final ActiveMQQueue queue = new ActiveMQQueue("testqueue");
    final Connection conn = cf.createConnection();

    Runnable r =
        new Runnable() {
          public void run() {
            try {
              Session session = conn.createSession(false, 1);
              MessageConsumer consumer = session.createConsumer(queue, null);
              consumer.receive(1000);
            } catch (JMSException e) {
              e.printStackTrace();
            }
          }
        };
    new Thread(r).start();
    conn.start();

    try {
      synchronized (this) {
        wait(3000);
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 24
0
  public static void consumeTopic() throws Exception {

    ActiveMQConnectionFactory connectionFactory =
        new ActiveMQConnectionFactory(
            ActiveMQConnectionFactory.DEFAULT_USER,
            ActiveMQConnectionFactory.DEFAULT_PASSWORD,
            ActiveMQConnectionFactory.DEFAULT_BROKER_URL);
    Connection connection = connectionFactory.createConnection();
    connection.setClientID(clientID);
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = session.createTopic(topicName);
    MessageConsumer consumer = session.createDurableSubscriber(topic, topicName);
    consumer.setMessageListener(
        new MessageListener() {
          public void onMessage(Message message) {

            TextMessage m = (TextMessage) message;
            try {
              System.out.println(m.getText());
            } catch (JMSException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          }
        });
    connection.start();
  }
 public Publisher() throws JMSException {
   factory = new ActiveMQConnectionFactory(brokerURL);
   connection = factory.createConnection(username, password);
   connection.start();
   session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   producer = session.createProducer(null);
 }
  @Test
  public void testSendReceiveMessage() throws Exception {
    Connection conn = createConnection();

    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    MessageProducer prod = sess.createProducer(queue1);

    // Make persistent to make sure message gets serialized
    prod.setDeliveryMode(DeliveryMode.PERSISTENT);

    MessageConsumer cons = sess.createConsumer(queue1);

    TestMessage tm = new TestMessage(123, false);

    ObjectMessage om = sess.createObjectMessage();

    om.setObject(tm);

    conn.start();

    prod.send(om);

    ObjectMessage om2 = (ObjectMessage) cons.receive(1000);

    ProxyAssertSupport.assertNotNull(om2);

    TestMessage tm2 = (TestMessage) om2.getObject();

    ProxyAssertSupport.assertEquals(123, tm2.getID());

    conn.close();
  }
Ejemplo n.º 27
0
  public OneToOneReceiver(String topicName, ChatPanel chatPanel) {
    try {
      // Create a ConnectionFactory
      ActiveMQConnectionFactory connectionFactory =
          new ActiveMQConnectionFactory(Constants.ActiveMQConnect);

      // Create a Connection
      Connection connection = connectionFactory.createConnection();
      connection.start();

      // connection.setExceptionListener((ExceptionListener) this);

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

      // Create the destination (Topic or Queue)
      // Destination destination = session.createQueue("CHAT");
      Topic topic = session.createTopic(topicName);
      // Create a MessageConsumer from the Session to the Topic or Queue
      consumer = session.createConsumer(topic);
      Thread receiverThread = new Thread(this);
      this.chatPanel = chatPanel;
      receiverThread.start();
    } catch (Exception ex) {
      LOG.error(ex);
    }
  }
Ejemplo n.º 28
0
  @Test
  public void testCompositeDestConsumer() throws Exception {

    final int numDests = 20;
    final int numMessages = 200;
    StringBuffer stringBuffer = new StringBuffer();
    for (int i = 0; i < numDests; i++) {
      if (stringBuffer.length() != 0) {
        stringBuffer.append(',');
      }
      stringBuffer.append("ST." + i);
    }
    stringBuffer.append("?consumer.prefetchSize=100");
    ActiveMQQueue activeMQQueue = new ActiveMQQueue(stringBuffer.toString());
    ConnectionFactory factory = new ActiveMQConnectionFactory(brokerService.getVmConnectorURI());
    Connection connection = factory.createConnection();
    connection.start();
    MessageProducer producer =
        connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createProducer(activeMQQueue);
    for (int i = 0; i < numMessages; i++) {
      producer.send(new ActiveMQTextMessage());
    }

    MessageConsumer consumer =
        connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer(activeMQQueue);
    try {
      for (int i = 0; i < numMessages * numDests; i++) {
        assertNotNull("recieved:" + i, consumer.receive(4000));
      }
    } finally {
      connection.close();
    }
  }
  public DigitalLibraryServer() {
    try {
      Properties properties = new Properties();
      properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
      properties.put(Context.URL_PKG_PREFIXES, "org.jnp.interfaces");
      properties.put(Context.PROVIDER_URL, "localhost");

      InitialContext jndi = new InitialContext(properties);
      ConnectionFactory conFactory = (ConnectionFactory) jndi.lookup("XAConnectionFactory");
      connection = conFactory.createConnection();

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

      try {
        counterTopic = (Topic) jndi.lookup("counterTopic");
      } catch (NamingException NE1) {
        System.out.println("NamingException: " + NE1 + " : Continuing anyway...");
      }

      if (null == counterTopic) {
        counterTopic = session.createTopic("counterTopic");
        jndi.bind("counterTopic", counterTopic);
      }

      consumer = session.createConsumer(counterTopic);
      consumer.setMessageListener(this);
      System.out.println("Server started waiting for client requests");
      connection.start();
    } catch (NamingException NE) {
      System.out.println("Naming Exception: " + NE);
    } catch (JMSException JMSE) {
      System.out.println("JMS Exception: " + JMSE);
      JMSE.printStackTrace();
    }
  }
Ejemplo n.º 30
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);
    }
  }