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.springframework.cloud.stream.binder.jms.solace.SolaceQueueProvisioner.java

@Override
public Destinations provisionTopicAndConsumerGroup(String name, String... groups) {
    Destinations.Factory destinationsFactory = new Destinations.Factory();

    try {// www . j  a  v  a  2 s  . com
        Topic topic = JCSMPFactory.onlyInstance().createTopic(name);
        JCSMPSession session = sessionFactory.build();
        Connection connection = connectionFactory.createConnection();
        javax.jms.Session jmsSession = connection.createSession(false, 1);

        // Using Durable... because non-durable Solace TopicEndpoints don't have names
        TopicEndpoint topicEndpoint = new DurableTopicEndpointImpl(name);
        session.provision(topicEndpoint, null, JCSMPSession.FLAG_IGNORE_ALREADY_EXISTS);
        destinationsFactory.withTopic(jmsSession.createTopic(name));

        if (ArrayUtils.isEmpty(groups)) {
            return destinationsFactory.build();
        }

        for (String group : groups) {
            destinationsFactory.addGroup(jmsSession.createQueue(group));
            doProvision(session, topic, group);
        }

        JmsUtils.commitIfNecessary(jmsSession);
        JmsUtils.closeSession(jmsSession);
        JmsUtils.closeConnection(connection);
    } catch (JCSMPErrorResponseException e) {
        if (JCSMPErrorResponseSubcodeEx.SUBSCRIPTION_ALREADY_PRESENT != e.getSubcodeEx()) {
            throw new RuntimeException(e);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return destinationsFactory.build();
}

From source file:org.dawnsci.commandserver.core.process.ProgressableProcess.java

/**
 * Starts a connection which listens to the topic and if
 * a cancel is found published, tries to terminate the subprocess.
 * /*  w ww .  j a va  2  s  . co m*/
 * @param p
 */
protected void createTerminateListener() throws Exception {

    ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    ProgressableProcess.this.topicConnection = connectionFactory.createConnection();
    topicConnection.start();

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

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

    final Class clazz = bean.getClass();
    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 tbean = mapper.readValue(t.getText(), clazz);

                    if (bean.getStatus().isFinal()) { // Something else already happened
                        topicConnection.close();
                        return;
                    }

                    if (bean.getUniqueId().equals(tbean.getUniqueId())) {
                        if (tbean.getStatus() == Status.REQUEST_TERMINATE) {
                            bean.merge(tbean);
                            out.println("Terminating job '" + tbean.getName() + "'");

                            terminate();
                            topicConnection.close();

                            bean.setStatus(Status.TERMINATED);
                            bean.setMessage("Foricibly terminated before finishing.");
                            broadcast(bean);

                            return;
                        }
                    }

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

    };
    consumer.setMessageListener(listener);

}

From source file:jenkins.plugins.logstash.persistence.ActiveMqDao.java

@Override
public void push(String data) throws IOException {
    TopicConnection connection = null;/*from   w ww. j  a va2 s.  c o m*/
    Session session = null;
    try {
        // Create a Connection
        connection = connectionFactory.createTopicConnection();

        connection.start();

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

        // Create the destination Queue
        Destination destination = session.createTopic(key);

        // Create the MessageProducer from the Session to the Queue
        MessageProducer producer = session.createProducer(destination);

        producer.setDeliveryMode(DeliveryMode.PERSISTENT);

        // Create the message
        TextMessage message = session.createTextMessage(data);
        message.setJMSType("application/json");
        // Tell the producer to send the message
        producer.send(message);

        //logger.log( Level.FINER, String.format("JMS message sent with ID [%s]", message.getJMSMessageID()));

    } catch (JMSException e) {
        logger.log(Level.SEVERE, null != e.getMessage() ? e.getMessage() : e.getClass().getName());
        throw new IOException(e);
    } finally {
        // Clean up
        try {
            if (null != session)
                session.close();
        } catch (JMSException e) {
            logger.log(Level.WARNING, null != e.getMessage() ? e.getMessage() : e.getClass().getName());
        }
        try {
            if (null != connection)
                connection.close();
        } catch (JMSException e) {
            logger.log(Level.WARNING, null != e.getMessage() ? e.getMessage() : e.getClass().getName());
        }
    }
}

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

/**
 * Listens to a topic/*from  ww  w  .java  2s  . c  om*/
 */
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);
                topicConnection = connectionFactory.createConnection();
                topicConnection.start();

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

                final Topic topic = session.createTopic(Constants.ALIVE_TOPIC);
                final MessageConsumer consumer = session.createConsumer(topic);

                final ObjectMapper mapper = new ObjectMapper();

                MessageListener listener = new MessageListener() {
                    public void onMessage(Message message) {
                        try {
                            if (message instanceof TextMessage) {
                                TextMessage t = (TextMessage) message;
                                final ConsumerBean bean = mapper.readValue(t.getText(), ConsumerBean.class);
                                bean.setLastAlive(System.currentTimeMillis());
                                consumers.put(bean.getConsumerId(), bean);
                            }
                        } catch (Exception e) {
                            logger.error("Updating changed bean from topic", e);
                        }
                    }
                };
                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.ahp.core.messaging.AhpJmsProducer.java

