예제 #1
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();
    }
  }
예제 #2
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 testCachingConnectionFactoryWithTopicConnectionFactoryAndJms102Usage()
      throws JMSException {
    MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class);
    TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock();
    MockControl conControl = MockControl.createControl(TopicConnection.class);
    TopicConnection con = (TopicConnection) conControl.getMock();
    MockControl txSessionControl = MockControl.createControl(TopicSession.class);
    TopicSession txSession = (TopicSession) txSessionControl.getMock();
    MockControl nonTxSessionControl = MockControl.createControl(TopicSession.class);
    TopicSession nonTxSession = (TopicSession) nonTxSessionControl.getMock();

    cf.createTopicConnection();
    cfControl.setReturnValue(con, 1);
    con.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
    conControl.setReturnValue(txSession, 1);
    txSession.getTransacted();
    txSessionControl.setReturnValue(true, 2);
    txSession.close();
    txSessionControl.setVoidCallable(1);
    con.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE);
    conControl.setReturnValue(nonTxSession, 1);
    nonTxSession.close();
    nonTxSessionControl.setVoidCallable(1);
    con.start();
    conControl.setVoidCallable(1);
    con.stop();
    conControl.setVoidCallable(1);
    con.close();
    conControl.setVoidCallable(1);

    cfControl.replay();
    conControl.replay();
    txSessionControl.replay();
    nonTxSessionControl.replay();

    CachingConnectionFactory scf = new CachingConnectionFactory(cf);
    scf.setReconnectOnException(false);
    Connection con1 = scf.createTopicConnection();
    Session session1 = con1.createSession(true, Session.AUTO_ACKNOWLEDGE);
    session1.getTransacted();
    session1.close(); // should lead to rollback
    session1 = con1.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    session1.close(); // should be ignored
    con1.start();
    con1.close(); // should be ignored
    TopicConnection con2 = scf.createTopicConnection();
    Session session2 = con2.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE);
    session2.close(); // should be ignored
    session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE);
    session2.getTransacted();
    session2.close(); // should be ignored
    con2.start();
    con2.close(); // should be ignored
    scf.destroy(); // should trigger actual close

    cfControl.verify();
    conControl.verify();
    txSessionControl.verify();
    nonTxSessionControl.verify();
  }
  /**
   * Send some messages in transacted session. Don't commit. Verify message are not received by
   * consumer.
   */
  @Test
  public void testSendNoCommitQueue() throws Exception {
    Connection conn = null;

    try {
      conn = createConnection();

      Session producerSess = conn.createSession(true, Session.CLIENT_ACKNOWLEDGE);
      MessageProducer producer = producerSess.createProducer(queue1);

      Session consumerSess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
      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);
      }

      checkEmpty(queue1);
    } finally {
      if (conn != null) {
        conn.close();
      }
    }
  }
  @Test
  public void testSendRollbackQueue() throws Exception {
    Connection conn = null;

    try {
      conn = createConnection();

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

      Session consumerSess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
      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);
      }

      producerSess.rollback();

      Message m = consumer.receive(500);

      ProxyAssertSupport.assertNull(m);
    } finally {
      if (conn != null) {
        conn.close();
      }
    }
  }
  /**
   * Send some messages in transacted session. Don't commit. Verify message are not received by
   * consumer.
   */
  @Test
  public void testSendNoCommitTopic() throws Exception {
    Connection conn = null;

    try {
      conn = createConnection();

      Session producerSess = conn.createSession(true, Session.SESSION_TRANSACTED);
      MessageProducer producer = producerSess.createProducer(ActiveMQServerTestCase.topic1);

      Session consumerSess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
      MessageConsumer consumer = consumerSess.createConsumer(ActiveMQServerTestCase.topic1);
      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);
      }

      Message m = consumer.receive(500);
      ProxyAssertSupport.assertNull(m);
    } finally {
      if (conn != null) {
        conn.close();
      }
    }
  }
  /**
   * 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();
  }
  @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();
      }
    }
  }
  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
  /**
   * 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 void _testSendCommitQueueCommitsInOrder() throws Exception {
    Connection conn = null;

    try {
      conn = createConnection();

      Session producerSess = conn.createSession(true, Session.CLIENT_ACKNOWLEDGE);
      MessageProducer producer = producerSess.createProducer(queue1);
      producer.setDeliveryMode(DeliveryMode.PERSISTENT);

      Session consumerSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageConsumer consumer = consumerSession.createConsumer(queue1);
      CountDownLatch latch = new CountDownLatch(1);
      conn.start();
      myReceiver myReceiver = new myReceiver(latch, conn);
      consumer.setMessageListener(myReceiver);
      long lastBatchTime = System.currentTimeMillis();
      int sentId = 0;
      boolean started = false;
      // Send some messages
      while (true) {
        try {
          Message m = producerSess.createMessage();
          m.setIntProperty("foo", sentId);
          sentId++;
          producer.send(m);

          if (sentId == 1 || System.currentTimeMillis() - lastBatchTime > 50) {
            lastBatchTime = System.currentTimeMillis();
            producerSess.commit();
          }
        } catch (JMSException e) {
          // ignore connection closed by consumer
        }

        // wait for the first message to be received before we continue sending
        if (!started) {
          Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
          started = true;
        } else {
          if (myReceiver.failed) {
            throw myReceiver.e;
          }
        }
      }

    } finally {
      if (conn != null) {
        conn.close();
      }
      removeAllMessages(queue1.getQueueName(), true);
    }
  }
예제 #12
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();
  }
예제 #13
0
    @Override
    public MessageConsumerResources makeObject() throws Exception {
      MessageConsumerResources answer;
      Connection conn = getConnectionResource().borrowConnection();
      try {
        Session session;
        if (isEndpointTransacted()) {
          session = conn.createSession(true, Session.SESSION_TRANSACTED);
        } else {
          session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        }

        Destination replyToDestination;
        if (ObjectHelper.isEmpty(getNamedReplyTo())) {
          replyToDestination =
              getEndpoint()
                  .getDestinationCreationStrategy()
                  .createTemporaryDestination(session, isTopic());
        } else {
          replyToDestination =
              getEndpoint()
                  .getDestinationCreationStrategy()
                  .createDestination(session, getNamedReplyTo(), isTopic());
        }
        MessageConsumer messageConsumer =
            JmsObjectFactory.createMessageConsumer(
                session, replyToDestination, null, isTopic(), null, true);
        messageConsumer.setMessageListener(
            new MessageListener() {

              @Override
              public void onMessage(final Message message) {
                log.debug("Message Received in the Consumer Pool");
                log.debug("  Message : {}", message);
                try {
                  Exchanger<Object> exchanger = EXCHANGERS.get(message.getJMSCorrelationID());
                  exchanger.exchange(message, getResponseTimeOut(), TimeUnit.MILLISECONDS);
                } catch (Exception e) {
                  log.error("Unable to exchange message: {}", message, e);
                }
              }
            });
        answer = new MessageConsumerResources(session, messageConsumer, replyToDestination);
      } catch (Exception e) {
        log.error("Unable to create the MessageConsumerResource: " + e.getLocalizedMessage());
        throw new CamelException(e);
      } finally {
        getConnectionResource().returnConnection(conn);
      }
      return answer;
    }
예제 #14
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();
  }
  /**
   * 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();
  }
  /**
   * Make sure redelivered flag is set on redelivery via rollback, different setup: we close the
   * rolled back session and we receive the message whose acknowledgment was cancelled on a new
   * session.
   */
  @Test
  public void testRedeliveredQueue2() throws Exception {
    Connection conn = null;

    try {
      conn = createConnection();

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

      MessageProducer prod = sendSession.createProducer(queue1);
      prod.send(sendSession.createTextMessage("a message"));

      conn.close();

      conn = createConnection();
      Session sess = conn.createSession(true, Session.SESSION_TRANSACTED);

      MessageConsumer cons = sess.createConsumer(queue1);

      conn.start();

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

      ProxyAssertSupport.assertEquals("a message", tm.getText());

      ProxyAssertSupport.assertFalse(tm.getJMSRedelivered());
      ProxyAssertSupport.assertEquals(1, tm.getIntProperty("JMSXDeliveryCount"));

      sess.rollback();

      sess.close();

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

      cons = sess2.createConsumer(queue1);

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

      ProxyAssertSupport.assertEquals("a message", tm.getText());

      ProxyAssertSupport.assertEquals(2, tm.getIntProperty("JMSXDeliveryCount"));

      ProxyAssertSupport.assertTrue(tm.getJMSRedelivered());
    } finally {
      if (conn != null) {
        conn.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();
    }
  }
  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;
    }
  }
