List of usage examples for javax.jms Session createQueue
Queue createQueue(String queueName) throws JMSException;
From source file:org.dawnsci.commandserver.core.producer.ProcessConsumer.java
/** * WARNING - starts infinite loop - you have to kill * @param uri//from ww w. j a v a 2s. co m * @param submitQName * @param statusTName * @param statusQName * @throws Exception */ private void monitorSubmissionQueue(URI uri, String submitQName, String statusTName, String statusQName) throws Exception { ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(submitQName); final MessageConsumer consumer = session.createConsumer(queue); connection.start(); System.out.println("Starting consumer for submissions to queue " + submitQName); while (isActive()) { // You have to kill it or call stop() to stop it! try { // Consumes messages from the queue. Message m = consumer.receive(1000); if (m != null) { // TODO FIXME Check if we have the max number of processes // exceeded and wait until we dont... TextMessage t = (TextMessage) m; ObjectMapper mapper = new ObjectMapper(); final StatusBean bean = mapper.readValue(t.getText(), getBeanClass()); if (bean != null) { // We add this to the status list so that it can be rendered in the UI if (!isHandled(bean)) continue; // Consume it and move on // Now we put the bean in the status queue and we // start the process RemoteSubmission factory = new RemoteSubmission(uri); factory.setLifeTime(t.getJMSExpiration()); factory.setPriority(t.getJMSPriority()); factory.setTimestamp(t.getJMSTimestamp()); factory.setQueueName(statusQName); // Move the message over to a status queue. factory.submit(bean, false); final ProgressableProcess process = createProcess(uri, statusTName, statusQName, bean); if (process != null) { if (process.isBlocking()) { System.out.println("About to run job " + bean.getName() + " messageid(" + t.getJMSMessageID() + ")"); } processCount++; process.start(); if (process.isBlocking()) { System.out.println( "Ran job " + bean.getName() + " messageid(" + t.getJMSMessageID() + ")"); } else { System.out.println("Started job " + bean.getName() + " messageid(" + t.getJMSMessageID() + ")"); } } } } } catch (Throwable ne) { // Really basic error reporting, they have to pipe to file. ne.printStackTrace(); setActive(false); } } }
From source file:fr.xebia.springframework.jms.ManagedCachingConnectionFactoryTest.java
@Test public void testMessageConsumer() throws Exception { ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory( "vm://localhost?broker.persistent=false&broker.useJmx=true"); ManagedConnectionFactory connectionFactory = new ManagedConnectionFactory(activeMQConnectionFactory); Connection connection = null; Session session = null; MessageConsumer consumer = null;//from ww w. j a v a 2 s . co m try { connection = connectionFactory.createConnection(); assertEquals(1, connectionFactory.getActiveConnectionCount()); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); assertEquals(1, connectionFactory.getActiveSessionCount()); Destination myQueue = session.createQueue("test-queue"); consumer = session.createConsumer(myQueue); assertEquals(1, connectionFactory.getActiveMessageConsumerCount()); consumer.receiveNoWait(); assertEquals(0, connectionFactory.getActiveMessageProducerCount()); } finally { JmsUtils.closeMessageConsumer(consumer); assertEquals(0, connectionFactory.getActiveMessageConsumerCount()); JmsUtils.closeSession(session); assertEquals(0, connectionFactory.getActiveSessionCount()); JmsUtils.closeConnection(connection); assertEquals(0, connectionFactory.getActiveConnectionCount()); } }
From source file:fr.xebia.springframework.jms.ManagedCachingConnectionFactoryTest.java
@Test public void testMessageProducer() throws Exception { ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory( "vm://localhost?broker.persistent=false&broker.useJmx=true"); ManagedConnectionFactory connectionFactory = new ManagedConnectionFactory(activeMQConnectionFactory); Connection connection = null; Session session = null; MessageProducer messageProducer = null; try {/*w w w .j a v a 2s .c o m*/ connection = connectionFactory.createConnection(); assertEquals(1, connectionFactory.getActiveConnectionCount()); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); assertEquals(1, connectionFactory.getActiveSessionCount()); Destination myQueue = session.createQueue("test-queue"); messageProducer = session.createProducer(myQueue); assertEquals(1, connectionFactory.getActiveMessageProducerCount()); messageProducer.send(myQueue, session.createTextMessage("test")); assertEquals(0, connectionFactory.getActiveMessageConsumerCount()); } finally { JmsUtils.closeMessageProducer(messageProducer); assertEquals(0, connectionFactory.getActiveMessageProducerCount()); JmsUtils.closeSession(session); assertEquals(0, connectionFactory.getActiveSessionCount()); JmsUtils.closeConnection(connection); assertEquals(0, connectionFactory.getActiveConnectionCount()); } }
From source file:org.dawnsci.commandserver.core.consumer.RemoteSubmission.java
/** * Submits the bean onto the server. From there events about this * bean are tacked by monitoring the status queue. * //from w w w . j a va 2 s. c o m * @param uri * @param bean */ public synchronized TextMessage submit(StatusBean bean, boolean prepareBean) throws Exception { if (getQueueName() == null || "".equals(getQueueName())) throw new Exception("Please specify a queue name!"); Connection send = null; Session session = null; MessageProducer producer = null; try { QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri); send = connectionFactory.createConnection(); session = send.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(queueName); producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.PERSISTENT); ObjectMapper mapper = new ObjectMapper(); if (getTimestamp() < 1) setTimestamp(System.currentTimeMillis()); if (getPriority() < 1) setPriority(1); if (getLifeTime() < 1) setLifeTime(7 * 24 * 60 * 60 * 1000); // 7 days in ms if (prepareBean) { if (bean.getUserName() == null) bean.setUserName(System.getProperty("user.name")); bean.setUniqueId(uniqueId); bean.setSubmissionTime(getTimestamp()); } String jsonString = mapper.writeValueAsString(bean); TextMessage message = session.createTextMessage(jsonString); message.setJMSMessageID(uniqueId); message.setJMSExpiration(getLifeTime()); message.setJMSTimestamp(getTimestamp()); message.setJMSPriority(getPriority()); producer.send(message); return message; } finally { if (send != null) send.close(); if (session != null) session.close(); if (producer != null) producer.close(); } }
From source file:me.norman.maurer.james.queue.HornetQMailQueue.java
@Override protected void produceMail(Session session, Map<String, Object> props, int msgPrio, Mail mail) throws JMSException, MessagingException, IOException { MessageProducer producer = null;/*from w w w . ja v a 2s . c o m*/ try { BytesMessage message = session.createBytesMessage(); Iterator<String> propIt = props.keySet().iterator(); while (propIt.hasNext()) { String key = propIt.next(); message.setObjectProperty(key, props.get(key)); } // set the stream to read frome message.setObjectProperty("JMS_HQ_InputStream", new BufferedInputStream(new MimeMessageInputStream(mail.getMessage()))); Queue q = session.createQueue(queuename); producer = session.createProducer(q); producer.send(message, Message.DEFAULT_DELIVERY_MODE, msgPrio, Message.DEFAULT_TIME_TO_LIVE); } finally { if (producer != null) { producer.close(); } } }
From source file:Vendor.java
public void run() { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url); Session session = null; Destination orderQueue;/*from w w w .j a v a 2s . co m*/ 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:com.aol.advertising.qiao.emitter.AMQEmitter.java
/** * Create JMS connectins, sessions, producers, destination objects. (one * producer per connection)/*from w w w . ja v a 2 s . c o m*/ * * @throws Exception */ protected void createJmsResources() throws Exception { Connection conn; Session session; MessageProducer producer; // create connections logger.info("creating producers..."); for (int i = 0; i < numProducer; i++) { conn = connectionFactory.createConnection(); connList.add(conn); // create sessions for a connection session = conn.createSession(transacted, ackMode); if (destination == null) { if (isQueue) { destination = session.createQueue(destinationName); } else { destination = session.createTopic(destinationName); } } producer = session.createProducer(destination); producer.setDeliveryMode(deliveryMode); Producer p = new Producer(session, producer); producersPool.add(p); producersStack.add(p); } logger.info("AMQ producer(s) created, count=" + producersStack.size()); }
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 . j a va2s .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:com.cws.esolutions.core.utils.MQUtils.java
/** * Gets an MQ message off a specified queue and returns it as an * <code>Object</code> to the requestor for further processing. * * @param connName - The connection name to utilize * @param authData - The authentication data to utilize, if required * @param responseQueue - The request queue name to put the message on * @param timeout - How long to wait for a connection or response * @param messageId - The JMS correlation ID of the message the response is associated with * @return <code>Object</code> - The serializable data returned by the MQ request * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing *//* www . j ava2 s . c o m*/ public static final synchronized Object getMqMessage(final String connName, final List<String> authData, final String responseQueue, final long timeout, final String messageId) throws UtilityException { final String methodName = MQUtils.CNAME + "getMqMessage(final String connName, final List<String> authData, final String responseQueue, final long timeout, final String messageId) throws UtilityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", connName); DEBUGGER.debug("Value: {}", responseQueue); DEBUGGER.debug("Value: {}", timeout); DEBUGGER.debug("Value: {}", messageId); } Connection conn = null; Session session = null; Object response = null; Context envContext = null; MessageConsumer consumer = null; ConnectionFactory connFactory = null; try { try { InitialContext 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); } if (envContext != null) { try { consumer = session.createConsumer((Destination) envContext.lookup(responseQueue), "JMSCorrelationID='" + messageId + "'"); } catch (NamingException nx) { throw new UtilityException(nx.getMessage(), nx); } } else { Destination destination = session.createQueue(responseQueue); if (DEBUG) { DEBUGGER.debug("Destination: {}", destination); } consumer = session.createConsumer(destination, "JMSCorrelationID='" + messageId + "'"); } if (DEBUG) { DEBUGGER.debug("MessageConsumer: {}", consumer); } ObjectMessage message = (ObjectMessage) consumer.receive(timeout); if (DEBUG) { DEBUGGER.debug("ObjectMessage: {}", message); } if (message == null) { throw new UtilityException("Failed to retrieve message within the timeout specified."); } response = message.getObject(); message.acknowledge(); if (DEBUG) { DEBUGGER.debug("Object: {}", response); } } 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 response; }
From source file:org.apache.james.queue.activemq.ActiveMQMailQueue.java
/** * Produce the mail to the JMS Queue// www . j ava 2 s . c o m */ protected void produceMail(Session session, Map<String, Object> props, int msgPrio, Mail mail) throws JMSException, MessagingException, IOException { MessageProducer producer = null; BlobMessage blobMessage = null; boolean reuse = false; try { // check if we should use a blob message here if (useBlob) { MimeMessage mm = mail.getMessage(); MimeMessage wrapper = mm; ActiveMQSession amqSession = getAMQSession(session); /* * Remove this optimization as it could lead to problems when the same blob content * is shared across different messages. * * I still think it would be a good idea to somehow do this but at the moment it's just * safer to disable it. * * TODO: Re-Enable it again once it works! * * See JAMES-1240 if (wrapper instanceof MimeMessageCopyOnWriteProxy) { wrapper = ((MimeMessageCopyOnWriteProxy) mm).getWrappedMessage(); } if (wrapper instanceof MimeMessageWrapper) { URL blobUrl = (URL) mail.getAttribute(JAMES_BLOB_URL); String fromQueue = (String) mail.getAttribute(JAMES_QUEUE_NAME); MimeMessageWrapper mwrapper = (MimeMessageWrapper) wrapper; if (blobUrl != null && fromQueue != null && mwrapper.isModified() == false) { // the message content was not changed so don't need to // upload it again and can just point to the url blobMessage = amqSession.createBlobMessage(blobUrl); reuse = true; } }*/ if (blobMessage == null) { // just use the MimeMessageInputStream which can read every // MimeMessage implementation blobMessage = amqSession.createBlobMessage(new MimeMessageInputStream(wrapper)); } // store the queue name in the props props.put(JAMES_QUEUE_NAME, queuename); Queue queue = session.createQueue(queuename); producer = session.createProducer(queue); for (Map.Entry<String, Object> entry : props.entrySet()) { blobMessage.setObjectProperty(entry.getKey(), entry.getValue()); } producer.send(blobMessage, Message.DEFAULT_DELIVERY_MODE, msgPrio, Message.DEFAULT_TIME_TO_LIVE); } else { super.produceMail(session, props, msgPrio, mail); } } catch (JMSException e) { if (!reuse && blobMessage != null && blobMessage instanceof ActiveMQBlobMessage) { ((ActiveMQBlobMessage) blobMessage).deleteFile(); } throw e; } finally { try { if (producer != null) producer.close(); } catch (JMSException e) { // ignore here } } }