コード例 #1
0
ファイル: JMSTestBase.java プロジェクト: yogidevendra/Malhar
  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();
  }
コード例 #2
0
ファイル: Producer.java プロジェクト: mariuszs/jms-client
  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);
    }
  }
コード例 #3
0
 @Override
 public void run() {
   try {
     // Create a ConncetionFactory
     ActiveMQConnectionFactory connectionFactory =
         new ActiveMQConnectionFactory("tcp://MSPL-08-09-D158:61616");
     // Create a Connection
     Connection connection = connectionFactory.createConnection();
     connection.start();
     // Create a session
     Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
     // Create the destination (Topic or Queue)
     Destination destination = session.createQueue("HELLOWORLD.TESTQ");
     // Create a MessageProducer from the Session to the Topic or Queue
     MessageConsumer consumer = session.createConsumer(destination);
     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);
     }
     consumer.close();
     session.close();
     connection.close();
   } catch (Exception e) {
     System.out.println("Error Occure : " + e);
     e.printStackTrace();
   }
 }
コード例 #4
0
ファイル: CraigsBugTest.java プロジェクト: siriusSP/activemq
  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();
    }
  }
コード例 #5
0
  @Test
  public void testIndexRebuilds() throws Exception {
    IOHelper.deleteFile(schedulerStoreDir);

    JobSchedulerStoreImpl schedulerStore = createScheduler();
    broker = createBroker(schedulerStore);
    broker.start();
    ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost");
    Connection connection = cf.createConnection();
    connection.start();
    for (int i = 0; i < NUM_JOBS; ++i) {
      scheduleRepeating(connection);
    }
    connection.close();

    JobScheduler scheduler = schedulerStore.getJobScheduler("JMS");
    assertNotNull(scheduler);
    assertEquals(NUM_JOBS, scheduler.getAllJobs().size());

    broker.stop();

    IOHelper.delete(new File(schedulerStoreDir, "scheduleDB.data"));

    schedulerStore = createScheduler();
    broker = createBroker(schedulerStore);
    broker.start();

    scheduler = schedulerStore.getJobScheduler("JMS");
    assertNotNull(scheduler);
    assertEquals(NUM_JOBS, scheduler.getAllJobs().size());
  }
コード例 #6
0
  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();
  }
コード例 #7
0
  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);
    }
  }
コード例 #8
0
  private static synchronized void initMQConnectionFactory() {

    pool_conn_factory = new PooledConnectionFactory();

    MQConfig config = new MQConfig();

    String url = config.getProperty(MQConfig.ACTIVEMQ_CONN_URL, DEFAULT_URL);

    String user = config.getProperty(MQConfig.ACTIVEMQ_CONN_USER, DEFAULT_USER);

    String passwd = config.getProperty(MQConfig.ACTIVEMQ_CONN_PASSWD, DEFAULT_PASSWORD);

    ActiveMQConnectionFactory activeMQConnFactory =
        new ActiveMQConnectionFactory(user, passwd, url);

    if (Boolean.TRUE
        .toString()
        .equalsIgnoreCase(config.getProperty(MQConfig.ACTIVEMQ_POOL_USE_ASYNCSEND, "false"))) {
      activeMQConnFactory.setUseAsyncSend(true);
    }

    pool_conn_factory.setConnectionFactory(activeMQConnFactory);

    pool_conn_factory.setMaxConnections(
        config.getIntProperty(MQConfig.ACTIVEMQ_POOL_CONN_MAX, "10"));

    // Sets the maximum number of active sessions per connection
    pool_conn_factory.setMaximumActive(
        config.getIntProperty(MQConfig.ACTIVEMQ_POOL_ACTIVE_SESSION_MAX, "200"));

    pool_conn_factory.setIdleTimeout(
        config.getIntProperty(MQConfig.ACTIVEMQ_POOL_IDLETIMEOUT, "30000"));
  }
