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());
  }
Beispiel #2
0
  /**
   * @param inId
   * @param command
   * @param parameters
   * @return
   * @throws NamingException
   */
  @Override
  public boolean executeProcessOnInMail(long inId, String command, String parameters)
      throws NamingException, JMSException {

    boolean suc = false;
    InitialContext ic = null;
    Connection connection = null;
    String msgFactoryJndiName = getJNDIPrefix() + SEDValues.EBMS_JMS_CONNECTION_FACTORY_JNDI;
    String msgQueueJndiName = getJNDI_JMSPrefix() + SEDValues.JNDI_QUEUE_EXECUTION;
    try {
      ic = new InitialContext();
      ConnectionFactory cf = (ConnectionFactory) ic.lookup(msgFactoryJndiName);
      Queue queue = (Queue) ic.lookup(msgQueueJndiName);
      connection = cf.createConnection();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer sender = session.createProducer(queue);
      Message message = session.createMessage();

      message.setLongProperty(SEDValues.EBMS_QUEUE_PARAM_MAIL_ID, inId);
      message.setStringProperty(SEDValues.EXEC_COMMAND, command);
      message.setStringProperty(SEDValues.EXEC_PARAMS, parameters);
      sender.send(message);
      suc = true;
    } finally {
      if (ic != null) {
        try {
          ic.close();
        } catch (Exception ignore) {
        }
      }
      closeConnection(connection);
    }

    return suc;
  }
  @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();
      }
    }
  }
  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));
    }
    */
  }
  @Test
  public void sendToNonExistantDestination() throws Exception {
    Destination destination = HornetQJMSClient.createQueue("DoesNotExist");
    TransportConfiguration transportConfiguration =
        new TransportConfiguration(InVMConnectorFactory.class.getName());
    ConnectionFactory localConnectionFactory =
        HornetQJMSClient.createConnectionFactoryWithoutHA(
            JMSFactoryType.CF, transportConfiguration);
    // Using JMS 1 API
    Connection connection = localConnectionFactory.createConnection();
    Session session = connection.createSession();
    try {
      MessageProducer messageProducer = session.createProducer(null);
      messageProducer.send(destination, session.createMessage());
      Assert.fail("Succeeded in sending message to a non-existant destination using JMS 1 API!");
    } catch (JMSException e) { // Expected }

    }

    // Using JMS 2 API
    JMSContext context = localConnectionFactory.createContext();
    JMSProducer jmsProducer = context.createProducer().setDeliveryMode(DeliveryMode.PERSISTENT);

    try {
      jmsProducer.send(destination, context.createMessage());
      Assert.fail("Succeeded in sending message to a non-existant destination using JMS 2 API!");
    } catch (JMSRuntimeException e) { // Expected }
    }
  }
  /**
   * 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();
      }
    }
  }
  /**
   * 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();
      }
    }
  }
 private void testJmsConnection(final javax.jms.Connection connection) throws JMSException {
   final Session session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE);
   final Topic topic = session.createTopic("test");
   final MessageProducer producer = session.createProducer(topic);
   producer.send(session.createMessage());
   producer.close();
   session.close();
   connection.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();
      }
    }
  }
  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);
    }
  }
 private void sendMessage(int timeToLive) throws Exception {
   ActiveMQConnection producerConnection = (ActiveMQConnection) createConnection();
   producerConnection.start();
   Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = producerSession.createProducer(destination);
   if (timeToLive > 0) {
     producer.setTimeToLive(timeToLive);
   }
   Message message = producerSession.createMessage();
   message.setStringProperty("data", data);
   producer.send(message);
   producerConnection.close();
 }
  @Test(timeout = 30000)
  public void testSendMessagePassthrough() throws Exception {
    JmsConnectionFactory factory = new JmsConnectionFactory("failover:(mock://localhost)");

    Connection connection = factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    Queue queue = session.createQueue(getTestName());
    MessageProducer producer = session.createProducer(queue);
    producer.send(session.createMessage());

    connection.close();

    assertEquals(1, mockPeer.getContextStats().getSendCalls());
  }
    public void run() {
      while (true) {
        if (count == CorruptMessageStressTest.MESSAGE_COUNT) {
          break;
        }

        try {
          Message m = session.createMessage();
          m.setStringProperty("XXX", "XXX-VALUE");
          m.setStringProperty("YYY", "YYY-VALUE");
          producer.send(m);
          count++;
        } catch (Exception e) {
          CorruptMessageStressTest.log.error("Sender thread failed", e);
          break;
        }
      }
    }
Beispiel #14
0
  /**
   * @param biPosiljkaId
   * @param strPmodeId
   * @param retry
   * @param delay
   * @param transacted
   * @return
   * @throws NamingException
   * @throws JMSException
   */
  @Override
  public boolean sendMessage(long biPosiljkaId, int retry, long delay, boolean transacted)
      throws NamingException, JMSException {
    boolean suc = false;
    InitialContext ic = null;
    Connection connection = null;
    String msgFactoryJndiName = getJNDIPrefix() + SEDValues.EBMS_JMS_CONNECTION_FACTORY_JNDI;
    String msgQueueJndiName = getJNDI_JMSPrefix() + SEDValues.JNDI_QUEUE_EBMS;
    try {
      ic = new InitialContext();
      ConnectionFactory cf = (ConnectionFactory) ic.lookup(msgFactoryJndiName);
      Queue queue = (Queue) ic.lookup(msgQueueJndiName);
      connection = cf.createConnection();
      Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
      MessageProducer sender = session.createProducer(queue);
      Message message = session.createMessage();

      message.setLongProperty(SEDValues.EBMS_QUEUE_PARAM_MAIL_ID, biPosiljkaId);
      message.setIntProperty(SEDValues.EBMS_QUEUE_PARAM_RETRY, retry);
      message.setLongProperty(SEDValues.EBMS_QUEUE_PARAM_DELAY, delay);
      message.setLongProperty(SEDValues.EBMS_QUEUE_DELAY_AMQ, delay);
      message.setLongProperty(
          SEDValues.EBMS_QUEUE_DELAY_Artemis, System.currentTimeMillis() + delay);

      sender.send(message);
      suc = true;
    } finally {
      if (ic != null) {
        try {
          ic.close();
        } catch (Exception ignore) {
        }
      }
      closeConnection(connection);
    }

    return suc;
  }
  @Test
  public void testSendMultipleQueue() throws Exception {
    Connection 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;
    final int NUM_TX = 10;

    // Send some messages

    for (int j = 0; j < NUM_TX; j++) {
      for (int i = 0; i < NUM_MESSAGES; i++) {
        Message m = producerSess.createMessage();
        producer.send(m);
      }

      producerSess.commit();
    }

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

    ProxyAssertSupport.assertEquals(NUM_MESSAGES * NUM_TX, count);
  }
  public static Message createMessage(Session session, Class messageClazz) throws JMSException {
    if (session == null) {
      throw new JMSException("session cannot be null");
    }
    if (Message.class.isAssignableFrom(messageClazz)) {
      throw new JMSException("cannot create message of type: " + messageClazz.getName());
    }

    if (TextMessage.class.equals(messageClazz)) {
      return session.createTextMessage();
    } else if (StreamMessage.class.equals(messageClazz)) {
      return session.createStreamMessage();
    } else if (MapMessage.class.equals(messageClazz)) {
      return session.createMapMessage();
    } else if (ObjectMessage.class.equals(messageClazz)) {
      return session.createObjectMessage();
    } else if (BytesMessage.class.equals(messageClazz)) {
      return session.createBytesMessage();
    } else if (Message.class.equals(messageClazz)) {
      return session.createMessage();
    } else {
      throw new JMSException("cannot create message of type: " + messageClazz.getName());
    }
  }
  /**
   * Try to use ActiveMQ StatisticsPlugin to get size and if that fails fallback to {@link
   * JMSMailQueue#getSize()}
   */
  @Override
  public long getSize() throws MailQueueException {

    Connection connection = null;
    Session session = null;
    MessageConsumer consumer = null;
    MessageProducer producer = null;
    TemporaryQueue replyTo = null;
    long size;

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

      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      replyTo = session.createTemporaryQueue();
      consumer = session.createConsumer(replyTo);

      Queue myQueue = session.createQueue(queueName);
      producer = session.createProducer(null);

      String queueName = "ActiveMQ.Statistics.Destination." + myQueue.getQueueName();
      Queue query = session.createQueue(queueName);

      Message msg = session.createMessage();
      msg.setJMSReplyTo(replyTo);
      producer.send(query, msg);
      MapMessage reply = (MapMessage) consumer.receive(2000);
      if (reply != null && reply.itemExists("size")) {
        try {
          size = reply.getLong("size");
          return size;
        } catch (NumberFormatException e) {
          // if we hit this we can't calculate the size so just catch
          // it
        }
      }

    } catch (Exception e) {
      throw new MailQueueException("Unable to remove mails", e);

    } finally {

      if (consumer != null) {

        try {
          consumer.close();
        } catch (JMSException e1) {
          e1.printStackTrace();
          // ignore on rollback
        }
      }

      if (producer != null) {

        try {
          producer.close();
        } catch (JMSException e1) {
          // ignore on rollback
        }
      }

      if (replyTo != null) {
        try {

          // we need to delete the temporary queue to be sure we will
          // free up memory if thats not done and a pool is used
          // its possible that we will register a new mbean in jmx for
          // every TemporaryQueue which will never get unregistered
          replyTo.delete();
        } catch (JMSException e) {
        }
      }
      try {
        if (session != null) session.close();
      } catch (JMSException e1) {
        // ignore here
      }

      try {
        if (connection != null) connection.close();
      } catch (JMSException e1) {
        // ignore here
      }
    }

    // if we came to this point we should just fallback to super method
    return super.getSize();
  }