예제 #19
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);
    }
  }
예제 #20
0
파일: Produces.java 프로젝트: ITA-G03/O2O
  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();
    }
  }
 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);
 }
예제 #22
0
  @Test
  public void testCreateTopic() throws Exception {
    liveJMSService.createTopic(true, "topic", "/topic/t1");
    assertNotNull(ctx1.lookup("//topic/t1"));

    ActiveMQConnectionFactory jbcf =
        ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.CF, livetc);

    jbcf.setReconnectAttempts(-1);

    Connection conn = null;

    try {
      conn = JMSUtil.createConnectionAndWaitForTopology(jbcf, 2, 5);

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

      ClientSession coreSession = ((ActiveMQSession) sess).getCoreSession();

      JMSUtil.crash(liveService, coreSession);

      assertNotNull(ctx2.lookup("/topic/t1"));
    } finally {
      if (conn != null) {
        conn.close();
      }
    }
  }
예제 #23
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();
  }
예제 #24
0
 public UserMessageService(String brokerURL, String queueName) throws JMSException {
   this.queueName = queueName;
   ConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL);
   this.con = factory.createConnection();
   session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
   this.producer = session.createProducer(null);
 }
예제 #25
0
  /*
   * Initiate the snapshot by sending a Marker message to one of the Players (Player0)
   * Any Player could have been used to initiate the snapshot.
   */
  private void sendInitSnapshot() {
    try {
      // Gather necessary JMS resources
      Context ctx = new InitialContext();
      ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/myConnectionFactory");
      Queue q = (Queue) ctx.lookup("jms/PITplayer0");
      Connection con = cf.createConnection();
      Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer writer = session.createProducer(q);

      /*
       * As part of the snapshot algorithm, players need to record
       * what other Players they receive markers from.
       * "-1" indicates to the PITplayer0 that this marker is coming from
       * the monitor, not another Player.
       */
      Marker m = new Marker(-1);
      ObjectMessage msg = session.createObjectMessage(m);
      System.out.println("Initiating Snapshot");
      writer.send(msg);
      con.close();
    } catch (JMSException e) {
      System.out.println("JMS Exception thrown" + e);
    } catch (Throwable e) {
      System.out.println("Throwable thrown" + e);
    }
  }