コード例 #9
0
  @Override
  protected void setUp() throws Exception {
    System.setProperty("javax.net.ssl.trustStore", TRUST_KEYSTORE);
    System.setProperty("javax.net.ssl.trustStorePassword", PASSWORD);
    System.setProperty("javax.net.ssl.trustStoreType", KEYSTORE_TYPE);
    System.setProperty("javax.net.ssl.keyStore", SERVER_KEYSTORE);
    System.setProperty("javax.net.ssl.keyStoreType", KEYSTORE_TYPE);
    System.setProperty("javax.net.ssl.keyStorePassword", PASSWORD);

    broker = new BrokerService();
    broker.setPersistent(false);
    broker.setUseJmx(false);
    TransportConnector connector =
        broker.addConnector("nio+ssl://localhost:0?transport.needClientAuth=true");
    broker.start();
    broker.waitUntilStarted();

    messageData = new byte[MESSAGE_SIZE];
    for (int i = 0; i < MESSAGE_SIZE; i++) {
      messageData[i] = (byte) (i & 0xff);
    }

    ActiveMQConnectionFactory factory =
        new ActiveMQConnectionFactory("nio+ssl://localhost:" + connector.getConnectUri().getPort());
    connection = factory.createConnection();
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    connection.start();
  }
コード例 #10
0
 @Override
 protected ConnectionFactory createConnectionFactory() throws URISyntaxException, IOException {
   ActiveMQConnectionFactory factory =
       new ActiveMQConnectionFactory(
           broker.getTransportConnectors().get(0).getServer().getConnectURI());
   factory.setUseAsyncSend(true);
   return factory;
 }
コード例 #11
0
  private static void init() throws JMSException {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(URL);
    connection = connectionFactory.createConnection();
    connection.start();

    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createQueue("receive");
    producer = session.createProducer(destination);
  }
コード例 #12
0
 /** Configures the given connection factory */
 public void configure(ActiveMQConnectionFactory factory, MessageActivationSpec activationSpec) {
   if (serverUrl != null) {
     factory.setBrokerURL(serverUrl);
   }
   if (clientid != null) {
     factory.setClientID(clientid);
   }
   if (redeliveryPolicy != null) {
     factory.setRedeliveryPolicy(redeliveryPolicy);
   }
   if (prefetchPolicy != null) {
     factory.setPrefetchPolicy(prefetchPolicy);
   }
   if (factory instanceof ActiveMQSslConnectionFactory) {
     String trustStore =
         defaultValue(
             activationSpec == null ? null : activationSpec.getTrustStore(), getTrustStore());
     String trustStorePassword =
         defaultValue(
             activationSpec == null ? null : activationSpec.getTrustStorePassword(),
             getTrustStorePassword());
     String keyStore =
         defaultValue(activationSpec == null ? null : activationSpec.getKeyStore(), getKeyStore());
     String keyStorePassword =
         defaultValue(
             activationSpec == null ? null : activationSpec.getKeyStorePassword(),
             getKeyStorePassword());
     String keyStoreKeyPassword =
         defaultValue(
             activationSpec == null ? null : activationSpec.getKeyStoreKeyPassword(),
             getKeyStoreKeyPassword());
     ActiveMQSslConnectionFactory sslFactory = (ActiveMQSslConnectionFactory) factory;
     if (trustStore != null) {
       try {
         sslFactory.setTrustStore(trustStore);
       } catch (Exception e) {
         log.warn("Unable to set TrustStore", e);
       }
     }
     if (trustStorePassword != null) {
       sslFactory.setTrustStorePassword(trustStorePassword);
     }
     if (keyStore != null) {
       try {
         sslFactory.setKeyStore(keyStore);
       } catch (Exception e) {
         log.warn("Unable to set KeyStore", e);
       }
     }
     if (keyStorePassword != null) {
       sslFactory.setKeyStorePassword(keyStorePassword);
     }
     if (keyStoreKeyPassword != null) {
       sslFactory.setKeyStoreKeyPassword(keyStoreKeyPassword);
     }
   }
 }
コード例 #13
0
ファイル: Producer.java プロジェクト: 354447958/test
 // 初始化
 private void initialize() throws JMSException, Exception {
   ActiveMQConnectionFactory connFac =
       new ActiveMQConnectionFactory(Config.userName, Config.password, Config.brokerURL);
   connection = connFac.createConnection();
   session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   destination = session.createQueue(Config.queueName);
   producer = session.createProducer(destination);
   producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); // 设置发送模式
 }
