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.seedstack.seed.jms.internal.JmsPlugin.java

@SuppressWarnings("unchecked")
private void configureMessageListeners(Collection<Class<?>> listenerCandidates) {
    for (Class<?> candidate : listenerCandidates) {
        if (MessageListener.class.isAssignableFrom(candidate)) {
            Class<? extends MessageListener> messageListenerClass = (Class<? extends MessageListener>) candidate;
            String messageListenerName = messageListenerClass.getCanonicalName();
            JmsMessageListener annotation = messageListenerClass.getAnnotation(JmsMessageListener.class);

            boolean isTransactional;
            try {
                isTransactional = transactionPlugin
                        .isTransactional(messageListenerClass.getMethod("onMessage", Message.class));
            } catch (NoSuchMethodException e) {
                throw SeedException.wrap(e, JmsErrorCodes.UNEXPECTED_EXCEPTION);
            }//from  w w w. j av a2  s .  c o  m

            Connection listenerConnection = connections.get(annotation.connection());

            if (listenerConnection == null) {
                throw SeedException.createNew(JmsErrorCodes.MISSING_CONNECTION_FACTORY)
                        .put(ERROR_CONNECTION_NAME, annotation.connection())
                        .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName);
            }

            Session session;
            try {
                session = listenerConnection.createSession(isTransactional, Session.AUTO_ACKNOWLEDGE);
            } catch (JMSException e) {
                throw SeedException.wrap(e, JmsErrorCodes.UNABLE_TO_CREATE_SESSION)
                        .put(ERROR_CONNECTION_NAME, annotation.connection())
                        .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName);
            }

            Destination destination;
            try {
                switch (annotation.destinationType()) {
                case QUEUE:
                    destination = session.createQueue(annotation.destinationName());
                    break;
                case TOPIC:
                    destination = session.createTopic(annotation.destinationName());
                    break;
                default:
                    throw SeedException.createNew(JmsErrorCodes.UNKNOWN_DESTINATION_TYPE)
                            .put(ERROR_CONNECTION_NAME, annotation.connection())
                            .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName);
                }
            } catch (JMSException e) {
                throw SeedException.wrap(e, JmsErrorCodes.UNABLE_TO_CREATE_DESTINATION)
                        .put(ERROR_CONNECTION_NAME, annotation.connection())
                        .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName);
            }

            Class<? extends MessagePoller> messagePollerClass = null;
            if (annotation.poller().length > 0) {
                messagePollerClass = annotation.poller()[0];
            }

            registerMessageListener(new MessageListenerDefinition(messageListenerName, annotation.connection(),
                    session, destination, annotation.selector(), messageListenerClass, messagePollerClass));
        }
    }
}

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

@Override
public boolean sendMessage(Run<?, ?> build, TaskListener listener, MessageUtils.MESSAGE_TYPE type, String props,
        String content) {/*from  ww  w  .  j a v  a2  s .  c  o  m*/
    Connection connection = null;
    Session session = null;
    MessageProducer publisher = null;

    try {
        String ltopic = getTopic();
        if (provider.getAuthenticationMethod() != null && ltopic != null && provider.getBroker() != null) {
            ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory();
            connection = connectionFactory.createConnection();
            connection.start();

            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createTopic(ltopic);
            publisher = session.createProducer(destination);

            TextMessage message;
            message = session.createTextMessage("");
            message.setJMSType(JSON_TYPE);

            message.setStringProperty("CI_NAME", build.getParent().getName());
            message.setStringProperty("CI_TYPE", type.getMessage());
            if (!build.isBuilding()) {
                message.setStringProperty("CI_STATUS",
                        (build.getResult() == Result.SUCCESS ? "passed" : "failed"));
            }

            StrSubstitutor sub = new StrSubstitutor(build.getEnvironment(listener));

            if (props != null && !props.trim().equals("")) {
                Properties p = new Properties();
                p.load(new StringReader(props));
                @SuppressWarnings("unchecked")
                Enumeration<String> e = (Enumeration<String>) p.propertyNames();
                while (e.hasMoreElements()) {
                    String key = e.nextElement();
                    message.setStringProperty(key, sub.replace(p.getProperty(key)));
                }
            }

            message.setText(sub.replace(content));

            publisher.send(message);
            log.info("Sent " + type.toString() + " message for job '" + build.getParent().getName()
                    + "' to topic '" + ltopic + "':\n" + formatMessage(message));
        } else {
            log.severe("One or more of the following is invalid (null): user, password, topic, broker.");
            return false;
        }

    } catch (Exception e) {
        log.log(Level.SEVERE, "Unhandled exception in perform.", e);
    } finally {
        if (publisher != null) {
            try {
                publisher.close();
            } catch (JMSException e) {
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
            }
        }
    }
    return true;
}

