Example usage for javax.jms Session createTopic

List of usage examples for javax.jms Session createTopic

Introduction

In this page you can find the example usage for javax.jms Session createTopic.

Prototype

Topic createTopic(String topicName) throws JMSException;

Source Link

Document

Creates a Topic object which encapsulates a specified provider-specific topic name.

Usage

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testTopicMessageSize() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.setClientID("clientId");
    connection.start();/*w  w w.j a  v  a  2  s .c o  m*/
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(session.createTopic(defaultTopicName));

    publishTestTopicMessages(200, publishedMessageSize);

    verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get());
    verifyPendingDurableStats(defaultQueueName, 0, 0);

    // consume all messages
    consumeTestMessages(consumer, 200);

    // All messages should now be gone
    verifyPendingStats(defaultTopicName, 0, 0);
    verifyPendingDurableStats(defaultQueueName, 0, 0);

    connection.close();
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testTopicPersistentAndNonPersistentMessageSize() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();
    AtomicLong publishedNonPersistentMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.setClientID("clientId");
    connection.start();//w  w w .java2s.  co m
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(session.createTopic(defaultTopicName));

    publishTestTopicMessages(100, DeliveryMode.NON_PERSISTENT, publishedNonPersistentMessageSize);
    publishTestTopicMessages(100, DeliveryMode.PERSISTENT, publishedMessageSize);

    verifyPendingStats(defaultTopicName, 200,
            publishedMessageSize.get() + publishedNonPersistentMessageSize.get());

    // consume all messages
    consumeTestMessages(consumer, 200);

    // All messages should now be gone
    verifyPendingStats(defaultTopicName, 0, 0);

    connection.close();
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testTopicMessageSizeShared() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.setClientID("clientId");
    connection.start();/* w w w. j  av  a  2s . c  om*/
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createSharedConsumer(session.createTopic(defaultTopicName), "sub1");
    MessageConsumer consumer2 = session.createSharedConsumer(session.createTopic(defaultTopicName), "sub1");

    publishTestTopicMessages(200, publishedMessageSize);

    verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get());
    verifyPendingDurableStats(defaultTopicName, 0, 0);
    consumer2.close();

    // consume all messages
    consumeTestMessages(consumer, 200);

    // All messages should now be gone
    verifyPendingStats(defaultTopicName, 0, 0);
    verifyPendingDurableStats(defaultTopicName, 0, 0);

    connection.close();
}

From source file:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java

@Override
public String waitForMessage(Run<?, ?> build, String selector, String variable, Integer timeout) {
    String ip = null;// ww  w.j ava  2 s.  c  o m
    try {
        ip = Inet4Address.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
        log.severe("Unable to get localhost IP address.");
    }

    String ltopic = getTopic();
    if (ip != null && provider.getAuthenticationMethod() != null && ltopic != null
            && provider.getBroker() != null) {
        log.info("Waiting for message with selector: " + selector);
        Connection connection = null;
        MessageConsumer consumer = null;
        try {
            ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory();
            connection = connectionFactory.createConnection();
            connection.setClientID(ip + "_" + UUID.randomUUID().toString());
            connection.start();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Topic destination = session.createTopic(ltopic);

            consumer = session.createConsumer(destination, selector);

            Message message = consumer.receive(timeout * 60 * 1000);
            if (message != null) {
                String value = getMessageBody(message);
                if (build != null) {
                    if (StringUtils.isNotEmpty(variable)) {
                        EnvVars vars = new EnvVars();
                        vars.put(variable, value);
                        build.addAction(new CIEnvironmentContributingAction(vars));

                    }
                }
                log.info("Received message with selector: " + selector + "\n" + formatMessage(message));
                return value;
            }
            log.info("Timed out waiting for message!");
        } catch (Exception e) {
            log.log(Level.SEVERE, "Unhandled exception waiting for message.", e);
        } finally {
            if (consumer != null) {
                try {
                    consumer.close();
                } catch (Exception e) {
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception e) {
                }
            }
        }
    } else {
        log.severe("One or more of the following is invalid (null): ip, user, password, topic, broker.");
    }
    return null;
}

From source file:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java

