Example usage for javax.jms Topic getTopicName

List of usage examples for javax.jms Topic getTopicName

Introduction

In this page you can find the example usage for javax.jms Topic getTopicName.

Prototype


String getTopicName() throws JMSException;

Source Link

Document

Gets the name of this topic.

Usage

From source file:example.wildcard.Client.java

public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();/*  w w w .  j  a va2 s. c o m*/
    }
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url);
    Connection connection = null;

    try {
        Topic senderTopic = new ActiveMQTopic(System.getProperty("topicName"));

        connection = connectionFactory.createConnection("admin", "password");

        Session senderSession = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        MessageProducer sender = senderSession.createProducer(senderTopic);

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

        String policyType = System.getProperty("wildcard", ".*");
        String receiverTopicName = senderTopic.getTopicName() + policyType;
        Topic receiverTopic = receiverSession.createTopic(receiverTopicName);

        MessageConsumer receiver = receiverSession.createConsumer(receiverTopic);
        receiver.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {
                try {
                    if (message instanceof TextMessage) {
                        String text = ((TextMessage) message).getText();
                        System.out.println("We received a new message: " + text);
                    }
                } catch (JMSException e) {
                    System.out.println("Could not read the receiver's topic because of a JMSException");
                }
            }
        });

        connection.start();
        System.out.println("Listening on '" + receiverTopicName + "'");
        System.out.println("Enter a message to send: ");

        Scanner inputReader = new Scanner(System.in);

        while (true) {
            String line = inputReader.nextLine();
            if (line == null) {
                System.out.println("Done!");
                break;
            } else if (line.length() > 0) {
                try {
                    TextMessage message = senderSession.createTextMessage();
                    message.setText(line);
                    System.out.println("Sending a message: " + message.getText());
                    sender.send(message);
                } catch (JMSException e) {
                    System.out.println("Exception during publishing a message: ");
                }
            }
        }

        receiver.close();
        receiverSession.close();
        sender.close();
        senderSession.close();

    } catch (Exception e) {
        System.out.println("Caught exception!");
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                System.out.println("When trying to close connection: ");
            }
        }
    }

}

From source file:fr.xebia.springframework.jms.ManagedDefaultMessageListenerContainer.java

public ObjectName getObjectName() throws MalformedObjectNameException {
    if (objectName == null) {
        String destinationName = getDestinationName();
        Destination destination = getDestination();
        if (destinationName == null && destination != null) {
            try {
                if (destination instanceof Queue) {
                    Queue queue = (Queue) destination;
                    destinationName = queue.getQueueName();

                } else if (destination instanceof Topic) {
                    Topic topic = (Topic) destination;
                    destinationName = topic.getTopicName();
                }/*w  ww .  j  a v  a  2 s .co m*/
            } catch (JMSException e) {
                throw new UncategorizedJmsException(e);
            }
        }
        objectName = ObjectName.getInstance("javax.jms:type=MessageListenerContainer,name="
                + ObjectName.quote(getBeanName()) + ",destination=" + destinationName);
    }
    return objectName;
}

From source file:org.openmrs.event.EventEngine.java

/**
 * @see Event#unsubscribe(Destination, EventListener)
 *//*  w w  w  .java2s .  c o m*/
public void unsubscribe(Destination dest, EventListener listener) {

    initializeIfNeeded();

    if (dest != null) {
        Topic topic = (Topic) dest;
        try {
            String key = topic.getTopicName() + DELIMITER + listener.getClass().getName();
            if (subscribers.get(key) != null)
                subscribers.get(key).close();

            subscribers.remove(key);
        } catch (JMSException e) {
            log.error("Failed to unsubscribe from the specified destination:", e);
        }
    }
}

From source file:org.openmrs.event.EventEngine.java

/**
 * @see Event#subscribe(Destination, EventListener)
 */// w w  w  .  j a  v a2 s.c  om
