Example #1
0
 public Message receive(Scenario scenario) throws Exception {
   Connection connection = null;
   try {
     ConnectionFactory factory = new ActiveMQConnectionFactory(scenario.getBrokerUrl());
     connection = factory.createConnection();
     connection.start();
     Session session = null;
     try {
       session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge());
       ActiveMQQueue destination = new ActiveMQQueue(scenario.getOutputQueue());
       MessageConsumer consumer = null;
       try {
         consumer = session.createConsumer(destination);
         return scenario.receive(session, consumer);
       } finally {
         if (consumer != null) {
           consumer.close();
         }
       }
     } finally {
       if (session != null) {
         session.close();
       }
     }
   } finally {
     if (connection != null) {
       connection.close();
     }
   }
 }
Example #2
0
  public void sendMessage(Order order) {
    ConnectionFactory factory = new ActiveMQConnectionFactory("failover://tcp://localhost:61616");
    Queue queue = new ActiveMQQueue("sequence");
    Connection conn = null;
    Session sen = null;
    MessageProducer producer = null;
    TextMessage msg = null;
    JSONMapper mapper = new JSONMapper();

    Destination des = null;
    try {
      conn = factory.createConnection();
      sen = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      producer = sen.createProducer(queue);
      conn.start();
      String str = mapper.writeObjectAsString(order);
      System.out.println(str);
      msg = sen.createTextMessage(str);
      producer.send(msg);
      producer.close();
      sen.close();
      conn.close();
    } catch (JMSException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  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;
    }
  }
Example #4
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();
  }
Example #5
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();
      }
    }
  }
  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) {

        }
      }
    }
  }
  /*
   * 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);
    }
  }
  public static void consumeTopic() throws Exception {

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

            TextMessage m = (TextMessage) message;
            try {
              System.out.println(m.getText());
            } catch (JMSException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          }
        });
    connection.start();
  }
  @Test
  public void testSendReceiveMessage() throws Exception {
    Connection conn = createConnection();

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

    MessageProducer prod = sess.createProducer(queue1);

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

    MessageConsumer cons = sess.createConsumer(queue1);

    TestMessage tm = new TestMessage(123, false);

    ObjectMessage om = sess.createObjectMessage();

    om.setObject(tm);

    conn.start();

    prod.send(om);

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

    ProxyAssertSupport.assertNotNull(om2);

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

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

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

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

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

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

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

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

    connection.close();
  }
  @Override
  @Test(timeout = 30000)
  public void testMessageSizeTwoDurables() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

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

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

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

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

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

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

    connection.stop();
  }
  @Override
  @Test(timeout = 30000)
  public void testMessageSizeOneDurablePartialConsumption() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

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

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

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

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

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

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

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

    connection.close();
  }
Example #13
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 #14
0
 public void send(Scenario scenario) throws Exception {
   Connection connection = null;
   try {
     ConnectionFactory factory = new ActiveMQConnectionFactory(scenario.getBrokerUrl());
     connection = factory.createConnection();
     connection.start();
     Session session = null;
     try {
       session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge());
       ActiveMQQueue destination = new ActiveMQQueue(scenario.getInputQueue());
       MessageProducer producer = null;
       try {
         producer = session.createProducer(destination);
         scenario.send(session, producer);
       } finally {
         if (producer != null) {
           producer.close();
         }
       }
     } finally {
       if (session != null) {
         session.close();
       }
     }
   } finally {
     if (connection != null) {
       connection.close();
     }
   }
 }
  @Test
  public void testReconnectMultipleTimesWithSameClientID() throws Exception {
    try {
      sameIdConnection = (ActiveMQConnection) this.factory.createConnection();
      useConnection(sameIdConnection);

      // now lets create another which should fail
      for (int i = 1; i < 11; i++) {
        Connection connection2 = this.factory.createConnection();
        try {
          useConnection(connection2);
          fail("Should have thrown InvalidClientIDException on attempt" + i);
        } catch (InvalidClientIDException e) {
          System.err.println("Caught expected: " + e);
        } finally {
          connection2.close();
        }
      }

      // now lets try closing the original connection and creating a new
      // connection with the same ID
      sameIdConnection.close();
      sameIdConnection = (ActiveMQConnection) factory.createConnection();
      useConnection(connection);
    } finally {
      if (sameIdConnection != null) {
        sameIdConnection.close();
      }
    }
  }
Example #16
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();
    }
  }
  @Test
  public void testNetworkedBrokerDetach() throws Exception {
    LOG.info("Creating Consumer on the networked broker ...");
    // Create a consumer on the networked broker
    ConnectionFactory consFactory = createConnectionFactory(networkedBroker);
    Connection consConn = consFactory.createConnection();
    Session consSession = consConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQDestination destination =
        (ActiveMQDestination) consSession.createQueue(DESTINATION_NAME);
    for (int i = 0; i < NUM_CONSUMERS; i++) {
      consSession.createConsumer(destination);
    }

    assertTrue(
        "got expected consumer count from mbean within time limit",
        verifyConsumerCount(1, destination, broker));

    LOG.info("Stopping Consumer on the networked broker ...");
    // Closing the connection will also close the consumer
    consConn.close();

    // We should have 0 consumer for the queue on the local broker
    assertTrue(
        "got expected 0 count from mbean within time limit",
        verifyConsumerCount(0, destination, broker));
  }
Example #18
0
  @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 }
    }
  }
Example #19
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();
  }
Example #20
0
  public static void main(String[] args) {
    try {
      Parameters parameters = new Parameters(args);

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

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

      Topic destination = session.createTopic(parameters.topic);

      MessageProducer producer = session.createProducer(destination);
      producer.setDeliveryMode(DeliveryMode.PERSISTENT);

      String messageBody = IOUtils.toString(new FileReader(parameters.message));

      TextMessage message = session.createTextMessage(messageBody);
      message.setStringProperty("Channel", parameters.channel);
      message.setJMSExpiration(parameters.expiration);

      LOG.info("Sent message: {}", message);
      producer.send(message);

      session.close();
      connection.close();
    } catch (Exception e) {
      LOG.error("Producing interrupted", e);
    }
  }
Example #21
0
  public void testConnectionFactory() throws Exception {
    final ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(connectionUri);
    final ActiveMQQueue queue = new ActiveMQQueue("testqueue");
    final Connection conn = cf.createConnection();

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

    try {
      synchronized (this) {
        wait(3000);
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
  /**
   * Send a command via JMS.
   *
   * <p>Note: Opens and closes the connection per invocation of this method which, when run outside
   * a JavaEE container, is not very efficient.
   *
   * @param command
   * @throws JMSException
   */
  public void sendCommandMessage(Command command) throws JMSException {
    Connection connection = null;
    Session session = null;
    try {
      connection = connectionFactory.createConnection();
      session = connection.createSession(TRANSACTIONAL, Session.AUTO_ACKNOWLEDGE);

      // Construct a JMS "TextMessage"
      final TextMessage newMessage = session.createTextMessage();
      newMessage.setStringProperty("issuer", command.getIssuer());
      newMessage.setStringProperty("type", command.getType());
      newMessage.setText(command.getPayload());

      // Send the message
      final MessageProducer producer = session.createProducer(this.commandQueue);
      producer.send(newMessage);

      if (TRANSACTIONAL) {
        // JavaEE containers would manage this
        session.commit();
      }
    } finally {
      if (connection != null) {
        try {
          if (session != null) {
            session.close();
          }
          connection.stop();
          connection.close();
        } catch (JMSException e) {
          e.printStackTrace();
        }
      }
    }
  }