From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java

/**
 * Clear the specified topic//  w ww  .  j  a v  a2 s.c om
 */
protected void purgeTopic(String destination, String topic) throws Exception {
    Connection c = null;
    Session s = null;

    try {
        logger.debug("purging topic : " + topic);
        c = getConnection(true, false);
        if (c == null) {
            logger.debug("could not create a connection to topic : " + destination);
        }

        c.start();
        s = ((TopicConnection) c).createTopicSession(true, Session.SESSION_TRANSACTED);

        logger.debug("created topic session");
        Topic dest = s.createTopic(destination);
        logger.debug("created topic destination");

        if (client != null) {
            client.dispose();
        }

        MessageConsumer consumer = null;

        try {
            consumer = s.createDurableSubscriber(dest, topic);
            logger.debug("created consumer");
            while (consumer.receiveNoWait() != null) {
                logger.debug("Topic " + topic + " isn't empty, draining it");
            }
            logger.debug("topic should be empty");
            consumer.close();
            s.unsubscribe(topic);
        } catch (JMSException e) {
            logger.debug("could not unsubscribe : " + topic);
        }
    }

    finally {
        if (c != null) {
            c.stop();
            if (s != null) {
                s.close();
            }
            try {
                c.close();
            } catch (JMSException e) {
                logger.warn("Failed to close jms connection: " + e.getMessage());
            }
        }
    }
    logger.debug("completed draining topic :" + topic);
}

From source file:tools.ProducerTool.java

@Override
public void run() {
    Connection connection = null;
    Session session = null;
    try {//w w  w  .j a v  a  2 s . c om
        connection = connectionFactory.createConnection();
        if (clientId != null) {
            connection.setClientID(clientId);
        }
        session = connection.createSession(transacted, acknowledgeMode);
        Destination destination = null;
        if (jndiLookupDestinations) {
            destination = (Destination) context.lookup(destinationName);
        } else {
            if (useQueueDestinations) {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryQueue();
                } else {
                    destination = session.createQueue(destinationName);
                }
            } else {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryTopic();
                } else {
                    destination = session.createTopic(destinationName);
                }
            }
        }

        MessageProducer producer = session.createProducer(destination);
        if (durable) {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } else {
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        }

        int numMessagesToSend = useFinalControlMessage ? numMessages - 1 : numMessages;

        for (int i = 0; i < numMessagesToSend; i++) {
            String messageText = "Message " + i + " at " + new Date();
            if (bytesLength > -1) {
                byte[] messageTextBytes = messageText.getBytes(StandardCharsets.UTF_8);
                BytesMessage bytesMessage = session.createBytesMessage();
                bytesMessage.writeBytes(messageTextBytes);
                if (messageTextBytes.length < bytesLength) {
                    byte[] paddingBytes = new byte[bytesLength - messageTextBytes.length];
                    bytesMessage.writeBytes(paddingBytes);
                }
                if (messageGroupId != null) {
                    bytesMessage.setStringProperty("JMSXGroupID", messageGroupId);
                }
                LOGGER.info("Sending bytes message");
                producer.send(bytesMessage);
            } else {
                TextMessage textMessage = session.createTextMessage(messageText);
                if (messageGroupId != null) {
                    textMessage.setStringProperty("JMSXGroupID", messageGroupId);
                }
                LOGGER.info("Sending text message: " + messageText);
                producer.send(textMessage);
            }

            if (perMessageSleepMS > 0) {
                Thread.sleep(perMessageSleepMS);
            }
            if (transacted) {
                if ((i + 1) % batchSize == 0) {
                    session.commit();
                }
            }
        }
        if (useFinalControlMessage) {
            Message message = session.createMessage();
            if (messageGroupId != null) {
                message.setStringProperty("JMSXGroupID", messageGroupId);
            }
            LOGGER.info("Sending message");
            producer.send(message);
            if (transacted) {
                session.commit();
            }
        }
        producer.close();
    } catch (Exception ex) {
        LOGGER.error("ProducerTool hit exception: " + ex.getMessage(), ex);
    } finally {
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing session", e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing session", e);
            }
        }
    }
}

