List of usage examples for javax.jms TopicConnection createTopicSession
TopicSession createTopicSession(boolean transacted, int acknowledgeMode) throws JMSException;
From source file:org.wso2.carbon.integration.test.client.JMSPublisherClient.java
/** * This method will publish the data in the test data file to the given topic via ActiveMQ message broker * * @param topicName the topic which the messages should be published under * @param format format of the test data file (csv or text) * @param testCaseFolderName Testcase folder name which is in the test artifacts folder * @param dataFileName data file name with the extension to be read * *///from w w w .j a v a2 s . co m public static void publish(String topicName, String format, String testCaseFolderName, String dataFileName) { if (format == null || "map".equals(format)) { format = "csv"; } try { Properties properties = new Properties(); String filePath = getTestDataFileLocation(testCaseFolderName, dataFileName); properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties")); Context context = new InitialContext(properties); TopicConnectionFactory connFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory"); TopicConnection topicConnection = connFactory.createTopicConnection(); topicConnection.start(); Session session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic(topicName); MessageProducer producer = session.createProducer(topic); List<String> messagesList = readFile(filePath); try { if (format.equalsIgnoreCase("csv")) { log.info("Sending Map messages on '" + topicName + "' topic"); publishMapMessages(producer, session, messagesList); } else { log.info("Sending " + format + " messages on '" + topicName + "' topic"); publishTextMessage(producer, session, messagesList); } } catch (JMSException e) { log.error("Can not subscribe." + e.getMessage(), e); } finally { producer.close(); session.close(); topicConnection.stop(); topicConnection.close(); } } catch (Exception e) { log.error("Error when publishing messages" + e.getMessage(), e); } log.info("All Order Messages sent"); }
From source file:org.wso2.carbon.sample.jmsclient.JMSClient.java
public static void publishMessages(String topicName, String broker) { try {/*ww w . ja 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); } }
From source file:org.apache.stratos.adc.topology.mgt.subscriber.TopologySubscriber.java
public static void subscribe(String topicName) { Properties initialContextProperties = new Properties(); TopicSubscriber topicSubscriber = null; TopicSession topicSession = null;/*from w w w .j a v a 2 s . c o m*/ TopicConnection topicConnection = null; InitialContext initialContext = null; initialContextProperties.put("java.naming.factory.initial", "org.wso2.andes.jndi.PropertiesFileInitialContextFactory"); String mbServerIp = System.getProperty(TopologyConstants.MB_SERVER_IP) == null ? TopologyConstants.DEFAULT_MB_SERVER_IP : System.getProperty(TopologyConstants.MB_SERVER_IP); String connectionString = "amqp://admin:admin@clientID/carbon?brokerlist='tcp://" + mbServerIp + "'&reconnect='true'"; initialContextProperties.put("connectionfactory.qpidConnectionfactory", connectionString); try { initialContext = new InitialContext(initialContextProperties); TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) initialContext .lookup("qpidConnectionfactory"); topicConnection = topicConnectionFactory.createTopicConnection(); topicConnection.start(); topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = topicSession.createTopic(topicName); topicSubscriber = topicSession.createSubscriber(topic); topicSubscriber.setMessageListener(new TopologyListener()); } catch (Exception e) { log.error(e.getMessage(), e); try { if (topicSubscriber != null) { topicSubscriber.close(); } if (topicSession != null) { topicSession.close(); } if (topicConnection != null) { topicConnection.close(); } } catch (JMSException e1) { // ignore } } finally { // start the health checker Thread healthChecker = new Thread(new TopicHealthChecker(topicName, topicSubscriber)); healthChecker.start(); } }
From source file:org.apache.activemq.usecases.DurableSubscriptionHangTestCase.java
private void produceExpiredAndOneNonExpiredMessages() throws JMSException { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName); TopicConnection connection = connectionFactory.createTopicConnection(); TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic(topicName); MessageProducer producer = session.createProducer(topic); producer.setTimeToLive(TimeUnit.SECONDS.toMillis(1)); for (int i = 0; i < 40000; i++) { sendRandomMessage(session, producer); }/*w w w. ja v a 2 s .c o m*/ producer.setTimeToLive(TimeUnit.DAYS.toMillis(1)); sendRandomMessage(session, producer); connection.close(); LOG.info("produceExpiredAndOneNonExpiredMessages done"); }
From source file:org.apache.activemq.usecases.DurableSubscriptionHangTestCase.java
private void registerDurableSubscription() throws JMSException { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName); TopicConnection connection = connectionFactory.createTopicConnection(); connection.setClientID(clientID);/*from ww w . j a v a 2 s . com*/ TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = topicSession.createTopic(topicName); TopicSubscriber durableSubscriber = topicSession.createDurableSubscriber(topic, durableSubName); connection.start(); durableSubscriber.close(); connection.close(); LOG.info("Durable Sub Registered"); }
From source file:org.apache.activemq.usecases.DurableSubscriptionHangTestCase.java
private Message collectMessagesFromDurableSubscriptionForOneMinute() throws Exception { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName); TopicConnection connection = connectionFactory.createTopicConnection(); connection.setClientID(clientID);/*from w ww . j av a 2s . com*/ TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = topicSession.createTopic(topicName); connection.start(); TopicSubscriber subscriber = topicSession.createDurableSubscriber(topic, durableSubName); LOG.info("About to receive messages"); Message message = subscriber.receive(120000); subscriber.close(); connection.close(); LOG.info("collectMessagesFromDurableSubscriptionForOneMinute done"); return message; }
From source file:org.apache.stratos.lb.endpoint.subscriber.TopologySubscriber.java
public static void subscribe(String topicName) { Properties initialContextProperties = new Properties(); TopicSubscriber topicSubscriber = null; TopicSession topicSession = null;/* w ww. j a v a2 s . co m*/ TopicConnection topicConnection = null; InitialContext initialContext = null; initialContextProperties.put("java.naming.factory.initial", "org.wso2.andes.jndi.PropertiesFileInitialContextFactory"); String mbServerUrl = null; if (ConfigHolder.getInstance().getLbConfig() != null) { mbServerUrl = ConfigHolder.getInstance().getLbConfig().getLoadBalancerConfig().getMbServerUrl(); } String connectionString = "amqp://admin:admin@clientID/carbon?brokerlist='tcp://" + (mbServerUrl == null ? TopologyConstants.DEFAULT_MB_SERVER_URL : mbServerUrl) + "'&reconnect='true'"; initialContextProperties.put("connectionfactory.qpidConnectionfactory", connectionString); try { initialContext = new InitialContext(initialContextProperties); TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) initialContext .lookup("qpidConnectionfactory"); topicConnection = topicConnectionFactory.createTopicConnection(); topicConnection.start(); topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = topicSession.createTopic(topicName); topicSubscriber = topicSession.createSubscriber(topic); topicSubscriber.setMessageListener(new TopologyListener()); } catch (Exception e) { log.error(e.getMessage(), e); try { if (topicSubscriber != null) { topicSubscriber.close(); } if (topicSession != null) { topicSession.close(); } if (topicConnection != null) { topicConnection.close(); } } catch (JMSException e1) { // ignore } } finally { // start the health checker Thread healthChecker = new Thread(new TopicHealthChecker(topicName, topicSubscriber)); healthChecker.start(); } }
From source file:org.wso2.carbon.appfactory.eventing.jms.TopicPublisher.java
public void publishMessage(Event event) throws AppFactoryEventException { Properties properties = new Properties(); properties.put(Context.INITIAL_CONTEXT_FACTORY, QPID_ICF); properties.put(CF_NAME_PREFIX + CF_NAME, Util.getTCPConnectionURL()); properties.put(CarbonConstants.REQUEST_BASE_CONTEXT, "true"); try {//from w w w . j a v a2 s .co m ctx = new InitialContext(properties); connFactory = (TopicConnectionFactory) ctx.lookup(CF_NAME); } catch (NamingException e) { throw new AppFactoryEventException("Failed to initialize InitialContext.", e); } TopicConnection topicConnection = null; TopicSession topicSession = null; try { topicConnection = connFactory.createTopicConnection(); topicSession = topicConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE); // Send message String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); Topic topic = topicSession.createTopic(event.getTarget()); //Until MB supports 'Dynamic Topics' we have to create a subscription, therefore forcing Message broker to // create the topic. String defaultSubscriptionId = tenantDomain + "/" + DEFAULT_SUBSCRIPTION + UUID.randomUUID(); topicSubscriber = topicSession.createDurableSubscriber(topic, defaultSubscriptionId); // We are unsubscribing from the Topic as soon as topicSession.unsubscribe(defaultSubscriptionId); // create the message to send MapMessage mapMessage = topicSession.createMapMessage(); mapMessage.setString(MESSAGE_TITLE, event.getMessageTitle()); mapMessage.setString(MESSAGE_BODY, event.getMessageBody()); javax.jms.TopicPublisher topicPublisher = topicSession.createPublisher(topic); topicConnection.start(); topicPublisher.publish(mapMessage); if (log.isDebugEnabled()) { log.debug("Message with Id:" + mapMessage.getJMSMessageID() + ", with title:" + event.getMessageTitle() + " was successfully published."); } } catch (JMSException e) { log.error("Failed to publish message due to " + e.getMessage(), e); throw new AppFactoryEventException("Failed to publish message due to " + e.getMessage(), e); } finally { if (topicSubscriber != null) { try { topicSubscriber.close(); } catch (JMSException e) { log.error("Failed to close default topic subscriber", e); } } if (topicSession != null) { try { topicSession.close(); } catch (JMSException e) { log.error("Failed to close topic session", e); } } if (topicConnection != null) { try { topicConnection.close(); } catch (JMSException e) { log.error("Failed to close topic connection", e); } } } }
From source file:org.wso2.carbon.event.core.internal.delivery.jms.JMSDeliveryManager.java
public void publish(Message message, String topicName, int deliveryMode) throws EventBrokerException { if (isDeactivated()) { return;// ww w. jav a2 s . c om } try { String userName = getLoggedInUserName(); if ((userName == null) || (userName.equals(""))) { // use the system user name userName = CarbonConstants.REGISTRY_SYSTEM_USERNAME; } TopicConnection topicConnection = getTopicConnection(userName); TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); String tenantDomain = EventBrokerHolder.getInstance().getTenantDomain(); if (tenantDomain != null && (!tenantDomain.equals(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME))) { if (!topicName.startsWith("/")) { topicName = getTopicName(tenantDomain + "/" + topicName); } else { topicName = getTopicName(tenantDomain + topicName); } } else { topicName = getTopicName(topicName); } Topic topic = topicSession.createTopic(topicName); //Some times we are not getting the proper topic with the required syntax, if it is not //appropriate we need to check and add the BURL syntax to fix the issue https://wso2.org/jira/browse/MB-185 if (!topic.toString().startsWith("topic://amq.topic")) { topic = topicSession.createTopic("BURL:" + topicName); } TopicPublisher topicPublisher = topicSession.createPublisher(topic); topicPublisher.setDeliveryMode(deliveryMode); TextMessage textMessage = topicSession.createTextMessage(message.getMessage().toString()); Map<String, String> properties = message.getProperties(); for (String key : properties.keySet()) { textMessage.setStringProperty(key, properties.get(key)); } // saving the domain to be used send with the soap header if (CarbonContext.getThreadLocalCarbonContext().getTenantDomain() != null) { textMessage.setStringProperty(MultitenantConstants.TENANT_DOMAIN_HEADER_NAME, CarbonContext.getThreadLocalCarbonContext().getTenantDomain()); } topicPublisher.publish(textMessage); topicPublisher.close(); topicSession.close(); topicConnection.stop(); topicConnection.close(); } catch (JMSException e) { throw new EventBrokerException("Can not publish to topic " + topicName + " " + e.getMessage(), e); } }
From source file:org.wso2.carbon.event.core.internal.delivery.jms.JMSDeliveryManager.java
public void subscribe(Subscription subscription) throws EventBrokerException { if (isDeactivated()) { return;/*from w w w . j av a2 s .c om*/ } // in a multi tenant envirionment deployment synchronizer may creates subscriptions before // the event observer get activated. if (this.subscriptionIDSessionDetailsMap.containsKey(subscription.getId())) { log.warn( "There is an subscription already exists for the subscription with id " + subscription.getId()); return; } JMSMessageListener jmsMessageListener = new JMSMessageListener(this.notificationManager, subscription); try { TopicConnection topicConnection = getTopicConnection(subscription.getOwner()); TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); String topicName = ""; if (subscription.getTenantDomain() != null && (!subscription.getTenantDomain() .equals(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME))) { if (!subscription.getTopicName().startsWith("/")) { topicName = getTopicName(subscription.getTenantDomain() + "/" + subscription.getTopicName()); } else { topicName = getTopicName(subscription.getTenantDomain() + subscription.getTopicName()); } } else { topicName = getTopicName(subscription.getTopicName()); } Topic topic = topicSession.createTopic(topicName); //Some times we are not getting the proper topic with the required syntax, if it is not //appropriate we need to check and add the BURL syntax to fix the issue https://wso2.org/jira/browse/MB-185 if (!topic.toString().startsWith("topic://amq.topic")) { topic = topicSession.createTopic("BURL:" + topicName); } TopicSubscriber topicSubscriber = topicSession.createDurableSubscriber(topic, subscription.getId()); topicSubscriber.setMessageListener(jmsMessageListener); this.subscriptionIDSessionDetailsMap.put(subscription.getId(), new JMSSubscriptionDetails(topicSubscriber, topicSession, topicConnection)); } catch (JMSException e) { throw new EventBrokerException( "Can not subscribe to topic " + subscription.getTopicName() + " " + e.getMessage(), e); } }