List of usage examples for javax.jms Session createMessage
Message createMessage() throws JMSException;
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 w ww. ja va 2s .c o 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:springchat.service.MessagesServiceImpl.java
@Override @Secured({ "ROLE_CHATUSER" }) public void postMessage(final String message) { jmsTemplate.send("java:comp/env/NewTextMessageChannel", new MessageCreator() { public Message createMessage(Session session) throws JMSException { Message notification = session.createMessage(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); notification.setStringProperty("user", auth.getName()); notification.setLongProperty("date", new Date().getTime()); notification.setStringProperty("message", message); return notification; }/*from w w w . j a v a 2 s . co m*/ }); }
From source file:com.amalto.core.server.routing.DefaultRoutingEngine.java
private void sendMessage(final ItemPOJOPK itemPOJOPK, ArrayList<RoutingRulePOJO> routingRulesThatMatched) { // Sort execution order and send JMS message Collections.sort(routingRulesThatMatched); final String[] ruleNames = new String[routingRulesThatMatched.size()]; int i = 0;// w w w. ja v a 2s.c om for (RoutingRulePOJO rulePOJO : routingRulesThatMatched) { ruleNames[i] = rulePOJO.getPK().getUniqueId(); i++; } jmsTemplate.send(new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { Message message = session.createMessage(); setRulesList(message, ruleNames); message.setStringProperty(JMS_CONTAINER_PROPERTY, itemPOJOPK.getDataClusterPOJOPK().getUniqueId()); message.setStringProperty(JMS_TYPE_PROPERTY, itemPOJOPK.getConceptName()); message.setStringProperty(JMS_PK_PROPERTY, Util.joinStrings(itemPOJOPK.getIds(), ".")); message.setLongProperty(JMS_SCHEDULED, System.currentTimeMillis()); return message; } }); }
From source file:Supplier.java
public void run() { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url); Session session = null; Destination orderQueue;//from w w w.ja v a 2s .c o m try { Connection connection = connectionFactory.createConnection(); session = connection.createSession(true, Session.SESSION_TRANSACTED); orderQueue = session.createQueue(QUEUE); MessageConsumer consumer = session.createConsumer(orderQueue); connection.start(); while (true) { Message message = consumer.receive(); MessageProducer producer = session.createProducer(message.getJMSReplyTo()); MapMessage orderMessage; if (message instanceof MapMessage) { orderMessage = (MapMessage) message; } else { // End of Stream producer.send(session.createMessage()); session.commit(); producer.close(); break; } int quantity = orderMessage.getInt("Quantity"); System.out.println( ITEM + " Supplier: Vendor ordered " + quantity + " " + orderMessage.getString("Item")); MapMessage outMessage = session.createMapMessage(); outMessage.setInt("VendorOrderNumber", orderMessage.getInt("VendorOrderNumber")); outMessage.setString("Item", ITEM); quantity = Math.min(orderMessage.getInt("Quantity"), new Random().nextInt(orderMessage.getInt("Quantity") * 10)); outMessage.setInt("Quantity", quantity); producer.send(outMessage); System.out.println(ITEM + " Supplier: Sent " + quantity + " " + ITEM + "(s)"); session.commit(); System.out.println(ITEM + " Supplier: committed transaction"); producer.close(); } connection.close(); } catch (JMSException e) { e.printStackTrace(); } }
From source file:org.apache.james.queue.activemq.ActiveMQMailQueue.java
/** * Try to use ActiveMQ StatisticsPlugin to get size and if that fails * fallback to {@link JMSMailQueue#getSize()} *///from w w w . ja v a 2 s. co m @Override public long getSize() throws MailQueueException { Connection connection = null; Session session = null; MessageConsumer consumer = null; MessageProducer producer = null; TemporaryQueue replyTo = null; long size = -1; try { connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); replyTo = session.createTemporaryQueue(); consumer = session.createConsumer(replyTo); Queue myQueue = session.createQueue(queuename); producer = session.createProducer(null); String queueName = "ActiveMQ.Statistics.Destination." + myQueue.getQueueName(); Queue query = session.createQueue(queueName); Message msg = session.createMessage(); msg.setJMSReplyTo(replyTo); producer.send(query, msg); MapMessage reply = (MapMessage) consumer.receive(2000); if (reply != null && reply.itemExists("size")) { try { size = reply.getLong("size"); return size; } catch (NumberFormatException e) { // if we hit this we can't calculate the size so just catch // it } } } catch (Exception e) { throw new MailQueueException("Unable to remove mails", e); } finally { if (consumer != null) { try { consumer.close(); } catch (JMSException e1) { e1.printStackTrace(); // ignore on rollback } } if (producer != null) { try { producer.close(); } catch (JMSException e1) { // ignore on rollback } } if (replyTo != null) { try { // we need to delete the temporary queue to be sure we will // free up memory if thats not done and a pool is used // its possible that we will register a new mbean in jmx for // every TemporaryQueue which will never get unregistered replyTo.delete(); } catch (JMSException e) { } } try { if (session != null) session.close(); } catch (JMSException e1) { // ignore here } try { if (connection != null) connection.close(); } catch (JMSException e1) { // ignore here } } // if we came to this point we should just fallback to super method return super.getSize(); }
From source file:Retailer.java
public void run() { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url); try {/*from ww w . j a va2s .co m*/ Connection connection = connectionFactory.createConnection(); // The Retailer's session is non-trasacted. Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination vendorOrderQueue = session.createQueue("VendorOrderQueue"); TemporaryQueue retailerConfirmQueue = session.createTemporaryQueue(); MessageProducer producer = session.createProducer(vendorOrderQueue); MessageConsumer replyConsumer = session.createConsumer(retailerConfirmQueue); connection.start(); for (int i = 0; i < 5; i++) { MapMessage message = session.createMapMessage(); message.setString("Item", "Computer(s)"); int quantity = (int) (Math.random() * 4) + 1; message.setInt("Quantity", quantity); message.setJMSReplyTo(retailerConfirmQueue); producer.send(message); System.out.println("Retailer: Ordered " + quantity + " computers."); MapMessage reply = (MapMessage) replyConsumer.receive(); if (reply.getBoolean("OrderAccepted")) { System.out.println("Retailer: Order Filled"); } else { System.out.println("Retailer: Order Not Filled"); } } // Send a non-MapMessage to signal the end producer.send(session.createMessage()); replyConsumer.close(); connection.close(); } catch (JMSException e) { e.printStackTrace(); } }
From source file:Vendor.java
public void run() { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url); Session session = null; Destination orderQueue;//from www . j a v a2 s . c om Destination monitorOrderQueue; Destination storageOrderQueue; TemporaryQueue vendorConfirmQueue; MessageConsumer orderConsumer = null; MessageProducer monitorProducer = null; MessageProducer storageProducer = null; try { Connection connection = connectionFactory.createConnection(); session = connection.createSession(true, Session.SESSION_TRANSACTED); orderQueue = session.createQueue("VendorOrderQueue"); monitorOrderQueue = session.createQueue("MonitorOrderQueue"); storageOrderQueue = session.createQueue("StorageOrderQueue"); orderConsumer = session.createConsumer(orderQueue); monitorProducer = session.createProducer(monitorOrderQueue); storageProducer = session.createProducer(storageOrderQueue); Connection asyncconnection = connectionFactory.createConnection(); asyncSession = asyncconnection.createSession(true, Session.SESSION_TRANSACTED); vendorConfirmQueue = asyncSession.createTemporaryQueue(); MessageConsumer confirmConsumer = asyncSession.createConsumer(vendorConfirmQueue); confirmConsumer.setMessageListener(this); asyncconnection.start(); connection.start(); while (true) { Order order = null; try { Message inMessage = orderConsumer.receive(); MapMessage message; if (inMessage instanceof MapMessage) { message = (MapMessage) inMessage; } else { // end of stream Message outMessage = session.createMessage(); outMessage.setJMSReplyTo(vendorConfirmQueue); monitorProducer.send(outMessage); storageProducer.send(outMessage); session.commit(); break; } // Randomly throw an exception in here to simulate a Database error // and trigger a rollback of the transaction if (new Random().nextInt(3) == 0) { throw new JMSException("Simulated Database Error."); } order = new Order(message); MapMessage orderMessage = session.createMapMessage(); orderMessage.setJMSReplyTo(vendorConfirmQueue); orderMessage.setInt("VendorOrderNumber", order.getOrderNumber()); int quantity = message.getInt("Quantity"); System.out.println("Vendor: Retailer ordered " + quantity + " " + message.getString("Item")); orderMessage.setInt("Quantity", quantity); orderMessage.setString("Item", "Monitor"); monitorProducer.send(orderMessage); System.out.println("Vendor: ordered " + quantity + " Monitor(s)"); orderMessage.setString("Item", "HardDrive"); storageProducer.send(orderMessage); System.out.println("Vendor: ordered " + quantity + " Hard Drive(s)"); session.commit(); System.out.println("Vendor: Comitted Transaction 1"); } catch (JMSException e) { System.out.println("Vendor: JMSException Occured: " + e.getMessage()); e.printStackTrace(); session.rollback(); System.out.println("Vendor: Rolled Back Transaction."); } } synchronized (supplierLock) { while (numSuppliers > 0) { try { supplierLock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } connection.close(); asyncconnection.close(); } catch (JMSException e) { e.printStackTrace(); } }
From source file:nl.knaw.huygens.timbuctoo.messages.Action.java
public Message createMessage(Session session) throws JMSException { Message message = session.createMessage(); message.setStringProperty(PROP_ACTION, actionType.getStringRepresentation()); message.setStringProperty(PROP_ENTITY_TYPE, TypeNames.getInternalName(type)); message.setBooleanProperty(PROP_FOR_MULTI_ENTITIES, forMultiEntities); if (!forMultiEntities) { message.setStringProperty(PROP_ENTITY_ID, id); }/* w w w . ja v a 2 s . c o m*/ return message; }
From source file:org.apache.activemq.bugs.VMTransportClosureTest.java
/** * This test demonstrates how the "disposeOnDisonnect" feature of * VMTransportServer can incorrectly close all VM connections to the local * broker./*from w w w. j av a 2s .com*/ */ public void testPrematureClosure() throws Exception { // Open a persistent connection to the local broker. The persistent // connection is maintained through the test and should prevent the // VMTransportServer from stopping itself when the local transport is // closed. ActiveMQConnection persistentConn = (ActiveMQConnection) createConnection(); persistentConn.start(); Session session = persistentConn.createSession(true, Session.SESSION_TRANSACTED); MessageProducer producer = session.createProducer(destination); for (int i = 0; i < NUM_ATTEMPTS; i++) { LOG.info("Attempt: " + i); // Open and close a local transport connection. As is done by by // most users of the transport, ensure that the transport is stopped // when closed by the peer (via ShutdownInfo). Closing the local // transport should not affect the persistent connection. final Transport localTransport = TransportFactory.connect(broker.getVmConnectorURI()); localTransport.setTransportListener(new TransportListener() { public void onCommand(Object command) { if (command instanceof ShutdownInfo) { try { localTransport.stop(); } catch (Exception ex) { throw new RuntimeException(ex); } } } public void onException(IOException error) { // ignore } public void transportInterupted() { // ignore } public void transportResumed() { // ignore } }); localTransport.start(); localTransport.stop(); // Ensure that the persistent connection is still usable. producer.send(session.createMessage()); session.rollback(); } persistentConn.close(); }