@Test
  public void testCreateDurableQueueUsingJMXAndRestartServer() throws Exception {
    String queueName = RandomUtil.randomString();
    String binding = RandomUtil.randomString();

    ActiveMQTestBase.checkNoBinding(context, binding);
    checkNoResource(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queueName));

    JMSServerControl control = ManagementControlHelper.createJMSServerControl(mbeanServer);
    control.createQueue(queueName, binding);

    Object o = ActiveMQTestBase.checkBinding(context, binding);
    Assert.assertTrue(o instanceof Queue);
    Queue queue = (Queue) o;
    Assert.assertEquals(queueName, queue.getQueueName());
    checkResource(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queueName));

    serverManager.stop();

    ActiveMQTestBase.checkNoBinding(context, binding);
    checkNoResource(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queueName));

    serverManager = createJMSServer();
    serverManager.start();

    o = ActiveMQTestBase.checkBinding(context, binding);
    Assert.assertTrue(o instanceof Queue);
    queue = (Queue) o;
    Assert.assertEquals(queueName, queue.getQueueName());
    checkResource(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queueName));
  }
  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 testAddDestinationDetailsToMapIfNeeded() throws JMSException {
    Queue queue = mock(Queue.class);
    when(queue.getQueueName()).thenReturn("mock-queue");

    Operation op = new Operation();
    OperationMap map = op.createMap("test-map");

    addDestinationDetailsToMapIfNeeded(queue, map, "test");

    String type = map.get("test" + TYPE, String.class);
    String name = map.get("test" + NAME, String.class);

    assertNotNull(type);
    assertNotNull(name);

    assertEquals(type, DestinationType.Queue.name());
    assertEquals(name, "mock-queue");

    queue = null;
    op = new Operation();
    map = op.createMap("test-map");

    addDestinationDetailsToMapIfNeeded(queue, map, "test");
    type = map.get("test" + TYPE, String.class);
    name = map.get("test" + NAME, String.class);

    assertNull(type);
    assertNull(name);
  }
  @AroundInvoke
  public Object checkArguments(InvocationContext ctx) throws Exception {
    try {
      log = Logger.getLogger(LogoutInterceptor.class);
      Object[] args = ctx.getParameters();
      String className = ctx.getTarget().getClass().getSimpleName();
      log.trace("Class name: " + className);
      String methodName = ctx.getMethod().getName();
      log.trace("Method: " + methodName);

      String sessionId = (String) args[0];
      if ((sessionId == null) || (sessionId.length() == 0)) {
        throw new Exception("sessionId should not be null");
      }

      cf = (QueueConnectionFactory) new InitialContext().lookup(QueueNames.CONNECTION_FACTORY);
      queue = (Queue) new InitialContext().lookup(QueueNames.LOGOUT_QUEUE);
      log.trace("Queue logout: " + queue.getQueueName());
      QueueConnection connection = cf.createQueueConnection();
      QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
      QueueSender sender = session.createSender(queue);

      Message logoutMessage = session.createTextMessage(sessionId);
      Timestamp time = new Timestamp(new Date().getTime());
      // Messages will not accept timestamp property- must change to string
      logoutMessage.setStringProperty(PropertyNames.TIME, time.toString());
      sender.send(logoutMessage);
      session.close();

    } catch (Exception e) {
      log.fatal("Error in LogoutInterceptor", e);
    }
    return ctx.proceed();
  }