コード例 #14
0
 @Test
 public void testActiveMQOverriddenPoolAndStandalone() {
   load(TestConfiguration.class, "spring.activemq.pooled:true", "spring.activemq.inMemory:false");
   JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class);
   PooledConnectionFactory pool = this.context.getBean(PooledConnectionFactory.class);
   assertThat(jmsTemplate).isNotNull();
   assertThat(pool).isNotNull();
   assertThat(pool).isEqualTo(jmsTemplate.getConnectionFactory());
   ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool.getConnectionFactory();
   assertThat(factory.getBrokerURL()).isEqualTo(ACTIVEMQ_NETWORK_URL);
 }
コード例 #15
0
  @Test
  public void testNoSuspendedCallbackOnNoReconnect() throws Exception {

    String uriString =
        "failover://(" + newURI(1) + "," + newURI(2) + ")?randomize=false&maxReconnectAttempts=0";

    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(uriString);
    final AtomicInteger calls = new AtomicInteger(0);
    connectionFactory.setTransportListener(
        new TransportListener() {
          @Override
          public void onCommand(Object command) {}

          @Override
          public void onException(IOException error) {
            LOG.info("on exception: " + error);
            calls.set(0x01 | calls.intValue());
          }

          @Override
          public void transportInterupted() {
            LOG.info("on transportInterupted");
            calls.set(0x02 | calls.intValue());
          }

          @Override
          public void transportResumed() {
            LOG.info("on transportResumed");
            calls.set(0x04 | calls.intValue());
          }
        });
    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue destination = session.createQueue("foo");
    MessageProducer producer = session.createProducer(destination);

    final Message message = session.createTextMessage("TEST");
    producer.send(message);

    // clear listener state
    calls.set(0);

    LOG.info("Stopping the Broker1...");
    server1.stop();

    LOG.info("Attempting to send... failover should throw on disconnect");
    try {
      producer.send(destination, message);
      fail("Expect IOException to bubble up on send");
    } catch (javax.jms.IllegalStateException producerClosed) {
    }

    assertEquals("Only an exception is reported to the listener", 0x1, calls.get());
  }
コード例 #16
0
  @Bean
  public ConnectionFactory amqConnectionFactory() {
    CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
    ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory();
    activeMQConnectionFactory.setBrokerURL("vm://localhost?broker.persistent=false");

    cachingConnectionFactory.setTargetConnectionFactory(activeMQConnectionFactory);
    cachingConnectionFactory.setSessionCacheSize(10);
    cachingConnectionFactory.setCacheProducers(true);
    cachingConnectionFactory.setReconnectOnException(true);
    return cachingConnectionFactory;
  }
コード例 #17
0
ファイル: DlqTest.java プロジェクト: siriusSP/activemq
 private void sendJMSMessageToKickOffRoute() throws Exception {
   ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://testDlq");
   factory.setWatchTopicAdvisories(false);
   Connection connection = factory.createConnection();
   connection.start();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(new ActiveMQQueue("fidEtpOrders"));
   TextMessage message = session.createTextMessage("Some Text, messageCount:" + messageCount++);
   message.setJMSCorrelationID("pleaseCorrelate");
   producer.send(message);
   connection.close();
 }
コード例 #18
0
  public void testSlowConnection() throws Exception {

    MockBroker broker = new MockBroker();
    broker.start();

    socketReadyLatch.await();
    int timeout = 1000;
    URI tcpUri =
        new URI(
            "tcp://localhost:"
                + broker.ss.getLocalPort()
                + "?soTimeout="
                + timeout
                + "&trace=true&connectionTimeout="
                + timeout
                + "&wireFormat.maxInactivityDurationInitalDelay="
                + timeout);

    ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + tcpUri + ")");
    final Connection connection = cf.createConnection();

    new Thread(
            new Runnable() {
              @Override
              public void run() {
                try {
                  connection.start();
                } catch (Throwable ignored) {
                }
              }
            })
        .start();

    int count = 0;
    assertTrue(
        "Transport count: " + count + ", expected <= 1",
        Wait.waitFor(
            new Wait.Condition() {
              @Override
              public boolean isSatisified() throws Exception {
                int count = 0;
                for (Thread thread : Thread.getAllStackTraces().keySet()) {
                  if (thread.getName().contains("ActiveMQ Transport")) {
                    count++;
                  }
                }
                return count == 1;
              }
            }));

    broker.interrupt();
    broker.join();
  }
