List of usage examples for javax.jms Message acknowledge
void acknowledge() throws JMSException;
From source file:org.wso2.mb.integration.common.clients.operations.queue.QueueMessageListener.java
public void onMessage(Message message) { messageCount.incrementAndGet();/*from w ww.j av a 2s .co m*/ localMessageCount++; Message receivedMessage = message; try { String redelivery = ""; if (message.getJMSRedelivered()) { redelivery = "REDELIVERED"; } else { redelivery = "ORIGINAL"; } if (messageCount.get() % printNumberOfMessagesPer == 0) { log.info("[QUEUE RECEIVE] ThreadID:" + Thread.currentThread().getId() + " queue:" + queueName + " " + "localMessageCount:" + localMessageCount + " totalMessageCount:" + messageCount.get() + " max" + " count:" + stopMessageCount); } if (receivedMessage instanceof TextMessage) { TextMessage textMessage = (TextMessage) receivedMessage; if (isToPrintEachMessage) { log.info("(count:" + messageCount.get() + "/threadID:" + Thread.currentThread().getId() + "/queue:" + queueName + ") " + redelivery + " >> " + textMessage.getText()); AndesClientUtils.writeToFile(textMessage.getText(), fileToWriteReceivedMessages); } } if (messageCount.get() % ackAfterEach == 0) { if (queueSession.getAcknowledgeMode() == QueueSession.CLIENT_ACKNOWLEDGE) { receivedMessage.acknowledge(); log.info("Acked message : " + receivedMessage.getJMSMessageID()); } } //commit get priority if (messageCount.get() % commitPerMessageCount == 0) { queueSession.commit(); log.info("Committed Queue Session"); } else if (messageCount.get() % rollbackPerMessagecount == 0) { queueSession.rollback(); log.info("Rollbacked Queue Session"); } if (messageCount.get() >= stopMessageCount) { stopMessageListener(); AndesClientUtils.sleepForInterval(200); } if (delayBetweenMessages != 0) { try { Thread.sleep(delayBetweenMessages); } catch (InterruptedException e) { //silently ignore } } } catch (NumberFormatException e) { log.error("Wrong inputs.", e); } catch (JMSException e) { log.error("JMS Exception", e); } }
From source file:com.ccc.ccm.client.JMSTemplateAutowired.java
/** * Actually receive a JMS message./*from www. j a v a2 s. co m*/ * @param session the JMS Session to operate on * @param consumer the JMS MessageConsumer to receive with * @return the JMS Message received, or <code>null</code> if none * @throws JMSException if thrown by JMS API methods */ protected Message doReceive(Session session, MessageConsumer consumer) throws JMSException { try { // Use transaction timeout (if available). long timeout = getReceiveTimeout(); JmsResourceHolder resourceHolder = (JmsResourceHolder) TransactionSynchronizationManager .getResource(getConnectionFactory()); if (resourceHolder != null && resourceHolder.hasTimeout()) { timeout = resourceHolder.getTimeToLiveInMillis(); } Message message = doReceive(consumer, timeout); if (session.getTransacted()) { // Commit necessary - but avoid commit call within a JTA transaction. if (isSessionLocallyTransacted(session)) { // Transacted session created by this template -> commit. JmsUtils.commitIfNecessary(session); } } else if (isClientAcknowledge(session)) { // Manually acknowledge message, if any. if (message != null) { message.acknowledge(); } } return message; } finally { JmsUtils.closeMessageConsumer(consumer); } }
From source file:org.wso2.carbon.inbound.endpoint.protocol.jms.JMSPollingConsumer.java
/** * Create connection with broker and retrieve the messages. Then inject * according to the registered handler// ww w. j a v a 2s .c om */ public Message poll() { logger.debug("Polling JMS messages."); try { connection = jmsConnectionFactory.getConnection(strUserName, strPassword); if (connection == null) { logger.warn("Inbound JMS endpoint unable to get a connection."); isConnected = false; return null; } if (retryIteration != 0) { logger.info("Reconnection attempt: " + retryIteration + " for the JMS Inbound: " + name + " was successful!"); this.retryIteration = 0; this.retryDuration = 1; } isConnected = true; session = jmsConnectionFactory.getSession(connection); //Fixing ESBJAVA-4446 //Closing the connection if we cannot get a session. //Then in the next poll iteration it will create a new connection //instead of using cached connection if (session == null) { logger.warn("Inbound JMS endpoint unable to get a session."); jmsConnectionFactory.closeConnection(); return null; } destination = jmsConnectionFactory.getDestination(session); if (replyDestinationName != null && !replyDestinationName.trim().equals("")) { if (logger.isDebugEnabled()) { logger.debug( "Using the reply destination as " + replyDestinationName + " in inbound endpoint."); } replyDestination = jmsConnectionFactory.createDestination(session, replyDestinationName); } messageConsumer = jmsConnectionFactory.getMessageConsumer(session, destination); Message msg = receiveMessage(messageConsumer); if (msg == null) { logger.debug("Inbound JMS Endpoint. No JMS message received."); return null; } while (msg != null) { if (!JMSUtils.inferJMSMessageType(msg).equals(TextMessage.class.getName())) { logger.error("JMS " + "Inbound transport support JMS TextMessage type only. Found message type " + JMSUtils.inferJMSMessageType(msg)); return null; } if (injectHandler != null) { boolean commitOrAck = true; // Set the reply destination and connection if (replyDestination != null) { injectHandler.setReplyDestination(replyDestination); } injectHandler.setConnection(connection); commitOrAck = injectHandler.invoke(msg, name); // if client acknowledgement is selected, and processing // requested ACK if (jmsConnectionFactory.getSessionAckMode() == Session.CLIENT_ACKNOWLEDGE) { if (commitOrAck) { try { msg.acknowledge(); if (logger.isDebugEnabled()) { logger.debug("Message : " + msg.getJMSMessageID() + " acknowledged"); } } catch (JMSException e) { logger.error("Error acknowledging message : " + msg.getJMSMessageID(), e); } } else { // Need to create a new consumer and session since // we need to rollback the message if (messageConsumer != null) { jmsConnectionFactory.closeConsumer(messageConsumer); } if (session != null) { jmsConnectionFactory.closeSession(session); } session = jmsConnectionFactory.getSession(connection); messageConsumer = jmsConnectionFactory.getMessageConsumer(session, destination); } } // if session was transacted, commit it or rollback if (jmsConnectionFactory.isTransactedSession()) { try { if (session.getTransacted()) { if (commitOrAck) { session.commit(); if (logger.isDebugEnabled()) { logger.debug( "Session for message : " + msg.getJMSMessageID() + " committed"); } } else { session.rollback(); if (logger.isDebugEnabled()) { logger.debug( "Session for message : " + msg.getJMSMessageID() + " rolled back"); } } } } catch (JMSException e) { logger.error("Error " + (commitOrAck ? "committing" : "rolling back") + " local session txn for message : " + msg.getJMSMessageID(), e); } } } else { return msg; } msg = receiveMessage(messageConsumer); } } catch (JMSException e) { logger.error("Error while receiving JMS message. " + e.getMessage(), e); } catch (Exception e) { logger.error("Error while receiving JMS message. " + e.getMessage(), e); } finally { if (!isConnected) { if (reconnectDuration != null) { retryDuration = reconnectDuration; logger.error("Reconnection attempt : " + (retryIteration++) + " for JMS Inbound : " + name + " failed. Next retry in " + (retryDuration / 1000) + " seconds. (Fixed Interval)"); } else { retryDuration = (long) (retryDuration * reconnectionProgressionFactor); if (retryDuration > maxReconnectDuration) { retryDuration = maxReconnectDuration; logger.info("InitialReconnectDuration reached to MaxReconnectDuration."); } logger.error("Reconnection attempt : " + (retryIteration++) + " for JMS Inbound : " + name + " failed. Next retry in " + (retryDuration / 1000) + " seconds"); } try { Thread.sleep(retryDuration); } catch (InterruptedException ignore) { } } if (messageConsumer != null) { jmsConnectionFactory.closeConsumer(messageConsumer); } if (session != null) { jmsConnectionFactory.closeSession(session); } if (connection != null) { jmsConnectionFactory.closeConnection(connection); } } return null; }
From source file:com.oneops.inductor.Listener.java
/** * MessageListener mapped in application-context.xml - will deserialize to a * WorkOrder (iaas/swdist) or ActionOrder (procedure) * * @param msg Message//from w ww . j a va2s .co m * @see javax.jms.MessageListener#onMessage(javax.jms.Message) */ public void onMessage(Message msg) { try { checkFreeSpace(); activeThreads.getAndIncrement(); if (msg instanceof TextMessage) { String msgText = ((TextMessage) msg).getText(); final String correlationID = msg.getJMSCorrelationID(); Map<String, String> responseMsgMap; String type = msg.getStringProperty("type"); CmsWorkOrderSimpleBase wo; // WorkOrder if (type.equals(WORK_ORDER_TYPE)) { long t = System.currentTimeMillis(); wo = getWorkOrderOf(msgText, CmsWorkOrderSimple.class); wo.putSearchTag("iWoCrtTime", Long.toString(System.currentTimeMillis() - t)); preProcess(wo); wo.putSearchTag("rfcAction", wo.getAction()); responseMsgMap = workOrderExecutor.process(wo, correlationID); // ActionOrder } else if (type.equals(ACTION_ORDER_TYPE)) { long t = System.currentTimeMillis(); wo = getWorkOrderOf(msgText, CmsActionOrderSimple.class); wo.putSearchTag("iAoCrtTime", Long.toString(System.currentTimeMillis() - t)); preProcess(wo); responseMsgMap = actionOrderExecutor.process(wo, correlationID); } else { logger.error(new IllegalArgumentException("Unknown msg type - " + type)); msg.acknowledge(); return; } // Controller will process this message responseMsgMap.put("correlationID", correlationID); responseMsgMap.put("type", type); long startTime = System.currentTimeMillis(); if (!correlationID.equals("test")) messagePublisher.publishMessage(responseMsgMap); long endTime = System.currentTimeMillis(); long duration = endTime - startTime; // ack message logger.debug("send message took:" + duration + "ms"); msg.acknowledge(); } } catch (JMSException | SecurityException | IOException | IllegalArgumentException e) { logger.error("Error occurred in processing message", e); } finally { /* * Decrement the total number of active threads consumed by 1 */ activeThreads.getAndDecrement(); clearStateFile(); } }
From source file:ConsumerTool.java
public void onMessage(Message message) { messagesReceived++;//from w ww . j ava 2s . c o m try { if (message instanceof TextMessage) { TextMessage txtMsg = (TextMessage) message; if (verbose) { String msg = txtMsg.getText(); int length = msg.length(); if (length > 50) { msg = msg.substring(0, 50) + "..."; } System.out.println("[" + this.getName() + "] Received: '" + msg + "' (length " + length + ")"); } } else { if (verbose) { System.out.println("[" + this.getName() + "] Received: '" + message + "'"); } } if (message.getJMSReplyTo() != null) { replyProducer.send(message.getJMSReplyTo(), session.createTextMessage("Reply: " + message.getJMSMessageID())); } if (transacted) { if ((messagesReceived % batch) == 0) { System.out.println("Commiting transaction for last " + batch + " messages; messages so far = " + messagesReceived); session.commit(); } } else if (ackMode == Session.CLIENT_ACKNOWLEDGE) { if ((messagesReceived % batch) == 0) { System.out.println( "Acknowledging last " + batch + " messages; messages so far = " + messagesReceived); message.acknowledge(); } } } catch (JMSException e) { System.out.println("[" + this.getName() + "] Caught: " + e); e.printStackTrace(); } finally { if (sleepTime > 0) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { } } } }
From source file:org.wso2.mb.integration.common.clients.operations.queue.QueueMessageReceiver.java
public void run() { try {// w w w.java2 s . co m if (useMessageListener) { QueueMessageListener messageListener = new QueueMessageListener(queueConnection, queueSession, queueReceiver, queueName, messageCounter, delayBetweenMessages, printNumberOfMessagesPer, isToPrintEachMessage, fileToWriteReceivedMessages, stopAfter, ackAfterEach, commitAfterEach, rollbackAfterEach); queueReceiver.setMessageListener(messageListener); } else { int localMessageCount = 0; while (true) { Message message = queueReceiver.receive(); if (message != null && message instanceof TextMessage) { messageCounter.incrementAndGet(); localMessageCount++; String redelivery; TextMessage textMessage = (TextMessage) message; if (message.getJMSRedelivered()) { redelivery = "REDELIVERED"; } else { redelivery = "ORIGINAL"; } if (messageCounter.get() % printNumberOfMessagesPer == 0) { log.info("[QUEUE RECEIVE] ThreadID:" + Thread.currentThread().getId() + " queue:" + queueName + " localMessageCount:" + localMessageCount + " totalMessageCount:" + messageCounter.get() + " max count:" + stopAfter); } if (isToPrintEachMessage) { log.info("(count:" + messageCounter.get() + "/threadID:" + Thread.currentThread().getId() + "/queue:" + queueName + ") " + redelivery + " >> " + textMessage.getText()); AndesClientUtils.writeToFile(textMessage.getText(), fileToWriteReceivedMessages); } } if (messageCounter.get() % ackAfterEach == 0) { if (queueSession.getAcknowledgeMode() == QueueSession.CLIENT_ACKNOWLEDGE) { if (message != null) { message.acknowledge(); } } } //commit get priority if (messageCounter.get() % commitAfterEach == 0) { queueSession.commit(); log.info("Committed Queue Session"); } else if (messageCounter.get() % rollbackAfterEach == 0) { queueSession.rollback(); log.info("Rollbacked Queue Session"); } if (messageCounter.get() == stopAfter) { stopListening(); break; } if (delayBetweenMessages != 0) { try { Thread.sleep(delayBetweenMessages); } catch (InterruptedException e) { //silently ignore } } } } } catch (JMSException e) { log.error("Error while listening for messages", e); } }
From source file:org.wso2.mb.integration.common.clients.operations.topic.TopicMessageReceiver.java
public void run() { try {//from www . j a v a 2 s . co m if (useMessageListener) { TopicMessageListener messageListener = new TopicMessageListener(topicConnection, topicSession, topicSubscriber, topicName, subscriptionId, messageCounter, delayBetweenMessages, printNumberOfMessagesPer, isToPrintEachMessage, fileToWriteReceivedMessages, stopAfter, unSubscribeAfter, ackAfterEach, rollbackAfterEach, commitAfterEach); topicSubscriber.setMessageListener(messageListener); } else { int localMessageCount = 0; while (true) { Message message = topicSubscriber.receive(); if (message != null && message instanceof TextMessage) { messageCounter.incrementAndGet(); localMessageCount++; String redelivery; TextMessage textMessage = (TextMessage) message; if (message.getJMSRedelivered()) { redelivery = "REDELIVERED"; } else { redelivery = "ORIGINAL"; } if (messageCounter.get() % printNumberOfMessagesPer == 0) { log.info("[TOPIC RECEIVE] ThreadID:" + Thread.currentThread().getId() + " topic:" + topicName + " localMessageCount:" + localMessageCount + " totalMessageCount:" + messageCounter.get() + " max count:" + stopAfter); } if (isToPrintEachMessage) { log.info("(count:" + messageCounter.get() + "/threadID:" + Thread.currentThread().getId() + "/topic:" + topicName + ") " + redelivery + " >> " + textMessage.getText()); AndesClientUtils.writeToFile(textMessage.getText(), fileToWriteReceivedMessages); } } if (messageCounter.get() % ackAfterEach == 0) { if (topicSession.getAcknowledgeMode() == QueueSession.CLIENT_ACKNOWLEDGE) { if (message != null) { message.acknowledge(); } } } //commit get priority if (messageCounter.get() % commitAfterEach == 0) { topicSession.commit(); log.info("Committed session"); } else if (messageCounter.get() % rollbackAfterEach == 0) { topicSession.rollback(); log.info("Rollbacked session"); } if (messageCounter.get() >= unSubscribeAfter) { unsubscribe(); break; } else if (messageCounter.get() >= stopAfter) { stopListening(); break; } if (delayBetweenMessages != 0) { try { Thread.sleep(delayBetweenMessages); } catch (InterruptedException e) { //silently ignore } } } } } catch (JMSException e) { log.error("Error while listening for messages", e); } }
From source file:com.chinamobile.bcbsp.comm.ConsumerTool.java
/** * Put message into messageQueue and update information. *//*from w w w.j av a 2 s . c o m*/ public void onMessage(Message message) { messagesReceived++; try { if (message instanceof ObjectMessage) { ObjectMessage objMsg = (ObjectMessage) message; BSPMessagesPack msgPack = (BSPMessagesPack) objMsg.getObject(); IMessage bspMsg; Iterator<IMessage> iter = msgPack.getPack().iterator(); while (iter.hasNext()) { bspMsg = iter.next(); String vertexID = bspMsg.getDstVertexID(); this.messageQueues.incomeAMessage(vertexID, bspMsg); this.messageCount++; this.messageBytesCount += bspMsg.size(); } } else { // Message received is not ObjectMessage. LOG.error("[ConsumerTool] Message received is not ObjectMessage!"); } if (message.getJMSReplyTo() != null) { replyProducer.send(message.getJMSReplyTo(), session.createTextMessage("Reply: " + message.getJMSMessageID())); } if (transacted) { if ((messagesReceived % batch) == 0) { LOG.info("Commiting transaction for last " + batch + " messages; messages so far = " + messagesReceived); session.commit(); } } else if (ackMode == Session.CLIENT_ACKNOWLEDGE) { if ((messagesReceived % batch) == 0) { LOG.info("Acknowledging last " + batch + " messages; messages so far = " + messagesReceived); message.acknowledge(); } } } catch (JMSException e) { throw new RuntimeException("[ConsumerTool] caught: ", e); } finally { if (sleepTime > 0) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { LOG.error("[ConsumerTool] Message received not ObjectMessage!", e); throw new RuntimeException("[ConsumerTool] Message received not ObjectMessage! s", e); } } } }
From source file:org.mot.core.simulation.listener.SimulationMessageListener.java
@SuppressWarnings("unchecked") @Override//from w w w . j a va2 s.co m public void onMessage(Message msg) { // TODO Auto-generated method stub BytesMessage message = (BytesMessage) msg; // Read in properties from file Configuration simulationProperties; byte[] bytes; try { PropertiesFactory pf = PropertiesFactory.getInstance(); simulationProperties = new PropertiesConfiguration(pf.getConfigDir() + "/simulation.properties"); final Double minProfit = simulationProperties.getDouble("simulation.default.db.requireMinProfit", 2.0); final Double txnpct = simulationProperties.getDouble("simulation.order.txncost.pct", 0.0024); bytes = new byte[(int) message.getBodyLength()]; message.readBytes(bytes); SimulationRequest sr = SimulationRequest.deserialize(bytes); sr.setMinProfit(minProfit); sr.setTxnPct(txnpct); String className = sr.getClassName(); Class<?> c; try { c = Class.forName(className); Object inst = c.newInstance(); // Make sure the startup method is called for initialization... //Method m1= c.getDeclaredMethod("startup", String.class, String.class, LoadValue[].class, Boolean.class, Integer.class ); //m1.invoke(inst, sr.getClassName(), sr.getSymbol(), lvc.convertStringToValues(sr.getLoadValues()), true, sr.getQuantity()); // Call the backtest Processing class... Method m = c.getDeclaredMethod("processSimulationRequests", SimulationRequest.class); Object ret = m.invoke(inst, sr); ArrayList<SimulationResponse> simulationResponses = (ArrayList<SimulationResponse>) ret; // Iterate over the expressions Iterator<SimulationResponse> it = simulationResponses.iterator(); while (it.hasNext()) { SimulationResponse u = it.next(); this.writeToDB(u); } } catch (Exception e) { e.printStackTrace(); } msg.acknowledge(); } catch (JMSException | ClassNotFoundException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { } }
From source file:com.amalto.core.server.routing.DefaultRoutingEngine.java
@Override public void consume(final Message message) { try {//from w ww .j a v a 2s .c o m @SuppressWarnings("unchecked") String[] rules = getRulesList(message); final String pk = message.getStringProperty(JMS_PK_PROPERTY); final String type = message.getStringProperty(JMS_TYPE_PROPERTY); final String container = message.getStringProperty(JMS_CONTAINER_PROPERTY); final long timeScheduled = message.getLongProperty(JMS_SCHEDULED); final String routingOrderId = message.getJMSMessageID(); for (int ruleIndex = 0; ruleIndex < rules.length; ruleIndex++) { String rule = rules[ruleIndex]; final RoutingRulePOJO routingRule = routingRules.getRoutingRule(new RoutingRulePOJOPK(rule)); // Apparently rule is not (yet) deployed onto this system's DB instance, but... that 's // rather unexpected since all nodes in cluster are supposed to share same system DB. if (routingRule == null) { throw new RuntimeException( "Cannot execute rule(s) " + rules + ": routing rule '" + rule + "' can not be found."); } SecurityConfig.invokeSynchronousPrivateInternal(new Runnable() { @Override public void run() { // execute all rules synchronously final ItemPOJOPK itemPOJOPK = new ItemPOJOPK(new DataClusterPOJOPK(container), type, pk.split("\\.")); applyRule(itemPOJOPK, routingRule, routingOrderId, timeScheduled); } }); } // acknowledge message once all rules are executed message.acknowledge(); } catch (Exception e) { throw new RuntimeException("Unable to process message.", e); } }