Example #5
0
  private int receiveUntilEmpty(Session session, Queue queue) {
    Message message = null;
    int count = 0;
    do {
      try {
        message = receiveMessage(session, queue);
        if (message != null) {
          // JCA queue returns a message of the ObjectMessage type
          Object messageText =
              (message instanceof TextMessage
                  ? ((TextMessage) message).getText()
                  : ((ObjectMessage) message).getObject());
          System.out.println("===== Received message: " + messageText + " =====");
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      count++;
    } while (message != null);

    if (count != 0) {
      try {
        System.out.println(
            "===== Received " + count + " messages from queue " + queue.getQueueName() + " =====");
      } catch (JMSException e) {
        e.printStackTrace();
      }
    }
    return count;
  }
  @Test
  public void testCreateDurableQueueUsingJMSAndRestartServer() throws Exception {
    String queueName = RandomUtil.randomString();
    String binding = RandomUtil.randomString();

    ActiveMQTestBase.checkNoBinding(context, binding);
    checkNoResource(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queueName));

    TransportConfiguration config =
        new TransportConfiguration(InVMConnectorFactory.class.getName());
    Connection connection =
        ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, config)
            .createConnection();
    connection.start();
    Queue managementQueue = ActiveMQJMSClient.createQueue("activemq.management");
    QueueSession session = (QueueSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    QueueRequestor requestor = new QueueRequestor(session, managementQueue);
    Message message = session.createMessage();
    JMSManagementHelper.putOperationInvocation(
        message, "jms.server", "createQueue", queueName, binding);
    Message reply = requestor.request(message);
    Assert.assertTrue(JMSManagementHelper.hasOperationSucceeded(reply));
    connection.close();

    Object o = ActiveMQTestBase.checkBinding(context, binding);
    Assert.assertTrue(o instanceof Queue);
    Queue queue = (Queue) o;
    Assert.assertEquals(queueName, queue.getQueueName());
    checkResource(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queueName));

    serverManager.stop();

    ActiveMQTestBase.checkNoBinding(context, binding);
    checkNoResource(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queueName));

    serverManager = createJMSServer();
    serverManager.start();

    o = ActiveMQTestBase.checkBinding(context, binding);
    Assert.assertTrue(o instanceof Queue);
    queue = (Queue) o;
    Assert.assertEquals(queueName, queue.getQueueName());
    checkResource(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queueName));
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String infoString = "";
    String listString = "";
    logger.info("zzzzzzzzzzzzzzzzzzzzzzzzzzz beginning run");

    try {
      Context initCtx = new InitialContext();
      Context envCtx = (Context) initCtx.lookup("java:comp/env");
      Object oo = envCtx.lookup("jms/ConnectionFactory");
      if (oo != null) {
        infoString += "<h4>Sample lookup: " + oo.getClass().getName() + "</h4>";
      }
      NamingEnumeration<NameClassPair> nameInfo = envCtx.list("jms");
      while (nameInfo.hasMore()) {
        NameClassPair n = nameInfo.next();
        listString += "<li>" + n.getClassName() + " -- " + n.getName() + "</li>";
      }
      Queue tomcatQueue = (Queue) envCtx.lookup("jms/TomcatQueue");
      infoString += "<h4>Tomcat queue: " + tomcatQueue.getQueueName() + "</h4>";
      ActiveMQQueue aQueue = (ActiveMQQueue) tomcatQueue;
      infoString += "<h4>Apache queue: " + aQueue.getDestinationTypeAsString() + "</h4>";

    } catch (Exception ex) {
      String exI = "Error: " + ex.getClass().getName() + "-- " + ex.getMessage();
      logger.error(exI);
      infoString += "Error: <b>" + exI + "</b>";
    }

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet JmsTestServlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>List of items at java:comp/env/jms</h1>");
    out.println("<p>" + infoString + "</p>");
    out.println("<ol>" + listString + "</ol>");
    out.println("</body>");
    out.println("</html>");
  }
 @Override
 public EmbeddedJMS createArtemisBroker() throws Exception {
   Configuration config0 = createConfig("localhost", 0);
   String coreQueueAddress = "jms.queue." + brokerZeroQueue.getQueueName();
   AddressSettings addrSettings = new AddressSettings();
   addrSettings.setQueuePrefetch(0);
   config0.getAddressesSettings().put(coreQueueAddress, addrSettings);
   EmbeddedJMS newbroker =
       new EmbeddedJMS().setConfiguration(config0).setJmsConfiguration(new JMSConfigurationImpl());
   return newbroker;
 }
  private void doTestDeployQueuesWithUnusualNames(
      final String queueName, final String htmlEncodedName, final String jndiName)
      throws Exception {
    JMSServerDeployer deployer = new JMSServerDeployer(jmsServer, deploymentManager);

    String xml =
        "<queue name=\""
            + htmlEncodedName
            + "\">"
            + "<entry name=\""
            + jndiName
            + "\"/>"
            + "</queue>";

    Element rootNode = org.hornetq.utils.XMLUtil.stringToElement(xml);

    deployer.deploy(rootNode);

    Queue queue = (Queue) context.lookup(jndiName);
    Assert.assertNotNull(queue);
    Assert.assertEquals(queueName, queue.getQueueName());
  }