Beispiel #18
0
  protected Message createJmsMessage(
      Exchange exchange,
      Object body,
      Map<String, Object> headers,
      Session session,
      CamelContext context)
      throws JMSException {
    JmsMessageType type = null;

    // special for transferExchange
    if (endpoint != null && endpoint.isTransferExchange()) {
      LOG.trace("Option transferExchange=true so we use JmsMessageType: Object");
      Serializable holder = DefaultExchangeHolder.marshal(exchange);
      Message answer = session.createObjectMessage(holder);
      // ensure default delivery mode is used by default
      answer.setJMSDeliveryMode(Message.DEFAULT_DELIVERY_MODE);
      return answer;
    }

    // use a custom message converter
    if (endpoint != null && endpoint.getMessageConverter() != null) {
      if (LOG.isTraceEnabled()) {
        LOG.trace(
            "Creating JmsMessage using a custom MessageConverter: {} with body: {}",
            endpoint.getMessageConverter(),
            body);
      }
      return endpoint.getMessageConverter().toMessage(body, session);
    }

    // check if header have a type set, if so we force to use it
    if (headers.containsKey(JmsConstants.JMS_MESSAGE_TYPE)) {
      type =
          context
              .getTypeConverter()
              .convertTo(JmsMessageType.class, headers.get(JmsConstants.JMS_MESSAGE_TYPE));
    } else if (endpoint != null && endpoint.getConfiguration().getJmsMessageType() != null) {
      // force a specific type from the endpoint configuration
      type = endpoint.getConfiguration().getJmsMessageType();
    } else {
      type = getJMSMessageTypeForBody(exchange, body, headers, session, context);
    }

    // create the JmsMessage based on the type
    if (type != null) {
      if (body == null && (endpoint != null && !endpoint.getConfiguration().isAllowNullBody())) {
        throw new JMSException(
            "Cannot send message as message body is null, and option allowNullBody is false.");
      }
      LOG.trace("Using JmsMessageType: {}", type);
      Message answer = createJmsMessageForType(exchange, body, headers, session, context, type);
      // ensure default delivery mode is used by default
      answer.setJMSDeliveryMode(Message.DEFAULT_DELIVERY_MODE);
      return answer;
    }

    // check for null body
    if (body == null && (endpoint != null && !endpoint.getConfiguration().isAllowNullBody())) {
      throw new JMSException(
          "Cannot send message as message body is null, and option allowNullBody is false.");
    }

    // warn if the body could not be mapped
    if (body != null && LOG.isWarnEnabled()) {
      LOG.warn(
          "Cannot determine specific JmsMessage type to use from body class."
              + " Will use generic JmsMessage."
              + " Body class: "
              + ObjectHelper.classCanonicalName(body)
              + ". If you want to send a POJO then your class might need to implement java.io.Serializable"
              + ", or you can force a specific type by setting the jmsMessageType option on the JMS endpoint.");
    }

    // return a default message
    Message answer = session.createMessage();
    // ensure default delivery mode is used by default
    answer.setJMSDeliveryMode(Message.DEFAULT_DELIVERY_MODE);
    return answer;
  }
  /** Test that close() hierarchically closes all child objects */
  public void testCloseHierarchy() throws Exception {
    Connection conn = cf.createConnection();
    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = sess.createConsumer(topic1);
    MessageProducer producer = sess.createProducer(topic1);
    sess.createBrowser(queue1);
    Message m = sess.createMessage();

    conn.close();

    // Session

    /* If the session is closed then any method invocation apart from close()
     * will throw an IllegalStateException
     */
    try {
      sess.createMessage();
      fail("Session is not closed");
    } catch (javax.jms.IllegalStateException e) {
    }

    try {
      sess.getAcknowledgeMode();
      fail("should throw IllegalStateException");
    } catch (javax.jms.IllegalStateException e) {
      // OK
    }

    try {
      sess.getTransacted();
      fail("should throw IllegalStateException");
    } catch (javax.jms.IllegalStateException e) {
      // OK
    }

    try {
      sess.getMessageListener();
      fail("should throw IllegalStateException");
    } catch (javax.jms.IllegalStateException e) {
      // OK
    }

    try {
      sess.createProducer(queue1);
      fail("should throw IllegalStateException");
    } catch (javax.jms.IllegalStateException e) {
      // OK
    }

    try {
      sess.createConsumer(queue1);
      fail("should throw IllegalStateException");
    } catch (javax.jms.IllegalStateException e) {
      // OK
    }

    // Producer

    /* If the producer is closed then any method invocation apart from close()
     * will throw an IllegalStateException
     */
    try {
      producer.send(m);
      fail("Producer is not closed");
    } catch (javax.jms.IllegalStateException e) {
    }

    try {
      producer.getDisableMessageID();
      fail("should throw IllegalStateException");
    } catch (javax.jms.IllegalStateException e) {
      // OK
    }

    try {
      producer.getPriority();
      fail("should throw IllegalStateException");
    } catch (javax.jms.IllegalStateException e) {
      // OK
    }

    try {
      producer.getDestination();
      fail("should throw IllegalStateException");
    } catch (javax.jms.IllegalStateException e) {
      // OK
    }

    try {
      producer.getTimeToLive();
      fail("should throw IllegalStateException");
    } catch (javax.jms.IllegalStateException e) {
      // OK
    }

    // ClientConsumer

    try {
      consumer.getMessageSelector();
      fail("should throw exception");
    } catch (javax.jms.IllegalStateException e) {
      // OK
    }

    try {
      consumer.getMessageListener();
      fail("should throw exception");
    } catch (javax.jms.IllegalStateException e) {
      // OK
    }

    try {
      consumer.receive();
      fail("should throw exception");
    } catch (javax.jms.IllegalStateException e) {
      // OK
    }

    // Browser

  }