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.solveapuzzle.mapping.agnostic.JmsMessageListener.java

/**
 * Implementation of <code>MessageListener</code>.
 *//*  w w  w  .ja va2s .c  om*/
public void onMessage(Message message) {
    try {
        int messageCount = message.getIntProperty(JmsMessageProducer.MESSAGE_COUNT);

        logger.info("Processed message '{}'.  value={}", message, messageCount);

        counter.incrementAndGet();

        if (message instanceof TextMessage) {
            TextMessage tm = (TextMessage) message;
            String msg = tm.getText();

            logger.info(" Read Transform property " + message.getStringProperty(TRANSFORM));

            try {

                String parser = tm.getStringProperty(PARSER);
                String key = tm.getStringProperty(TRANSFORM);

                logger.info(" Read Transform propertys " + parser + " " + key);

                String response = engine.onTransformEvent(this.createConfig(parser, key), tm.getText(),
                        Charset.defaultCharset());

                logger.info(" Response " + response);

                logger.info("message ReplyTo ID " + tm.getJMSCorrelationID());

                tm.setJMSDestination(this.outDestination);

                javax.jms.Queue queue = (javax.jms.Queue) tm.getJMSDestination();
                logger.info("ReplyTo Queue name = " + queue.getQueueName());

                tm.clearBody();

                tm.setText(response);
                // Push to response queue

            } catch (MappingException e) {
                logger.error("Mapping exception from transformation ", e);
                // push to mapping error Queue?
                // May be fixable with input xml change or due to data quality, invalid against schema

                throw new RuntimeException(e);
            } catch (ConfigurationException e) {
                logger.error("Configuration exception from transformation", e);
                // Can't fix - dead letter queue - but worth tracing what config went missing?
                throw new RuntimeException(e);
            }

        }
    } catch (JMSException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:eu.eubrazilcc.lvl.storage.security.shiro.BaseAuthorizingRealm.java

public BaseAuthorizingRealm(final CredentialsMatcher credentialsMatcher, final String identityProvider) {
    super(CACHE_MANAGER, credentialsMatcher);
    // enable authentication caching
    setAuthenticationCachingEnabled(true);
    // subscribe to changes in users' permissions
    ACTIVEMQ_CONN.subscribe(permissionChangedTopic(identityProvider), new MessageListener() {
        @Override// w  ww . ja v  a2s .com
        public void onMessage(final Message message) {
            if (message instanceof TextMessage) {
                final TextMessage textMessage = (TextMessage) message;
                try {
                    final String ownerId = textMessage.getText();
                    clearCache(new SimplePrincipalCollection(ownerId, getName()));
                    LOGGER.trace(
                            getName() + " - Cached authorization info was evicted for account: " + ownerId);
                } catch (JMSException e) {
                    LOGGER.error(getName() + " - Failed to read message", e);
                }
            }
        }
    });
}

From source file:net.lr.jmsbridge.BridgeServlet.java

/**
 * Forward HTTP request to a jms queue and listen on a temporary queue for the reply.
 * Connects to the jms server by using the username and password from the HTTP basic auth.
 *//*from w  ww . j  a  v a 2  s  .  com*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String authHeader = req.getHeader("Authorization");
    if (authHeader == null) {
        resp.setHeader("WWW-Authenticate", "Basic realm=\"Bridge\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "auth");
        return;
    }
    UserNameAndPassword auth = extractUserNamePassword(authHeader);
    PrintStream out = new PrintStream(resp.getOutputStream());
    String contextPath = req.getContextPath();
    String uri = req.getRequestURI();
    String queueName = uri.substring(contextPath.length() + 1);
    final StringBuffer reqContent = retrieveRequestContent(req.getReader());

    ConnectionFactory cf = connectionPool.getConnectionFactory(auth);
    JmsTemplate jmsTemplate = new JmsTemplate();
    jmsTemplate.setConnectionFactory(cf);
    jmsTemplate.setReceiveTimeout(10000);
    final Destination replyDest = connectionPool.getReplyDestination(cf, auth);
    jmsTemplate.send(queueName, new MessageCreator() {

        @Override
        public Message createMessage(Session session) throws JMSException {
            TextMessage message = session.createTextMessage(reqContent.toString());
            message.setJMSReplyTo(replyDest);
            return message;
        }

    });
    Message replyMsg = jmsTemplate.receive(replyDest);
    if (replyMsg instanceof TextMessage) {
        TextMessage replyTMessage = (TextMessage) replyMsg;
        try {
            out.print(replyTMessage.getText());
        } catch (JMSException e) {
            JmsUtils.convertJmsAccessException(e);
        }
    }
}

From source file:org.easybatch.jms.JmsIntegrationTest.java

@Test
public void testJmsRecordWriter() throws Exception {
    Context jndiContext = getJndiContext();
    Queue queue = (Queue) jndiContext.lookup("q");
    QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) jndiContext
            .lookup("QueueConnectionFactory");
    QueueConnection queueConnection = queueConnectionFactory.createQueueConnection();
    QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    queueConnection.start();//w  w w .  j a v a2 s. com

    String dataSource = "foo" + LINE_SEPARATOR + "bar";

    aNewJob().reader(new StringRecordReader(dataSource)).processor(new JmsMessageTransformer(queueSession))
            .writer(new JmsQueueRecordWriter(queueConnectionFactory, queue)).call();

    // Assert that queue contains 2 messages: "foo" and "bar"
    QueueBrowser queueBrowser = queueSession.createBrowser(queue);
    Enumeration enumeration = queueBrowser.getEnumeration();

    assertThat(enumeration.hasMoreElements()).isTrue();
    TextMessage message1 = (TextMessage) enumeration.nextElement();
    assertThat(message1.getText()).isEqualTo("foo");

    assertThat(enumeration.hasMoreElements()).isTrue();
    TextMessage message2 = (TextMessage) enumeration.nextElement();
    assertThat(message2.getText()).isEqualTo("bar");

    assertThat(enumeration.hasMoreElements()).isFalse();

    queueSession.close();
    queueConnection.close();
}

From source file:org.easybatch.jms.JmsIntegrationTest.java

@Test
public void testJmsSupport() throws Exception {
    Context jndiContext = getJndiContext();
    QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) jndiContext
            .lookup("QueueConnectionFactory");
    Queue queue = (Queue) jndiContext.lookup("q");

    QueueConnection queueConnection = queueConnectionFactory.createQueueConnection();
    QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    QueueSender queueSender = queueSession.createSender(queue);
    queueConnection.start();/*from   w w  w  .j  ava  2 s  .  co m*/

    //send a regular message to the queue
    TextMessage message = queueSession.createTextMessage();
    message.setText(MESSAGE_TEXT);
    queueSender.send(message);

    //send a poison record to the queue
    queueSender.send(new JmsPoisonMessage());

    Job job = aNewJob().reader(new JmsQueueRecordReader(queueConnectionFactory, queue))
            .filter(new JmsPoisonRecordFilter()).processor(new RecordCollector())
            .jobListener(new JmsQueueSessionListener(queueSession))
            .jobListener(new JmsQueueConnectionListener(queueConnection)).build();

    JobReport jobReport = JobExecutor.execute(job);

    assertThat(jobReport).isNotNull();
    assertThat(jobReport.getParameters().getDataSource()).isEqualTo(EXPECTED_DATA_SOURCE_NAME);
    assertThat(jobReport.getMetrics().getTotalCount()).isEqualTo(2);
    assertThat(jobReport.getMetrics().getFilteredCount()).isEqualTo(1);
    assertThat(jobReport.getMetrics().getSuccessCount()).isEqualTo(1);

    List<JmsRecord> records = (List<JmsRecord>) jobReport.getResult();

    assertThat(records).isNotNull().isNotEmpty().hasSize(1);

    JmsRecord jmsRecord = records.get(0);
    Header header = jmsRecord.getHeader();
    assertThat(header).isNotNull();
    assertThat(header.getNumber()).isEqualTo(1);
    assertThat(header.getSource()).isEqualTo(EXPECTED_DATA_SOURCE_NAME);

    Message payload = jmsRecord.getPayload();
    assertThat(payload).isNotNull().isInstanceOf(TextMessage.class);

    TextMessage textMessage = (TextMessage) payload;
    assertThat(textMessage.getText()).isNotNull().isEqualTo(MESSAGE_TEXT);

}

From source file:org.apache.stratos.messaging.message.receiver.health.stat.HealthStatEventMessageDelegator.java

@Override
public void run() {
    try {//  www. j av a2 s .c  o  m
        if (log.isInfoEnabled()) {
            log.info("Health stat event message delegator started");
        }

        while (!terminated) {
            try {
                TextMessage message = messageQueue.take();

                String messageText = message.getText();
                if (log.isDebugEnabled()) {
                    log.debug("Health event message received: [message] " + messageText);
                }
                EventMessage eventMessage = jsonToEventMessage(messageText);
                if (eventMessage == null) {
                    log.error("Error occurred while extracting message");
                    continue;
                }
                String type = eventMessage.getEventName();
                String json = eventMessage.getMessage();

                if (log.isDebugEnabled()) {
                    log.debug(String.format("Instance notifier event message received from queue: %s", type));
                }

                // Delegate message to message processor chain
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Delegating instance notifier event message: %s", type));
                }
                processorChain.process(type, json, null);
            } catch (Exception e) {
                log.error("Failed to retrieve instance notifier event message", e);
            }
        }
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Instance notifier event message delegator failed", e);
        }
    }
}

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