public void sendTextMessage(String pTextMessage, AhpJmsDestinationTypes pAhpJmsDestinationTypes,
        AhpJmsDestinationNames pAhpJmsDestinationNames) {
    Connection lConnection = null;
    Session lSession = null;
    try {/*from   www .  j av a 2 s.  c  om*/
        lConnection = this.mJmsConnectionFactory.createConnection();
        lSession = lConnection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        Destination lDestination = null;
        if (pAhpJmsDestinationTypes.equals(AhpJmsDestinationTypes.Queue))
            lDestination = lSession.createQueue(pAhpJmsDestinationNames.toString());
        else
            lDestination = lSession.createTopic(pAhpJmsDestinationNames.toString());
        MessageProducer lMessageProducer = lSession.createProducer(lDestination);
        lMessageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
        //lMessageProducer.setTimeToLive( timeToLive );
        Message lTextMessage = lSession.createTextMessage(pTextMessage);
        LOGGER.debug("AhpJmsProducer sending message to Destination " + pAhpJmsDestinationNames.toString()
                + " TextMessage :: \n" + pTextMessage);
        lMessageProducer.send(lTextMessage);
        lSession.commit();
    } catch (JMSException exJms) {
        LOGGER.error("", exJms);
    } finally {
        try {
            lConnection.close();
        } catch (JMSException exJms) {
            LOGGER.error("", exJms);
        }
    }
}

From source file:com.moss.veracity.core.cluster.jms.UpdateTransmitterJMSImpl.java

private void sendMessage(Object o) {

    Session session = null;
    MessageProducer producer = null;/*from  www .j  a  va  2  s . c  om*/
    try {
        StringWriter writer = new StringWriter();
        Marshaller m = jaxbContext.createMarshaller();
        m.marshal(o, writer);
        String text = writer.getBuffer().toString();

        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic(UpdateTopic.NAME);
        producer = session.createProducer(topic);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);

        TextMessage message = session.createTextMessage(text);
        producer.send(message);

        producer.close();
        session.close();
    } catch (Exception ex) {

        if (producer != null) {
            try {
                producer.close();
            } catch (JMSException e) {
                if (log.isErrorEnabled()) {
                    log.error("Failed to close producer after failure", e);
                } else {
                    ex.printStackTrace();
                }
            }
        }

        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                if (log.isErrorEnabled()) {
                    log.error("Failed to close session after failure", e);
                } else {
                    ex.printStackTrace();
                }
            }
        }

        throw new RuntimeException("Message transmission failed: " + o, ex);
    }
}

From source file:org.sakaiproject.kernel.email.outgoing.OutgoingEmailMessageListener.java