@Override
public boolean subscribe(String jobname, String selector) {
    this.topic = getTopic();
    if (this.topic != null) {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                if (!isConnected()) {
                    if (!connect()) {
                        return false;
                    }//from  w w  w . j a  v  a2 s. c o  m
                }
                if (subscriber == null) {
                    log.info("Subscribing job '" + jobname + "' to '" + this.topic + "' topic.");
                    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                    Topic destination = session.createTopic(this.topic);

                    subscriber = session.createDurableSubscriber(destination, jobname, selector, false);
                    log.info("Successfully subscribed job '" + jobname + "' to '" + this.topic
                            + "' topic with selector: " + selector);
                } else {
                    log.fine("Already subscribed to '" + this.topic + "' topic with selector: " + selector
                            + " for job '" + jobname);
                }
                return true;
            } catch (JMSException ex) {

                // Either we were interrupted, or something else went
                // wrong. If we were interrupted, then we will jump ship
                // on the next iteration. If something else happened,
                // then we just unsubscribe here, sleep, so that we may
                // try again on the next iteration.

                log.log(Level.SEVERE, "JMS exception raised while subscribing job '" + jobname
                        + "', retrying in " + RETRY_MINUTES + " minutes.", ex);
                if (!Thread.currentThread().isInterrupted()) {

                    unsubscribe(jobname);

                    try {
                        Thread.sleep(RETRY_MINUTES * 60 * 1000);
                    } catch (InterruptedException ie) {
                        // We were interrupted while waiting to retry.
                        // We will jump ship on the next iteration.

                        // NB: The interrupt flag was cleared when
                        // InterruptedException was thrown. We have to
                        // re-install it to make sure we eventually
                        // leave this thread.
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }
    }
    return false;
}

From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java

public void createProducer(final CreateProducerCommand command) {
    try {//  w w w. j a  v a 2s .  c  om
        final Session session = _testSessions.get(command.getSessionName());
        if (session == null) {
            throw new DistributedTestException("No test session found called: " + command.getSessionName(),
                    command);
        }

        synchronized (session) {
            final Destination destination;
            if (command.isTopic()) {
                destination = session.createTopic(command.getDestinationName());
            } else {
                destination = session.createQueue(command.getDestinationName());
            }

            final MessageProducer jmsProducer = session.createProducer(destination);

            if (command.getPriority() != -1) {
                jmsProducer.setPriority(command.getPriority());
            }
            if (command.getTimeToLive() > 0) {
                jmsProducer.setTimeToLive(command.getTimeToLive());
            }

            if (command.getDeliveryMode() == DeliveryMode.NON_PERSISTENT
                    || command.getDeliveryMode() == DeliveryMode.PERSISTENT) {
                jmsProducer.setDeliveryMode(command.getDeliveryMode());
            }

            addProducer(command.getParticipantName(), jmsProducer);
        }
    } catch (final JMSException jmse) {
        throw new DistributedTestException("Unable to create new producer: " + command, jmse);
    }
}

From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java

public void createConsumer(final CreateConsumerCommand command) {
    try {//from w w  w  . ja  va2 s.c o  m
        final Session session = _testSessions.get(command.getSessionName());
        if (session == null) {
            throw new DistributedTestException("No test session found called: " + command.getSessionName(),
                    command);
        }

        synchronized (session) {
            Destination destination;
            MessageConsumer jmsConsumer;
            if (command.isTopic()) {
                Topic topic = session.createTopic(command.getDestinationName());
                if (command.isDurableSubscription()) {
                    String subscription = "subscription-" + command.getParticipantName()
                            + System.currentTimeMillis();
                    jmsConsumer = session.createDurableSubscriber(topic, subscription);

                    _testSubscriptions.put(subscription, session);
                    LOGGER.debug("created durable suscription " + subscription + " to topic " + topic);
                } else {
                    jmsConsumer = session.createConsumer(topic, command.getSelector());
                }

                destination = topic;
            } else {
                destination = session.createQueue(command.getDestinationName());
                jmsConsumer = session.createConsumer(destination, command.getSelector());
            }

            _testConsumers.put(command.getParticipantName(), jmsConsumer);
        }
    } catch (final JMSException jmse) {
        throw new DistributedTestException("Unable to create new consumer: " + command, jmse);
    }
}

From source file:com.aol.advertising.qiao.emitter.AMQEmitter.java

/**
 * Create JMS connectins, sessions, producers, destination objects. (one
 * producer per connection)/*  ww w  . j a v a  2  s  . co  m*/
 *
 * @throws Exception
 */
protected void createJmsResources() throws Exception {

    Connection conn;
    Session session;
    MessageProducer producer;

    // create connections
    logger.info("creating producers...");
    for (int i = 0; i < numProducer; i++) {
        conn = connectionFactory.createConnection();
        connList.add(conn);

        // create sessions for a connection
        session = conn.createSession(transacted, ackMode);

        if (destination == null) {
            if (isQueue) {
                destination = session.createQueue(destinationName);
            } else {
                destination = session.createTopic(destinationName);
            }
        }

        producer = session.createProducer(destination);
        producer.setDeliveryMode(deliveryMode);

        Producer p = new Producer(session, producer);
        producersPool.add(p);
        producersStack.add(p);
    }

    logger.info("AMQ producer(s) created, count=" + producersStack.size());
}

From source file:org.dawnsci.commandserver.ui.view.StatusQueueView.java

/**
 * Listens to a topic/*from www .  java2  s . c o m*/
 */
private void createTopicListener(final URI uri) throws Exception {

    // Use job because connection might timeout.
    final Job topicJob = new Job("Create topic listener") {

        @Override
        protected IStatus run(IProgressMonitor monitor) {
            try {
                ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
                StatusQueueView.this.topicConnection = connectionFactory.createConnection();
                topicConnection.start();

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

                Topic topic = session.createTopic(getTopicName());
                MessageConsumer consumer = session.createConsumer(topic);

                final Class clazz = getBeanClass();
                final ObjectMapper mapper = new ObjectMapper();

                MessageListener listener = new MessageListener() {
                    public void onMessage(Message message) {
                        try {
                            if (message instanceof TextMessage) {
                                TextMessage t = (TextMessage) message;
                                final StatusBean bean = mapper.readValue(t.getText(), clazz);
                                mergeBean(bean);
                            }
                        } catch (Exception e) {
                            logger.error("Updating changed bean from topic", e);
                        }
                    }
                };
                consumer.setMessageListener(listener);

                // Create a listener for administrator broadcast messages.
                topic = session.createTopic(Constants.ADMIN_MESSAGE_TOPIC);
                consumer = session.createConsumer(topic);
                listener = new MessageListener() {
                    public void onMessage(Message message) {
                        try {
                            if (message instanceof TextMessage) {
                                // AdministratorMessage shows a message to the user.
                                final Class msgClass = AdministratorMessage.class;

                                TextMessage t = (TextMessage) message;
                                final AdministratorMessage bean = mapper.readValue(t.getText(), msgClass);

                                getSite().getShell().getDisplay().syncExec(new Runnable() {
                                    public void run() {
                                        MessageDialog.openError(getViewSite().getShell(), bean.getTitle(),
                                                bean.getMessage());

                                        viewer.refresh();
                                    }
                                });
                            }
                        } catch (Exception e) {
                            // Not a big deal if they do not get admin messages.
                        }
                    }
                };
                consumer.setMessageListener(listener);

                return Status.OK_STATUS;

            } catch (Exception ne) {
                logger.error("Cannot listen to topic changes because command server is not there", ne);
                return Status.CANCEL_STATUS;
            }
        }

    };

    topicJob.setPriority(Job.INTERACTIVE);
    topicJob.setSystem(true);
    topicJob.setUser(false);
    topicJob.schedule();
}

From source file:org.wso2.carbon.sample.jmsclient.JMSClient.java

public static void publishMessages(String topicName, String broker) {
    try {/*from   w w w. j a  v a2  s .c  o m*/

        //            filePath = JMSClientUtil.getEventFilePath(sampleNumber, format, topicName, filePath);

        TopicConnection topicConnection = null;
        Session session = null;

        Properties properties = new Properties();
        if (broker.equalsIgnoreCase("activemq")) {
            properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
            Context context = new InitialContext(properties);
            TopicConnectionFactory connFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
            topicConnection = connFactory.createTopicConnection();
            topicConnection.start();
            session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        } else if (broker.equalsIgnoreCase("mb")) {
            properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
            Context context = new InitialContext(properties);
            TopicConnectionFactory connFactory = (TopicConnectionFactory) context
                    .lookup("qpidConnectionFactory");
            topicConnection = connFactory.createTopicConnection();
            topicConnection.start();
            session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        } else if (broker.equalsIgnoreCase("qpid")) {
            properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
            Context context = new InitialContext(properties);
            TopicConnectionFactory connFactory = (TopicConnectionFactory) context
                    .lookup("qpidConnectionFactory");
            topicConnection = connFactory.createTopicConnection();
            topicConnection.start();
            session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        } else {
            log.info("Please enter a valid JMS message broker. (ex: activemq, mb, qpid");
        }

        if (session != null) {
            Topic topic = session.createTopic(topicName);
            MessageProducer producer = session.createProducer(topic);

            try {

                List<Map<String, Object>> messageList = new ArrayList<Map<String, Object>>();

                Random random = new Random();
                for (int j = 0; j < sessionsPerThread; j++) {
                    for (int i = 0; i < msgsPerSession; i++) {
                        HashMap<String, Object> map = new HashMap<String, Object>();

                        map.put("id", random.nextInt() + "");
                        map.put("value", random.nextInt());
                        map.put("content", "sample content");
                        map.put("client", "jmsQueueClient");
                        // setting the timestamp later
                        messageList.add(map);
                    }

                    publishMapMessage(producer, session, messageList);

                }
            } catch (JMSException e) {
                log.error("Can not subscribe." + e.getMessage(), e);
            } catch (IOException e) {
                log.error("Error when reading the data file." + e.getMessage(), e);
            } finally {
                producer.close();
                session.close();
                topicConnection.stop();
            }
        }
    } catch (Exception e) {
        log.error("Error when publishing message" + e.getMessage(), e);
    }
}