Exemple #1
0
  /**
   * Title: getMQSessionNoClient Description:取得session Created On: 2015-4-1 下午7:08:13
   *
   * @author jason
   * @return
   */
  public Session getMQSessionNoClient() {
    if (mqSession != null) {
      return mqSession;
    }
    try {
      // 创建MQ连接
      ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);
      mqConnection = connectionFactory.createConnection();
      if (log != null) {
        log.debug("mqConnect to MQ '" + brokerUrl + "' successfully!");
      }
      // 创建Session
      mqSession = mqConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      // 启动连接
      mqConnection.start();

      return mqSession;
    } catch (JMSException e) {
      if (log != null) {
        log.error("Connect to MQ '" + brokerUrl + "' failed!", e);
      }
    }

    return null;
  }
 public UserMessageService(String brokerURL, String queueName) throws JMSException {
   this.queueName = queueName;
   ConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL);
   this.con = factory.createConnection();
   session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
   this.producer = session.createProducer(null);
 }
  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;
    }
  }
  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);
    }
  }
  /**
   * 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;
    }
  }
 private void createAndStartConnection(String userName, String password, String url)
     throws JMSException {
   ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(userName, password, url);
   connection = (ActiveMQConnection) connectionFactory.createConnection();
   connection.start();
   LOG.info("Connected successfully to {}", url);
 }
  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();
    }
  }
Exemple #9
0
  @Test
  public void procuder() throws Exception {
    Connection connection = null;
    Session session = null;
    try {
      // 创建链接工厂
      ConnectionFactory factory =
          new ActiveMQConnectionFactory(
              ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, BROKER_URL);
      // 通过工厂创建一个连接
      connection = factory.createConnection();
      // 启动连接
      connection.start();
      // 创建一个session会话
      session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
      // 创建一个消息队列
      Destination destination = session.createQueue(DESTINATION);
      // 创建消息制作者
      MessageProducer producer = session.createProducer(destination);
      // 设置持久化模式
      producer.setDeliveryMode(DeliveryMode.PERSISTENT);
      sendMessage(session, producer);
      // 提交会话
      session.commit();

    } finally {
      // 关闭释放资源
      if (session != null) {
        session.close();
      }
      if (connection != null) {
        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();
    }
  }
Exemple #11
0
  /**
   * Creates and configures a new instance.
   *
   * @param dataDirectory root directory where persistent messages are stored
   * @param useLibAio true to use libaio, false if not installed. See <a
   *     href="http://docs.jboss.org/hornetq/2.2.5.Final/user-manual/en/html/libaio.html">Libaio
   *     Native Libraries</a>
   * @param injector Google Guice injector. Used to inject dependency members into commands if
   *     needed.
   * @param queueConfigs vararg of QueueConfig> instances.
   */
  public HornetNest(
      String dataDirectory, boolean useLibAio, Injector injector, QueueConfig... queueConfigs) {
    jmsServer = new EmbeddedJMS();
    config = new ConfigurationImpl();
    jmsConfig = new JMSConfigurationImpl();

    try {
      configureLocations(dataDirectory);
      configureAcceptor();
      configureConnectionFactory();
      configurePaging();
      config.setJournalType(useLibAio ? JournalType.ASYNCIO : JournalType.NIO);
      configureQueues(queueConfigs);

      config.setThreadPoolMaxSize(-1);
      config.setScheduledThreadPoolMaxSize(10);
      jmsServer.setConfiguration(config);
      jmsServer.setJmsConfiguration(jmsConfig);
      jmsServer.start();

      ConnectionFactory connectionFactory = (ConnectionFactory) jmsServer.lookup("/cf");
      if (connectionFactory == null) {
        throw new HornetNestException(
            "Failed to start EmbeddedJMS due to previous errors. Please, see earlier output from HornetQ.");
      }
      consumerConnection = connectionFactory.createConnection();
      producerConnection = connectionFactory.createConnection();
      configureListeners(injector, queueConfigs);
    } catch (HornetNestException e) {
      throw e;
    } catch (Exception e) {
      throw new HornetNestException("Failed to start EmbeddedJMS", e);
    }
  }
  // https://issues.apache.org/jira/browse/ARTEMIS-214
  @Test
  public void testSendingBigMessage() throws Exception {
    Connection connection = null;
    ConnectionFactory connectionFactory = new JmsConnectionFactory("amqp://localhost:61616");

    try {
      connection = connectionFactory.createConnection();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Queue queue = session.createQueue("jms.queue.exampleQueue");
      MessageProducer sender = session.createProducer(queue);

      String body = createMessage(10240);
      sender.send(session.createTextMessage(body));
      connection.start();

      MessageConsumer consumer = session.createConsumer(queue);
      TextMessage m = (TextMessage) consumer.receive(5000);

      Assert.assertEquals(body, m.getText());
    } finally {
      if (connection != null) {
        connection.close();
      }
    }
  }
  @Test
  public void testSendMessage() throws Exception {
    ConnectionFactory cf = null;
    Connection connection = null;
    Session session = null;

    try {
      cf = (ConnectionFactory) initialContext.lookup("jms/RemoteConnectionFactory");
      Queue queue = (Queue) initialContext.lookup(QUEUE_NAME);
      connection = cf.createConnection("guest", "guest");
      connection.start(); // for consumer we need to start connection
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer sender = session.createProducer(queue);
      TemporaryQueue replyQueue = session.createTemporaryQueue();
      TextMessage message = session.createTextMessage("hello goodbye");
      message.setJMSReplyTo(replyQueue);
      sender.send(message);
      log.trace("testSendMessage(): Message sent!");

      MessageConsumer consumer = session.createConsumer(replyQueue);
      Message replyMsg = consumer.receive(5000);
      Assert.assertNotNull(replyMsg);
      Assert.assertTrue(replyMsg instanceof TextMessage);
      String actual = ((TextMessage) replyMsg).getText();
      Assert.assertEquals("Howdy Fred! GoodBye user1", actual);
    } finally {
      if (session != null) {
        session.close();
      }
      closeConnection(connection);
    }
  }