public void subscribe(Destination destination, final EventListener listenerToRegister) {

    initializeIfNeeded();

    TopicConnection conn;
    Topic topic = (Topic) destination;

    try {
        conn = (TopicConnection) jmsTemplate.getConnectionFactory().createConnection();
        TopicSession session = conn.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
        TopicSubscriber subscriber = session.createSubscriber(topic);
        subscriber.setMessageListener(new MessageListener() {

            @Override
            public void onMessage(Message message) {
                listenerToRegister.onMessage(message);
            }
        });

        //Check if this is a duplicate and remove it
        String key = topic.getTopicName() + DELIMITER + listenerToRegister.getClass().getName();
        if (subscribers.containsKey(key)) {
            unsubscribe(destination, listenerToRegister);
        }

        subscribers.put(key, subscriber);
        conn.start();

    } catch (JMSException e) {
        // TODO Auto-generated catch block. Do something smarter here.
        e.printStackTrace();
    }

    //      List<EventListener> currentListeners = listeners.get(key);
    //
    //      if (currentListeners == null) {
    //         currentListeners = new ArrayList<EventListener>();
    //         currentListeners.add(listenerToRegister);
    //         listeners.put(key, currentListeners);
    //         if (log.isInfoEnabled())
    //            log.info("subscribed: " + listenerToRegister + " to key: "
    //                  + key);
    //
    //      } else {
    //         // prevent duplicates because of weird spring loading
    //         String listernToRegisterName = listenerToRegister.getClass()
    //               .getName();
    //         Iterator<EventListener> iterator = currentListeners.iterator();
    //         while (iterator.hasNext()) {
    //            EventListener lstnr = iterator.next();
    //            if (lstnr.getClass().getName().equals(listernToRegisterName))
    //               iterator.remove();
    //         }
    //
    //         if (log.isInfoEnabled())
    //            log.info("subscribing: " + listenerToRegister + " to key: "
    //                  + key);
    //
    //         currentListeners.add(listenerToRegister);
    //      }

}

From source file:net.timewalker.ffmq4.local.session.LocalMessageConsumer.java

protected final void initDestination() throws JMSException {
    // Security : a consumer destination may only be set at creation time
    //            so we check permissions here once and for all.
    LocalConnection conn = (LocalConnection) session.getConnection();
    if (conn.isSecurityEnabled()) {
        if (destination instanceof Queue) {
            String queueName = ((Queue) destination).getQueueName();
            if (conn.isRegisteredTemporaryQueue(queueName)) {
                // OK, temporary destination
            } else if (queueName.equals(FFMQConstants.ADM_REQUEST_QUEUE)) {
                // Only the internal admin thread can consume on this queue
                if (conn.getSecurityContext() != null)
                    throw new FFMQException("Access denied to administration queue " + queueName,
                            "ACCESS_DENIED");
            } else if (queueName.equals(FFMQConstants.ADM_REPLY_QUEUE)) {
                conn.checkPermission(Resource.SERVER, Action.REMOTE_ADMIN);
            } else {
                // Standard queue
                conn.checkPermission(destination, Action.CONSUME);
            }/*from  www.j  ava  2 s .c  o m*/
        } else if (destination instanceof Topic) {
            String topicName = ((Topic) destination).getTopicName();
            if (conn.isRegisteredTemporaryTopic(topicName)) {
                // OK, temporary destination
            } else {
                // Standard topic
                conn.checkPermission(destination, Action.CONSUME);
            }
        }
    }

    // Lookup a local destination object from the given reference
    if (destination instanceof Queue) {
        Queue queueRef = (Queue) destination;
        this.localQueue = engine.getLocalQueue(queueRef.getQueueName());

        // Check temporary destinations scope (JMS Spec 4.4.3 p2)
        session.checkTemporaryDestinationScope(localQueue);

        this.localQueue.registerConsumer(this);
    } else if (destination instanceof Topic) {
        Topic topicRef = (Topic) destination;
        this.localTopic = engine.getLocalTopic(topicRef.getTopicName());

        // Check temporary destinations scope (JMS Spec 4.4.3 p2)
        session.checkTemporaryDestinationScope(localTopic);

        // Deploy a local queue for this consumer
        TopicDefinition topicDef = this.localTopic.getDefinition();
        QueueDefinition tempDef = topicDef.createQueueDefinition(topicRef.getTopicName(), subscriberId,
                !isDurable());
        if (engine.localQueueExists(tempDef.getName()))
            this.localQueue = engine.getLocalQueue(tempDef.getName());
        else
            this.localQueue = engine.createQueue(tempDef);

        // Register on both the queue and topic
        this.localQueue.registerConsumer(this);
        this.localTopic.registerConsumer(this);
    } else
        throw new InvalidDestinationException("Unsupported destination : " + destination);
}

From source file:net.timewalker.ffmq4.local.session.LocalSession.java

private AbstractLocalDestination getLocalDestination(AbstractMessage message) throws JMSException {
    Destination destination = message.getJMSDestination();

    if (destination instanceof Queue) {
        Queue queueRef = (Queue) destination;
        return engine.getLocalQueue(queueRef.getQueueName());
    } else if (destination instanceof Topic) {
        Topic topicRef = (Topic) destination;
        return engine.getLocalTopic(topicRef.getTopicName());
    } else/*from   w w w.j  av a2  s.  c  o m*/
        throw new InvalidDestinationException("Unsupported destination : " + destination);
}

From source file:org.apache.synapse.transport.jms.JMSUtils.java

/**
 * Create a JMS Topic using the given connection with the JNDI destination name, and return the
 * JMS Destination name of the created queue
 *
 * @param con the JMS Connection to be used
 * @param destinationJNDIName the JNDI name of the Topic to be created
 * @return the JMS Destination name of the created Topic
 * @throws JMSException on error//from   www .  jav  a 2 s .c  o m
 */