From source file:tools.ConsumerTool.java

@Override
public void run() {
    Connection connection = null;
    Session session = null;
    try {/*from  w  w  w  .j  av  a2  s. c  o m*/
        connection = connectionFactory.createConnection();
        if (clientId != null) {
            connection.setClientID(clientId);
        }
        connection.start();
        session = connection.createSession(transacted, acknowledgeMode);
        Destination destination = null;
        if (jndiLookupDestinations) {
            destination = (Destination) context.lookup(destinationName);
        } else {
            if (useQueueDestinations) {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryQueue();
                } else {
                    destination = session.createQueue(destinationName);
                }
            } else {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryTopic();
                } else {
                    destination = session.createTopic(destinationName);
                }
            }
        }

        if (useQueueBrowser) {
            runQueueBrowser(session, (Queue) destination);
        } else {
            MessageConsumer consumer = null;
            if (useQueueDestinations) { //Queues
                if (selector != null) {
                    consumer = session.createConsumer(destination, selector);
                } else {
                    consumer = session.createConsumer(destination);
                }
            } else { //Queues
                if (durable) { //Durable Subscribers
                    if (selector != null) {
                        consumer = session.createDurableSubscriber((Topic) destination, subscriptionName,
                                selector, false);
                    } else {
                        consumer = session.createDurableSubscriber((Topic) destination, subscriptionName);
                    }
                } else { //Non-Durable Subscribers
                    if (selector != null) {
                        consumer = session.createConsumer(destination, selector);
                    } else {
                        consumer = session.createConsumer(destination);
                    }
                }
            }

            if (useAsyncListener) {
                final Session consumerSession = session;

                final AtomicInteger perConsumerReceivedMessages = new AtomicInteger(0);
                consumer.setMessageListener(new MessageListener() {

                    @Override
                    public void onMessage(Message message) {
                        perConsumerReceivedMessages.incrementAndGet();
                        handleMessage(consumerSession, message, perConsumerReceivedMessages.get());
                    }
                });
                while (perConsumerReceivedMessages.get() < numMessages) {
                    Thread.sleep(100);
                }
            } else {
                int perConsumerReceivedMessages = 0;
                while (perConsumerReceivedMessages < numMessages) {

                    Message message = null;
                    if (receiveTimeoutMS > -1) {
                        message = consumer.receive(receiveTimeoutMS);
                    } else {
                        message = consumer.receive();
                    }

                    if (message != null) {
                        perConsumerReceivedMessages++;
                        handleMessage(session, message, perConsumerReceivedMessages);
                    }
                }
            }
            consumer.close();
        }

    } catch (Exception ex) {
        LOGGER.error("ConsumerTool hit exception: " + ex.getMessage(), ex);
    } finally {
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing session", e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing connection", e);
            }
        }
    }
}

From source file:com.cws.esolutions.core.utils.MQUtils.java

