List of usage examples for javax.jms TextMessage getText
String getText() throws JMSException;
From source file:org.apache.servicemix.jms.JmsConsumerEndpointTest.java
public void testConsumerDefaultInOutJmsTx() throws Exception { JmsComponent component = new JmsComponent(); JmsConsumerEndpoint endpoint = new JmsConsumerEndpoint(); endpoint.setService(new QName("jms")); endpoint.setEndpoint("endpoint"); endpoint.setTargetService(new QName("echo")); endpoint.setListenerType("default"); endpoint.setConnectionFactory(connectionFactory); endpoint.setDestinationName("destination"); endpoint.setReplyDestinationName("replyDestination"); endpoint.setTransacted("jms"); endpoint.setMarshaler(new DefaultConsumerMarshaler(JbiConstants.IN_OUT)); component.setEndpoints(new JmsConsumerEndpoint[] { endpoint }); container.activateComponent(component, "servicemix-jms"); jmsTemplate.convertAndSend("destination", "<hello>world</hello>"); TextMessage msg = (TextMessage) jmsTemplate.receive("replyDestination"); Element e = sourceTransformer.toDOMElement(new StringSource(msg.getText())); assertEquals("hello", e.getTagName()); assertEquals("world", e.getTextContent()); Thread.sleep(500);//from w ww .jav a 2 s .com }
From source file:Replier.java
/** * Handle the message./*ww w. jav a 2s . c o m*/ * (as specified in the javax.jms.MessageListener interface). * * IMPORTANT NOTES: * (1)We must follow the design paradigm for JMS * synchronous requests. That is, we must: * - get the message * - look for the header specifying JMSReplyTo * - send a reply to the queue specified there. * Failing to follow these steps might leave the originator * of the request waiting forever. * (2)Unlike the 'Talk' sample and others using an asynchronous * message listener, it is possible here to use ONLY * ONE SESSION because the messages being sent are sent from * the same thread of control handling message delivery. For * more information see the JMS spec v1.0.2 section 4.4.6. * * OPTIONAL BEHAVIOR: The following actions taken by the * message handler represent good programming style, but are * not required by the design paradigm for JMS requests. * - set the JMSCorrelationID (tying the response back to * the original request. * - use transacted session "commit" so receipt of request * won't happen without the reply being sent. * */ public void onMessage(javax.jms.Message aMessage) { try { // Cast the message as a text message. javax.jms.TextMessage textMessage = (javax.jms.TextMessage) aMessage; // This handler reads a single String from the // message and prints it to the standard output. try { String string = textMessage.getText(); System.out.println("[Request] " + string); // Check for a ReplyTo Queue javax.jms.Queue replyQueue = (javax.jms.Queue) aMessage.getJMSReplyTo(); if (replyQueue != null) { // Send the modified message back. javax.jms.TextMessage reply = session.createTextMessage(); if (imode == UPPERCASE) reply.setText("Uppercasing-" + string.toUpperCase()); else reply.setText("Lowercasing-" + string.toLowerCase()); reply.setJMSCorrelationID(aMessage.getJMSMessageID()); replier.send(replyQueue, reply); session.commit(); } } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } } catch (java.lang.RuntimeException rte) { rte.printStackTrace(); } }
From source file:TransactedTalk.java
/** * Handle the message/*from ww w .ja va2 s.co m*/ * (as specified in the javax.jms.MessageListener interface). */ public void onMessage(javax.jms.Message aMessage) { try { // Cast the message as a text message. javax.jms.TextMessage textMessage = (javax.jms.TextMessage) aMessage; // This handler reads a single String from the // message and prints it to the standard output. try { String string = textMessage.getText(); System.out.println(string); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } } catch (java.lang.RuntimeException rte) { rte.printStackTrace(); } }
From source file:it.cnr.isti.labsedc.glimpse.manager.GlimpseManager.java
public void onMessage(Message arg0) { TextMessage msg = null; try {//from w w w . ja v a 2s. com msg = (TextMessage) arg0; DebugMessages.line(); DebugMessages.println(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), "receive " + msg.getText()); DebugMessages.line(); String XMLRule = msg.getText(); String sender = msg.getStringProperty("SENDER"); ComplexEventRuleActionListDocument ruleDoc; ruleDoc = ComplexEventRuleActionListDocument.Factory.parse(XMLRule); ComplexEventRuleActionType rules = ruleDoc.getComplexEventRuleActionList(); //the topic where the listener will give analysis results answerTopic = "answerTopic" + "#" + this.getName() + "#" + System.nanoTime(); DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), "Create answerTopic"); connectionTopic = publishSession.createTopic(answerTopic); //tPub = publishSession.createPublisher(connectionTopic); DebugMessages.ok(); DebugMessages.println(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), "Setting up ComplexEventProcessor with new rule."); try { Object[] loadedKnowledgePackage = rulesManagerOne.loadRules(rules); //inserisco la coppia chiave valore dove la chiave il KnowledgePackage //caricato, generato da DroolsRulesManager con la loadRules //e il valore l'enabler che l'ha inviata //(il KnowledgePackage array dovrebbe avere sempre dimensione 1 essendo creato ad ogni loadrules) for (int i = 0; i < loadedKnowledgePackage.length; i++) { KnowledgePackageImp singleKnowlPack = (KnowledgePackageImp) loadedKnowledgePackage[i]; Rule[] singleRuleContainer = new Rule[singleKnowlPack.getRules().size()]; singleRuleContainer = singleKnowlPack.getRules().toArray(singleRuleContainer); for (int j = 0; j < singleRuleContainer.length; j++) { requestMap.put(singleRuleContainer[j].getName(), new ConsumerProfile(sender, answerTopic)); } } DebugMessages.println(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), "KnowledgeBase packages loaded: " + rulesManagerOne.getLoadedKnowledgePackageCardinality()); DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), "Communicate the answerTopic to the requester"); sendMessage(createMessage("AnswerTopic == " + answerTopic, sender)); DebugMessages.ok(); } catch (IncorrectRuleFormatException e) { sendMessage(createMessage("PROVIDED RULE CONTAINS ERRORS", sender)); } } catch (NullPointerException asd) { try { sendMessage(createMessage("PROVIDED RULE IS NULL, PLEASE PROVIDE A VALID RULE", msg.getStringProperty("SENDER"))); } catch (JMSException e) { e.printStackTrace(); } } catch (XmlException e) { try { sendMessage(createMessage("PROVIDED XML CONTAINS ERRORS", msg.getStringProperty("SENDER"))); } catch (JMSException e1) { e1.printStackTrace(); } } catch (JMSException ee) { ee.printStackTrace(); } DebugMessages.line(); }
From source file:org.ala.jms.service.JmsMessageListener.java
/** * Implementation of <code>MessageListener</code>. * * JSON Message:/*from w w w . j a va2 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.dawnsci.commandserver.core.process.ProgressableProcess.java
/** * Starts a connection which listens to the topic and if * a cancel is found published, tries to terminate the subprocess. * //from w w w .j a v a2s .co m * @param p */ protected void createTerminateListener() throws Exception { ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri); ProgressableProcess.this.topicConnection = connectionFactory.createConnection(); topicConnection.start(); Session session = topicConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); final Topic topic = session.createTopic(statusTName); final MessageConsumer consumer = session.createConsumer(topic); final Class clazz = bean.getClass(); final ObjectMapper mapper = new ObjectMapper(); MessageListener listener = new MessageListener() { public void onMessage(Message message) { try { if (message instanceof TextMessage) { TextMessage t = (TextMessage) message; final StatusBean tbean = mapper.readValue(t.getText(), clazz); if (bean.getStatus().isFinal()) { // Something else already happened topicConnection.close(); return; } if (bean.getUniqueId().equals(tbean.getUniqueId())) { if (tbean.getStatus() == Status.REQUEST_TERMINATE) { bean.merge(tbean); out.println("Terminating job '" + tbean.getName() + "'"); terminate(); topicConnection.close(); bean.setStatus(Status.TERMINATED); bean.setMessage("Foricibly terminated before finishing."); broadcast(bean); return; } } } } catch (Exception e) { e.printStackTrace(); } } }; consumer.setMessageListener(listener); }
From source file:com.mothsoft.alexis.engine.textual.ParseResponseMessageListener.java
@Override public void onMessage(final TextMessage message, final Session session) throws JMSException { final long documentId = message.getLongProperty(DOCUMENT_ID); logger.info("Received response for document ID: " + documentId); final String xml = message.getText(); try {/*w ww . jav a 2 s .c o m*/ final ParsedContent parsedContent = readResponse(xml); updateDocument(documentId, parsedContent); } catch (final IOException e) { final JMSException e2 = new JMSException(e.getMessage()); e2.setLinkedException(e); throw e2; } }
From source file:org.oxymores.chronix.engine.Runner.java
private void recvTextMessage(TextMessage tmsg) throws JMSException { String res = tmsg.getText(); String cid = tmsg.getJMSCorrelationID(); String pjid = cid.split("\\|")[0]; String paramid = cid.split("\\|")[1]; // Get the PipelineJob PipelineJob resolvedJob = null;/*from ww w . j a v a 2 s . c o m*/ for (PipelineJob pj : this.resolving) { if (pj.getId().toString().equals(pjid)) { resolvedJob = pj; break; } } if (resolvedJob == null) { log.error("received a param resolution for a job that is not in queue - ignored"); return; } // Get the parameter awaiting resolution int paramIndex = -1; ArrayList<Parameter> prms = resolvedJob.getActive(ctx).getParameters(); for (int i = 0; i < prms.size(); i++) { if (prms.get(i).getId().toString().equals(paramid)) { paramIndex = i; break; } } if (paramIndex == -1) { log.error("received a param resolution for a job that has no such parameter - ignored"); return; } // Update the parameter with its value trTransac.begin(); resolvedJob.setParamValue(paramIndex, res); trTransac.commit(); // Perhaps launch the job if (resolvedJob.isReady(ctx)) { this.sendRunDescription(resolvedJob.getRD(ctx), resolvedJob.getPlace(ctx), resolvedJob); } }
From source file:org.dawnsci.commandserver.ui.view.ConsumerView.java
/** * Listens to a topic/*from w w w .jav a 2 s .c o m*/ */ private void createTopicListener(final URI uri) throws Exception { // Use job because connection might timeout. final Job topicJob = new Job("Create topic listener") { @Override protected IStatus run(IProgressMonitor monitor) { try { ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri); topicConnection = connectionFactory.createConnection(); topicConnection.start(); Session session = topicConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); final Topic topic = session.createTopic(Constants.ALIVE_TOPIC); final MessageConsumer consumer = session.createConsumer(topic); final ObjectMapper mapper = new ObjectMapper(); MessageListener listener = new MessageListener() { public void onMessage(Message message) { try { if (message instanceof TextMessage) { TextMessage t = (TextMessage) message; final ConsumerBean bean = mapper.readValue(t.getText(), ConsumerBean.class); bean.setLastAlive(System.currentTimeMillis()); consumers.put(bean.getConsumerId(), bean); } } catch (Exception e) { logger.error("Updating changed bean from topic", e); } } }; consumer.setMessageListener(listener); return Status.OK_STATUS; } catch (Exception ne) { logger.error("Cannot listen to topic changes because command server is not there", ne); return Status.CANCEL_STATUS; } } }; topicJob.setPriority(Job.INTERACTIVE); topicJob.setSystem(true); topicJob.setUser(false); topicJob.schedule(); }
From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java
private ArrayList<String> browseMessagesViaJMS(BrokerService brokerService) throws Exception { ArrayList<String> rc = new ArrayList<String>(); ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( "tcp://localhost:" + connectPort(brokerService)); Connection connection = factory.createConnection(); try {/* w ww .j a v a 2 s . c o m*/ connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); QueueBrowser browser = session.createBrowser(session.createQueue("FOO")); Enumeration enumeration = browser.getEnumeration(); while (enumeration.hasMoreElements()) { TextMessage textMessage = (TextMessage) enumeration.nextElement(); rc.add(textMessage.getText()); } } finally { connection.close(); } return rc; }