Example #1
0
  /**
   * Listen to a message from JMS from a given destination by name.
   *
   * @param destinationName destinationName
   * @param messageListener messageListener
   */
  public void listenTextMessagesWithDestination(
      final String destinationName, final Consumer<String> messageListener) {
    final MessageConsumer consumer = getConsumer(destinationName);
    try {
      consumer.setMessageListener(
          message -> {
            try {
              messageListener.accept(((TextMessage) message).getText());

              if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE) {
                message.acknowledge();
              }

            } catch (JMSException e) {

              throw new IllegalStateException(
                  "Unable to register get text from message in listener " + destinationName, e);
            } catch (Exception ex) {

              throw new IllegalStateException("Unable handle JMS Consumer  " + destinationName, ex);
            }
          });
    } catch (JMSException e) {

      throw new IllegalStateException("Unable to register message listener " + destinationName, e);
    }
  }
Example #2
0
  public static void main(String[] args) {
    try {

      // Gets the JgetTopicName()NDI context
      Context jndiContext = new InitialContext();

      // Looks up the administered objects
      ConnectionFactory connectionFactory =
          (ConnectionFactory) jndiContext.lookup("jms/javaee6/ConnectionFactory");
      Queue queue = (Queue) jndiContext.lookup("jms/javaee6/Queue");

      // Creates the needed artifacts to connect to the queue
      Connection connection = connectionFactory.createConnection();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageConsumer consumer = session.createConsumer(queue);
      connection.start();

      // Loops to receive the messages
      System.out.println("\nInfinite loop. Waiting for a message...");
      while (true) {
        TextMessage message = (TextMessage) consumer.receive();
        System.out.println("Message received: " + message.getText());
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #3
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();
  }
Example #4
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 static void main(String[] args) {
    try {
      Context ctx = new InitialContext();
      ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory");
      Queue queue = (Queue) ctx.lookup("inbound");

      Connection con = factory.createConnection();
      final Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
      final MessageConsumer consumer = session.createConsumer(queue);

      consumer.setMessageListener(
          new MessageListener() {
            @Override
            public void onMessage(Message message) {
              final String type;
              try {
                type = message.getStringProperty("type");
                if (type != null && type.equals("xml")) {

                  System.out.println(((TextMessage) message).getText());
                }

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

      con.start();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #6
0
  /**
   * Receive a message from destination with timeout.
   *
   * @param destinationName destinationName
   * @param timeout timeout
   * @return message
   */
  public String receiveTextMessageFromDestinationWithTimeout(
      final String destinationName, final int timeout) {

    if (!this.isConnected()) {
      throw new JmsNotConnectedException("Not connected");
    }
    MessageConsumer consumer = getConsumer(destinationName);
    TextMessage message;
    try {
      if (timeout == 0) {
        message = (TextMessage) consumer.receiveNoWait();
      } else {
        message = (TextMessage) consumer.receive(timeout);
      }
      if (message != null) {

        if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE) {
          message.acknowledge();
        }
        return message.getText();
      } else {
        return null;
      }
    } catch (JMSException e) {
      throw new IllegalStateException("Unable to receive message from " + destinationName, e);
    }
  }
  public static void main(String args[]) {
    Connection connection = null;

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

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

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

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

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

      consumer.close();
      session.close();
    } catch (Throwable t) {
      LOG.error("Error receiving message", t);
    } finally {
      // Cleanup code
      // In general, you should always close producers, consumers,
      // sessions, and connections in reverse order of creation.
      // For this simple example, a JMS connection.close will
      // clean up all other resources.
      if (connection != null) {
        try {
          connection.close();
        } catch (JMSException e) {
          LOG.error("Error closing connection", e);
        }
      }
    }
  }
Example #8
0
  public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
      url = args[0].trim();
    }
    System.out.println(
        "\nWaiting to receive messages... will timeout after " + TIMEOUT / 1000 + "s");
    ActiveMQConnectionFactory connectionFactory =
        new ActiveMQConnectionFactory("admin", "password", url);
    Connection connection = null;

    try {

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

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

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

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

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

    } catch (Exception e) {
      System.out.println("Caught exception!");
    } finally {
      if (connection != null) {
        try {
          connection.close();
        } catch (JMSException e) {
          System.out.println("Could not close an open connection...");
        }
      }
    }
  }
Example #9
0
  public static void main(String[] args) throws JMSException {

    String user = env("ACTIVEMQ_USER", "");
    String password = env("ACTIVEMQ_PASSWORD", "");
    String host = env("ACTIVEMQ_HOST", "localhost");
    int port = Integer.parseInt(env("ACTIVEMQ_PORT", "61616"));
    String destination = arg(args, 0, "foo.bar");

    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://" + host + ":" + port);

    Connection connection = factory.createConnection(user, password);
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination dest = new ActiveMQQueue(destination);

    MessageConsumer consumer = session.createConsumer(dest);
    long start = System.currentTimeMillis();
    long count = 1;
    System.out.println("Waiting for messages...");
    while (true) {
      Message msg = consumer.receive();
      if (msg instanceof TextMessage) {
        String body = ((TextMessage) msg).getText();
        if ("THE.END".equals(body)) {
          long diff = System.currentTimeMillis() - start;
          System.out.println(
              String.format("Received %d in %.2f seconds", count, (1.0 * diff / 1000.0)));
          break;
        } else {
          if (count != msg.getIntProperty("id")) {
            System.out.println("mismatch: " + count + "!=" + msg.getIntProperty("id"));
          }
          count = msg.getIntProperty("id");

          if (count == 0) {
            start = System.currentTimeMillis();
          }
          if (count % 1000 == 0) {
            System.out.println(String.format("Received %d messages.", count));
          }
          count++;
        }

      } else {
        System.out.println("Unexpected message type: " + msg.getClass());
      }
    }
    connection.close();
  }
Example #10
0
 /**
  * Receives a command from a queue synchronously. If this queue also has listeners, then commands
  * will be distributed across all consumers.
  *
  * @param queueName name of queue
  * @param timeout timeout in milliseconds. If a command is not received during a timeout, this
  *     methods returns null.
  * @return command if found. If command not found, this method will block till a command is
  *     present in queue or a timeout expires.
  */
 public Command receiveCommand(String queueName, long timeout) {
   Session session = null;
   try {
     session = consumerConnection.createSession();
     Queue queue = (Queue) jmsServer.lookup("/queue/" + queueName);
     MessageConsumer consumer = session.createConsumer(queue);
     return message2Command((TextMessage) consumer.receive(timeout));
   } catch (Exception e) {
     throw new HornetNestException("Could not get command", e);
   } finally {
     try {
       if (session != null) session.close();
     } catch (Throwable e) {
     }
   }
 }
  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();
    }
  }
  @Test
  public void testReceiveMessageTimeout() throws JMSException {
    JmsMessageReceiver receiver = new JmsMessageReceiver();
    receiver.setConnectionFactory(connectionFactory);

    receiver.setDestination(destination);

    reset(jmsTemplate, connectionFactory, destination, connection, session, messageConsumer);

    expect(connectionFactory.createConnection()).andReturn(connection).once();
    expect(connection.createSession(anyBoolean(), anyInt())).andReturn(session).once();
    expect(session.getTransacted()).andReturn(false).once();
    expect(session.getAcknowledgeMode()).andReturn(Session.AUTO_ACKNOWLEDGE).once();

    expect(session.createConsumer(destination, null)).andReturn(messageConsumer).once();

    expect(messageConsumer.receive(5000L)).andReturn(null).once();

    connection.start();
    expectLastCall().once();

    replay(jmsTemplate, connectionFactory, destination, connection, session, messageConsumer);

    try {
      receiver.receive();
    } catch (ActionTimeoutException e) {
      Assert.assertTrue(
          e.getMessage().startsWith("Action timed out while receiving JMS message on"));
      return;
    }

    Assert.fail(
        "Missing " + CitrusRuntimeException.class + " because of receiveing message timeout");
  }
  /**
   * Stellt die Nachricht an alle Consumer zu.
   *
   * @param consumers die Message-Consumer.
   * @param msg
   */
  private void deliver(Message msg) {
    if (pool.isTerminating() || pool.isTerminated()) {
      Logger.warn("shutdown in progress, no more messages accepted");
      return; // wir nehmen keine Nachrichten mehr entgegen.
    }

    // BUGZILLA 1413 Wir koennen leider doch nicht auf einer Kopie der Liste arbeiten, weil
    // diese waehrend der Zustellung erweitert werden kann. Z.bsp. der "AutoRegisterMessageConsumer"
    // erhaelt die SYSTEM_STARTED-Message und registriert daraufhin neue Consumer. Unter anderem
    // den DeployMessageConsumer aus jameica.webadmin, der ebenfalls auf die SYSTEM_STARTED-Message
    // lauscht.
    Logger.debug("deliver message " + msg.toString());
    MessageConsumer consumer = null;
    for (int i = 0; i < this.consumers.size(); ++i) {
      consumer = this.consumers.get(i);
      Class[] expected = consumer.getExpectedMessageTypes();
      boolean send = expected == null;
      if (expected != null) {
        for (int j = 0; j < expected.length; ++j) {
          if (expected[j].isInstance(msg)) {
            send = true;
            break;
          }
        }
      }
      try {
        if (send) consumer.handleMessage(msg);
      } catch (ApplicationException ae) {
        Application.getMessagingFactory()
            .sendSyncMessage(new StatusBarMessage(ae.getMessage(), StatusBarMessage.TYPE_ERROR));
      } catch (OperationCanceledException oce) {
        Logger.debug("consumer " + consumer.getClass().getName() + " cancelled message " + msg);
      } catch (Throwable t) {
        Logger.error(
            "consumer "
                + consumer.getClass().getName()
                + " produced an error ("
                + t.getClass().getName()
                + ": "
                + t
                + ") while consuming message "
                + msg);
        Logger.write(Level.INFO, "error while processing message", t);
      }
    }
  }
Example #14
0
 private void consume() {
   try {
     consumer = session.createConsumer(queue);
     message = consumer.receive();
   } catch (JMSException e) {
     e.printStackTrace();
   }
 }
Example #15
0
 @Override
 public void stop() {
   try {
     messageConsumer.close();
     connection.stop();
   } catch (JMSException e) {
     e.printStackTrace();
   }
 }
Example #16
0
    public void run() {
      try {

        // Create a ConnectionFactory
        String conStr = "tcp://localhost:61616";

        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(conStr);

        System.out.println("Connecting...");
        // Create a Connection
        Connection connection = connectionFactory.createConnection();
        connection.start();

        connection.setExceptionListener(this);

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

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

        // Create a MessageConsumer from the Session to the Topic or
        // Queue
        MessageConsumer consumer = session.createConsumer(destination);

        while (true) {
          // Wait for a message
          Message message = consumer.receive(1000);

          if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            String text = textMessage.getText();
            System.out.println("Received: " + text);
          } else {
            System.out.println("Received: " + message);
          }
        }
      } catch (Exception e) {
        System.out.println("Caught: " + e);
        e.printStackTrace();
      }
    }
Example #17
0
  public Value receive(Env env, @Optional("1") long timeout) throws JMSException {
    Message message = _consumer.receive(timeout);

    if (message == null) return BooleanValue.FALSE;

    if (message instanceof ObjectMessage) {
      Object object = ((ObjectMessage) message).getObject();

      return env.wrapJava(object);
    } else if (message instanceof TextMessage) {
      return env.createString(((TextMessage) message).getText());
    } else if (message instanceof StreamMessage) {
      Object object = ((StreamMessage) message).readObject();

      return env.wrapJava(object);
    } else if (message instanceof BytesMessage) {
      BytesMessage bytesMessage = (BytesMessage) message;
      int length = (int) bytesMessage.getBodyLength();

      StringValue bb = env.createBinaryBuilder(length);

      TempBuffer tempBuffer = TempBuffer.allocate();
      int sublen;

      while (true) {
        sublen = bytesMessage.readBytes(tempBuffer.getBuffer());

        if (sublen > 0) bb.append(tempBuffer.getBuffer(), 0, sublen);
        else break;
      }

      TempBuffer.free(tempBuffer);

      return bb;
    } else if (message instanceof MapMessage) {
      MapMessage mapMessage = (MapMessage) message;

      Enumeration mapNames = mapMessage.getMapNames();

      ArrayValue array = new ArrayValueImpl();

      while (mapNames.hasMoreElements()) {
        String name = mapNames.nextElement().toString();

        Object object = mapMessage.getObject(name);

        array.put(env.createString(name), env.wrapJava(object));
      }

      return array;
    } else {
      return BooleanValue.FALSE;
    }
  }
  /**
   * @see
   *     de.willuhn.jameica.messaging.MessagingQueue#unRegisterMessageConsumer(de.willuhn.jameica.messaging.MessageConsumer)
   */
  public void unRegisterMessageConsumer(MessageConsumer consumer) {
    if (consumer == null) return;

    if (this.consumers.size() == 0) {
      Logger.debug("queue contains no consumers, skip unregistering");
      return;
    }

    Logger.debug(
        "queue " + this.name + ": unregistering message consumer " + consumer.getClass().getName());
    this.consumers.remove(consumer);
  }
Example #19
0
  private void setupMessageQueueConsumer() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(messageBrokerUrl);
    Connection connection;
    try {
      connection = connectionFactory.createConnection();
      connection.start();
      this.session = connection.createSession(this.transacted, ackMode);
      Destination adminQueue = this.session.createQueue(messageQueueName);

      // Setup a message producer to respond to messages from clients, we will get the destination
      // to send to from the JMSReplyTo header field from a Message
      this.replyProducer = this.session.createProducer(null);
      this.replyProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

      // Set up a consumer to consume messages off of the admin queue
      MessageConsumer consumer = this.session.createConsumer(adminQueue);
      consumer.setMessageListener(this);
    } catch (JMSException e) {
      // Handle the exception appropriately
    }
  }
