Example usage for javax.jms TextMessage getText

List of usage examples for javax.jms TextMessage getText

Introduction

In this page you can find the example usage for javax.jms TextMessage getText.

Prototype


String getText() throws JMSException;

Source Link

Document

Gets the string containing this message's data.

Usage

From source file:com.provenance.cloudprovenance.connector.policy.PolicyEventConsumer.java

/** Method called when a new message arrives */
public void onMessage(final Message message) {

    final String outcome;

    logger.info("Received policy request message = " + counter++);

    // Check if the message is a text message
    if (message instanceof TextMessage) {
        TextMessage textMessage = (TextMessage) message;
        String policyRequest = null;
        try {//from w ww  .ja va 2  s  . co m
            policyRequest = textMessage.getText();

            logger.info("Sending  poicy request: " + policyRequest + " .....");
            String response = poEnforcement.policyRequest(serviceID, policyRequest);

            logger.info("Response received for policy request: " + response);

            String responsURI = resExtraction.getResponseURI(response);

            logger.debug("Sucessfully extracted response message URI from the policy execution: " + responsURI);

            outcome = poEnforcement.policyResponse(serviceID, new URL(responsURI));

            logger.info("Successfully retrieved a policy response: " + outcome);

            logger.info(
                    "Sending the retrieved response to a Queue for a client to read: " + outcome + " ......");

            jmsTemplate.send(responsePolicyQueueName, new MessageCreator() {

                public Message createMessage(Session session) throws JMSException {
                    TextMessage message = session.createTextMessage(outcome);
                    return message;
                }
            });

            logger.info("Successfully sent the response via the JMS queue to a client");

        } catch (JMSException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        logger.warn("Message received, but unable to process : " + message + " ... !");
    }
}

From source file:org.wso2.carbon.andes.event.core.internal.delivery.jms.JMSMessageListener.java

/**
 * Fire when message receive and send notification to carbon notification manager
 *
 * @param message message/* w  w  w  .ja  va2s .  c o m*/
 */
public void onMessage(Message message) {
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(this.subscription.getTenantId());
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.subscription.getOwner());
        PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true);
        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            org.wso2.carbon.andes.event.core.Message messageToSend = new org.wso2.carbon.andes.event.core.Message();
            messageToSend.setMessage(textMessage.getText());
            // set the properties
            Enumeration propertyNames = message.getPropertyNames();
            String key = null;
            while (propertyNames.hasMoreElements()) {
                key = (String) propertyNames.nextElement();
                messageToSend.addProperty(key, message.getStringProperty(key));
            }

            this.notificationManager.sendNotification(messageToSend, this.subscription);
        } else {
            log.warn("Non text message received");
        }
    } catch (JMSException e) {
        log.error("Can not read the text message ", e);
    } catch (EventBrokerException e) {
        log.error("Can not send the notification ", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }

}

From source file:com.provenance.cloudprovenance.eventhandler.service.EventProducer.java