/**
 * Puts an MQ message on a specified queue and returns the associated
 * correlation ID for retrieval upon request.
 *
 * @param connName - The connection name to utilize
 * @param authData - The authentication data to utilize, if required
 * @param requestQueue - The request queue name to put the message on
 * @param targetHost - The target host for the message
 * @param value - The data to place on the request. MUST be <code>Serialiable</code>
 * @return <code>String</code> - the JMS correlation ID associated with the message
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 *///from   w ww .j ava  2  s.c om
public static final synchronized String sendMqMessage(final String connName, final List<String> authData,
        final String requestQueue, final String targetHost, final Serializable value) throws UtilityException {
    final String methodName = MQUtils.CNAME
            + "sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", connName);
        DEBUGGER.debug("Value: {}", requestQueue);
        DEBUGGER.debug("Value: {}", targetHost);
        DEBUGGER.debug("Value: {}", value);
    }

    Connection conn = null;
    Session session = null;
    Context envContext = null;
    InitialContext initCtx = null;
    MessageProducer producer = null;
    ConnectionFactory connFactory = null;

    final String correlationId = RandomStringUtils.randomAlphanumeric(64);

    if (DEBUG) {
        DEBUGGER.debug("correlationId: {}", correlationId);
    }

    try {
        try {
            initCtx = new InitialContext();
            envContext = (Context) initCtx.lookup(MQUtils.INIT_CONTEXT);

            connFactory = (ConnectionFactory) envContext.lookup(connName);
        } catch (NamingException nx) {
            // we're probably not in a container
            connFactory = new ActiveMQConnectionFactory(connName);
        }

        if (DEBUG) {
            DEBUGGER.debug("ConnectionFactory: {}", connFactory);
        }

        if (connFactory == null) {
            throw new UtilityException("Unable to create connection factory for provided name");
        }

        // Create a Connection
        conn = connFactory.createConnection(authData.get(0),
                PasswordUtils.decryptText(authData.get(1), authData.get(2), authData.get(3),
                        Integer.parseInt(authData.get(4)), Integer.parseInt(authData.get(5)), authData.get(6),
                        authData.get(7), authData.get(8)));
        conn.start();

        if (DEBUG) {
            DEBUGGER.debug("Connection: {}", conn);
        }

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

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", session);
        }

        // Create a MessageProducer from the Session to the Topic or Queue
        if (envContext != null) {
            try {
                producer = session.createProducer((Destination) envContext.lookup(requestQueue));
            } catch (NamingException nx) {
                throw new UtilityException(nx.getMessage(), nx);
            }
        } else {
            Destination destination = session.createTopic(requestQueue);

            if (DEBUG) {
                DEBUGGER.debug("Destination: {}", destination);
            }

            producer = session.createProducer(destination);
        }

        if (producer == null) {
            throw new JMSException("Failed to create a producer object");
        }

        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        if (DEBUG) {
            DEBUGGER.debug("MessageProducer: {}", producer);
        }

        ObjectMessage message = session.createObjectMessage(true);
        message.setJMSCorrelationID(correlationId);
        message.setStringProperty("targetHost", targetHost);

        if (DEBUG) {
            DEBUGGER.debug("correlationId: {}", correlationId);
        }

        message.setObject(value);

        if (DEBUG) {
            DEBUGGER.debug("ObjectMessage: {}", message);
        }

        producer.send(message);
    } catch (JMSException jx) {
        throw new UtilityException(jx.getMessage(), jx);
    } finally {
        try {
            // Clean up
            if (!(session == null)) {
                session.close();
            }

            if (!(conn == null)) {
                conn.close();
                conn.stop();
            }
        } catch (JMSException jx) {
            ERROR_RECORDER.error(jx.getMessage(), jx);
        }
    }

    return correlationId;
}

From source file:org.apache.activemq.usecases.RequestReplyToTopicViaThreeNetworkHopsTest.java

/**
 * TEST TOPICS//from  w ww.  j a v  a 2  s.  c  o  m
 */
public void testTopic(String prod_broker_url, String cons_broker_url) throws Exception {
    int num_msg;

    Connection conn;
    Session sess;
    String topic_name;

    Destination cons_dest;

    num_msg = 5;

    LOG.info("TESTING TOPICS " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)");

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

    //
    // Create the destination on which messages are being tested.
    //
    topic_name = "topotest2.perm.topic";
    LOG.trace("Removing existing Topic");
    removeTopic(conn, topic_name);
    LOG.trace("Creating Topic, " + topic_name);
    cons_dest = sess.createTopic(topic_name);

    testOneDest(conn, sess, cons_dest, num_msg);

    //
    // Cleanup
    //
    removeTopic(conn, topic_name);
    sess.close();
    conn.close();
}

From source file:org.mule.transport.jms.Jms11Support.java