Example #20
0
 @Override
 public void start() {
   try {
     connection = connectionFactory.createConnection();
     Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
     messageConsumer = session.createConsumer(schedulerQueue);
     messageConsumer.setMessageListener(this);
     connection.start();
   } catch (JMSException e) {
     e.printStackTrace();
   }
 }
Example #21
0
  public static void main(String[] args) throws Exception {

    stopMQService();

    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory();

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

    final Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createQueue("my-queue");

    MessageConsumer consumer = session.createConsumer(destination);
    /*
     * //listener 方式 consumer.setMessageListener(new MessageListener() {
     *
     * public void onMessage(Message msg) { MapMessage message =
     * (MapMessage) msg; //TODO something.... System.out.println("收到消息:" +
     * new Date(message.getLong("count"))); session.commit(); }
     *
     * }); Thread.sleep(30000);
     */
    int i = 0;
    int num = 0;
    while (i < 3) {
      num++;
      MapMessage message = (MapMessage) consumer.receive();
      session.commit();
      // TODO something....
      // System.out.println("收到消息:" + new Date(message.getLong("count")));
      System.out.println("2收到第" + num + "条消息:" + message.getString("count"));

      //			System.out.println("收到第"+num+"条消息:" + message.getString("mes"));

    }

    session.close();
    connection.close();
  }
  /** @param args the command line arguments */
  public static void main(String[] args)
      throws NamingException, JMSException, InterruptedException {

    BasicConfigurator.resetConfiguration();
    BasicConfigurator.configure();

    try {
      Properties props = new Properties();
      props.setProperty(
          Context.INITIAL_CONTEXT_FACTORY,
          "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
      props.setProperty(Context.PROVIDER_URL, "tcp://miniserver.local:61616");
      Context context = new InitialContext(props);

      ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("ConnectionFactory");

      FileSystemListener myListener = new FileSystemListener();

      Destination destination = (Destination) context.lookup("dynamicTopics/eXistdb");

      LOG.info("Destination=" + destination);

      Connection connection = connectionFactory.createConnection();

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

      MessageConsumer messageConsumer = session.createConsumer(destination);

      messageConsumer.setMessageListener(myListener);

      connection.start();

      LOG.info("Receiver is ready");

    } catch (Throwable t) {
      LOG.error(t.getMessage(), t);
    }
  }
 @Override
 public T take() throws FalconException {
   try {
     TextMessage textMessage = (TextMessage) consumer.receive();
     T event =
         new RerunEventFactory<T>()
             .getRerunEvent(textMessage.getStringProperty("TYPE"), textMessage.getText());
     LOG.debug("Dequeued Message: {}", event.toString());
     return event;
   } catch (Exception e) {
     LOG.error("Error getting the message from ActiveMQ", e);
     throw new FalconException("Error getting the message from ActiveMQ: ", e);
   }
 }
  /**
   * @see
   *     de.willuhn.jameica.messaging.MessagingQueue#registerMessageConsumer(de.willuhn.jameica.messaging.MessageConsumer)
   */
  public void registerMessageConsumer(MessageConsumer consumer) {
    if (consumer == null) return;

    Logger.debug(
        "queue " + this.name + ": registering message consumer " + consumer.getClass().getName());
    this.consumers.add(consumer);

    // Wir haben mindestens eine zwischengespeicherte Message und wenigstens einen Consumer - wir
    // koennen die Queue jetzt leeren
    int size = this.queue.size();
    if (size > 0) {
      Logger.info("delivering " + size + " queued messages to queue: " + this.name);
      this.queue.drainTo(messages);
    }
  }
  @Test
  public void testWithMessageSelectorAndCustomTimeout() throws JMSException {
    JmsMessageReceiver receiver = new JmsMessageReceiver();
    receiver.setConnectionFactory(connectionFactory);

    receiver.setDestination(destination);
    receiver.setReceiveTimeout(10000L);

    Map<String, Object> controlHeaders = new HashMap<String, Object>();
    final Message<String> controlMessage =
        MessageBuilder.withPayload("<TestRequest><Message>Hello World!</Message></TestRequest>")
            .copyHeaders(controlHeaders)
            .build();

    Map<String, String> headers = new HashMap<String, String>();

    reset(jmsTemplate, connectionFactory, destination, connection, session, messageConsumer);

    expect(connectionFactory.createConnection()).andReturn(connection).once();
    expect(connection.createSession(anyBoolean(), anyInt())).andReturn(session).once();
    expect(session.getTransacted()).andReturn(false).once();
    expect(session.getAcknowledgeMode()).andReturn(Session.AUTO_ACKNOWLEDGE).once();

    expect(session.createConsumer(destination, "Operation = 'sayHello'"))
        .andReturn(messageConsumer)
        .once();

    connection.start();
    expectLastCall().once();

    expect(messageConsumer.receive(10000L))
        .andReturn(
            new TextMessageImpl(
                "<TestRequest><Message>Hello World!</Message></TestRequest>", headers))
        .once();

    replay(jmsTemplate, connectionFactory, destination, connection, session, messageConsumer);

    Message<?> receivedMessage = receiver.receiveSelected("Operation = 'sayHello'");
    Assert.assertEquals(receivedMessage.getPayload(), controlMessage.getPayload());

    verify(jmsTemplate, connectionFactory, destination, connection, session, messageConsumer);
  }
Example #26
0
  public static void main(String[] args) {
    _logger.info("Starting...");

    final String host;
    final int port;
    final String username;
    final String password;
    final String virtualPath;
    final int numExpectedMessages;
    if (args.length == 0) {
      host = "localhost";
      port = 5672;
      username = "******";
      password = "******";
      virtualPath = "/test";
      numExpectedMessages = 100;
    } else if (args.length == 6) {
      host = args[0];
      port = Integer.parseInt(args[1]);
      username = args[2];
      password = args[3];
      virtualPath = args[4];
      numExpectedMessages = Integer.parseInt(args[5]);
    } else {
      System.out.println("Usage: host port username password virtual-path expectedMessageCount");
      System.exit(1);
      throw new RuntimeException("cannot be reached");
    }

    try {
      InetAddress address = InetAddress.getLocalHost();
      AMQConnection con =
          new AMQConnection(host, port, username, password, address.getHostName(), virtualPath);
      final AMQSession session = (AMQSession) con.createSession(false, Session.AUTO_ACKNOWLEDGE);

      final int expectedMessageCount = numExpectedMessages;

      MessageConsumer consumer =
          session.createConsumer(
              new AMQTopic(session.getDefaultTopicExchangeName(), new AMQShortString("large")),
              100,
              true,
              false,
              null);

      consumer.setMessageListener(
          new MessageListener() {
            private int _messageCount;

            private long _startTime = 0;

            public void onMessage(Message message) {
              validateMessage(message);
              if (_messageCount++ == 0) {
                _startTime = System.currentTimeMillis();
              }
              if (_logger.isInfoEnabled()) {
                _logger.info("Got message '" + message + "'");
              }
              if (_messageCount == expectedMessageCount) {
                long totalTime = System.currentTimeMillis() - _startTime;
                _logger.error(
                    "Total time to receive "
                        + _messageCount
                        + " messages was "
                        + totalTime
                        + "ms. Rate is "
                        + (_messageCount / (totalTime / 1000.0)));
              }
            }

            private void validateMessage(Message message) {
              if (!(message instanceof BytesMessage)) {
                _logger.error(
                    "Message is not of correct type - should be BytesMessage and is "
                        + message.getClass());
              }
              BytesMessage bm = (BytesMessage) message;
              final int expectedSize = 1024 * 187; // 187k
              try {
                if (bm.getBodyLength() != expectedSize) {
                  _logger.error(
                      "Message is not correct length - should be  "
                          + expectedSize
                          + " and is "
                          + bm.getBodyLength());
                }
              } catch (JMSException e) {
                _logger.error("Failed to validate message: " + e, e);
              }
              try {
                byte[] data = new byte[(int) bm.getBodyLength()];
                bm.readBytes(data);
                for (int i = 0; i < data.length; i++) {
                  if (data[i] != (byte) (i % 25)) {
                    _logger.error(
                        "byte "
                            + i
                            + " of message is wrong - should be "
                            + i % 25
                            + " but is "
                            + data[i]);
                  }
                }
                _logger.info("***** Validated message successfully");
              } catch (JMSException e) {
                _logger.error("Failed to validate message: " + e, e);
              }
            }
          });
      con.start();
    } catch (Throwable t) {
      System.err.println("Fatal error: " + t);
      t.printStackTrace();
    }

    System.out.println("Waiting...");
  }
  public static void main(String... args) throws Exception {

    ConnectionFactory connectionFactory = null;
    Connection connection = null;
    Session session = null;
    MessageProducer producer = null;
    MessageConsumer consumer = null;
    Destination destination = null;
    TextMessage message = null;
    Context context = null;

    try {
      // Set up the context for the JNDI lookup
      final Properties env = new Properties();
      env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
      env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));
      env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME));
      env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD));
      context = new InitialContext(env);

      // Perform the JNDI lookups
      String connectionFactoryString =
          System.getProperty("connection.factory", DEFAULT_CONNECTION_FACTORY);
      log.info("Attempting to acquire connection factory \"" + connectionFactoryString + "\"");
      connectionFactory = (ConnectionFactory) context.lookup(connectionFactoryString);
      log.info("Found connection factory \"" + connectionFactoryString + "\" in JNDI");

      String destinationString = System.getProperty("destination", DEFAULT_DESTINATION);
      log.info("Attempting to acquire destination \"" + destinationString + "\"");
      destination = (Destination) context.lookup(destinationString);
      log.info("Found destination \"" + destinationString + "\" in JNDI");

      // Create the JMS connection, session, producer, and consumer
      connection =
          connectionFactory.createConnection(
              System.getProperty("username", DEFAULT_USERNAME),
              System.getProperty("password", DEFAULT_PASSWORD));
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      producer = session.createProducer(destination);
      consumer = session.createConsumer(destination);
      connection.start();

      int count = Integer.parseInt(System.getProperty("message.count", DEFAULT_MESSAGE_COUNT));
      String content = System.getProperty("message.content", DEFAULT_MESSAGE);

      log.info("Sending " + count + " messages with content: " + content);

      // Send the specified number of messages
      for (int i = 0; i < count; i++) {
        message = session.createTextMessage(content);
        producer.send(message);
      }

      // Then receive the same number of messages that were sent
      for (int i = 0; i < count; i++) {
        message = (TextMessage) consumer.receive(5000);
        log.info("Received message with content " + message.getText());
      }
    } catch (Exception exception) {
      log.severe(exception.getMessage());
      throw exception;
    } finally {
      if (context != null) {
        context.close();
      }

      // closing the connection takes care of the session, producer, and consumer
      if (connection != null) {
        connection.close();
      }
    }
  }
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("<html><head></head><body>");

    try {
      // Gather necessary JMS resources
      Context ctx = new InitialContext();
      ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/myConnectionFactory");
      Connection con = cf.createConnection();
      con.start(); // don't forget to start the connection
      QueueSession session = (QueueSession) con.createSession(false, Session.AUTO_ACKNOWLEDGE);

      // The PITsnapshot Queue is used for responses from the Players to this serverlet
      Queue q = (Queue) ctx.lookup("jms/PITsnapshot");
      MessageConsumer reader = session.createConsumer(q);

      /*
       * Throw out old PITsnapshot messages that may have been left from past
       * snapshots that did not complete (because of some error).
       */
      ObjectMessage m = null;
      while ((m = (ObjectMessage) reader.receiveNoWait()) != null) {
        System.out.println("Found an orphaned PITsnapshot message");
      }

      // Initialize the snapshot my sending a marker to a Player
      sendInitSnapshot();

      /*
       * Receive the snapshot messages from all Players.
       * Each snapshot is a HahsMap.  Put them into an array of HashMaps             *
       */
      HashMap state[] = new HashMap[numPlayers + 1];
      int stateResponses = 0;
      int failures = 0;
      while (stateResponses < numPlayers) {
        if ((m = (ObjectMessage) reader.receive(1000)) == null) {
          if (++failures > 10) {
            System.out.println("Not all players reported, giving up after " + stateResponses);
            break;
          }
          continue;
        }
        state[stateResponses++] = (HashMap) m.getObject();
      }

      /*
       * For each commodity, sum the number of them reported from
       * each Player.  Store these into a two dimensional table
       * that will then be used to generate the report back to the user.
       */
      String commodity[] = {"rice", "gold", "oil"};
      int total[][] = new int[numPlayers][commodity.length];
      for (int c = 0; c < commodity.length; c++) {
        for (int p = 0; p < stateResponses; p++) {
          try {
            Integer ccount = (Integer) state[p].get(commodity[c]);
            if (ccount == null) {
              total[p][c] = 0;
            } else {
              total[p][c] = (Integer) ccount.intValue();
            }
          } catch (Exception e) {
            System.out.println("Servlet threw exception " + e);
          }
        }
      }

      /*
       * Now turn the table of commodities, and the state from each Player
       * into a response to the user.
       */
      for (int c = 0; c < commodity.length; c++) {
        int ctotal = 0;
        out.print("<h2>Commodity: " + commodity[c] + "</h2>");
        out.print("<table border='1'><tr><th>Player</th><th>Quantity</th></tr>");
        for (int p = 0; p < stateResponses; p++) {
          out.print("<tr><td>" + p + "</td><td>" + total[p][c] + "</td></tr>");
          ctotal += total[p][c];
        }
        out.print("<tr><td><b>Total</b></td><td>" + ctotal + "</td></tr>");
        out.print("</table></br></br>");
      }

      // Close the connection
      con.close();

      out.println("</BODY></HTML>");

    } catch (Exception e) {
      System.out.println("Servlet threw exception " + e);
    } finally {
      out.println("</body></html>");
      out.close();
    }
  }
  public static void main(String[] args) {
    Connection connection = null;
    try {
      Context context = new InitialContext();
      ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME);
      Destination destination = (Destination) context.lookup(DESTINATION_NAME);
      Destination controlDestination = (Destination) context.lookup(CONTROL_DESTINATION_NAME);

      connection = factory.createConnection();

      // create a session for the control producer
      Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
      MessageProducer controlProducer = session.createProducer(controlDestination);

      MessageConsumer consumer = session.createConsumer(destination);
      consumer.setMessageListener(new JmsMessageListener(session, controlProducer));

      // Must have a separate session or connection for the sync MessageConsumer
      // per JMS spec you cannot have sync and async message consumers on the same
      // session
      Session controlSession = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
      MessageConsumer controlConsumer = controlSession.createConsumer(controlDestination);

      // calling start after the listeners have been registered
      connection.start();

      LOG.info("Start control message consumer");
      int i = 1;
      while (true) {
        // sync receive for message consumer
        Message message = controlConsumer.receive(MESSAGE_TIMEOUT_MILLISECONDS);
        if (message != null) {
          if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            String text = textMessage.getText();
            LOG.info("Got " + (i++) + ". message: " + text);

            if (text.startsWith("SHUTDOWN")) {
              break;
            }
          }
        }
      }

      controlConsumer.close();
      controlSession.close();
      consumer.close();
      controlProducer.close();
      session.close();

    } catch (Exception e) {
      LOG.error(e);
    } finally {
      // got to clean up the connections and other resources!
      if (connection != null) {
        try {
          connection.close();
        } catch (JMSException e) {
          LOG.error(e);
        }
      }
    }
  }
