List of usage examples for javax.jms Session createProducer
MessageProducer createProducer(Destination destination) throws JMSException;
From source file:example.transaction.Client.java
public static void main(String[] args) { String url = BROKER_URL; if (args.length > 0) { url = args[0].trim();/*from w w w . j a va 2 s. c o m*/ } ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url); Connection connection = null; try { connection = connectionFactory.createConnection(); connection.start(); Topic destination = new ActiveMQTopic("transacted.client.example"); Session senderSession = connection.createSession(TRANSACTED, Session.AUTO_ACKNOWLEDGE); Session receiverSession = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); MessageConsumer receiver = receiverSession.createConsumer(destination); receiver.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { if (message instanceof TextMessage) { try { String value = ((TextMessage) message).getText(); System.out.println("We received a new message: " + value); } catch (JMSException e) { System.out.println("Could not read the receiver's topic because of a JMSException"); } } } }); MessageProducer sender = senderSession.createProducer(destination); connection.start(); acceptInputFromUser(senderSession, sender); senderSession.close(); receiverSession.close(); } catch (Exception e) { System.out.println("Caught exception!"); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { System.out.println("Could not close an open connection..."); } } } }
From source file:io.datalayer.activemq.producer.SimpleProducer.java
/** * @param args the destination name to send to and optionally, the number of * messages to send//from www. j a v a2 s . co m */ public static void main(String... args) { Context jndiContext = null; ConnectionFactory connectionFactory = null; Connection connection = null; Session session = null; Destination destination = null; MessageProducer producer = null; String destinationName = null; final int numMsgs; if ((args.length < 1) || (args.length > 2)) { LOG.info("Usage: java SimpleProducer <destination-name> [<number-of-messages>]"); System.exit(1); } destinationName = args[0]; LOG.info("Destination name is " + destinationName); if (args.length == 2) { numMsgs = (new Integer(args[1])).intValue(); } else { numMsgs = 1; } /* * Create a JNDI API InitialContext object */ try { jndiContext = new InitialContext(); } catch (NamingException e) { LOG.info("Could not create JNDI API context: " + e.toString()); System.exit(1); } /* * Look up connection factory and destination. */ try { connectionFactory = (ConnectionFactory) jndiContext.lookup("ConnectionFactory"); destination = (Destination) jndiContext.lookup(destinationName); } catch (NamingException e) { LOG.info("JNDI API lookup failed: " + e); System.exit(1); } /* * Create connection. Create session from connection; false means * session is not transacted. Create sender and text message. Send * messages, varying text slightly. Send end-of-messages message. * Finally, close connection. */ try { connection = connectionFactory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(destination); TextMessage message = session.createTextMessage(); for (int i = 0; i < numMsgs; i++) { message.setText("This is message " + (i + 1)); LOG.info("Sending message: " + message.getText()); producer.send(message); } /* * Send a non-text control message indicating end of messages. */ producer.send(session.createMessage()); } catch (JMSException e) { LOG.info("Exception occurred: " + e); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { } } } }
From source file:org.apache.uima.examples.as.GetMetaRequest.java
/** * retrieve meta information for a UIMA-AS Service attached to a broker * It uses the port 1099 as the JMX port on the broker, unless overridden * by defining the system property activemq.broker.jmx.port with a value of another port number * It uses the default JMX ActiveMQ Domain "org.apache.activemq", unless overridden * by defining the system property activemq.broker.jmx.domain with a value of the domain to use * This normally never needs to be done unless multiple brokers are run on the same node * as is sometimes done for unit tests. * @param args - brokerUri serviceName [-verbose] *///from w w w .jav a2s.com public static void main(String[] args) { if (args.length < 2) { System.err.println("Need arguments: brokerURI serviceName [-verbose]"); System.exit(1); } String brokerURI = args[0]; String queueName = args[1]; boolean printReply = false; if (args.length > 2) { if (args[2].equalsIgnoreCase("-verbose")) { printReply = true; } else { System.err.println("Unknown argument: " + args[2]); System.exit(1); } } final Connection connection; Session producerSession = null; Queue producerQueue = null; MessageProducer producer; MessageConsumer consumer; Session consumerSession = null; TemporaryQueue consumerDestination = null; long startTime = 0; // Check if JMX server port number was specified jmxPort = System.getProperty("activemq.broker.jmx.port"); if (jmxPort == null || jmxPort.trim().length() == 0) { jmxPort = "1099"; // default } try { // First create connection to a broker ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI); connection = factory.createConnection(); connection.start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { try { if (connection != null) { connection.close(); } if (jmxc != null) { jmxc.close(); } } catch (Exception ex) { } } })); URI target = new URI(brokerURI); String brokerHost = target.getHost(); attachToRemoteBrokerJMXServer(brokerURI); if (isQueueAvailable(queueName) == QueueState.exists) { System.out.println("Queue " + queueName + " found on " + brokerURI); System.out.println("Sending getMeta..."); } else if (isQueueAvailable(queueName) == QueueState.existsnot) { System.err.println("Queue " + queueName + " does not exist on " + brokerURI); System.exit(1); } else { System.out.println("Cannot see queues on JMX port " + brokerHost + ":" + jmxPort); System.out.println("Sending getMeta anyway..."); } producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producerQueue = producerSession.createQueue(queueName); producer = producerSession.createProducer(producerQueue); consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); consumerDestination = consumerSession.createTemporaryQueue(); // ----------------------------------------------------------------------------- // Create message consumer. The consumer uses a selector to filter out messages other // then GetMeta replies. Currently UIMA AS service returns two messages for each request: // ServiceInfo message and GetMeta message. The ServiceInfo message is returned by the // service immediately upon receiving a message from a client. This serves dual purpose, // 1) to make sure the client reply destination exists // 2) informs the client which service is processing its request // ----------------------------------------------------------------------------- consumer = consumerSession.createConsumer(consumerDestination, "Command=2001"); TextMessage msg = producerSession.createTextMessage(); msg.setStringProperty(AsynchAEMessage.MessageFrom, consumerDestination.getQueueName()); msg.setStringProperty(UIMAMessage.ServerURI, brokerURI); msg.setIntProperty(AsynchAEMessage.MessageType, AsynchAEMessage.Request); msg.setIntProperty(AsynchAEMessage.Command, AsynchAEMessage.GetMeta); msg.setJMSReplyTo(consumerDestination); msg.setText(""); producer.send(msg); startTime = System.nanoTime(); System.out.println("Sent getMeta request to " + queueName + " at " + brokerURI); System.out.println("Waiting for getMeta reply..."); ActiveMQTextMessage reply = (ActiveMQTextMessage) consumer.receive(); long waitTime = (System.nanoTime() - startTime) / 1000000; System.out.println( "Reply from " + reply.getStringProperty("ServerIP") + " received in " + waitTime + " ms"); if (printReply) { System.out.println("Reply MessageText: " + reply.getText()); } } catch (Exception e) { System.err.println(e.toString()); } System.exit(0); }
From source file:service.emailer.Emailer.java
/** * Send email with parameters to emailQueue * @param area/*from w ww .j ava 2 s . c o m*/ * @param email */ public static void sendEmail(String area, List<String> email) { try { //JMS QUEUE SEND final ConnectionFactory connectionFactory = lookup(ConnectionFactory.class, JNDI_CONNECTION_FACTORY); final Queue queue = lookup(Queue.class, JNDI_QUEUE); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); MapMessage message = session.createMapMessage(); message.setString("type", "warnFile"); message.setString("area", area); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(email); message.setString("emailReceivers", json); producer.send(message); } catch (JMSException ex) { Logger.getLogger(Emailer.class.getName()).log(Level.SEVERE, null, ex); } catch (JsonProcessingException ex) { Logger.getLogger(Emailer.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.dawnsci.commandserver.core.util.JSONUtils.java
/** * Generic way of sending a topic notification * @param connection - does not get closed afterwards nust be started before. * @param message/*from w ww . jav a 2 s . com*/ * @param topicName * @param uri * @throws Exception */ private static final void sendTopic(Connection connection, Object message, String topicName, URI uri) throws Exception { // JMS messages are sent and received using a Session. We will // create here a non-transactional session object. If you want // to use transactions you should set the first parameter to 'true' Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); try { Topic topic = session.createTopic(topicName); MessageProducer producer = session.createProducer(topic); final ObjectMapper mapper = new ObjectMapper(); // Here we are sending the message out to the topic TextMessage temp = session.createTextMessage(mapper.writeValueAsString(message)); producer.send(temp, DeliveryMode.NON_PERSISTENT, 1, 5000); } finally { session.close(); } }
From source file:org.wso2.carbon.bpmn.extensions.jms.JMSUtils.java
/** * This is a JMS spec independent method to create a MessageProducer. Please be cautious when * making any changes// w w w .j a v a 2 s .c o m * * @param session JMS session * @param destination the Destination * @param isQueue is the Destination a queue? * @return a MessageProducer to send messages to the given Destination * @throws JMSException on errors, to be handled and logged by the caller */ public static MessageProducer createProducer(Session session, Destination destination, Boolean isQueue) throws JMSException { if (isQueue == null) { return session.createProducer(destination); } else { if (isQueue) { return ((QueueSession) session).createSender((Queue) destination); } else { return ((TopicSession) session).createPublisher((Topic) destination); } } }
From source file:org.apache.activemq.bugs.AMQ7118Test.java
protected static boolean produce(Session session, Topic topic, int messageCount, int messageSize) throws JMSException { MessageProducer producer = session.createProducer(topic); for (int i = 0; i < messageCount; i++) { TextMessage helloMessage = session.createTextMessage(StringUtils.repeat("a", messageSize)); try {/*from www. j a v a2s . com*/ producer.send(helloMessage); } catch (ResourceAllocationException e) { return false; } } return true; }
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 queue via ActiveMQ message broker * * @param queueName the queue which the messages should be published under * @param messageFormat messageFormat of the test data file * @param testCaseFolderName Testcase folder name which is in the test artifacts folder * @param dataFileName data file name with the extension to be read * *//*w w w. j av a2 s.c om*/ public static void publishToQueue(String queueName, String messageFormat, String testCaseFolderName, String dataFileName) throws JMSException, IOException, NamingException { //create connection Properties properties = new Properties(); properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties")); Context context = new InitialContext(properties); QueueConnectionFactory connFactory = (QueueConnectionFactory) context.lookup("ConnectionFactory"); QueueConnection queueConnection = connFactory.createQueueConnection(); queueConnection.start(); Session session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(queueName); MessageProducer producer = session.createProducer(queue); //publish data String filePath = getTestDataFileLocation(testCaseFolderName, dataFileName); List<String> messagesList = readFile(filePath); if (messageFormat.equalsIgnoreCase("map")) { publishMapMessages(producer, session, messagesList); } else { publishTextMessage(producer, session, messagesList); } //close connection producer.close(); session.close(); queueConnection.stop(); queueConnection.close(); }
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 ww . j a va2s. c o 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:test.SecureSampleApp.java
private static String sendMessage(final String encryptedMessage) { return template.execute(new SessionCallback<String>() { @Override/*from w w w.ja v a 2 s . c o m*/ public String doInJms(Session session) throws JMSException { TextMessage message = session.createTextMessage(encryptedMessage); Queue outQueue = session.createQueue("receive"); Destination inDest = session.createTemporaryQueue(); String correlationID = UUID.randomUUID().toString(); message.setJMSReplyTo(inDest); message.setJMSCorrelationID(correlationID); MessageProducer producer = session.createProducer(outQueue); producer.send(outQueue, message); return ((TextMessage) session.createConsumer(inDest).receive(10000)).getText(); } }, true); }