Example #10
0
  public boolean checkEmpty(final Queue queue, final int index) throws Exception {
    ManagementService managementService = server0.getManagementService();
    if (index == 1) {
      managementService = server1.getManagementService();
    }
    JMSQueueControl queueControl =
        (JMSQueueControl)
            managementService.getResource(ResourceNames.JMS_QUEUE + queue.getQueueName());

    Long messageCount = queueControl.getMessageCount();

    if (messageCount > 0) {
      queueControl.removeMessages(null);
    }
    return true;
  }
Example #11
0
  /**
   * Test that if the alert value is change from the previous value we can still get alerts.
   *
   * <p>Test sends two messages to the broker then restarts the broker with new configuration.
   *
   * <p>If the test is running inVM the test validates that the new configuration has been applied.
   *
   * <p>Validates that we only have two messages on the queue and then sends enough messages to
   * trigger the alert.
   *
   * <p>The alert is then validate.
   *
   * @throws Exception
   */
  public void testAlertingReallyWorksWithChanges() throws Exception {
    // send some messages and nuke the logs
    sendMessage(_session, _destination, 2);
    _session.commit();
    // To prevent any failover/retry/connection dropped errors
    _connection.close();

    stopBroker();

    _monitor.reset();

    // Change max message count to 5, start broker and make sure that that's triggered at the right
    // time
    setConfigurationProperty(
        "virtualhosts.virtualhost." + VIRTUALHOST + ".queues.maximumMessageCount", "5");

    startBroker();

    if (isInternalBroker()) {
      assertEquals(
          "Alert Max Msg Count is not correct",
          5,
          ApplicationRegistry.getInstance()
              .getVirtualHostRegistry()
              .getVirtualHost(VIRTUALHOST)
              .getQueueRegistry()
              .getQueue(new AMQShortString(_destination.getQueueName()))
              .getMaximumMessageCount());
    }

    setupConnection();

    // Validate the queue depth is as expected
    long messageCount = ((AMQSession<?, ?>) _session).getQueueDepth((AMQDestination) _destination);
    assertEquals("Broker has invalid message count for test", 2, messageCount);

    // Ensure the alert has not occured yet
    assertLoggingNotYetOccured(MESSAGE_COUNT_ALERT);

    // Trigger the new value
    sendMessage(_session, _destination, 3);
    _session.commit();

    // Validate that the alert occured.
    wasAlertFired();
  }
Example #12
0
 public void testQueueNamesWithTrailingSpaces() throws Exception {
   Queue queue = (Queue) ctx.lookup("QueueNameWithSpace");
   assertEquals("QueueNameWithSpace", queue.getQueueName());
 }