Example #30
0
  @Override
  public int run() throws Exception {
    // Default values of command line arguments
    String host = DEFAULT_HOST;
    int port = DEFAULT_PORT;
    String user = DEFAULT_USER;
    String pass = DEFAULT_PASS;
    String destination = DEFAULT_DESTINATION;
    String file = ""; // No default -- if not given, don't read/write file
    int sleep = 0;
    boolean showpercent = false;
    int batchSize = 0;
    int length = 500; // Length of message generated internally
    String properties = "";
    String format = "short";
    String durable = null;

    int n = 1; // n is the number of messages to process, or a specific
    //   message number, depending on content
    String url = ""; // No default -- if not given, don't use it

    String[] nonSwitchArgs = cl.getArgs();
    if (nonSwitchArgs.length > 0) n = Integer.parseInt(nonSwitchArgs[0]);

    String _destination = cl.getOptionValue("destination");
    if (_destination != null) destination = _destination;

    String _host = cl.getOptionValue("host");
    if (_host != null) host = _host;

    String _port = cl.getOptionValue("port");
    if (_port != null) port = Integer.parseInt(_port);

    String _file = cl.getOptionValue("file");
    if (_file != null) file = _file;

    String _user = cl.getOptionValue("user");
    if (_user != null) user = _user;

    String _pass = cl.getOptionValue("password");
    if (_pass != null) pass = _pass;

    String _url = cl.getOptionValue("url");
    if (_url != null) url = _url;

    String _sleep = cl.getOptionValue("sleep");
    if (_sleep != null) sleep = Integer.parseInt(_sleep);

    if (cl.hasOption("percent")) showpercent = true;

    String _batchSize = cl.getOptionValue("batch");
    if (_batchSize != null) batchSize = Integer.parseInt(_batchSize);

    String _L = cl.getOptionValue("length");
    if (_L != null) length = Integer.parseInt(_L);

    String _properties = cl.getOptionValue("properties");
    if (_properties != null) properties = _properties;

    String _durable = cl.getOptionValue("durable");
    if (_durable != null) durable = _durable;

    boolean batch = false;
    if (batchSize != 0) batch = true;

    String _format = cl.getOptionValue("format");
    if (_format != null) format = _format;

    ActiveMQConnectionFactory factory = getFactory(host, port, url);

    Connection connection = factory.createConnection(user, pass);

    if (durable != null) connection.setClientID(durable);

    connection.start();

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

    Topic topic = session.createTopic(destination);

    MessageConsumer consumer = null;
    if (durable != null) consumer = session.createDurableSubscriber(topic, "amqutil");
    else consumer = session.createConsumer(topic);

    int oldpercent = 0;
    for (int i = 0; i < n; i++) {
      javax.jms.Message message = consumer.receive();

      if (batch) if ((i + 1) % batchSize == 0) session.commit();

      if (sleep != 0) Thread.sleep(sleep);

      JMSUtil.outputMessage(format, message, file);

      if (showpercent) {
        int percent = i * 100 / n;
        if (percent != oldpercent) System.out.println("" + percent + "%");
        oldpercent = percent;
      }
    }

    if (batch) session.commit();

    connection.close();

    return 0;
  }