public String sendToQueue(final String eventTypeDestination, final String resourceElements) {

    String policyResponseMsg = null;
    final String IGNORE_RECEIVE_QUEUE = "traceabilityQueue";

    jmsTemplate.send(eventTypeDestination, new MessageCreator() {

        public Message createMessage(Session session) throws JMSException {
            TextMessage message = session.createTextMessage(resourceElements);
            return message;
        }/*  w  w w. ja  v  a2  s.  c  o m*/
    });

    logger.info("Message sent: " + resourceElements);

    if (!(eventTypeDestination.equals(IGNORE_RECEIVE_QUEUE))) {

        logger.info("waiting for response message from queue: " + responsePolicyQueueName);
        jmsTemplate.setReceiveTimeout(5000);
        Message message = jmsTemplate.receive(responsePolicyQueueName);

        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            try {
                policyResponseMsg = textMessage.getText();

                logger.info("Message received: " + policyResponseMsg);
                return policyResponseMsg;

            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
        // it is a traceability event, i.e asynchronized
    } else if (eventTypeDestination.equals(IGNORE_RECEIVE_QUEUE)) {
        // need to return the policy id

        // if a response is needed from the store record (i.e synchronized)
        if (traceabilityStoreStorageAck) {
            // wait for a response;

            logger.info(
                    "waiting for a traceability response message from queue: " + responseTraceabilityQueueName);
            jmsTemplate.setReceiveTimeout(5000);
            Message message = jmsTemplate.receive(responseTraceabilityQueueName);

            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                try {
                    String traceabilityResponseMsg = textMessage.getText();

                    logger.info("Message received, Id : " + traceabilityResponseMsg);
                    return traceabilityResponseMsg;

                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
        return "traceability stored successfully";

    }
    // did not recognise the message
    return null;
}

From source file:com.inkubator.hrm.service.impl.NotificationEmailRecruitmentSelectionScheduleMessagesListener.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/* ww w. j  ava2 s.c o  m*/
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, timeout = 50, rollbackFor = Exception.class)
public void onMessage(Message message) {
    try {
        LOGGER.info("Begin Send Email Recruitment Selection Schedule");
        TextMessage textMessage = (TextMessage) message;
        String json = textMessage.getText();
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy");
        SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm:ss");
        RecruitSelectionApplicantSchedulleDetailHistory scheduleDetailHistory = (RecruitSelectionApplicantSchedulleDetailHistory) jsonConverter
                .getClassFromJson(json, RecruitSelectionApplicantSchedulleDetailHistory.class);
        RecruitSelectionApplicantSchedulleDetailHistory scheduleDetailHistoryFromDb = recruitSelectionApplicantSchedulleDetailHistoryDao
                .getEntiyByPK(scheduleDetailHistory.getId());
        String locale = "in";
        if (scheduleDetailHistoryFromDb.getEmailNotification() == 0) {
            RecruitApplicant applicant = recruitApplicantDao
                    .getEntityByPkWithDetail(scheduleDetailHistoryFromDb.getApplicantId());
            EmpData empData = empDataDao.getByIdWithBioData(scheduleDetailHistoryFromDb.getPicEmpId());

            VelocityTempalteModel vtm = new VelocityTempalteModel();
            List<String> toSend = new ArrayList<>();
            List<String> toSentCC = new ArrayList<String>();
            List<String> toSentBCC = new ArrayList<String>();

            vtm.setFrom(ownerEmail);
            toSend.add(scheduleDetailHistoryFromDb.getEmailAddress());
            toSentCC.add("deni.arianto1606@gmail.com");
            toSentCC.add("rizal2_dhfr@yahoo.com");
            //                 toSentCC.add("yosa.mareta@gmail.com");
            toSentCC.add("guntur@incubatechnology.com");
            toSentCC.add("rizkykojek@gmail.com");
            toSentCC.add("amjadicky@gmail.com");
            vtm.setTo(toSend.toArray(new String[toSend.size()]));
            vtm.setCc(toSentCC.toArray(new String[toSentCC.size()]));
            vtm.setBcc(toSentBCC.toArray(new String[toSentBCC.size()]));

            Map maptoSend = new HashMap();
            if (StringUtils.equals(locale, "en")) {
                //not yet implemented

            } else {

                /* maptoSend.put("ownerAdministrator", ownerAdministrator);
                 maptoSend.put("ownerCompany", ownerCompany);
                 maptoSend.put("applicationUrl", applicationUrl);
                 maptoSend.put("applicationName", applicationName);
                 velocityTemplateSender.sendMail(vtm, maptoSend);*/

                //update scheduleDetailHistory, set EmailNotification == 1
                if (scheduleDetailHistoryFromDb.getEmailNotification() == 0) {
                    scheduleDetailHistoryFromDb.setEmailNotification(1);
                    this.recruitSelectionApplicantSchedulleDetailHistoryDao.update(scheduleDetailHistoryFromDb);
                }
            }
        }

    } catch (Exception ex) {
        LOGGER.error("Error", ex);
    }
}

From source file:TopicRequestor.java

/** Create JMS client for publishing and subscribing to messages. */
private void start(String broker, String username, String password) {
    // Create a connection.
    try {//from w  w  w  .  j  av a  2s. c o  m
        javax.jms.TopicConnectionFactory factory;
        factory = new ActiveMQConnectionFactory(username, password, broker);
        connect = factory.createTopicConnection(username, password);
        session = connect.createTopicSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
    } catch (javax.jms.JMSException jmse) {
        System.err.println("error: Cannot connect to Broker - " + broker);
        jmse.printStackTrace();
        System.exit(1);
    }

    // Create Topic for all requests.  TopicRequestor will be created
    // as needed.
    javax.jms.Topic topic = null;
    try {
        topic = session.createTopic(APP_TOPIC);
        // Now that all setup is complete, start the Connection
        connect.start();
    } catch (javax.jms.JMSException jmse) {
        jmse.printStackTrace();
    }
    try {
        // Read all standard input and send it as a message.
        java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
        System.out.println("\nRequestor application:\n" + "============================\n"
                + "The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME
                + ".\n" + "The application uses a TopicRequestor to on the " + APP_TOPIC + " topic."
                + "The Replier application gets the message, and transforms it."
                + "The Requestor application displays the result.\n\n"
                + "Type some mixed case text, and then press Enter to make a request.\n");
        while (true) {
            String s = stdin.readLine();

            if (s == null)
                exit();
            else if (s.length() > 0) {
                javax.jms.TextMessage msg = session.createTextMessage();
                msg.setText(username + ": " + s);
                // Instead of publishing, we will use a TopicRequestor.
                javax.jms.TopicRequestor requestor = new javax.jms.TopicRequestor(session, topic);
                javax.jms.Message response = requestor.request(msg);
                // The message should be a TextMessage.  Just report it.
                javax.jms.TextMessage textMessage = (javax.jms.TextMessage) response;
                System.out.println("[Reply] " + textMessage.getText());
            }
        }
    } catch (java.io.IOException ioe) {
        ioe.printStackTrace();
    } catch (javax.jms.JMSException jmse) {
        jmse.printStackTrace();
    }
}

From source file:com.oneops.controller.jms.CmsListenerTest.java

@Test
public void msgRelease() throws Exception {
    TextMessage message = mock(TextMessage.class);
    when(message.getStringProperty("source")).thenReturn("release");
    String msgJson = gson.toJson(createCmsRelease("active"));
    when(message.getText()).thenReturn(msgJson);

    listener.onMessage(message);// w  ww .j  a v  a2 s. c  o  m
    //once more to get a SKIP
    when(message.getText()).thenReturn(gson.toJson(createCmsRelease("aintactive")));
    listener.onMessage(message);
}

From source file:de.taimos.dvalin.interconnect.core.spring.DaemonEvents.java

@Override
public void onMessage(final Message message) {
    final String icoClass;
    try {//from  ww w  . ja v  a2 s  .  c o m
        icoClass = message.getStringProperty(InterconnectConnector.HEADER_ICO_CLASS); // can be null
    } catch (final Exception e) {
        this.logger.error("Exception", e);
        return;
    }
    try {
        if (message instanceof TextMessage) {
            final TextMessage textMessage = (TextMessage) message;
            this.logger.debug("TextMessage received: {}", textMessage.getText());
            if (MessageConnector.isMessageSecure(textMessage)) {
                MessageConnector.decryptMessage(textMessage);
            }
            final InterconnectObject ico;
            try {
                ico = InterconnectMapper.fromJson(textMessage.getText());
            } catch (final Exception e) {
                this.logEventError(icoClass, "Event not supported", e);
                return;
            }
            if (ico instanceof IVO) {
                this.emit((IVO) ico);
            } else {
                this.logEventError(icoClass, "Event not an IVO", null);
            }
        } else {
            this.logEventError(icoClass, "Event not a TextMessage", null);
        }
    } catch (final Exception e) {
        // we are in non transactional wonderland so we catch the exception which leads to a lost event.
        this.logEventError(icoClass, "Exception", e);
    }
}

From source file:com.amalto.core.storage.task.staging.ClusteredStagingTaskManager.java

@Override
public void onMessage(Message message) {
    if (message instanceof TextMessage) {
        TextMessage txtMessage = (TextMessage) message;
        String txt = StringUtils.EMPTY;
        try {/*from  www. j a  v a 2 s  . c  om*/
            txt = txtMessage.getText();
            StagingJobCancellationMessage cancellationMessage = StagingJobCancellationMessage.fromString(txt);
            if (cancellationMessage != null && cancellationMessage.getDataContainer() != null
                    && cancellationMessage.getTaskId() != null) {
                this.cancelTask(cancellationMessage.getDataContainer(), cancellationMessage.getTaskId(), false);
            } else {
                LOGGER.error("Received an invalid JMS cancellation message " + txt + " forgetting it.");
            }
        } catch (JAXBException e) {
            LOGGER.error("Received an unparsable JMS text message [" + txt + "] forgetting it.");
        } catch (JMSException e) {
            LOGGER.error("JMS Exception when reading message. Resending it", e);
            throw new RuntimeException(e);
        }
    } else {
        LOGGER.error("Received an unsupported JMS message " + message + " forgetting it.");
    }
}

From source file:org.apache.activemq.apollo.JmsQueueBrowserTest.java

public void testBrowseClose() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");

    connection.start();/*from w w  w .  j a v a 2s.  com*/

    TextMessage[] outbound = new TextMessage[] { session.createTextMessage("First Message"),
            session.createTextMessage("Second Message"), session.createTextMessage("Third Message") };

    MessageProducer producer = session.createProducer(destination);
    producer.send(outbound[0]);
    producer.send(outbound[1]);
    producer.send(outbound[2]);

    // create browser first
    QueueBrowser browser = session.createBrowser((Queue) destination);
    Enumeration enumeration = browser.getEnumeration();

    // browse some messages
    assertEquals(outbound[0], (Message) enumeration.nextElement());
    assertEquals(outbound[1], (Message) enumeration.nextElement());
    //assertEquals(outbound[2], (Message) enumeration.nextElement());

    browser.close();

    // create consumer
    MessageConsumer consumer = session.createConsumer(destination);

    // Receive the first message.
    TextMessage msg = (TextMessage) consumer.receive(1000);
    assertEquals("Expected " + outbound[0].getText() + " but received " + msg.getText(), outbound[0], msg);
    msg = (TextMessage) consumer.receive(1000);
    assertEquals("Expected " + outbound[1].getText() + " but received " + msg.getText(), outbound[1], msg);
    msg = (TextMessage) consumer.receive(1000);
    assertEquals("Expected " + outbound[2].getText() + " but received " + msg.getText(), outbound[2], msg);

    consumer.close();
    producer.close();

}

From source file:ProducerTool.java

protected void sendLoop(Session session, MessageProducer producer) throws Exception {

    for (int i = 0; i < messageCount || messageCount == 0; i++) {

        TextMessage message = session.createTextMessage(createMessageText(i));

        if (verbose) {
            String msg = message.getText();
            if (msg.length() > 50) {
                msg = msg.substring(0, 50) + "...";
            }// w  w  w.  j  ava 2s.c o  m
            System.out.println("[" + this.getName() + "] Sending message: '" + msg + "'");
        }

        producer.send(message);

        if (transacted && (i % batch == 0)) {
            System.out.println("[" + this.getName() + "] Committing " + messageCount + " messages");
            session.commit();
        }
        Thread.sleep(sleepTime);
    }
}