public void onMessage(Message message) {
    try {//from   www .j  a  va2 s  .c  o  m
        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;
            StAXOMBuilder stAXOMBuilder = new StAXOMBuilder(
                    new ByteArrayInputStream(textMessage.getText().getBytes()));
            org.wso2.carbon.registry.event.core.Message messageToSend = new org.wso2.carbon.registry.event.core.Message();
            messageToSend.setMessage(stAXOMBuilder.getDocumentElement());
            // 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 (XMLStreamException e) {
        log.error("Can not build the xml string", e);
    } catch (EventBrokerException e) {
        log.error("Can not send the notification ", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }

}

From source file:fi.vm.sade.log.client.LoggerJms.java

@Override
public void log(final Tapahtuma tapahtuma) {

    log.debug("log({})", tapahtuma);

    if (jmsTemplate == null) {
        throw new IllegalStateException("LoggerJms - invalid configuration 'jsmTemplate' not available!");
    }//from   ww w.j av a  2  s  .  co  m

    final LogEvent event = new LogEvent(tapahtuma);

    // Convert message to TextMessage with LogEvent as XML in payload
    jmsTemplate.send(new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            TextMessage message = session.createTextMessage();
            message.setText(encode(event));
            log.debug("  sending log message - text={}", message.getText());
            return message;
        }
    });

}