コード例 #19
0
 @Before
 public void setUp() throws Exception {
   broker = createBroker();
   broker.start();
   ActiveMQConnectionFactory connFactory =
       new ActiveMQConnectionFactory(connector.getConnectUri() + "?jms.prefetchPolicy.all=1000");
   connection = connFactory.createConnection();
   session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
   destination = new ActiveMQQueue("test-queue2");
   producer = session.createProducer(destination);
   connection.start();
 }
コード例 #20
0
 @Test
 public void testActiveMQOverriddenPoolAndRemoteServer() {
   load(
       TestConfiguration.class,
       "spring.activemq.pooled:true",
       "spring.activemq.brokerUrl:tcp://remote-host:10000");
   JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class);
   PooledConnectionFactory pool = this.context.getBean(PooledConnectionFactory.class);
   assertThat(jmsTemplate).isNotNull();
   assertThat(pool).isNotNull();
   assertThat(pool).isEqualTo(jmsTemplate.getConnectionFactory());
   ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool.getConnectionFactory();
   assertThat(factory.getBrokerURL()).isEqualTo("tcp://remote-host:10000");
 }
コード例 #21
0
  public static void main(String[] args) {

    ActiveMQConnectionFactory connectionFactory =
        new ActiveMQConnectionFactory("admin", "password", BROKER_URL);
    Connection connection = null;

    try {

      connection = connectionFactory.createConnection();
      connection.setClientID("duravel");
      connection.start();

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

      Destination destination;
      MessageProducer producer = null;
      for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) {

        System.out.println("Sending message #" + i);

        Operacao op = gerarOperacao();
        destination = session.createTopic(op.getDescricao());
        producer = session.createProducer(destination);

        ObjectMessage message = session.createObjectMessage(op);

        swingBasic.start(op);

        producer.send(message);
        Thread.sleep(DELAY);
      }

      producer.send(session.createTextMessage("END"));

      producer.close();
      session.close();

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (connection != null) {
        try {
          connection.close();
        } catch (JMSException e) {
          e.printStackTrace();
        }
      }
    }
  }
コード例 #22
0
ファイル: Listener.java プロジェクト: cm-forks/use-cases
  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();
  }
コード例 #23
0
  /*
   * http://blog.itpub.net/10742815/viewspace-580334/
   */
  public static void main(String[] args) throws Exception {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost");

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

    // 消息发送到这个Queue
    Queue queue = new ActiveMQQueue("testQueue");

    // 消息回复到这个Queue
    Queue replyQueue = new ActiveMQQueue("replyQueue");

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

    // 创建一个消息,并设置它的JMSReplyTo为replyQueue。
    Message message = session.createTextMessage("Andy");
    message.setJMSReplyTo(replyQueue);

    MessageProducer producer = session.createProducer(queue);
    producer.send(message);

    // 消息的接收者
    MessageConsumer comsumer = session.createConsumer(queue);
    comsumer.setMessageListener(
        new MessageListener() {
          public void onMessage(Message m) {
            try {
              // 创建一个新的MessageProducer来发送一个回复消息。
              MessageProducer producer = session.createProducer(m.getJMSReplyTo());
              producer.send(session.createTextMessage("Hello " + ((TextMessage) m).getText()));
            } catch (JMSException e1) {
              e1.printStackTrace();
            }
          }
        });

    // 这个接收者用来接收回复的消息
    MessageConsumer comsumer2 = session.createConsumer(replyQueue);
    comsumer2.setMessageListener(
        new MessageListener() {
          public void onMessage(Message m) {
            try {
              System.out.println(((TextMessage) m).getText());
            } catch (JMSException e) {
              e.printStackTrace();
            }
          }
        });
  }