Example #13
0
 public JmsQueueEndpoint(Queue destination) throws JMSException {
   this("jms:queue:" + destination.getQueueName(), null);
   setDestination(destination);
 }
  public void testDeployFullConfiguration2() throws Exception {
    JMSServerDeployer deployer = new JMSServerDeployer(jmsServer, deploymentManager);

    String conf = "hornetq-jms-for-JMSServerDeployerTest2.xml";
    URI confURL = Thread.currentThread().getContextClassLoader().getResource(conf).toURI();

    String[] connectionFactoryBindings =
        new String[] {
          "/fullConfigurationConnectionFactory",
          "/acme/fullConfigurationConnectionFactory",
          "java:/xyz/tfullConfigurationConnectionFactory",
          "java:/connectionfactories/acme/fullConfigurationConnectionFactory"
        };
    String[] queueBindings =
        new String[] {"/fullConfigurationQueue", "/queue/fullConfigurationQueue"};
    String[] topicBindings =
        new String[] {"/fullConfigurationTopic", "/topic/fullConfigurationTopic"};

    for (String binding : connectionFactoryBindings) {
      UnitTestCase.checkNoBinding(context, binding);
    }
    for (String binding : queueBindings) {
      UnitTestCase.checkNoBinding(context, binding);
    }
    for (String binding : topicBindings) {
      UnitTestCase.checkNoBinding(context, binding);
    }

    deployer.deploy(confURL);

    for (String binding : connectionFactoryBindings) {
      UnitTestCase.checkBinding(context, binding);
    }
    for (String binding : queueBindings) {
      UnitTestCase.checkBinding(context, binding);
    }
    for (String binding : topicBindings) {
      UnitTestCase.checkBinding(context, binding);
    }

    for (String binding : connectionFactoryBindings) {
      HornetQConnectionFactory cf = (HornetQConnectionFactory) context.lookup(binding);
      Assert.assertNotNull(cf);
      Assert.assertEquals(1234, cf.getClientFailureCheckPeriod());
      Assert.assertEquals(5678, cf.getCallTimeout());
      Assert.assertEquals(12345, cf.getConsumerWindowSize());
      Assert.assertEquals(6789, cf.getConsumerMaxRate());
      Assert.assertEquals(123456, cf.getConfirmationWindowSize());
      Assert.assertEquals(7712652, cf.getProducerWindowSize());
      Assert.assertEquals(789, cf.getProducerMaxRate());
      Assert.assertEquals(12, cf.getMinLargeMessageSize());
      Assert.assertEquals("TestClientID", cf.getClientID());
      Assert.assertEquals(3456, cf.getDupsOKBatchSize());
      Assert.assertEquals(4567, cf.getTransactionBatchSize());
      Assert.assertEquals(true, cf.isBlockOnAcknowledge());
      Assert.assertEquals(false, cf.isBlockOnNonDurableSend());
      Assert.assertEquals(true, cf.isBlockOnDurableSend());
      Assert.assertEquals(false, cf.isAutoGroup());
      Assert.assertEquals(true, cf.isPreAcknowledge());
      Assert.assertEquals(2345, cf.getConnectionTTL());
      assertEquals(true, cf.isFailoverOnInitialConnection());
      Assert.assertEquals(34, cf.getReconnectAttempts());
      Assert.assertEquals(5, cf.getRetryInterval());
      Assert.assertEquals(6.0, cf.getRetryIntervalMultiplier());
      Assert.assertEquals(true, cf.isCacheLargeMessagesClient());
    }

    for (String binding : queueBindings) {
      Queue queue = (Queue) context.lookup(binding);
      Assert.assertNotNull(queue);
      Assert.assertEquals("fullConfigurationQueue", queue.getQueueName());
    }

    for (String binding : topicBindings) {
      Topic topic = (Topic) context.lookup(binding);
      Assert.assertNotNull(topic);
      Assert.assertEquals("fullConfigurationTopic", topic.getTopicName());
    }
  }
  /**
   * 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();
  }
 @Test
 public void injectQueue() throws JMSException {
   Queue queue = q.get();
   Assert.assertNotNull(queue);
   Assert.assertNotNull("Q", queue.getQueueName());
 }
Example #17
0
 protected NevadoQueue(Queue queue) throws JMSException {
   super(queue.getQueueName());
 }