List of usage examples for javax.jms MessageProducer send
void send(Message message) throws JMSException;
From source file:Vendor.java
public void run() { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url); Session session = null;/*from ww w . j a v a 2 s.c o m*/ Destination orderQueue; 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:org.wso2.carbon.event.output.adapter.jms.internal.util.JMSMessageSender.java
/** * Perform actual send of JMS message to the Destination selected */// w w w. j a v a 2 s .c o m public void send(Object message, JMSEventAdapter.PublisherDetails publisherDetails, String jmsHeaders) { Map<String, String> messageProperties = publisherDetails.getMessageConfig(); Boolean jtaCommit = getBooleanProperty(messageProperties, BaseConstants.JTA_COMMIT_AFTER_SEND); Boolean rollbackOnly = getBooleanProperty(messageProperties, BaseConstants.SET_ROLLBACK_ONLY); Boolean persistent = getBooleanProperty(messageProperties, JMSConstants.JMS_DELIVERY_MODE); Integer priority = getIntegerProperty(messageProperties, JMSConstants.JMS_PRIORITY); Integer timeToLive = getIntegerProperty(messageProperties, JMSConstants.JMS_TIME_TO_LIVE); MessageProducer producer = null; Destination destination = null; Session session = null; boolean sendingSuccessful = false; JMSConnectionFactory.JMSPooledConnectionHolder pooledConnection = null; try { pooledConnection = jmsConnectionFactory.getConnectionFromPool(); producer = pooledConnection.getProducer(); session = pooledConnection.getSession(); Message jmsMessage = convertToJMSMessage(message, publisherDetails.getMessageConfig(), session); setJMSTransportHeaders(jmsMessage, jmsHeaders); // Do not commit, if message is marked for rollback if (rollbackOnly != null && rollbackOnly) { jtaCommit = Boolean.FALSE; } if (persistent != null) { try { producer.setDeliveryMode(DeliveryMode.PERSISTENT); } catch (JMSException e) { handleConnectionException("Error setting JMS Producer for PERSISTENT delivery", e); } } if (priority != null) { try { producer.setPriority(priority); } catch (JMSException e) { handleConnectionException("Error setting JMS Producer priority to : " + priority, e); } } if (timeToLive != null) { try { producer.setTimeToLive(timeToLive); } catch (JMSException e) { handleConnectionException("Error setting JMS Producer TTL to : " + timeToLive, e); } } // perform actual message sending // try { if (jmsSpec11 || isQueue == null) { producer.send(jmsMessage); } else { if (isQueue) { ((QueueSender) producer).send(jmsMessage); } else { ((TopicPublisher) producer).publish(jmsMessage); } } sendingSuccessful = true; if (log.isDebugEnabled()) { // // set the actual MessageID to the message context for use by any others down the line String msgId = null; try { msgId = jmsMessage.getJMSMessageID(); } catch (JMSException jmse) { log.error(jmse.getMessage(), jmse); } log.debug(" with JMS Message ID : " + msgId + " to destination : " + producer.getDestination()); } } catch (JMSException e) { handleConnectionException("Error sending message to destination : " + destination, e); } catch (Exception e) { log.error(e.getMessage(), e); } finally { if (jtaCommit != null) { try { if (session.getTransacted()) { if (sendingSuccessful && (rollbackOnly == null || !rollbackOnly)) { session.commit(); } else { session.rollback(); } } if (log.isDebugEnabled()) { log.debug((sendingSuccessful ? "Committed" : "Rolled back") + " local (JMS Session) Transaction"); } } catch (Exception e) { handleConnectionException("Error committing/rolling back local (i.e. session) " + "transaction after sending of message "//with MessageContext ID : " + + " to destination : " + destination, e); } } if (pooledConnection != null) { jmsConnectionFactory.returnPooledConnection(pooledConnection); } } }
From source file:com.chinamobile.bcbsp.comm.ProducerTool.java
/** * Send message into messageQueue, update information with serialize method. * @param session//from w w w.j a v a2s .c o m * @param producer * @throws Exception * e */ private void sendLoopOptimistic(final Session session, final MessageProducer producer) throws Exception { try { BSPMessage msg; int count = 0; int packCounts = messageQueue.size() / this.packSize; // LOG.info("send packSize = "+ this.packSize); int packCount = 0; while (packCount < packCounts) { BytesMessage message = session.createBytesMessage(); long start = System.currentTimeMillis(); /* Clock */ message.writeInt(this.packSize); count = 0; while (count < this.packSize) { msg = (BSPMessage) messageQueue.poll(); // LOG.info(msg.intoString()); // message.setInt("dstPartition", msg.getDstPartition()); message.writeInt(msg.getDstPartition()); // message.writeUTF(msg.getSrcVertexID()); // message.setString("dstVertexID", msg.getDstVertexID()); message.writeUTF(msg.getDstVertexID()); // message.setBytes("tag", msg.getTag()); message.writeInt(msg.getTag().length); message.writeBytes(msg.getTag()); // message.setBytes("data", msg.getData()); message.writeInt(msg.getData().length); message.writeBytes(msg.getData()); count++; this.messageCount++; } this.serializeTime += (System.currentTimeMillis() - start); /* Clock */ start = System.currentTimeMillis(); /* Clock */ producer.send(message); this.sendTime += (System.currentTimeMillis() - start); /* Clock */ packCount++; // if (messageCount % 100000 == 0 ){ // LOG.info("send " + messageCount); // } } // send remaining messags int sendSize = messageQueue.size(); if (sendSize != 0) { BytesMessage message = session.createBytesMessage(); long start = System.currentTimeMillis(); /* Clock */ // message.setInt("packSize", sendSize); message.writeInt(sendSize); while ((msg = (BSPMessage) messageQueue.poll()) != null) { // message.setInt("dstPartition", msg.getDstPartition()); message.writeInt(msg.getDstPartition()); // message.setString("dstVertexID", msg.getDstVertexID()); message.writeUTF(msg.getDstVertexID()); // message.setBytes("tag", msg.getTag()); message.writeInt(msg.getTag().length); message.writeBytes(msg.getTag()); // message.setBytes("data", msg.getData()); message.writeInt(msg.getData().length); message.writeBytes(msg.getData()); this.messageCount++; } this.serializeTime += (System.currentTimeMillis() - start); /* Clock */ start = System.currentTimeMillis(); /* Clock */ producer.send(message); this.sendTime += (System.currentTimeMillis() - start); /* Clock */ } } catch (Exception e) { LOG.error("[ProducerTool] send loop ", e); } }
From source file:nl.nn.adapterframework.jms.JMSFacade.java
public String send(MessageProducer messageProducer, Message message, boolean ignoreInvalidDestinationException) throws NamingException, JMSException { if (log.isDebugEnabled()) { log.debug(getLogPrefix() + "sender on [" + getDestinationName() + "] will send message with JMSDeliveryMode=[" + message.getJMSDeliveryMode() + "] \n JMSMessageID=[" + message.getJMSMessageID() + "] \n JMSCorrelationID=[" + message.getJMSCorrelationID() + "] \n JMSTimestamp=[" + DateUtils.format(message.getJMSTimestamp()) + "] \n JMSExpiration=[" + message.getJMSExpiration() + "] \n JMSPriority=[" + message.getJMSPriority() + "] \n Message=[" + message.toString() + "]"); }/* w w w .j a va 2 s . c om*/ try { if (useJms102()) { if (messageProducer instanceof TopicPublisher) { ((TopicPublisher) messageProducer).publish(message); } else { ((QueueSender) messageProducer).send(message); } return message.getJMSMessageID(); } else { messageProducer.send(message); return message.getJMSMessageID(); } } catch (InvalidDestinationException e) { if (ignoreInvalidDestinationException) { log.warn("queue [" + messageProducer.getDestination() + "] doesn't exist"); return null; } else { throw e; } } }
From source file:com.cws.esolutions.core.utils.MQUtils.java
/** * Puts an MQ message on a specified queue and returns the associated * correlation ID for retrieval upon request. * * @param connName - The connection name to utilize * @param authData - The authentication data to utilize, if required * @param requestQueue - The request queue name to put the message on * @param targetHost - The target host for the message * @param value - The data to place on the request. MUST be <code>Serialiable</code> * @return <code>String</code> - the JMS correlation ID associated with the message * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing *//* www. j ava 2s . co m*/ public static final synchronized String sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException { final String methodName = MQUtils.CNAME + "sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", connName); DEBUGGER.debug("Value: {}", requestQueue); DEBUGGER.debug("Value: {}", targetHost); DEBUGGER.debug("Value: {}", value); } Connection conn = null; Session session = null; Context envContext = null; InitialContext initCtx = null; MessageProducer producer = null; ConnectionFactory connFactory = null; final String correlationId = RandomStringUtils.randomAlphanumeric(64); if (DEBUG) { DEBUGGER.debug("correlationId: {}", correlationId); } try { try { 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); } // Create a MessageProducer from the Session to the Topic or Queue if (envContext != null) { try { producer = session.createProducer((Destination) envContext.lookup(requestQueue)); } catch (NamingException nx) { throw new UtilityException(nx.getMessage(), nx); } } else { Destination destination = session.createTopic(requestQueue); if (DEBUG) { DEBUGGER.debug("Destination: {}", destination); } producer = session.createProducer(destination); } if (producer == null) { throw new JMSException("Failed to create a producer object"); } producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); if (DEBUG) { DEBUGGER.debug("MessageProducer: {}", producer); } ObjectMessage message = session.createObjectMessage(true); message.setJMSCorrelationID(correlationId); message.setStringProperty("targetHost", targetHost); if (DEBUG) { DEBUGGER.debug("correlationId: {}", correlationId); } message.setObject(value); if (DEBUG) { DEBUGGER.debug("ObjectMessage: {}", message); } producer.send(message); } 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 correlationId; }
From source file:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java
@Override public boolean sendMessage(Run<?, ?> build, TaskListener listener, MessageUtils.MESSAGE_TYPE type, String props, String content) {/* w w w . j av a2s .co m*/ Connection connection = null; Session session = null; MessageProducer publisher = null; try { String ltopic = getTopic(); if (provider.getAuthenticationMethod() != null && ltopic != null && provider.getBroker() != null) { ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory(); connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createTopic(ltopic); publisher = session.createProducer(destination); TextMessage message; message = session.createTextMessage(""); message.setJMSType(JSON_TYPE); message.setStringProperty("CI_NAME", build.getParent().getName()); message.setStringProperty("CI_TYPE", type.getMessage()); if (!build.isBuilding()) { message.setStringProperty("CI_STATUS", (build.getResult() == Result.SUCCESS ? "passed" : "failed")); } StrSubstitutor sub = new StrSubstitutor(build.getEnvironment(listener)); if (props != null && !props.trim().equals("")) { Properties p = new Properties(); p.load(new StringReader(props)); @SuppressWarnings("unchecked") Enumeration<String> e = (Enumeration<String>) p.propertyNames(); while (e.hasMoreElements()) { String key = e.nextElement(); message.setStringProperty(key, sub.replace(p.getProperty(key))); } } message.setText(sub.replace(content)); publisher.send(message); log.info("Sent " + type.toString() + " message for job '" + build.getParent().getName() + "' to topic '" + ltopic + "':\n" + formatMessage(message)); } else { log.severe("One or more of the following is invalid (null): user, password, topic, broker."); return false; } } catch (Exception e) { log.log(Level.SEVERE, "Unhandled exception in perform.", e); } finally { if (publisher != null) { try { publisher.close(); } catch (JMSException e) { } } if (session != null) { try { session.close(); } catch (JMSException e) { } } if (connection != null) { try { connection.close(); } catch (JMSException e) { } } } return true; }
From source file:gov.medicaid.services.impl.ProviderEnrollmentServiceBean.java
/** * Sends the given provider for export to the message queue. * @param ticketId the ticket id//w w w. j av a2 s . co m */ @Override public void sendSyncronizationRequest(long ticketId) { Session session = null; Connection connection = null; try { connection = mqConnectionFactory.createConnection(); session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); MessageProducer sender = session.createProducer(dataSyncQueue); BytesMessage message = session.createBytesMessage(); byte[] content = exportAsFlatFile(ticketId); getLog().log(Level.INFO, "Sending data sync request:" + new String(content)); message.writeBytes(content); sender.send(message); } catch (PortalServiceException e) { getLog().log(Level.ERROR, e); throw new PortalServiceRuntimeException("While attempting to synchronize data", e); } catch (JMSException e) { getLog().log(Level.ERROR, e); throw new PortalServiceRuntimeException("While attempting to synchronize data", e); } }
From source file:com.tremolosecurity.provisioning.core.ProvisioningEngineImpl.java
public void enqueue(WorkflowHolder wfHolder) throws ProvisioningException { TextMessage bm;/*from www . j av a2 s . c o m*/ try { MessageProducer mp; MessageProducerHolder mph = null; if (this.isInternalQueue()) { mp = this.taskMP; bm = taskSession.createTextMessage(); bm.setStringProperty("OriginalQueue", this.taskQueue.getQueueName()); } else { mph = this.getTaskMessageProducer(); mp = mph.getProducer(); bm = mph.getSession().createTextMessage(); bm.setStringProperty("OriginalQueue", ((javax.jms.Queue) mph.getProducer().getDestination()).getQueueName()); } bm.setStringProperty("WorkflowName", wfHolder.getWorkflow().getName()); bm.setStringProperty("WorkflowSubject", wfHolder.getUser().getUserID()); bm.setStringProperty("JMSXGroupID", "unison"); bm.setStringProperty("nonce", UUID.randomUUID().toString()); TaskHolder holder = wfHolder.getWfStack().peek(); WorkflowTask task = holder.getParent().get(holder.getPosition()); bm.setStringProperty("WorkflowCurrentTask", task.getLabel()); EncryptedMessage encMsg = this.encryptObject(wfHolder); String json = JsonWriter.objectToJson(encMsg); bm.setText(json); try { mp.send(bm); } finally { if (!this.isInternalQueue()) { this.returnMessageProducer(mph); } } } catch (Exception e) { throw new ProvisioningException("Could not enqueue message", e); } }
From source file:org.gss_project.gss.server.ejb.ExternalAPIBean.java
private void indexFile(Long fileId, boolean delete) { Connection qConn = null;/* w ww .j a v a 2 s . c o m*/ Session session = null; MessageProducer sender = null; try { Context jndiCtx = new InitialContext(); ConnectionFactory factory = (QueueConnectionFactory) jndiCtx.lookup("java:/JmsXA"); Queue queue = (Queue) jndiCtx.lookup("queue/gss-indexingQueue"); qConn = factory.createConnection(); session = qConn.createSession(false, Session.AUTO_ACKNOWLEDGE); sender = session.createProducer(queue); MapMessage map = session.createMapMessage(); map.setObject("id", fileId); map.setBoolean("delete", delete); sender.send(map); } catch (NamingException e) { logger.error("Index was not updated: ", e); } catch (JMSException e) { logger.error("Index was not updated: ", e); } finally { try { if (sender != null) sender.close(); if (session != null) session.close(); if (qConn != null) qConn.close(); } catch (JMSException e) { logger.warn(e); } } }
From source file:org.sakaiproject.kernel.messaging.activemq.ActiveMQEmailDeliveryT.java
public void testCommonsEmailOneWaySeparateSessions() { Queue emailQueue = null;//from w w w . j a v a2s . c om MessageConsumer consumer = null; MessageProducer producer = null; Session clientSession = null; Session listenerSession = null; // it is not necessary to use the Email interface here // Email is used here just to allow for multiple types of emails to // occupy // the same varaible. SimpleEmail etc can each be used directly. List<Email> emails = new ArrayList<Email>(); EmailMessagingService messagingService = new EmailMessagingService(vmURL, emailQueueName, emailType, null, null, null, null); emails.add(new SimpleEmail(messagingService)); emails.add(new MultiPartEmail(messagingService)); emails.add(new HtmlEmail(messagingService)); try { listenerSession = listenerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); emailQueue = listenerSession.createQueue(emailQueueName); consumer = listenerSession.createConsumer(emailQueue); consumer.setMessageListener(new EmailListener()); listenerConn.start(); listenerSession.run(); } catch (JMSException e2) { e2.printStackTrace(); Assert.assertTrue(false); } Wiser smtpServer = new Wiser(); smtpServer.setPort(smtpTestPort); smtpServer.start(); try { clientSession = clientConn.createSession(false, Session.AUTO_ACKNOWLEDGE); emailQueue = clientSession.createQueue(emailQueueName); producer = clientSession.createProducer(emailQueue); clientConn.start(); clientSession.run(); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } for (Email em : emails) { try { em.addTo(TEST_EMAIL_TO); em.setFrom(TEST_EMAIL_FROM_ADDRESS, TEST_EMAIL_FROM_LABEL); // host and port will be ignored since the email session is // established // by // the listener em.setHostName("localhost"); em.setSmtpPort(smtpTestPort); em.setSubject(TEST_EMAIL_SUBJECT); if (em instanceof HtmlEmail) { em.setMsg(TEST_EMAIL_BODY_HTMLEMAIL); } else if (em instanceof MultiPartEmail) { em.setMsg(TEST_EMAIL_BODY_MULTIPARTEMAIL); } else if (em instanceof SimpleEmail) { em.setMsg(TEST_EMAIL_BODY_SIMPLEEMAIL); } } catch (EmailException e1) { Assert.assertTrue(false); e1.printStackTrace(); } try { em.buildMimeMessage(); } catch (EmailException e1) { e1.printStackTrace(); Assert.assertTrue(false); } ByteArrayOutputStream os = new ByteArrayOutputStream(); try { em.getMimeMessage().writeTo(os); } catch (javax.mail.MessagingException e) { e.printStackTrace(); Assert.assertTrue(false); } catch (IOException e) { e.printStackTrace(); Assert.assertTrue(false); } String content = os.toString(); ObjectMessage om; try { om = clientSession.createObjectMessage(content); om.setJMSType(emailType); LOG.info("Client: Sending test message...."); producer.send(om); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } } long start = System.currentTimeMillis(); while (listenerMessagesProcessed < 3 && System.currentTimeMillis() - start < 10000L) { // wait for transport } Assert.assertTrue(listenerMessagesProcessed == 3); List<WiserMessage> messages = smtpServer.getMessages(); Assert.assertTrue(messages.size() + " != expected value of 3", messages.size() == 3); for (WiserMessage wisermsg : messages) { String body = null; String subject = null; MimeMessage testmail = null; try { testmail = wisermsg.getMimeMessage(); } catch (MessagingException e) { Assert.assertTrue(false); e.printStackTrace(); } if (testmail != null) { LOG.info("SMTP server: test email received: "); try { LOG.info("To: " + testmail.getHeader("To", ",")); LOG.info("Subject: " + testmail.getHeader("Subject", ",")); body = getBodyAsString(testmail.getContent()); subject = testmail.getHeader("Subject", ","); } catch (MessagingException e) { Assert.assertTrue(false); e.printStackTrace(); } catch (IOException e) { Assert.assertTrue(false); e.printStackTrace(); } LOG.info("Body: " + body); Assert.assertTrue(subject.contains(TEST_EMAIL_SUBJECT)); Assert.assertTrue(body.contains("This is a Commons")); } else { Assert.assertTrue(false); } } if (clientSession != null) { try { clientSession.close(); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } clientSession = null; } if (listenerSession != null) { try { listenerSession.close(); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } listenerSession = null; } smtpServer.stop(); }