コード例 #24
0
ファイル: Consumer.java プロジェクト: sparsis/caelum
  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...");
        }
      }
    }
  }
コード例 #25
0
    private synchronized QueueConnection newQueueConnection() throws Exception {

      if (connectionFactory == null) {
        connectionFactory = new ActiveMQConnectionFactory(amqUser, amqPassword, activemqURL);
      }

      // Set the redelivery count to -1 (infinite), or else messages will start dropping
      // after the queue has had a certain number of failures (default is 6)
      RedeliveryPolicy policy = connectionFactory.getRedeliveryPolicy();
      policy.setMaximumRedeliveries(-1);

      QueueConnection amqConnection = connectionFactory.createQueueConnection();
      amqConnection.start();
      return amqConnection;
    }
コード例 #26
0
ファイル: EJBCustomer.java プロジェクト: pobrienjhu/ase_w4156
  private void connectToMQ() {
    try {
      ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url);
      connection = factory.createConnection();
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      topic = session.createTopic("aseAuctionHouse.auctionWonMessages");

      MessageConsumer consumer = session.createConsumer(topic);
      consumer.setMessageListener(this);

      connection.start();
    } catch (JMSException e) {
      System.out.println("Unable to connect to the MQ Server. Root Cause (" + e.getMessage() + ")");
    }
  }
コード例 #27
0
ファイル: JMSConsumer.java プロジェクト: sureshg/oo-commons
  public void startConsumer() {
    try {
      connection = connectionFactory.createConnection();
      connection.start();
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Destination destination = null;
      if ("topic".equalsIgnoreCase(destinationType)) {
        destination = session.createTopic(destinationName);
      } else {
        destination = session.createQueue(destinationName);
      }

      consumer = session.createConsumer(destination);
      isStarted.compareAndSet(false, true);
      while (true) {
        Message message = consumer.receive();

        if (message instanceof TextMessage) {
          TextMessage textMessage = (TextMessage) message;
          String text = textMessage.getText();
          // System.out.println("Received: " + text);
          counter.incrementAndGet();
          if (isRecording.get()) {
            addData(message, text);
          }
        }
      }

    } catch (Exception e) {
      // e.printStackTrace();
    } finally {
      terminate();
    }
  }
コード例 #28
0
ファイル: EventElf.java プロジェクト: patrickpreuss/ziptie
  static {
    try {
      // Create a ConnectionFactory
      String brokerUrl = System.getProperty("amq.broker.url", "vm://localhost");
      ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);

      // Create a Connection
      connection = connectionFactory.createConnection();
      connection.start();

      sessionPool = new StackKeyedObjectPool(new SessionKeyedObjectPoolFactory());
      producerPool = new StackKeyedObjectPool(new ProducerKeyedObjectPoolFactory());
    } catch (JMSException e) {
      throw new RuntimeException(e);
    }
  }
コード例 #29
0
  @Override
  public void setUp() throws Exception {

    brokerService = createBroker();

    ActiveMQConnectionFactory activeMQConnectionFactory =
        new ActiveMQConnectionFactory("vm://localhost");

    activeMQConnectionFactory.setWatchTopicAdvisories(true);
    connection = activeMQConnectionFactory.createConnection();
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    destination = new ActiveMQTopic(TOPIC_NAME);
    producer = session.createProducer(destination);

    connection.start();
  }
コード例 #30
0
  @Override
  public void reconnect() {
    int numTries = 0;
    int pauseInMs = 100;
    boolean connected = false;

    if (connectionFactory == null) {
      logger.warn("Asked to reconnect to AMQ but no connectionFactory was configured!");
      return;
    }

    synchronized (connectionMonitor) {
      close();
      while (!connected) {
        numTries++;
        try {
          connection = connectionFactory.createTopicConnection();
          connection.start();
          connected = true;
        } catch (JMSException ex) {
          logger.warn("Got error while trying to connect to activemq");
          try {
            Thread.sleep((long) pauseInMs);
          } catch (InterruptedException innerEx) {
            Thread.currentThread().interrupt();
            return;
          }
          if (numTries < 10) {
            pauseInMs += pauseInMs;
          }
        }
      }
    }
  }