public Destination createDestination(Session session, String name, boolean topic, ImmutableEndpoint endpoint)
        throws JMSException {
    if (connector.isJndiDestinations()) {
        try {//w w w .  ja  va  2s. c  o  m
            Destination dest = getJndiDestination(name);
            if (dest != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug(
                            MessageFormat.format("Destination {0} located in JNDI, will use it now", name));
                }
                return dest;
            } else {
                throw new JMSException("JNDI destination not found with name: " + name);
            }
        } catch (JMSException e) {
            if (connector.isForceJndiDestinations()) {
                throw e;
            } else {
                logger.warn("Unable to look up JNDI destination " + name + ": " + e.getMessage());
            }
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Using non-JNDI destination " + name + ", will create one now");
    }

    if (session == null) {
        throw new IllegalArgumentException("Session cannot be null when creating a destination");
    }
    if (name == null) {
        throw new IllegalArgumentException("Destination name cannot be null when creating a destination");
    }

    if (topic) {
        return session.createTopic(name);
    } else {
        return session.createQueue(name);
    }
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.jms.factory.JMSConnectionFactory.java

public Destination createDestination(Session session, String destinationName) {
    Destination destination = null;
    try {/*from w  w w .  j  a va 2s  .c o m*/
        if (this.destinationType.equals(JMSConstants.JMSDestinationType.QUEUE)) {
            destination = JMSUtils.lookupDestination(ctx, destinationName, JMSConstants.DESTINATION_TYPE_QUEUE);
        } else if (this.destinationType.equals(JMSConstants.JMSDestinationType.TOPIC)) {
            destination = JMSUtils.lookupDestination(ctx, destinationName, JMSConstants.DESTINATION_TYPE_TOPIC);
        }
    } catch (NameNotFoundException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Could not find destination '" + destinationName + "' on connection factory for '"
                    + this.connectionFactoryString + "'. " + e.getMessage());
            logger.debug("Creating destination '" + destinationName + "' on connection factory for '"
                    + this.connectionFactoryString + ".");
        }
        try {
            if (this.destinationType.equals(JMSConstants.JMSDestinationType.QUEUE)) {
                destination = (Queue) session.createQueue(destinationName);
            } else if (this.destinationType.equals(JMSConstants.JMSDestinationType.TOPIC)) {
                destination = (Topic) session.createTopic(destinationName);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Created '" + destinationName + "' on connection factory for '"
                        + this.connectionFactoryString + "'.");
            }
        } catch (JMSException e1) {
            logger.error("Could not find nor create '" + destinationName + "' on connection factory for '"
                    + this.connectionFactoryString + "'. " + e1.getMessage(), e1);
        }

    } catch (NamingException e) {
        logger.error("Naming exception while obtaining connection factory for '" + this.connectionFactoryString
                + "' " + e.getMessage(), e);
    }

    return destination;
}

From source file:org.apache.axis2.transport.jms.ServiceTaskManager.java

/**
 * Return the JMS Destination for the JNDI name of the Destination from the InitialContext
 * @param session which is used to create the destinations if not present and if possible 
 * @return the JMS Destination to which this STM listens for messages
 *///  ww  w  .jav  a  2s. c om
private Destination getDestination(Session session) {
    if (destination == null) {
        try {
            context = getInitialContext();
            destination = JMSUtils.lookupDestination(context, getDestinationJNDIName(),
                    JMSUtils.getDestinationTypeAsString(destinationType));
            if (log.isDebugEnabled()) {
                log.debug("JMS Destination with JNDI name : " + getDestinationJNDIName() + " found for service "
                        + serviceName);
            }
        } catch (NamingException e) {
            try {
                switch (destinationType) {
                case JMSConstants.QUEUE: {
                    destination = session.createQueue(getDestinationJNDIName());
                    break;
                }
                case JMSConstants.TOPIC: {
                    destination = session.createTopic(getDestinationJNDIName());
                    break;
                }
                default: {
                    handleException("Error looking up JMS destination : " + getDestinationJNDIName()
                            + " using JNDI properties : " + jmsProperties, e);
                }
                }
            } catch (JMSException j) {
                handleException("Error looking up JMS destination and auto " + "creating JMS destination : "
                        + getDestinationJNDIName() + " using JNDI properties : " + jmsProperties, e);
            }
        }
    }
    return destination;
}