List of usage examples for javax.jms TextMessage getText
String getText() throws JMSException;
From source file:org.dawnsci.commandserver.core.producer.ProcessConsumer.java
/** * Parse the queue for stale jobs and things that should be rerun. * @param bean/*from w w w .j ava 2 s. com*/ * @throws Exception */ private void processStatusQueue(URI uri, String statusQName) throws Exception { QueueConnection qCon = null; try { QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri); qCon = connectionFactory.createQueueConnection(); QueueSession qSes = qCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = qSes.createQueue(statusQName); qCon.start(); QueueBrowser qb = qSes.createBrowser(queue); @SuppressWarnings("rawtypes") Enumeration e = qb.getEnumeration(); ObjectMapper mapper = new ObjectMapper(); Map<String, StatusBean> failIds = new LinkedHashMap<String, StatusBean>(7); List<String> removeIds = new ArrayList<String>(7); while (e.hasMoreElements()) { Message m = (Message) e.nextElement(); if (m == null) continue; if (m instanceof TextMessage) { TextMessage t = (TextMessage) m; try { @SuppressWarnings("unchecked") final StatusBean qbean = mapper.readValue(t.getText(), getBeanClass()); if (qbean == null) continue; if (qbean.getStatus() == null) continue; if (!qbean.getStatus().isStarted()) { failIds.put(t.getJMSMessageID(), qbean); continue; } // If it has failed, we clear it up if (qbean.getStatus() == Status.FAILED) { removeIds.add(t.getJMSMessageID()); continue; } if (qbean.getStatus() == Status.NONE) { removeIds.add(t.getJMSMessageID()); continue; } // If it is running and older than a certain time, we clear it up if (qbean.getStatus() == Status.RUNNING) { final long submitted = qbean.getSubmissionTime(); final long current = System.currentTimeMillis(); if (current - submitted > getMaximumRunningAge()) { removeIds.add(t.getJMSMessageID()); continue; } } if (qbean.getStatus().isFinal()) { final long submitted = qbean.getSubmissionTime(); final long current = System.currentTimeMillis(); if (current - submitted > getMaximumCompleteAge()) { removeIds.add(t.getJMSMessageID()); } } } catch (Exception ne) { System.out.println("Message " + t.getText() + " is not legal and will be removed."); removeIds.add(t.getJMSMessageID()); } } } // We fail the non-started jobs now - otherwise we could // actually start them late. TODO check this final List<String> ids = new ArrayList<String>(); ids.addAll(failIds.keySet()); ids.addAll(removeIds); if (ids.size() > 0) { for (String jMSMessageID : ids) { MessageConsumer consumer = qSes.createConsumer(queue, "JMSMessageID = '" + jMSMessageID + "'"); Message m = consumer.receive(1000); if (removeIds.contains(jMSMessageID)) continue; // We are done if (m != null && m instanceof TextMessage) { MessageProducer producer = qSes.createProducer(queue); final StatusBean bean = failIds.get(jMSMessageID); bean.setStatus(Status.FAILED); producer.send(qSes.createTextMessage(mapper.writeValueAsString(bean))); System.out.println("Failed job " + bean.getName() + " messageid(" + jMSMessageID + ")"); } } } } finally { if (qCon != null) qCon.close(); } }
From source file:de.fraunhofer.iosb.ivct.IVCTcommander.java
/** {@inheritDoc} */ @Override/*from ww w . j av a 2 s . c om*/ public void onMessage(final Message message) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Received Command message"); } if (message instanceof TextMessage) { final TextMessage textMessage = (TextMessage) message; try { final String content = textMessage.getText(); try { JSONObject jsonObject = (JSONObject) jsonParser.parse(content); String commandTypeName = (String) jsonObject.get("commandType"); switch (commandTypeName) { case "announceVerdict": onMessageUiConsumer.run(jsonObject, IVCTcommander.listOfVerdicts); break; case "quit": // Should ignore break; case "setSUT": break; case "startTestCase": break; default: System.out.println("Unknown commandType name is: " + commandTypeName); break; } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (final JMSException ex) { LOGGER.warn("Problems with parsing Message", ex); } } }
From source file:org.wso2.carbon.bpmn.extensions.jms.JMSListener.java
/** * * @param message/*w ww . ja v a 2 s. co m*/ * This method will get executed once the destination receives a message. */ @Override public void onMessage(Message message) { try { //checks whether the message is of type TextMessage if (message instanceof TextMessage) { TextMessage text = (TextMessage) message; Map<String, Object> variableMap = new HashMap<>(); //gets the list of xpath or json path expressions given by the user in the BPMN process file. String outputMappings = parameters.get(JMSConstants.PARAM_OUTPUT_MAPPINGS); String contentType = parameters.get(JMSConstants.PARAM_CONTENT_TYPE); String expression = text.getText(); XPath xPath = XPathFactory.newInstance().newXPath(); if (outputMappings != null) { //sample outputMappings string: // name#$.student.name#required;age#$.student.age#required;messageName#$.student.msgName#required //';' is used to separate set of variable names String variables[] = outputMappings.split(";"); for (int i = 0; i < variables.length; i++) { //'#' is used to separate attributes of one variable. //these includes the variable name, xpath, json path or text expression, and whether the // variable is required or not. String fields[] = variables[i].split("#"); //the message body should include a value for msgName which will be used to invoke the process. if ("required".equals(fields[2])) { //if the message body content type is json if (JMSConstants.CONTENT_TYPE_JSON.equalsIgnoreCase(contentType)) { variableMap.put(fields[0], JsonPath.read(expression, fields[1]).toString()); } //if the message body content type is xml else if (JMSConstants.CONTENT_TYPE_XML.equalsIgnoreCase(contentType)) { variableMap.put(fields[0], xPath.evaluate(fields[1], new InputSource(new StringReader(expression)))); } //if the message body content type is plain text else if (JMSConstants.CONTENT_TYPE_TEXT.equalsIgnoreCase(contentType)) { variableMap.put("messageName", text.getText()); } } } } //starts the process instance ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); RuntimeService runtimeService = processEngine.getRuntimeService(); runtimeService.startProcessInstanceByMessageAndTenantId(variableMap.get("messageName").toString(), variableMap, "-1234"); } } catch (JMSException e) { String msg = "An error occurred while creating while getting the message from the destination"; if (log.isDebugEnabled()) log.debug(msg, e); } catch (XPathExpressionException e) { String msg = "An error occurred while executing the XPath expression"; if (log.isDebugEnabled()) log.debug(msg, e); } }
From source file:com.mdmserver.managers.ControllerFacade.java
public void uninstallApp(int accountId, String appPackageName) { Account account = databaseManager.getAccountByAccountId(accountId); Context ctx;//from w ww . j a va2 s . com try { ctx = new InitialContext(); ConnectionFactory connectionFactory = (ConnectionFactory) ctx.lookup("jms/mdmConnectionFactory"); Queue queue = (Queue) ctx.lookup("jms/mdmQueue"); MessageProducer messageProducer; System.out.println("Naming success"); try { javax.jms.Connection connection = connectionFactory.createConnection(); javax.jms.Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); messageProducer = session.createProducer(queue); TextMessage message = session.createTextMessage(); message.setStringProperty(Account.FIELD_NAME_CLOUD_ID, account.getCloudId()); ControlClient cClient = new ControlClient(); cClient.setCommandType(ControlClient.UNINSTALL_APP_CONTROL); cClient.setJsonCommandDetails(appPackageName); Gson gson = new Gson(); message.setStringProperty(ControlClient.CONTROL_CLIENT_KEY, gson.toJson(cClient)); System.out.println("It come from Servlet:" + message.getText()); messageProducer.send(message); System.out.println("JMS success"); } catch (JMSException ex) { // Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex); System.out.println("JMS exception"); } } catch (NamingException ex) { // Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Naming exception"); } }
From source file:com.linagora.obm.sync.TestQueueManager.java
@Test public void testClosedSession() throws Exception { String testText = "test text"; Connection connection = createManagedConnection(); connection.start();//from www . j av a 2 s.c o m Session consumerSession = queueManager.createSession(connection); MessageConsumer consumer = queueManager.createConsumerOnTopic(consumerSession, TOPIC); writeMessageOnTopic(testText, TOPIC, queueManager); TextMessage messageReceived1 = (TextMessage) consumer.receive(TIMEOUT); consumerSession.close(); writeMessageOnTopic(testText, TOPIC, queueManager); consumerSession = createManagedSession(connection); consumer = queueManager.createConsumerOnTopic(consumerSession, TOPIC); TextMessage messageReceived2 = (TextMessage) consumer.receive(TIMEOUT); Assert.assertEquals(testText, messageReceived1.getText()); Assert.assertNull(messageReceived2); }
From source file:org.apache.camel.component.jms.JmsBinding.java
/** * Extracts the body from the JMS message * * @param exchange the exchange/*from w w w . j a va 2s . co m*/ * @param message the message to extract its body * @return the body, can be <tt>null</tt> */ public Object extractBodyFromJms(Exchange exchange, Message message) { try { // is a custom message converter configured on endpoint then use it instead of doing the extraction // based on message type if (endpoint != null && endpoint.getMessageConverter() != null) { if (LOG.isTraceEnabled()) { LOG.trace("Extracting body using a custom MessageConverter: " + endpoint.getMessageConverter() + " from JMS message: " + message); } return endpoint.getMessageConverter().fromMessage(message); } // if we are configured to not map the jms message then return it as body if (endpoint != null && !endpoint.getConfiguration().isMapJmsMessage()) { if (LOG.isTraceEnabled()) { LOG.trace("Option map JMS message is false so using JMS message as body: " + message); } return message; } if (message instanceof ObjectMessage) { if (LOG.isTraceEnabled()) { LOG.trace("Extracting body as a ObjectMessage from JMS message: " + message); } ObjectMessage objectMessage = (ObjectMessage) message; Object payload = objectMessage.getObject(); if (payload instanceof DefaultExchangeHolder) { DefaultExchangeHolder holder = (DefaultExchangeHolder) payload; DefaultExchangeHolder.unmarshal(exchange, holder); return exchange.getIn().getBody(); } else { return objectMessage.getObject(); } } else if (message instanceof TextMessage) { if (LOG.isTraceEnabled()) { LOG.trace("Extracting body as a TextMessage from JMS message: " + message); } TextMessage textMessage = (TextMessage) message; return textMessage.getText(); } else if (message instanceof MapMessage) { if (LOG.isTraceEnabled()) { LOG.trace("Extracting body as a MapMessage from JMS message: " + message); } return createMapFromMapMessage((MapMessage) message); } else if (message instanceof BytesMessage) { if (LOG.isTraceEnabled()) { LOG.trace("Extracting body as a BytesMessage from JMS message: " + message); } return createByteArrayFromBytesMessage((BytesMessage) message); } else if (message instanceof StreamMessage) { if (LOG.isTraceEnabled()) { LOG.trace("Extracting body as a StreamMessage from JMS message: " + message); } return message; } else { return null; } } catch (JMSException e) { throw new RuntimeCamelException("Failed to extract body due to: " + e + ". Message: " + message, e); } }
From source file:org.apache.stratos.manager.listener.InstanceStatusListener.java
@Override public void onMessage(Message message) { TextMessage receivedMessage = (TextMessage) message; if (log.isInfoEnabled()) { log.info("Instance status message received"); }/*w w w. j a v a2s . com*/ try { String type = message.getStringProperty(Constants.EVENT_CLASS_NAME); if (log.isInfoEnabled()) { log.info(String.format("Event class name: %s ", type)); } // If member started event is received publish artifact update message // To do a git clone if (InstanceStartedEvent.class.getName().equals(type)) { String json = receivedMessage.getText(); InstanceStartedEvent event = (InstanceStartedEvent) Util.jsonToObject(json, InstanceStartedEvent.class); String clusterId = event.getClusterId(); if (log.isInfoEnabled()) { log.info("Cluster id: " + clusterId); } Set<CartridgeSubscription> cartridgeSubscriptions = new DataInsertionAndRetrievalManager() .getCartridgeSubscriptionForCluster(clusterId); if (cartridgeSubscriptions == null || cartridgeSubscriptions.isEmpty()) { // No subscriptions, return if (log.isDebugEnabled()) { log.debug("No subscription information found for cluster id " + clusterId); } return; } for (CartridgeSubscription cartridgeSubscription : cartridgeSubscriptions) { // We need to send this event for all types, single tenant and multi tenant. // In an autoscaling scenario, we need to send this event for all existing subscriptions for the newly spawned instance // Also in a case of restarting the agent, this event needs to be sent for all subscriptions for the existing instance if (cartridgeSubscription.getRepository() != null) { InstanceNotificationPublisher publisher = new InstanceNotificationPublisher(); publisher.sendArtifactUpdateEvent(cartridgeSubscription.getRepository(), clusterId, String.valueOf(cartridgeSubscription.getSubscriber().getTenantId())); } else { if (log.isDebugEnabled()) { log.debug("No repository found for subscription with alias: " + cartridgeSubscription.getAlias() + ", type: " + cartridgeSubscription.getType() + ". Not sending the Artifact Updated event"); } } } } } catch (Exception e) { if (log.isErrorEnabled()) { log.error("Could not process instance status message", e); } } }
From source file:org.wso2.mb.integration.tests.amqp.functional.PerMessageAcknowledgementsTestCase.java
/** * This test publishes 10 messages and the subscriber rejects the 8th message and then wait for the redelivered * message./*from ww w. j a va 2 s. co m*/ * * @throws AndesClientConfigurationException * @throws XPathExpressionException * @throws IOException * @throws JMSException * @throws AndesClientException * @throws NamingException */ @Test(groups = { "wso2.mb", "queue" }) public void unacknowledgeMiddleMessageMessageListenerPerAckTestCase() throws AndesClientConfigurationException, XPathExpressionException, IOException, JMSException, AndesClientException, NamingException { long sendCount = 10; final List<String> receivedMessages = new ArrayList<>(); // Creating a consumer client configuration AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(), ExchangeType.QUEUE, "unacknowledgeMiddleMessagePerAckQueue"); consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.PER_MESSAGE_ACKNOWLEDGE); consumerConfig.setAsync(false); // Creating a publisher client configuration AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration( getAMQPPort(), ExchangeType.QUEUE, "unacknowledgeMiddleMessagePerAckQueue"); publisherConfig.setNumberOfMessagesToSend(sendCount); // Creating clients AndesClient consumerClient = new AndesClient(consumerConfig, true); final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0); MessageConsumer receiver = andesJMSConsumer.getReceiver(); receiver.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { try { TextMessage textMessage = (TextMessage) message; if (!textMessage.getText().equals("#7") || receivedMessages.contains(textMessage.getText())) { message.acknowledge(); } receivedMessages.add(textMessage.getText()); andesJMSConsumer.getReceivedMessageCount().incrementAndGet(); } catch (JMSException e) { throw new RuntimeException("Exception occurred when receiving messages.", e); } } }); AndesClient publisherClient = new AndesClient(publisherConfig, true); MessageProducer sender = publisherClient.getPublishers().get(0).getSender(); for (int i = 0; i < sendCount; i++) { TextMessage textMessage = publisherClient.getPublishers().get(0).getSession() .createTextMessage("#" + Integer.toString(i)); sender.send(textMessage); } AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME); log.info("Received Messages : " + receivedMessages); for (int i = 0; i < sendCount; i++) { Assert.assertEquals(receivedMessages.get(i), "#" + Integer.toString(i), "Invalid messages received. #" + Integer.toString(i) + " expected."); } Assert.assertEquals(receivedMessages.get(10), "#7", "Invalid messages received. #7 expected."); Assert.assertEquals(receivedMessages.size(), sendCount + 1, "Message receiving failed."); }
From source file:org.wso2.mb.integration.tests.amqp.functional.PerMessageAcknowledgementsTestCase.java
/** * This test publishes 10 messages and the subscriber rejects a message after each 3 received messages and then wait * for the redelivered message./* ww w. j a v a 2 s .c om*/ * * @throws AndesClientConfigurationException * @throws XPathExpressionException * @throws IOException * @throws JMSException * @throws AndesClientException * @throws NamingException */ @Test(groups = { "wso2.mb", "queue" }) public void oneByOneUnacknowledgeMessageListenerPerAckTestCase() throws AndesClientConfigurationException, XPathExpressionException, IOException, JMSException, AndesClientException, NamingException { long sendCount = 10; final List<String> receivedMessages = new ArrayList<>(); // Creating a consumer client configuration AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(), ExchangeType.QUEUE, "oneByOneUnacknowledgePerAckQueue"); consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.PER_MESSAGE_ACKNOWLEDGE); consumerConfig.setAsync(false); // Creating a publisher client configuration AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration( getAMQPPort(), ExchangeType.QUEUE, "oneByOneUnacknowledgePerAckQueue"); publisherConfig.setNumberOfMessagesToSend(sendCount); // Creating clients AndesClient consumerClient = new AndesClient(consumerConfig, true); final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0); MessageConsumer receiver = andesJMSConsumer.getReceiver(); receiver.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { try { TextMessage textMessage = (TextMessage) message; if (Integer.parseInt(textMessage.getText().split("#")[1]) % 3 != 0 || receivedMessages.contains(textMessage.getText())) { message.acknowledge(); } receivedMessages.add(textMessage.getText()); andesJMSConsumer.getReceivedMessageCount().incrementAndGet(); } catch (JMSException e) { throw new RuntimeException("Exception occurred when receiving messages.", e); } } }); AndesClient publisherClient = new AndesClient(publisherConfig, true); MessageProducer sender = publisherClient.getPublishers().get(0).getSender(); for (int i = 0; i < sendCount; i++) { TextMessage textMessage = publisherClient.getPublishers().get(0).getSession() .createTextMessage("#" + Integer.toString(i)); sender.send(textMessage); } AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME); log.info("Received Messages : " + receivedMessages); for (int i = 0; i < sendCount; i++) { Assert.assertEquals(receivedMessages.get(i), "#" + Integer.toString(i), "Invalid messages received. #" + Integer.toString(i) + " expected."); } Assert.assertEquals(receivedMessages.get(10), "#0", "Invalid messages received. #0 expected."); Assert.assertEquals(receivedMessages.get(11), "#3", "Invalid messages received. #3 expected."); Assert.assertEquals(receivedMessages.get(12), "#6", "Invalid messages received. #6 expected."); Assert.assertEquals(receivedMessages.get(13), "#9", "Invalid messages received. #9 expected."); Assert.assertEquals(receivedMessages.size(), sendCount + 4, "Message receiving failed."); }
From source file:org.wso2.mb.integration.tests.amqp.functional.PerMessageAcknowledgementsTestCase.java
/** * This test publishes 10 messages and the subscriber rejects first 4 messages and then wait for the redelivered * message./*from ww w . j av a 2 s . c o m*/ * * @throws AndesClientConfigurationException * @throws XPathExpressionException * @throws IOException * @throws JMSException * @throws AndesClientException * @throws NamingException */ @Test(groups = { "wso2.mb", "queue" }) public void firstFewUnacknowledgeMessageListenerPerAckTestCase() throws AndesClientConfigurationException, XPathExpressionException, IOException, JMSException, AndesClientException, NamingException { long sendCount = 10; final List<String> receivedMessages = new ArrayList<>(); // Creating a consumer client configuration AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(), ExchangeType.QUEUE, "firstFewUnacknowledgePerAckQueue"); consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.PER_MESSAGE_ACKNOWLEDGE); consumerConfig.setAsync(false); // Creating a publisher client configuration AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration( getAMQPPort(), ExchangeType.QUEUE, "firstFewUnacknowledgePerAckQueue"); publisherConfig.setNumberOfMessagesToSend(sendCount); // Creating clients AndesClient consumerClient = new AndesClient(consumerConfig, true); final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0); MessageConsumer receiver = andesJMSConsumer.getReceiver(); receiver.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { try { TextMessage textMessage = (TextMessage) message; if (Integer.parseInt(textMessage.getText().split("#")[1]) >= 4 || receivedMessages.contains(textMessage.getText())) { message.acknowledge(); } receivedMessages.add(textMessage.getText()); andesJMSConsumer.getReceivedMessageCount().incrementAndGet(); } catch (JMSException e) { throw new RuntimeException("Exception occurred when receiving messages.", e); } } }); AndesClient publisherClient = new AndesClient(publisherConfig, true); MessageProducer sender = publisherClient.getPublishers().get(0).getSender(); for (int i = 0; i < sendCount; i++) { TextMessage textMessage = publisherClient.getPublishers().get(0).getSession() .createTextMessage("#" + Integer.toString(i)); sender.send(textMessage); } AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME); log.info("Received Messages : " + receivedMessages); for (int i = 0; i < sendCount; i++) { Assert.assertEquals(receivedMessages.get(i), "#" + Integer.toString(i), "Invalid messages received. #" + Integer.toString(i) + " expected."); } Assert.assertEquals(receivedMessages.get(10), "#0", "Invalid messages received. #0 expected."); Assert.assertEquals(receivedMessages.get(11), "#1", "Invalid messages received. #1 expected."); Assert.assertEquals(receivedMessages.get(12), "#2", "Invalid messages received. #2 expected."); Assert.assertEquals(receivedMessages.get(13), "#3", "Invalid messages received. #3 expected."); Assert.assertEquals(receivedMessages.size(), sendCount + 4, "Message receiving failed."); }