From source file:org.apache.servicemix.wsn.jms.JmsPullPoint.java

@Override
protected synchronized List<NotificationMessageHolderType> getMessages(int max)
        throws ResourceUnknownFault, UnableToGetMessagesFault {
    try {/*from  www  .  jav a  2 s. c  o  m*/
        if (max == 0) {
            max = 256;
        }
        initSession();
        List<NotificationMessageHolderType> messages = new ArrayList<NotificationMessageHolderType>();
        for (int i = 0; i < max; i++) {
            Message msg = consumer.receiveNoWait();
            if (msg == null) {
                break;
            }
            TextMessage txtMsg = (TextMessage) msg;
            StringReader reader = new StringReader(txtMsg.getText());
            Notify notify = (Notify) jaxbContext.createUnmarshaller().unmarshal(reader);
            messages.addAll(notify.getNotificationMessage());
        }
        return messages;
    } catch (JMSException e) {
        log.info("Error retrieving messages", e);
        if (session != null) {
            try {
                session.close();
            } catch (JMSException inner) {
                log.debug("Error closing session", inner);
            } finally {
                session = null;
            }
        }
        UnableToGetMessagesFaultType fault = new UnableToGetMessagesFaultType();
        throw new UnableToGetMessagesFault("Unable to retrieve messages", fault, e);
    } catch (JAXBException e) {
        log.info("Error retrieving messages", e);
        UnableToGetMessagesFaultType fault = new UnableToGetMessagesFaultType();
        throw new UnableToGetMessagesFault("Unable to retrieve messages", fault, e);
    }
}