List of usage examples for javax.jms TextMessage getText
String getText() throws JMSException;
From source file:com.inkubator.hrm.service.impl.CalculatePasswordComplexityCronListenerServiceImpl.java
@Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class) public void onMessage(Message msg) { SchedulerLog log = null;/*from w w w.ja va 2 s . c o m*/ try { TextMessage textMessage = (TextMessage) msg; log = schedulerLogDao.getEntiyByPK(Long.parseLong(textMessage.getText())); calculatePasswordComplexity(); log.setStatusMessages("FINISH"); super.doUpdateSchedulerLogSchedulerLog(log); } catch (Exception ex) { if (log != null) { log.setStatusMessages(ex.getMessage()); super.doUpdateSchedulerLogSchedulerLog(log); } LOGGER.error(ex, ex); } }
From source file:org.fusesource.fabric.itests.paxexam.mq.MQDistroTest.java
@Test public void testMQ() throws Exception { // send message via webconsole, consume from jms openwire HttpClient client = new HttpClient(); // set credentials client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD)); // need to first get the secret GetMethod get = new GetMethod(WEB_CONSOLE_URL + "send.jsp"); get.setDoAuthentication(true);// ww w .j ava2 s .c om // Give console some time to start for (int i = 0; i < 20; i++) { Thread.currentThread().sleep(1000); try { i = client.executeMethod(get); } catch (java.net.ConnectException ignored) { } } assertEquals("get succeeded on " + get, 200, get.getStatusCode()); String response = get.getResponseBodyAsString(); final String secretMarker = "<input type=\"hidden\" name=\"secret\" value=\""; String secret = response.substring(response.indexOf(secretMarker) + secretMarker.length()); secret = secret.substring(0, secret.indexOf("\"/>")); final String destination = "validate.console.send"; final String content = "Hi for the " + Math.random() + "' time"; PostMethod post = new PostMethod(WEB_CONSOLE_URL + "sendMessage.action"); post.setDoAuthentication(true); post.addParameter("secret", secret); post.addParameter("JMSText", content); post.addParameter("JMSDestination", destination); post.addParameter("JMSDestinationType", "queue"); // execute the send assertEquals("post succeeded, " + post, 302, client.executeMethod(post)); // consume what we sent ActiveMQConnection connection = (ActiveMQConnection) new ActiveMQConnectionFactory() .createConnection(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD); connection.start(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); TextMessage textMessage = (TextMessage) session.createConsumer(new ActiveMQQueue(destination)) .receive(10 * 1000); assertNotNull("got a message", textMessage); assertEquals("it is ours", content, textMessage.getText()); } finally { connection.close(); } // verify osgi registration of cf ConnectionFactory connectionFactory = getOsgiService(ConnectionFactory.class); assertTrue(connectionFactory instanceof ActiveMQConnectionFactory); ActiveMQConnection connectionFromOsgiFactory = (ActiveMQConnection) connectionFactory .createConnection(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD); connectionFromOsgiFactory.start(); try { assertEquals("same broker", connection.getBrokerName(), connectionFromOsgiFactory.getBrokerName()); } finally { connectionFromOsgiFactory.close(); } // verify mq-client Process process = Runtime.getRuntime() .exec("java -jar extras" + File.separator + "mq-client.jar producer --count 1 --user " + USER_NAME_ND_PASSWORD + " --password " + USER_NAME_ND_PASSWORD, null, // env new File(System.getProperty("user.dir"))); process.waitFor(); assertEquals("producer worked, exit(0)?", 0, process.exitValue()); process = Runtime.getRuntime() .exec("java -jar extras" + File.separator + "mq-client.jar consumer --count 1 --user " + USER_NAME_ND_PASSWORD + " --password " + USER_NAME_ND_PASSWORD, null, // env new File(System.getProperty("user.dir"))); process.waitFor(); assertEquals("consumer worked, exit(0)?", 0, process.exitValue()); }
From source file:com.inkubator.hrm.service.impl.NotificationApproverSmsMessagesListener.java
@Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, timeout = 50, rollbackFor = Exception.class) public void onMessage(Message message) { String approverNumber = StringUtils.EMPTY; String notifMessage = StringUtils.EMPTY; try {//w ww.jav a 2s . com TextMessage textMessage = (TextMessage) message; String json = textMessage.getText(); approverNumber = jsonConverter.getValueByKey(json, "senderNumber"); HrmUser approver = hrmUserDao.getEntityByPhoneNumber("+" + approverNumber); String content = jsonConverter.getValueByKey(json, "smsContent"); String[] arrContent = StringUtils.split(content, "#"); notifMessage = StringUtils.EMPTY; ApprovalActivity approvalActivity = StringUtils.isNumeric(arrContent[0]) ? approvalActivityDao.getEntiyByPK(Long.parseLong(arrContent[0])) : null; /** validation */ if (approver == null) { notifMessage = "Maaf, No Telepon tidak terdaftar "; } else if (arrContent.length != 3) { notifMessage = "Maaf, format tidak sesuai dengan standard : ApprovalActivityID#YES/NO/REVISI#COMMENT "; } else if (!(StringUtils.equalsIgnoreCase(arrContent[1], "YES") || StringUtils.equalsIgnoreCase(arrContent[1], "NO") || StringUtils.equalsIgnoreCase(arrContent[1], "REVISI"))) { notifMessage = "Maaf, format tidak sesuai dengan standard : ApprovalActivityID#YES/NO/REVISI#COMMENT "; } else if (!StringUtils.isNumeric(arrContent[0])) { notifMessage = "Maaf, Approval Activity ID tidak terdaftar"; } else if (approvalActivity == null) { notifMessage = "Maaf, approval activity ID tidak terdaftar"; } else if (!StringUtils.equals(approvalActivity.getApprovedBy(), approver.getUserId())) { notifMessage = "Maaf, No Telpon ini tidak berhak untuk melakukan approval"; } else if (approvalActivity.getApprovalStatus() != HRMConstant.APPROVAL_STATUS_WAITING_APPROVAL) { notifMessage = "Maaf, permintaan tidak dapat di proses karena status Approval sudah berubah"; } /** proses approval, jika memenuhi validasi */ if (StringUtils.isEmpty(notifMessage)) { if (StringUtils.equalsIgnoreCase(arrContent[1], "YES")) { /** do Approved */ switch (approvalActivity.getApprovalDefinition().getName()) { case HRMConstant.BUSINESS_TRAVEL: businessTravelService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.LOAN: loanNewApplicationService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.REIMBURSEMENT: rmbsApplicationService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.REIMBURSEMENT_DISBURSEMENT: rmbsDisbursementService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.SHIFT_SCHEDULE: tempJadwalKaryawanService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.LEAVE: leaveImplementationService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.LEAVE_CANCELLATION: leaveImplementationService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.ANNOUNCEMENT: announcementService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.EMP_CORRECTION_ATTENDANCE: wtEmpCorrectionAttendanceService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.VACANCY_ADVERTISEMENT: recruitVacancyAdvertisementService.approved(approvalActivity.getId(), null, arrContent[2]); break; case HRMConstant.EMPLOYEE_CAREER_TRANSITION: empCareerHistoryService.approved(approvalActivity.getId(), null, arrContent[2]); break; default: break; } notifMessage = "Terima kasih, permintaan untuk disetujui telah di proses"; } else if (StringUtils.equalsIgnoreCase(arrContent[1], "NO")) { /** do Rejected */ switch (approvalActivity.getApprovalDefinition().getName()) { case HRMConstant.BUSINESS_TRAVEL: businessTravelService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.LOAN: loanNewApplicationService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.REIMBURSEMENT: rmbsApplicationService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.REIMBURSEMENT_DISBURSEMENT: rmbsDisbursementService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.SHIFT_SCHEDULE: tempJadwalKaryawanService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.LEAVE: leaveImplementationService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.LEAVE_CANCELLATION: leaveImplementationService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.ANNOUNCEMENT: announcementService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.EMP_CORRECTION_ATTENDANCE: wtEmpCorrectionAttendanceService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.VACANCY_ADVERTISEMENT: recruitVacancyAdvertisementService.rejected(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.EMPLOYEE_CAREER_TRANSITION: empCareerHistoryService.rejected(approvalActivity.getId(), arrContent[2]); break; default: break; } notifMessage = "Terima kasih, permintaan untuk ditolak telah di proses"; } else if (StringUtils.equalsIgnoreCase(arrContent[1], "REVISI")) { /** do Asking Revised */ switch (approvalActivity.getApprovalDefinition().getName()) { case HRMConstant.LOAN: loanNewApplicationService.askingRevised(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.REIMBURSEMENT: rmbsApplicationService.askingRevised(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.REIMBURSEMENT_DISBURSEMENT: rmbsDisbursementService.askingRevised(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.ANNOUNCEMENT: announcementService.askingRevised(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.EMP_CORRECTION_ATTENDANCE: wtEmpCorrectionAttendanceService.askingRevised(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.VACANCY_ADVERTISEMENT: recruitVacancyAdvertisementService.askingRevised(approvalActivity.getId(), arrContent[2]); break; case HRMConstant.EMPLOYEE_CAREER_TRANSITION: empCareerHistoryService.askingRevised(approvalActivity.getId(), arrContent[2]); break; default: /** Tidak semua module implement asking revised, jika belum/tidak implement maka kirim sms balik ke sender untuk notifikasi */ notifMessage = "Maaf, permintaan untuk \"REVISI\" tidak dapat diproses. Hanya bisa melakukan proses \"YES\" atau \"NO\""; break; } if (StringUtils.isEmpty(notifMessage)) { notifMessage = "Terima kasih, permintaan untuk direvisi telah di proses"; } } } } catch (Exception ex) { notifMessage = "Maaf, permintaan tidak dapat di proses, ada kegagalan di sistem. Mohon ulangi proses via aplikasi web atau hubungi Administrator"; LOGGER.error("Error", ex); } /** kirim sms balik ke sender untuk notifikasi messagenya */ final SMSSend mSSend = new SMSSend(); LOGGER.error("Info SMS " + notifMessage); mSSend.setFrom(HRMConstant.SYSTEM_ADMIN); mSSend.setDestination("+" + approverNumber); mSSend.setContent(notifMessage); //Send notificatin SMS this.jmsTemplateSMS.send(new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { return session.createTextMessage(jsonConverter.getJson(mSSend)); } }); }
From source file:TopicReplier.java
/** * Handle the message.// w ww. j a v a 2 s.c o m * (as specified in the javax.jms.MessageListener interface). * * IMPORTANT NOTE: 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 topic specified there. * Failing to follow these steps might leave the originator * of the request waiting forever. * * 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 topic javax.jms.Topic replyTopic = (javax.jms.Topic) aMessage.getJMSReplyTo(); if (replyTopic != null) { // Send the modified message back. javax.jms.TextMessage reply = session.createTextMessage(); if (imode == UPPERCASE) reply.setText("Transformed " + string + " to all uppercase: " + string.toUpperCase()); else reply.setText("Transformed " + string + " to all lowercase " + string.toLowerCase()); reply.setJMSCorrelationID(aMessage.getJMSMessageID()); replier.send(replyTopic, reply); session.commit(); } } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } } catch (java.lang.RuntimeException rte) { rte.printStackTrace(); } }
From source file:eu.europa.ec.fisheries.uvms.rules.service.bean.RulesActivityServiceBean.java
public boolean checkSubscriptionPermissions(String request, MessageType type) { try {// w ww. j av a 2 s . c o m String requestStr = ActivityModuleRequestMapper.mapToSubscriptionRequest(request, type); String jmsCorrelationId = producer.sendDataSourceMessage(requestStr, DataSourceQueue.ACTIVITY); TextMessage message = consumer.getMessage(jmsCorrelationId, TextMessage.class); SubscriptionPermissionResponse subscriptionPermissionResponse = SubscriptionModuleResponseMapper .mapToSubscriptionPermissionResponse(message.getText()); SubscriptionPermissionAnswer subscriptionCheck = subscriptionPermissionResponse.getSubscriptionCheck(); return SubscriptionPermissionAnswer.YES.equals(subscriptionCheck); } catch (MessageException | ActivityModelMapperException | JMSException | JAXBException e) { log.error("[ERROR] while trying to check subscription permissions..", e); } return false; }
From source file:org.wso2.mb.integration.common.clients.operations.queue.QueueMessageListener.java
public void onMessage(Message message) { messageCount.incrementAndGet();//from w w w .j a v a 2 s. 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:tools.ConsumerTool.java
public void handleMessage(Session session, Message message, int perConsumerReceivedMessages) { try {// www .j a v a 2 s . co m if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; String text = textMessage.getText(); LOGGER.info("Received text message: " + text); } else { LOGGER.info("Received message: " + message); } if (perMessageSleepMS > 0) { try { Thread.sleep(perMessageSleepMS); } catch (InterruptedException e) { LOGGER.debug("Interrupted while sleeping", e); } } if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE) { if (perConsumerReceivedMessages % batchSize == 0) { message.acknowledge(); } } if (transacted) { if (perConsumerReceivedMessages % batchSize == 0) { session.commit(); } } } catch (JMSException e) { LOGGER.error("JMSException handling message: " + e.getMessage(), e); } }
From source file:fr.xebia.sample.springframework.jms.requestreply.RequestReplyClientInvoker.java
/** * Request/Reply SpringFramework sample. * /*from w ww .j a v a 2s .c o m*/ * @param request * sent to the remote service * @return reply returned by the remote service * @throws JMSException */ public String requestReply(String request) throws JMSException { Connection connection = connectionFactory.createConnection(); try { connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); try { MessageProducer messageProducer = session.createProducer(this.requestDestination); try { Message requestMessage = session.createTextMessage(request); requestMessage.setJMSReplyTo(this.replyToDestination); // requestMessage.setJMSCorrelationID(String.valueOf(random.nextLong())); messageProducer.send(requestMessage); String messageSelector = "JMSCorrelationID LIKE '" + requestMessage.getJMSMessageID() + "'"; MessageConsumer messageConsumer = session.createConsumer(this.replyToDestination, messageSelector); TextMessage replyMessage = (TextMessage) messageConsumer.receive(timeoutInMillis); Assert.notNull(replyMessage, "Timeout waiting for jms response"); logger.debug( "requestReply " + "\r\nrequest : " + requestMessage + "\r\nreply : " + replyMessage); String result = replyMessage.getText(); logger.debug("requestReply('" + request + "'): '" + result + "'"); return result; } finally { JmsUtils.closeMessageProducer(messageProducer); } } finally { JmsUtils.closeSession(session); } } finally { JmsUtils.closeConnection(connection); } }
From source file:org.apache.servicemix.jms.JmsConsumerEndpointTest.java
public void testConsumerDefaultInOut() 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.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 w w . ja v a 2 s. c o m }
From source file:Talk.java
/** * Handle the message// w w w. ja va 2 s. c om * (as specified in the javax.jms.MessageListener interface). */ public void onMessage(javax.jms.Message aMessage) { try { // Cast the message as a text message. // Otherwise report that invalid message arrived. if (aMessage instanceof javax.jms.TextMessage) { 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(); } } else { System.out.println("Warning: A message was discarded because it could not be processed " + "as a javax.jms.TextMessage."); } } catch (java.lang.RuntimeException rte) { rte.printStackTrace(); } }