Exemple #14
0
  /**
   * Title: getMQSession Description:取得session Created On: 2015-4-1 下午7:07:07
   *
   * @author jason
   * @return
   */
  protected Session getMQSession() {
    if (mqSession != null) {
      return mqSession;
    }

    try {
      // 创建MQ连接
      ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);
      mqConnection = connectionFactory.createConnection();
      if (log != null) {
        log.debug("mqConnection to MQ '" + brokerUrl + "'");
        log.debug("MQ clientId is:" + clientId);
      }

      // 设置ClientID
      mqConnection.setClientID(clientId);
      // 创建Session
      mqSession = mqConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      // 启动连接
      mqConnection.start();
      return mqSession;
    } catch (JMSException e) {
      if (log != null) {
        log.error("Connect to MQ '" + brokerUrl + "' failed!", e);
      }
    }
    return null;
  }
Exemple #15
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();
    }
  }
  public void testMultipleSenders() throws Exception {
    ConnectionFactory cf = (ConnectionFactory) ic.lookup("/ConnectionFactory");
    Queue queue = (Queue) ic.lookup("/queue/StressTestQueue");
    drainDestination(cf, queue);

    Connection conn = cf.createConnection();

    Session[] sessions = new Session[CorruptMessageStressTest.PRODUCER_COUNT];
    MessageProducer[] producers = new MessageProducer[CorruptMessageStressTest.PRODUCER_COUNT];

    for (int i = 0; i < CorruptMessageStressTest.PRODUCER_COUNT; i++) {
      sessions[i] = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      producers[i] = sessions[i].createProducer(queue);
      producers[i].setDeliveryMode(DeliveryMode.NON_PERSISTENT);
    }

    Thread[] threads = new Thread[CorruptMessageStressTest.PRODUCER_COUNT];

    for (int i = 0; i < CorruptMessageStressTest.PRODUCER_COUNT; i++) {
      threads[i] = new Thread(new Sender(sessions[i], producers[i]), "Sender Thread #" + i);
      threads[i].start();
    }

    // wait for the threads to finish

    for (int i = 0; i < CorruptMessageStressTest.PRODUCER_COUNT; i++) {
      threads[i].join();
    }

    conn.close();
  }
  @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 }
    }
  }
  public void testWithConnectionFactoryAndClientId() throws JMSException {
    MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
    ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
    MockControl conControl = MockControl.createControl(Connection.class);
    Connection con = (Connection) conControl.getMock();

    cf.createConnection();
    cfControl.setReturnValue(con, 1);
    con.setClientID("myId");
    conControl.setVoidCallable(1);
    con.start();
    conControl.setVoidCallable(1);
    con.stop();
    conControl.setVoidCallable(1);
    con.close();
    conControl.setVoidCallable(1);

    cfControl.replay();
    conControl.replay();

    SingleConnectionFactory scf = new SingleConnectionFactory(cf);
    scf.setClientId("myId");
    Connection con1 = scf.createConnection();
    con1.start();
    con1.close(); // should be ignored
    Connection con2 = scf.createConnection();
    con2.start();
    con2.close(); // should be ignored
    scf.destroy(); // should trigger actual close

    cfControl.verify();
    conControl.verify();
  }
  @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 void testWithConnectionFactoryAndExceptionListenerAndReconnectOnException()
      throws JMSException {
    MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
    ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
    TestConnection con = new TestConnection();

    TestExceptionListener listener = new TestExceptionListener();
    cf.createConnection();
    cfControl.setReturnValue(con, 2);
    cfControl.replay();

    SingleConnectionFactory scf = new SingleConnectionFactory(cf);
    scf.setExceptionListener(listener);
    scf.setReconnectOnException(true);
    Connection con1 = scf.createConnection();
    assertSame(listener, con1.getExceptionListener());
    con1.start();
    con.getExceptionListener().onException(new JMSException(""));
    Connection con2 = scf.createConnection();
    con2.start();
    scf.destroy(); // should trigger actual close

    cfControl.verify();
    assertEquals(2, con.getStartCount());
    assertEquals(2, con.getCloseCount());
    assertEquals(1, listener.getCount());
  }
  @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));
  }