예제 #26
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();
  }
  public void testBrokerStatsReset() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue replyTo = session.createTemporaryQueue();
    MessageConsumer consumer = session.createConsumer(replyTo);
    Queue testQueue = session.createQueue("Test.Queue");
    Queue query = session.createQueue(StatisticsBroker.STATS_BROKER_PREFIX);
    MessageProducer producer = session.createProducer(null);

    producer.send(testQueue, session.createMessage());

    Message msg = session.createMessage();
    msg.setJMSReplyTo(replyTo);
    producer.send(query, msg);
    MapMessage reply = (MapMessage) consumer.receive(10 * 1000);
    assertNotNull(reply);
    assertTrue(reply.getMapNames().hasMoreElements());
    assertTrue(reply.getLong("enqueueCount") >= 1);

    msg = session.createMessage();
    msg.setBooleanProperty(StatisticsBroker.STATS_BROKER_RESET_HEADER, true);
    msg.setJMSReplyTo(replyTo);
    producer.send(query, msg);
    reply = (MapMessage) consumer.receive(10 * 1000);
    assertNotNull(reply);
    assertTrue(reply.getMapNames().hasMoreElements());
    assertEquals(0, reply.getLong("enqueueCount"));
    assertTrue(reply.getJMSTimestamp() > 0);
    assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority());
  }
예제 #28
0
  @Override
  public MessageProducerResources doCreateProducerModel() throws Exception {
    MessageProducerResources answer;
    Connection conn = getConnectionResource().borrowConnection();
    try {
      TransactionCommitStrategy commitStrategy = null;
      if (isEndpointTransacted()) {
        commitStrategy =
            getCommitStrategy() == null
                ? new DefaultTransactionCommitStrategy()
                : getCommitStrategy();
      }
      Session session = conn.createSession(isEndpointTransacted(), getAcknowledgeMode());
      Destination destination =
          getEndpoint()
              .getDestinationCreationStrategy()
              .createDestination(session, getDestinationName(), isTopic());
      MessageProducer messageProducer =
          JmsObjectFactory.createMessageProducer(session, destination, isPersistent(), getTtl());

      answer = new MessageProducerResources(session, messageProducer, commitStrategy);

    } catch (Exception e) {
      log.error("Unable to create the MessageProducer", e);
      throw e;
    } finally {
      getConnectionResource().returnConnection(conn);
    }
    return answer;
  }
  public void testDestinationStats() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue replyTo = session.createTemporaryQueue();
    MessageConsumer consumer = session.createConsumer(replyTo);
    Queue testQueue = session.createQueue("Test.Queue");
    MessageProducer producer = session.createProducer(null);
    Queue query =
        session.createQueue(StatisticsBroker.STATS_DESTINATION_PREFIX + testQueue.getQueueName());
    Message msg = session.createMessage();

    producer.send(testQueue, msg);

    msg.setJMSReplyTo(replyTo);
    producer.send(query, msg);
    MapMessage reply = (MapMessage) consumer.receive(10 * 1000);
    assertNotNull(reply);
    assertTrue(reply.getMapNames().hasMoreElements());
    assertTrue(reply.getJMSTimestamp() > 0);
    assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority());
    /*
    for (Enumeration e = reply.getMapNames();e.hasMoreElements();) {
        String name = e.nextElement().toString();
        System.err.println(name+"="+reply.getObject(name));
    }
    */
  }
  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) {

        }
      }
    }
  }