List of usage examples for javax.jms Message toString
public String toString()
From source file:nl.nn.adapterframework.extensions.esb.EsbUtils.java
public static String receiveMessageAndMoveToErrorStorage(EsbJmsListener esbJmsListener, JdbcTransactionalStorage errorStorage) { String result = null;//from w w w . j a v a 2 s.com PoolingConnectionFactory jmsConnectionFactory = null; PoolingDataSource jdbcDataSource = null; BitronixTransactionManager btm = null; javax.jms.Connection jmsConnection = null; try { jmsConnectionFactory = getPoolingConnectionFactory(esbJmsListener); if (jmsConnectionFactory != null) { jdbcDataSource = getPoolingDataSource(errorStorage); if (jdbcDataSource != null) { String instanceNameLc = AppConstants.getInstance().getString("instance.name.lc", null); String logDir = AppConstants.getInstance().getString("log.dir", null); TransactionManagerServices.getConfiguration().setServerId(instanceNameLc + ".tm"); TransactionManagerServices.getConfiguration() .setLogPart1Filename(logDir + File.separator + instanceNameLc + "-btm1.tlog"); TransactionManagerServices.getConfiguration() .setLogPart2Filename(logDir + File.separator + instanceNameLc + "-btm2.tlog"); btm = TransactionManagerServices.getTransactionManager(); jmsConnection = jmsConnectionFactory.createConnection(); Session jmsSession = null; MessageConsumer jmsConsumer = null; java.sql.Connection jdbcConnection = null; btm.begin(); log.debug("started transaction [" + btm.getCurrentTransaction().getGtrid() + "]"); try { jmsSession = jmsConnection.createSession(true, Session.AUTO_ACKNOWLEDGE); String queueName = esbJmsListener.getPhysicalDestinationShortName(); Queue queue = jmsSession.createQueue(queueName); jmsConsumer = jmsSession.createConsumer(queue); jmsConnection.start(); long timeout = 30000; log.debug("looking for message on queue [" + queueName + "] with timeout of [" + timeout + "] msec"); Message rawMessage = jmsConsumer.receive(timeout); if (rawMessage == null) { log.debug("no message found on queue [" + queueName + "]"); } else { String id = rawMessage.getJMSMessageID(); log.debug("found message on queue [" + queueName + "] with messageID [" + id + "]"); Serializable sobj = null; if (rawMessage != null) { if (rawMessage instanceof Serializable) { sobj = (Serializable) rawMessage; } else { try { sobj = new MessageWrapper(rawMessage, esbJmsListener); } catch (ListenerException e) { log.error("could not wrap non serializable message for messageId [" + id + "]", e); if (rawMessage instanceof TextMessage) { TextMessage textMessage = (TextMessage) rawMessage; sobj = textMessage.getText(); } else { sobj = rawMessage.toString(); } } } } jdbcConnection = jdbcDataSource.getConnection(); result = errorStorage.storeMessage(jdbcConnection, id, id, new Date(System.currentTimeMillis()), "moved message", null, sobj); } log.debug("committing transaction [" + btm.getCurrentTransaction().getGtrid() + "]"); btm.commit(); } catch (Exception e) { if (btm.getCurrentTransaction() != null) { log.debug("rolling back transaction [" + btm.getCurrentTransaction().getGtrid() + "]"); btm.rollback(); } log.error("exception on receiving message and moving to errorStorage", e); } finally { if (jdbcConnection != null) { jdbcConnection.close(); } if (jmsConnection != null) { jmsConnection.stop(); } if (jmsConsumer != null) { jmsConsumer.close(); } if (jmsSession != null) { jmsSession.close(); } } } } } catch (Exception e) { log.error("exception on receiving message and moving to errorStorage", e); } finally { if (jmsConnection != null) { try { jmsConnection.close(); } catch (JMSException e) { log.warn("exception on closing connection", e); } } if (jmsConnectionFactory != null) { jmsConnectionFactory.close(); } if (jdbcDataSource != null) { jdbcDataSource.close(); } if (btm != null) { btm.shutdown(); } } return result; }
From source file:nl.nn.adapterframework.extensions.ifsa.jms.IfsaRequesterSender.java
/** * Execute a request to the IFSA service. * @return in Request/Reply, the retrieved message or TIMEOUT, otherwise null *//*from w ww . j a v a2 s . c o m*/ public String sendMessage(String dummyCorrelationId, String message, Map params, String bifName, byte btcData[]) throws SenderException, TimeOutException { String result = null; QueueSession session = null; QueueSender sender = null; Map udzMap = null; try { log.debug(getLogPrefix() + "creating session and sender"); session = createSession(); IFSAQueue queue; if (params != null && params.size() > 0) { // Use first param as serviceId String serviceId = (String) params.get("serviceId"); if (serviceId == null) { serviceId = getServiceId(); } String occurrence = (String) params.get("occurrence"); if (occurrence != null) { int i = serviceId.indexOf('/', serviceId.indexOf('/', serviceId.indexOf('/', serviceId.indexOf('/') + 1) + 1) + 1); int j = serviceId.indexOf('/', i + 1); serviceId = serviceId.substring(0, i + 1) + occurrence + serviceId.substring(j); } queue = getMessagingSource().lookupService(getMessagingSource().polishServiceId(serviceId)); if (queue == null) { throw new SenderException( getLogPrefix() + "got null as queue for serviceId [" + serviceId + "]"); } if (log.isDebugEnabled()) { log.info(getLogPrefix() + "got Queue to send messages on [" + queue.getQueueName() + "]"); } // Use remaining params as outgoing UDZs udzMap = new HashMap(); udzMap.putAll(params); udzMap.remove("serviceId"); udzMap.remove("occurrence"); } else { queue = getServiceQueue(); } sender = createSender(session, queue); log.debug(getLogPrefix() + "sending message with bifName [" + bifName + "]"); TextMessage sentMessage = sendMessage(session, sender, message, udzMap, bifName, btcData); log.debug(getLogPrefix() + "message sent"); if (isSynchronous()) { log.debug(getLogPrefix() + "waiting for reply"); Message msg = getRawReplyMessage(session, queue, sentMessage); try { long tsReplyReceived = System.currentTimeMillis(); long tsRequestSent = sentMessage.getJMSTimestamp(); long tsReplySent = msg.getJMSTimestamp(); // long jmsTimestampRcvd = msg.getJMSTimestamp(); //// long businessProcFinishSent=0; // long businessProcStartRcvd=0; // long businessProcStartSent=0; // long businessProcFinishRcvd=0; // if (sentMessage instanceof IFSAMessage) { // businessProcStartSent=((IFSAMessage)sentMessage).getBusinessProcessingStartTime(); //// businessProcFinishSent=((IFSAMessage)sentMessage).getBusinessProcessingFinishTime(); // } // if (msg instanceof IFSAMessage) { // businessProcStartRcvd=((IFSAMessage)msg).getBusinessProcessingStartTime(); // businessProcFinishRcvd=((IFSAMessage)msg).getBusinessProcessingFinishTime(); // } if (log.isInfoEnabled()) { log.info(getLogPrefix() + "A) RequestSent [" + DateUtils.format(tsRequestSent) + "]"); log.info(getLogPrefix() + "B) ReplySent [" + DateUtils.format(tsReplySent) + "] diff (~queing + processing) [" + (tsReplySent - tsRequestSent) + "]"); log.info(getLogPrefix() + "C) ReplyReceived [" + DateUtils.format(tsReplyReceived) + "] diff (transport of reply )[" + (tsReplyReceived - tsReplySent) + "]"); // log.info(getLogPrefix()+"C2) msgRcvd.businessProcStartRcvd ["+DateUtils.format(businessProcStartRcvd) +"] "); // log.info(getLogPrefix()+"D) msgRcvd.jmsTimestamp ["+DateUtils.format(jmsTimestampRcvd) +"] diff ["+(jmsTimestampRcvd-businessProcStartSent)+"]"); // log.info(getLogPrefix()+"E) msgRcvd.businessProcFinishRcvd ["+DateUtils.format(businessProcFinishRcvd)+"] diff ["+(businessProcFinishRcvd-jmsTimestampRcvd)+"] (=time spend on IFSA bus sending result?)"); // log.info(getLogPrefix()+"F) timestampAfterRcvd ["+DateUtils.format(timestampAfterRcvd) +"] diff ["+(timestampAfterRcvd-businessProcFinishRcvd)+"] "); // log.info(getLogPrefix()+"business processing time (E-C1) ["+(businessProcFinishRcvd-businessProcStartSent)+"] "); } // if (businessProcessTimes!=null) { // businessProcessTimes.addValue(businessProcFinishRcvd-businessProcStartSent); // } } catch (JMSException e) { log.warn(getLogPrefix() + "exception determining processing times", e); } if (msg instanceof TextMessage) { result = ((TextMessage) msg).getText(); } else { if (msg.getClass().getName().endsWith("IFSAReportMessage")) { if (msg instanceof IFSAReportMessage) { IFSAReportMessage irm = (IFSAReportMessage) msg; if (isThrowExceptions()) { throw new SenderException(getLogPrefix() + "received IFSAReportMessage [" + ToStringBuilder.reflectionToString(irm) + "], NoReplyReason [" + irm.getNoReplyReason() + "]"); } log.warn(getLogPrefix() + "received IFSAReportMessage [" + ToStringBuilder.reflectionToString(irm) + "], NoReplyReason [" + irm.getNoReplyReason() + "]"); result = "<IFSAReport>" + "<NoReplyReason>" + irm.getNoReplyReason() + "</NoReplyReason>" + "</IFSAReport>"; } } else { log.warn(getLogPrefix() + "received neither TextMessage nor IFSAReportMessage but [" + msg.getClass().getName() + "]"); result = msg.toString(); } } if (result == null) { log.info(getLogPrefix() + "received null reply"); } else { if (log.isDebugEnabled()) { if (AppConstants.getInstance().getBoolean("log.logIntermediaryResults", false)) { log.debug(getLogPrefix() + "received reply [" + result + "]"); } else { log.debug(getLogPrefix() + "received reply"); } } else { log.info(getLogPrefix() + "received reply"); } } } else { result = sentMessage.getJMSMessageID(); } } catch (JMSException e) { throw new SenderException(getLogPrefix() + "caught JMSException in sendMessage()", e); } catch (IfsaException e) { throw new SenderException(getLogPrefix() + "caught IfsaException in sendMessage()", e); } finally { if (sender != null) { try { log.debug(getLogPrefix() + "closing sender"); sender.close(); } catch (JMSException e) { log.debug(getLogPrefix() + "Exception closing sender", e); } } closeSession(session); } if (isThrowExceptions() && result != null && result.startsWith("<exception>")) { throw new SenderException("Retrieved exception message from IFSA bus: " + result); } return result; }
From source file:nl.nn.adapterframework.extensions.tibco.GetTibcoQueues.java
private String getQueueMessage(Session jSession, TibjmsAdmin admin, String queueName, int queueItem, LdapSender ldapSender) throws TibjmsAdminException, JMSException { QueueInfo qInfo = admin.getQueue(queueName); if (qInfo == null) { throw new JMSException(" queue [" + queueName + "] does not exist"); }//from w w w .ja va 2s . c o m XmlBuilder qMessageXml = new XmlBuilder("qMessage"); ServerInfo serverInfo = admin.getInfo(); String url = serverInfo.getURL(); qMessageXml.addAttribute("url", url); String resolvedUrl = getResolvedUrl(url); if (resolvedUrl != null) { qMessageXml.addAttribute("resolvedUrl", resolvedUrl); } qMessageXml.addAttribute("timestamp", DateUtils.getIsoTimeStamp()); qMessageXml.addAttribute("startTime", DateUtils.format(serverInfo.getStartTime(), DateUtils.fullIsoFormat)); XmlBuilder qNameXml = new XmlBuilder("qName"); qNameXml.setCdataValue(queueName); Queue queue = jSession.createQueue(queueName); QueueBrowser queueBrowser = null; try { queueBrowser = jSession.createBrowser(queue); Enumeration enm = queueBrowser.getEnumeration(); int count = 0; boolean found = false; String chompCharSizeString = AppConstants.getInstance().getString("browseQueue.chompCharSize", null); int chompCharSize = (int) Misc.toFileSize(chompCharSizeString, -1); while (enm.hasMoreElements() && !found) { count++; if (count == queueItem) { qNameXml.addAttribute("item", count); Object o = enm.nextElement(); if (o instanceof Message) { Message msg = (Message) o; XmlBuilder qMessageId = new XmlBuilder("qMessageId"); qMessageId.setCdataValue(msg.getJMSMessageID()); qMessageXml.addSubElement(qMessageId); XmlBuilder qTimestamp = new XmlBuilder("qTimestamp"); qTimestamp.setCdataValue(DateUtils.format(msg.getJMSTimestamp(), DateUtils.fullIsoFormat)); qMessageXml.addSubElement(qTimestamp); StringBuffer sb = new StringBuffer(""); Enumeration propertyNames = msg.getPropertyNames(); while (propertyNames.hasMoreElements()) { String propertyName = (String) propertyNames.nextElement(); Object object = msg.getObjectProperty(propertyName); if (sb.length() > 0) { sb.append("; "); } sb.append(propertyName); sb.append("="); sb.append(object); } XmlBuilder qPropsXml = new XmlBuilder("qProps"); qPropsXml.setCdataValue(sb.toString()); qMessageXml.addSubElement(qPropsXml); XmlBuilder qTextXml = new XmlBuilder("qText"); String msgText; try { TextMessage textMessage = (TextMessage) msg; msgText = textMessage.getText(); } catch (ClassCastException e) { msgText = msg.toString(); qTextXml.addAttribute("text", false); } int msgSize = msgText.length(); if (isHideMessage()) { qTextXml.setCdataValue("***HIDDEN***"); } else { if (chompCharSize >= 0 && msgSize > chompCharSize) { qTextXml.setCdataValue(msgText.substring(0, chompCharSize) + "..."); qTextXml.addAttribute("chomped", true); } else { qTextXml.setCdataValue(msgText); } } qMessageXml.addSubElement(qTextXml); XmlBuilder qTextSizeXml = new XmlBuilder("qTextSize"); qTextSizeXml.setValue(Misc.toFileSize(msgSize)); qMessageXml.addSubElement(qTextSizeXml); } found = true; } else { enm.nextElement(); } } } finally { if (queueBrowser != null) { try { queueBrowser.close(); } catch (JMSException e) { log.warn(getLogPrefix(null) + "exception on closing queue browser", e); } } } qMessageXml.addSubElement(qNameXml); Map aclMap = getAclMap(admin, ldapSender); XmlBuilder aclXml = new XmlBuilder("acl"); XmlBuilder qInfoXml = qInfoToXml(qInfo); aclXml.setValue((String) aclMap.get(qInfo.getName())); qInfoXml.addSubElement(aclXml); qMessageXml.addSubElement(qInfoXml); Map consumersMap = getConnectedConsumersMap(admin); XmlBuilder consumerXml = new XmlBuilder("connectedConsumers"); if (consumersMap.containsKey(qInfo.getName())) { LinkedList<String> consumers = (LinkedList<String>) consumersMap.get(qInfo.getName()); String consumersString = listToString(consumers); if (consumersString != null) { consumerXml.setCdataValue(consumersString); } } qInfoXml.addSubElement(consumerXml); return qMessageXml.toXML(); }
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() + "]"); }//from w w w. j a v a 2s . 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:nl.nn.adapterframework.jms.JmsListenerBase.java
protected String retrieveIdFromMessage(Message message, Map threadContext) throws ListenerException { String cid = "unset"; String mode = "unknown"; String id = "unset"; Date tsSent = null;/*ww w . j ava 2 s. com*/ Destination replyTo = null; try { mode = deliveryModeToString(message.getJMSDeliveryMode()); } catch (JMSException ignore) { log.debug("ignoring JMSException in getJMSDeliveryMode()", ignore); } // -------------------------- // retrieve MessageID // -------------------------- try { id = message.getJMSMessageID(); } catch (JMSException ignore) { log.debug("ignoring JMSException in getJMSMessageID()", ignore); } // -------------------------- // retrieve CorrelationID // -------------------------- try { if (isForceMessageIdAsCorrelationId()) { if (log.isDebugEnabled()) log.debug("forcing the messageID to be the correlationID"); cid = id; } else { cid = message.getJMSCorrelationID(); if (cid == null) { cid = id; log.debug("Setting correlation ID to MessageId"); } } } catch (JMSException ignore) { log.debug("ignoring JMSException in getJMSCorrelationID()", ignore); } // -------------------------- // retrieve TimeStamp // -------------------------- try { long lTimeStamp = message.getJMSTimestamp(); tsSent = new Date(lTimeStamp); } catch (JMSException ignore) { log.debug("ignoring JMSException in getJMSTimestamp()", ignore); } // -------------------------- // retrieve ReplyTo address // -------------------------- try { replyTo = message.getJMSReplyTo(); } catch (JMSException ignore) { log.debug("ignoring JMSException in getJMSReplyTo()", ignore); } if (log.isDebugEnabled()) { log.debug(getLogPrefix() + "listener on [" + getDestinationName() + "] got message with JMSDeliveryMode=[" + mode + "] \n JMSMessageID=[" + id + "] \n JMSCorrelationID=[" + cid + "] \n Timestamp Sent=[" + DateUtils.format(tsSent) + "] \n ReplyTo=[" + ((replyTo == null) ? "none" : replyTo.toString()) + "] \n Message=[" + message.toString() + "]"); } PipeLineSessionBase.setListenerParameters(threadContext, id, cid, null, tsSent); threadContext.put("timestamp", tsSent); threadContext.put("replyTo", replyTo); try { if (getAckMode() == Session.CLIENT_ACKNOWLEDGE) { message.acknowledge(); log.debug("Listener on [" + getDestinationName() + "] acknowledged message"); } } catch (JMSException e) { log.error("Warning in ack", e); } return cid; }
From source file:org.ala.jms.service.JmsMessageListener.java
/** * Implementation of <code>MessageListener</code>. * * JSON Message:/*ww w . ja v a 2 s .co m*/ * ============== * { * "guid" : "urn:lsid:cs.ala.org.au:Record:51", * "dataResourceUid" : "dr364", * "scientificName" : "Trichoglossus haematodus eyrei", * "vernacularName" : "Rainbow Lorikeet", * "locality" : "Emmet Yaraka Rd, Isisford QLD 4731, Australia", * "decimalLatitude" : "-24.729292", * "decimalLongitude" : "144.234375", * "individualCount" : "345", * "coordinateUncertaintyInMeters" : "222.0", * "occurrenceRemarks" : "rwe", * "eventDate" : "2011-07-11", * "eventTime" : "13:50:00EST", * "taxonID" : "urn:lsid:biodiversity.org.au:afd.taxon:13a00712-95cb-475b-88a5-f1c7917e10e3", * "family" : "Psittacidae", * "kingdom" : "Animalia", * "associatedMedia" : ["http://cs.ala.org.au/bdrs-ala/files/download.htm?className=au.com.gaiaresources.bdrs.model.taxa.AttributeValue&id=63&fileName=Argentina.gif"] * } */ public void onMessage(Message message) { String occId = ""; String json = ""; Method messageMethod = getMethod(message); logger.info("Message received from the queue..." + messageMethod); logger.debug(message.toString()); try { if (messageMethod != null) { Map<String, String> map = new java.util.HashMap<String, String>(); if (message instanceof TextMessage) { lastMessage = System.currentTimeMillis(); // prepare data TextMessage tm = (TextMessage) message; json = tm.getText(); if (json != null && !"".equals(json)) { logger.debug("creating map : " + json); try { Map<String, Object> omap = mapper.readValue(json, new TypeReference<HashMap<String, Object>>() { }); for (String key : omap.keySet()) { Object value = omap.get(key); if ("associatedMedia".equalsIgnoreCase(key)) { if (hasAssociatedMedia && value != null) { String newValue = org.apache.commons.lang.StringUtils.join((List) value, ";"); map.put("associatedMedia", newValue); } } // else if("userID".equalsIgnoreCase(key)){ // if(value != null) // map.put("recordedBy", value.toString()); // } else if ("guid".equalsIgnoreCase(key)) { if (value != null) map.put("occurrenceID", value.toString()); } else if (value != null) { map.put(key, omap.get(key).toString()); } } } catch (Exception e) { logger.error(e.getMessage(), e); } catch (Throwable e) { e.printStackTrace(); logger.error(e.getMessage(), e); } logger.debug("finished creating map " + map); } else { logger.error("Empty Json Message! Method: " + message.getStringProperty(MESSAGE_METHOD)); return; } if (map.get(TEST_MESSAGE) != null) { //log it and return. logger.info("Test message received. Will not proceed with commit to biocache"); return; } //remove transport info from payload if supplied map.remove("messageMethod"); //process request switch (messageMethod) { case CREATE: createOrUpdate(map); break; case UPDATE: createOrUpdate(map); break; case DELETE: if (map != null) { //TODO deletes for when the data resource UID is supplied occId = getDefaultDataResourceUid() + "|" + map.get("occurrenceID"); logger.info("Delete request received for ID: " + occId); synchronized (deleteList) { deleteList.add(occId); } } break; default: logger.error("Invalid method! Method: " + message.getStringProperty(MESSAGE_METHOD) + ". json= " + json); break; } logger.debug("Method = " + messageMethod + " : Processed message " + json); } } else { logger.error("Invalid method! Method: " + messageMethod); } } catch (Exception e) { logger.error("Error processing message: " + json + " Method :" + messageMethod); logger.error(e.getMessage(), e); } }
From source file:org.apache.falcon.messaging.JMSMessageConsumer.java
@Override public void onMessage(Message message) { MapMessage mapMessage = (MapMessage) message; LOG.info("Received JMS message {}", message.toString()); try {//ww w. j a va2s . c om WorkflowExecutionContext context = createContext(mapMessage); LOG.info("Created context from JMS message {}", context); // Login the user so listeners can access FS and WfEngine as this user CurrentUser.authenticate(context.getWorkflowUser()); if (context.hasWorkflowFailed()) { onFailure(context); } else if (context.hasWorkflowSucceeded()) { onSuccess(context); } } catch (JMSException e) { String errorMessage = "Error in onMessage for topicSubscriber of topic: " + topicName + ", Message: " + message.toString(); LOG.info(errorMessage, e); GenericAlert.alertJMSMessageConsumerFailed(errorMessage, e); } }
From source file:org.grouter.core.readers.JmsReaderJob.java
@Override protected List<CommandMessage> readFromSource() { logger.info("In readFromSource using uri :" + node.getInBound().getUri()); // a list of full paths on ftp server we will download from node List<CommandMessage> commandMessages = new ArrayList<CommandMessage>(); AbstractDestination client = null;/* w ww . j a v a 2 s . co m*/ try { client = initConnection(node); if (client == null) { logger.error("Could not create a client instance to JMS server"); return null; } // if type is queue AbstractListenerDestination clientQ = (AbstractListenerDestination) client; if (clientQ.getMessageConsumer() != null) { Message msg = clientQ.getMessageConsumer().receive(WAIT_TIME); if (msg != null) { File internalInFile = getInternalFile("jms"); FileUtils.writeStringToFile(internalInFile, msg.toString()); String message = getMessage(internalInFile); CommandMessage cmdMessage = new CommandMessage(message, internalInFile); commandMessages.add(cmdMessage); logger.info("Got a message ? :" + msg); } } } catch (Exception e) { node.setNodeStatus(NodeStatus.ERROR); node.setStatusMessage("Failed reading from JMS destination :" + node.getInBound().getUri() + " Error:" + e.getMessage()); logStrategy.log(node); logger.warn("Could not read data from destination. Probably connection problem with JMS server.", e); } finally { if (client != null) { logger.debug("Unbinding from JMS destination"); client.unbind(); } } return commandMessages; }
From source file:org.jwebsocket.plugins.scripting.ScriptingPlugIn.java
@Override public void systemStarted() throws Exception { // initializing apps Map<String, String> lApps = mSettings.getApps(); for (String lAppName : lApps.keySet()) { try {/*from w ww . java 2 s . co m*/ execAppBeforeLoadChecks(lAppName, lApps.get(lAppName)); loadApp(lAppName, lApps.get(lAppName), false); } catch (Exception lEx) { mLog.error(Logging.getSimpleExceptionMessage(lEx, "loading '" + lAppName + "' application")); } } notifyToApps(BaseScriptApp.EVENT_SYSTEM_STARTED, new Object[0]); try { // registering on message hub if running on a cluster getServer().getJMSManager().subscribe(new MessageListener() { @Override public void onMessage(Message aMessage) { try { // discard processing if the message comes from the current server node if (JWebSocketConfig.getConfig().getNodeId() .equals(aMessage.getStringProperty(Attributes.NODE_ID))) { return; } ClusterMessageTypes lType = ClusterMessageTypes .valueOf(aMessage.getStringProperty(Attributes.MESSAGE_TYPE)); switch (lType) { case LOAD_APP: { String lAppName = aMessage.getStringProperty("appName"); Boolean lHotLoad = aMessage.getBooleanProperty("hotLoad"); String lPath = mSettings.getApps().get(lAppName); // loading app loadApp(lAppName, lPath, lHotLoad); break; } case UNDEPLOY_APP: { String lAppName = aMessage.getStringProperty("appName"); // validating BaseScriptApp lScriptApp = mApps.get(lAppName); // notifying event before undeploy lScriptApp.notifyEvent(BaseScriptApp.EVENT_UNDEPLOYING, new Object[0]); // deleting app mApps.remove(lAppName); FileUtils.deleteDirectory(new File(lScriptApp.getPath())); break; } } } catch (Exception lEx) { mLog.error(Logging.getSimpleExceptionMessage(lEx, "processing cluster message: " + aMessage.toString())); } } }, "ns = '" + NS + "'"); } catch (Exception aException) { mLog.error("Exception catched while getting the JMS Manager instance with the following message: " + aException.getMessage()); } if (mLog.isDebugEnabled()) { mLog.debug("Scripting plug-in finished startup process!"); } }
From source file:org.sakaiproject.nakamura.grouper.event.SyncJMSMessageConsumer.java
@SuppressWarnings("unchecked") public void onMessage(Message message) { log.debug("Receiving a message on {} : {}", SyncJMSMessageProducer.QUEUE_NAME, message); try {// ww w . j ava 2 s. c o m String topic = message.getJMSType(); String groupId = (String) message.getStringProperty("path"); String operation = "UNKNOWN"; // A group was DELETED if ("org/sakaiproject/nakamura/lite/authorizables/DELETE".equals(topic) && config.getDeletesEnabled()) { Map<String, Object> attributes = (Map<String, Object>) message .getObjectProperty(StoreListener.BEFORE_EVENT_PROPERTY); grouperManager.deleteGroup(groupId, attributes); operation = "DELETED"; } // A new group was ADDED or an existing group was UPDATED if ("org/sakaiproject/nakamura/lite/authorizables/ADDED".equals(topic) || "org/sakaiproject/nakamura/lite/authorizables/UPDATED".equals(topic)) { // These events should be under org/sakaiproject/nakamura/lite/authorizables/UPDATED // http://jira.sakaiproject.org/browse/KERN-1795 String membersAdded = (String) message.getStringProperty(GrouperEventUtils.MEMBERS_ADDED_PROP); if (membersAdded != null) { // membership adds can be attached to the same event for the group add. grouperManager.createGroup(groupId, config.getGroupTypes()); grouperManager.addMemberships(groupId, Arrays.asList(StringUtils.split(membersAdded, ","))); operation = "ADD_MEMBERS"; } String membersRemoved = (String) message.getStringProperty(GrouperEventUtils.MEMBERS_REMOVED_PROP); if (membersRemoved != null) { grouperManager.removeMemberships(groupId, Arrays.asList(StringUtils.split(membersRemoved, ","))); operation = "REMOVE_MEMBERS"; } if (membersAdded == null && membersRemoved == null) { org.sakaiproject.nakamura.api.lite.Session repositorySession = repository.loginAdministrative(); AuthorizableManager am = repositorySession.getAuthorizableManager(); Group group = (Group) am.findAuthorizable(groupId); repositorySession.logout(); if (groupId.startsWith(ContactsGrouperNameProviderImpl.CONTACTS_GROUPID_PREFIX)) { // TODO Why are we not getting added and removed properties on the Message grouperManager.createGroup(groupId, null); grouperManager.addMemberships(groupId, Arrays.asList(group.getMembers())); operation = "UPDATE CONTACTS"; } else { grouperManager.createGroup(groupId, config.getGroupTypes()); grouperManager.addMemberships(groupId, Arrays.asList(group.getMembers())); operation = "CREATE"; } } } // The message was processed successfully. No exceptions were thrown. // We acknowledge the message and its removed from the queue message.acknowledge(); // We got a message that we didn't know what to do with. if (operation.equals("UNKNOWN")) { log.error("I don't know what to do with this topic: {}. Turn on debug logs to see the message.", topic); log.debug(message.toString()); } else { log.info("Successfully processed and acknowledged. {}, {}", operation, groupId); log.debug(message.toString()); } } catch (JMSException jmse) { log.error("JMSException while processing message.", jmse); } catch (Exception e) { log.error("Exception while processing message.", e); } }