protected void activate(ComponentContext ctx) {
    @SuppressWarnings("unchecked")
    Dictionary props = ctx.getProperties();

    Integer _maxRetries = (Integer) props.get(MAX_RETRIES);
    if (_maxRetries != null) {
        if (diff(maxRetries, _maxRetries)) {
            maxRetries = _maxRetries;//from  w  w w. j  ava2  s .co  m
        }
    } else {
        LOGGER.error("Maximum times to retry messages not set.");
    }

    Integer _retryInterval = (Integer) props.get(RETRY_INTERVAL);
    if (_retryInterval != null) {
        if (diff(_retryInterval, retryInterval)) {
            retryInterval = _retryInterval;
        }
    } else {
        LOGGER.error("SMTP retry interval not set.");
    }

    if (maxRetries * retryInterval < 4320 /* minutes in 3 days */) {
        LOGGER.warn("SMTP retry window is very short.");
    }

    Integer _smtpPort = (Integer) props.get(SMTP_PORT);
    boolean validPort = _smtpPort != null && _smtpPort >= 0 && _smtpPort <= 65535;
    if (validPort) {
        if (diff(smtpPort, _smtpPort)) {
            smtpPort = _smtpPort;
        }
    } else {
        LOGGER.error("Invalid port set for SMTP");
    }

    String _smtpServer = (String) props.get(SMTP_SERVER);
    boolean smtpServerEmpty = _smtpServer == null || _smtpServer.trim().length() == 0;
    if (!smtpServerEmpty) {
        if (diff(smtpServer, _smtpServer)) {
            smtpServer = _smtpServer;
        }
    } else {
        LOGGER.error("No SMTP server set");
    }

    String _brokerUrl = (String) props.get(BROKER_URL);

    try {
        boolean urlEmpty = _brokerUrl == null || _brokerUrl.trim().length() == 0;
        if (!urlEmpty) {
            if (diff(brokerUrl, _brokerUrl)) {
                LOGGER.info("Creating a new ActiveMQ Connection Factory");
                connectionFactory = connFactoryService.createFactory(_brokerUrl);
            }

            if (connectionFactory != null) {
                connection = connectionFactory.createConnection();
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                Topic dest = session.createTopic(TOPIC_NAME);
                MessageConsumer consumer = session.createConsumer(dest);
                consumer.setMessageListener(this);
                connection.start();
            }
        } else {
            LOGGER.error("Cannot create JMS connection factory with an empty URL.");
        }
        brokerUrl = _brokerUrl;
    } catch (JMSException e) {
        LOGGER.error(e.getMessage(), e);
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e1) {
            }
        }
    }
}

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

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

    Connection connection = cf.createConnection();
    connection.setClientID("clientId");
    connection.start();//from   w ww. j a v  a2  s.  c  o  m

    // The publish method will create a second shared consumer
    Session s = connection.createSession();
    MessageConsumer c = s.createSharedDurableConsumer(s.createTopic(defaultTopicName), "sub1");
    publishTestMessagesDurable(connection, new String[] { "sub1", }, 200, publishedMessageSize,
            DeliveryMode.PERSISTENT, true);

    // verify the count and size - double because two durables so two queue
    // bindings
    verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get());
    verifyPendingDurableStats(defaultTopicName, 200, publishedMessageSize.get());
    c.close();

    // consume messages for sub1
    consumeDurableTestMessages(connection, "sub1", 200, publishedMessageSize);
    verifyPendingStats(defaultTopicName, 0, publishedMessageSize.get());
    verifyPendingDurableStats(defaultTopicName, 0, publishedMessageSize.get());

    connection.close();
}

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

protected void publishTestTopicMessages(int publishSize, int deliveryMode, AtomicLong publishedMessageSize)
        throws Exception {
    // create a new queue
    Connection connection = cf.createConnection();
    connection.setClientID("clientId2");
    connection.start();/*from   w  w w  .  j  av  a2  s  .c  o m*/

    // Start the connection
    Session session = connection.createSession(false, TopicSession.AUTO_ACKNOWLEDGE);
    Topic topic = session.createTopic(defaultTopicName);

    try {
        // publish a bunch of non-persistent messages to fill up the temp
        // store
        MessageProducer prod = session.createProducer(topic);
        prod.setDeliveryMode(deliveryMode);
        for (int i = 0; i < publishSize; i++) {
            prod.send(
                    createMessage(i, session, JournalPendingMessageTest.maxMessageSize, publishedMessageSize));
        }

    } finally {
        connection.close();
    }
}

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

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

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

    publishTestTopicMessages(200, DeliveryMode.NON_PERSISTENT, publishedMessageSize);

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

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

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

    connection.close();
}