Example #23
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;
  }
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   resp.setContentType("text/html");
   PrintWriter out = resp.getWriter();
   Connection connection = null;
   out.write("<h1>Produce JMS ObjectMessages</h1>");
   try {
     connection = connectionFactory.createConnection();
     Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
     MessageProducer producer = session.createProducer(queue);
     ObjectMessage message = session.createObjectMessage();
     MyResource resource = new MyResource("This is my resource");
     message.setObject(resource);
     producer.send(message);
     out.write("<p>Send JMS Message with object: " + resource + "</p>");
   } catch (JMSException e) {
     e.printStackTrace();
     out.write("<h2>A problem occurred during the delivery of this message</h2>");
     out.write("</br>");
     out.write(
         "<p><i>Go your the JBoss Application Server console or Server log to see the error stack trace</i></p>");
   } finally {
     if (connection != null) {
       try {
         connection.close();
       } catch (JMSException e) {
         e.printStackTrace();
       }
     }
     if (out != null) {
       out.close();
     }
   }
 }
 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);
 }
  /**
   * Initializes the qpid connection with a jndiName of cow, and a host and port taken from the
   * cow-server.properties file.
   */
  public void init() {
    String connectionFactorylocation =
        "amqp://*****:*****@clientid/test?brokerlist='tcp://" + host + ":" + port + "'";
    String destinationType = "topic";
    String jndiName = "cow";
    String destinationName = "myTopic";

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

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

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

      messageProducer = session.createProducer(destination);
      initialized = true;
    } catch (Exception e) {
      log.debug(e.getMessage());
      initialized = false;
    }
  }
  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);
    }
  }
  @Test
  public void testSendMessage() throws Exception {
    ConnectionFactory connFactory = lookup("ConnectionFactory", ConnectionFactory.class);
    Connection conn = connFactory.createConnection();
    conn.start();
    Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    TemporaryQueue replyQueue = session.createTemporaryQueue();
    TextMessage msg = session.createTextMessage("Hello world");
    msg.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);
    msg.setJMSReplyTo(replyQueue);
    Queue queue = lookup("java:jboss/" + queueName, Queue.class);
    MessageProducer producer = session.createProducer(queue);
    producer.send(msg);
    MessageConsumer consumer = session.createConsumer(replyQueue);
    Message replyMsg = consumer.receive(5000);
    Assert.assertNotNull(replyMsg);
    if (replyMsg instanceof ObjectMessage) {
      Exception e = (Exception) ((ObjectMessage) replyMsg).getObject();
      throw e;
    }
    Assert.assertTrue(replyMsg instanceof TextMessage);
    String actual = ((TextMessage) replyMsg).getText();
    Assert.assertEquals("SUCCESS", actual);

    consumer.close();
    producer.close();
    session.close();
    conn.stop();
  }
  public 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 testWithTopicConnection() throws JMSException {
    MockControl conControl = MockControl.createControl(TopicConnection.class);
    Connection con = (TopicConnection) conControl.getMock();

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

    conControl.replay();

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

    conControl.verify();
  }