public static String createJMSTopic(Connection con, String destinationJNDIName) throws JMSException {
    try {
        TopicSession session = ((TopicConnection) con).createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic(destinationJNDIName);
        log.info("JMS Topic with JNDI name : " + destinationJNDIName + " created");
        return topic.getTopicName();

    } finally {
        try {
            con.close();
        } catch (JMSException ignore) {
        }
    }
}

From source file:org.codehaus.stomp.jms.StompSession.java

protected String convertDestination(Destination d) throws JMSException {
    if (d == null) {
        return null;
    }//from www  .j  ava2 s .  c  o m
    StringBuffer buffer = new StringBuffer();
    if (d instanceof Topic) {
        Topic topic = (Topic) d;
        // if (d instanceof TemporaryTopic) {
        // buffer.append("/temp-topic/");
        // temporaryDestination(topic.getTopicName(), d);
        // } else {
        buffer.append("/topic/");
        // }
        buffer.append(topic.getTopicName());
    } else {
        Queue queue = (Queue) d;
        // if (d instanceof TemporaryQueue) {
        // buffer.append("/temp-queue/");
        // temporaryDestination(queue.getQueueName(), d);
        // } else {
        buffer.append("/queue/");
        // }
        buffer.append(queue.getQueueName());
    }
    return buffer.toString();
}

From source file:org.openhie.openempi.notification.impl.NotificationServiceImpl.java

public void registerListener(List<String> eventTypeNames, MessageHandler handler) {
    if (brokerService == null || !brokerInitialized) {
        log.debug("The broker service is not running in registerListener.");
        return;//from   w w w.j  a v  a2 s .  c  o  m
    }

    if (!isValidHandler(handler)) {
        return;
    }

    ConnectionFactory connectionFactory = jmsTemplate.getConnectionFactory();
    Connection connection = null;
    try {
        connection = connectionFactory.createConnection();
        connection.setClientID(handler.getClientId());
    } catch (JMSException e) {
        log.error("Failed while setting up a registrant for notification events. Error: " + e, e);
        throw new RuntimeException("Unable to setup registration for event notification: " + e.getMessage());
    }

    for (String eventTypeName : eventTypeNames) {
        log.info("Registering handler for event " + eventTypeName);
        Topic topic = topicMap.get(eventTypeName);
        if (topic == null) {
            log.error("Caller attempted to register interest to events of unknown type " + eventTypeName);
            throw new RuntimeException("Unknown event type specified in registration request.");
        }

        if (isListenerRegistered(handler, eventTypeName)) {
            log.warn("Caller attempted to register interest for the same event again.");
            return;
        }

        try {
            Session topicSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            TopicSubscriber subscriber = topicSession.createDurableSubscriber(topic, topic.getTopicName());
            MessageListenerImpl listener = new MessageListenerImpl(connection, topicSession, subscriber,
                    handler);
            saveListenerRegistration(listener, eventTypeName);
            subscriber.setMessageListener(listener);
        } catch (JMSException e) {
            log.error("Failed while setting up a registrant for notification events. Error: " + e, e);
            throw new RuntimeException(
                    "Unable to setup registration for event notification: " + e.getMessage());
        }
    }

    try {
        connection.start();
    } catch (JMSException e) {
        log.error("Failed while setting up a registrant for notification events. Error: " + e, e);
        throw new RuntimeException("Unable to setup registration for event notification: " + e.getMessage());
    }
}

From source file:org.openhie.openempi.notification.impl.NotificationServiceImpl.java

public void unregisterListener(String eventTypeName, MessageHandler handler) {
    if (brokerService == null || !brokerInitialized) {
        log.debug("The broker service is not running in unregisterListener.");
        return;//from ww  w.  j ava 2  s .co m
    }

    log.info("Unregistering handler for event " + eventTypeName);
    if (!isValidHandler(handler)) {
        return;
    }

    Topic topic = topicMap.get(eventTypeName);
    if (topic == null) {
        log.error("Caller attempted to unregister interest to events of unknown type " + eventTypeName);
        throw new RuntimeException("Unknown event type specified in un-registration request.");
    }

    MessageListenerImpl listener = lookupMessageListener(handler, eventTypeName);
    if (listener == null) {
        log.warn("Caller attempted to unregister a listener that is not known to the system: "
                + buildMapKey(handler, eventTypeName));
        return;
    }

    try {
        listener.getConnection().stop();
        listener.getSubscriber().close();
        listener.getSession().unsubscribe(topic.getTopicName());
        listener.getSession().close();
    } catch (JMSException e) {
        log.error("Failed while unregistering a listener. Error: " + e, e);
        throw new RuntimeException("Unable to unregister a listener for event notification: " + e.getMessage());
    }
}