Exemple #22
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();
     }
   }
 }
Exemple #23
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();
  }
Exemple #24
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();
     }
   }
 }
 public void initConnection() throws Exception {
   ConnectionFactory connectionFactory =
       new ActiveMQConnectionFactory("vm://localhost?create=false");
   connection = (ActiveMQConnection) connectionFactory.createConnection();
   connection.setWatchTopicAdvisories(false);
   connection.start();
 }
  public void lookupJMSConnectionFactory() throws TestFailureException {
    try {
      try {
        final InitialContext ctx = new InitialContext();
        Assert.assertNotNull("The InitialContext is null", ctx);
        Object obj = ctx.lookup("java:comp/env/jms");
        Assert.assertNotNull("The JMS ConnectionFactory is null", obj);
        Assert.assertTrue("Not an instance of ConnectionFactory", obj instanceof ConnectionFactory);
        final ConnectionFactory connectionFactory = (ConnectionFactory) obj;
        testJmsConnection(connectionFactory.createConnection());

        obj = ctx.lookup("java:comp/env/TopicCF");
        Assert.assertNotNull("The JMS TopicConnectionFactory is null", obj);
        Assert.assertTrue(
            "Not an instance of TopicConnectionFactory", obj instanceof TopicConnectionFactory);
        final TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) obj;
        testJmsConnection(topicConnectionFactory.createConnection());

        obj = ctx.lookup("java:comp/env/QueueCF");
        Assert.assertNotNull("The JMS QueueConnectionFactory is null", obj);
        Assert.assertTrue(
            "Not an instance of QueueConnectionFactory", obj instanceof QueueConnectionFactory);
        final QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) obj;
        testJmsConnection(queueConnectionFactory.createConnection());
      } catch (final Exception e) {
        e.printStackTrace();
        Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage());
      }
    } catch (final AssertionFailedError afe) {
      throw new TestFailureException(afe);
    }
  }
Exemple #27
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 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();
  }
  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();
    }
  }
Exemple #30
0
  /**
   * @param inId
   * @param command
   * @param parameters
   * @return
   * @throws NamingException
   */
  @Override
  public boolean executeProcessOnInMail(long inId, String command, String parameters)
      throws NamingException, JMSException {

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

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

    return suc;
  }