Example usage for javax.jms Session createTextMessage

List of usage examples for javax.jms Session createTextMessage

Introduction

In this page you can find the example usage for javax.jms Session createTextMessage.

Prototype


TextMessage createTextMessage(String text) throws JMSException;

Source Link

Document

Creates an initialized TextMessage object.

Usage

From source file:org.ahp.core.messaging.AhpJmsProducer.java

public void sendTextMessage(String pTextMessage, AhpJmsDestinationTypes pAhpJmsDestinationTypes,
        AhpJmsDestinationNames pAhpJmsDestinationNames) {
    Connection lConnection = null;
    Session lSession = null;
    try {/*from   w ww .  j a  v  a  2s . c o  m*/
        lConnection = this.mJmsConnectionFactory.createConnection();
        lSession = lConnection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        Destination lDestination = null;
        if (pAhpJmsDestinationTypes.equals(AhpJmsDestinationTypes.Queue))
            lDestination = lSession.createQueue(pAhpJmsDestinationNames.toString());
        else
            lDestination = lSession.createTopic(pAhpJmsDestinationNames.toString());
        MessageProducer lMessageProducer = lSession.createProducer(lDestination);
        lMessageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
        //lMessageProducer.setTimeToLive( timeToLive );
        Message lTextMessage = lSession.createTextMessage(pTextMessage);
        LOGGER.debug("AhpJmsProducer sending message to Destination " + pAhpJmsDestinationNames.toString()
                + " TextMessage :: \n" + pTextMessage);
        lMessageProducer.send(lTextMessage);
        lSession.commit();
    } catch (JMSException exJms) {
        LOGGER.error("", exJms);
    } finally {
        try {
            lConnection.close();
        } catch (JMSException exJms) {
            LOGGER.error("", exJms);
        }
    }
}

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

@Override
protected void sendingApprovalNotification(ApprovalActivity appActivity) throws Exception {
    //send sms notification to approver if need approval OR
    //send sms notification to requester if need revision
    super.sendApprovalSmsnotif(appActivity);

    //initialization
    Gson gson = JsonUtil.getHibernateEntityGsonBuilder().create();
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMMM-yyyy", new Locale(appActivity.getLocale()));
    DecimalFormat decimalFormat = new DecimalFormat("###,###");

    //get all sendCC email address on status approve OR reject
    List<String> ccEmailAddresses = new ArrayList<String>();
    if ((appActivity.getApprovalStatus() == HRMConstant.APPROVAL_STATUS_APPROVED)
            || (appActivity.getApprovalStatus() == HRMConstant.APPROVAL_STATUS_REJECTED)) {
        ccEmailAddresses = super.getCcEmailAddressesOnApproveOrReject(appActivity);
    }//from w w  w.  j  a  v  a  2s  .  co m

    //parsing object data to json, for email purpose
    LoanNewApplication loanNewApplication = gson.fromJson(appActivity.getPendingData(),
            LoanNewApplication.class);
    List<LoanPaymentDetail> loanPaymentDetails = calculateLoanPaymentDetails(
            loanNewApplication.getLoanNewType().getInterest().doubleValue(), loanNewApplication.getTermin(),
            loanNewApplication.getDibursementDate(), loanNewApplication.getNominalPrincipal(),
            loanNewApplication.getLoanNewType().getInterestMethod());

    double nominalInstallment = 0.0;
    double interestInstallment = 0.0;
    double totalNominalInstallment = 0.0;
    for (LoanPaymentDetail loanPaymentDetail : loanPaymentDetails) {
        //angsuran pertama
        nominalInstallment = loanPaymentDetail.getPrincipal();
        interestInstallment = loanPaymentDetail.getInterest();
        totalNominalInstallment = nominalInstallment + interestInstallment;
        break;
    }

    final JSONObject jsonObj = new JSONObject();
    try {
        jsonObj.put("approvalActivityId", appActivity.getId());
        jsonObj.put("ccEmailAddresses", ccEmailAddresses);
        jsonObj.put("locale", appActivity.getLocale());
        jsonObj.put("proposeDate", dateFormat.format(loanNewApplication.getCreatedOn()));
        jsonObj.put("loanSchemaName", loanNewApplication.getLoanNewSchema().getLoanSchemaName());
        jsonObj.put("nominalPrincipal", decimalFormat.format(loanNewApplication.getNominalPrincipal()));
        jsonObj.put("interestRate", loanNewApplication.getLoanNewType().getInterest() + " %");
        jsonObj.put("nominalInstallment", decimalFormat.format(nominalInstallment));
        jsonObj.put("interestInstallment", decimalFormat.format(interestInstallment));
        jsonObj.put("totalNominalInstallment", decimalFormat.format(totalNominalInstallment));
        jsonObj.put("urlLinkToApprove",
                FacesUtil.getRequest().getContextPath() + "" + HRMConstant.LOAN_NEW_APPROVAL_PAGE + ""
                        + "?faces-redirect=true&execution=e" + appActivity.getId());

    } catch (JSONException e) {
        LOGGER.error("Error when create json Object ", e);
    }

    //send messaging, to trigger sending email
    super.jmsTemplateApproval.send(new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createTextMessage(jsonObj.toString());
        }
    });
}

From source file:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java

@Override
public boolean sendMessage(Run<?, ?> build, TaskListener listener, MessageUtils.MESSAGE_TYPE type, String props,
        String content) {/*www .j  a va2  s. c  o m*/
    Connection connection = null;
    Session session = null;
    MessageProducer publisher = null;

    try {
        String ltopic = getTopic();
        if (provider.getAuthenticationMethod() != null && ltopic != null && provider.getBroker() != null) {
            ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory();
            connection = connectionFactory.createConnection();
            connection.start();

            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createTopic(ltopic);
            publisher = session.createProducer(destination);

            TextMessage message;
            message = session.createTextMessage("");
            message.setJMSType(JSON_TYPE);

            message.setStringProperty("CI_NAME", build.getParent().getName());
            message.setStringProperty("CI_TYPE", type.getMessage());
            if (!build.isBuilding()) {
                message.setStringProperty("CI_STATUS",
                        (build.getResult() == Result.SUCCESS ? "passed" : "failed"));
            }

            StrSubstitutor sub = new StrSubstitutor(build.getEnvironment(listener));

            if (props != null && !props.trim().equals("")) {
                Properties p = new Properties();
                p.load(new StringReader(props));
                @SuppressWarnings("unchecked")
                Enumeration<String> e = (Enumeration<String>) p.propertyNames();
                while (e.hasMoreElements()) {
                    String key = e.nextElement();
                    message.setStringProperty(key, sub.replace(p.getProperty(key)));
                }
            }

            message.setText(sub.replace(content));

            publisher.send(message);
            log.info("Sent " + type.toString() + " message for job '" + build.getParent().getName()
                    + "' to topic '" + ltopic + "':\n" + formatMessage(message));
        } else {
            log.severe("One or more of the following is invalid (null): user, password, topic, broker.");
            return false;
        }

    } catch (Exception e) {
        log.log(Level.SEVERE, "Unhandled exception in perform.", e);
    } finally {
        if (publisher != null) {
            try {
                publisher.close();
            } catch (JMSException e) {
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
            }
        }
    }
    return true;
}

From source file:org.dawnsci.commandserver.core.consumer.RemoteSubmission.java

/**
 * Submits the bean onto the server. From there events about this
 * bean are tacked by monitoring the status queue.
 * /*  w  w  w .j av  a 2 s.  c  o m*/
 * @param uri
 * @param bean
 */
public synchronized TextMessage submit(StatusBean bean, boolean prepareBean) throws Exception {

    if (getQueueName() == null || "".equals(getQueueName()))
        throw new Exception("Please specify a queue name!");

    Connection send = null;
    Session session = null;
    MessageProducer producer = null;

    try {
        QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
        send = connectionFactory.createConnection();

        session = send.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(queueName);

        producer = session.createProducer(queue);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);

        ObjectMapper mapper = new ObjectMapper();

        if (getTimestamp() < 1)
            setTimestamp(System.currentTimeMillis());
        if (getPriority() < 1)
            setPriority(1);
        if (getLifeTime() < 1)
            setLifeTime(7 * 24 * 60 * 60 * 1000); // 7 days in ms

        if (prepareBean) {
            if (bean.getUserName() == null)
                bean.setUserName(System.getProperty("user.name"));
            bean.setUniqueId(uniqueId);
            bean.setSubmissionTime(getTimestamp());
        }
        String jsonString = mapper.writeValueAsString(bean);

        TextMessage message = session.createTextMessage(jsonString);

        message.setJMSMessageID(uniqueId);
        message.setJMSExpiration(getLifeTime());
        message.setJMSTimestamp(getTimestamp());
        message.setJMSPriority(getPriority());

        producer.send(message);

        return message;

    } finally {
        if (send != null)
            send.close();
        if (session != null)
            session.close();
        if (producer != null)
            producer.close();
    }

}

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

/**
 * Tests the queue browser. Browses the messages then the consumer tries to receive them. The messages should still
 * be in the queue even when it was browsed.
 *
 * Re-enable once https://issues.apache.org/jira/browse/APLO-226 is fixed.
 *
 * @throws Exception//from w ww . j a v  a2  s  .  c o m
 */
public void testReceiveBrowseReceive() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    connection.start();

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

    // lets consume any outstanding messages from previous test runs
    while (consumer.receive(1000) != null) {
    }

    producer.send(outbound[0]);
    producer.send(outbound[1]);
    producer.send(outbound[2]);

    // Get the first.
    assertEquals(outbound[0], consumer.receive(1000));
    consumer.close();
    //Thread.sleep(200);

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

    // browse the second
    assertTrue("should have received the second message", enumeration.hasMoreElements());
    assertEquals(outbound[1], (Message) enumeration.nextElement());

    // browse the third.
    assertTrue("Should have received the third message", enumeration.hasMoreElements());
    assertEquals(outbound[2], (Message) enumeration.nextElement());

    // There should be no more.
    boolean tooMany = false;
    while (enumeration.hasMoreElements()) {
        LOG.info("Got extra message: " + ((TextMessage) enumeration.nextElement()).getText());
        tooMany = true;
    }
    assertFalse(tooMany);
    browser.close();

    // Re-open the consumer.
    consumer = session.createConsumer(destination);
    // Receive the second.
    assertEquals(outbound[1], consumer.receive(1000));
    // Receive the third.
    assertEquals(outbound[2], consumer.receive(1000));
    consumer.close();

}

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

public void testBrowseReceive() 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 2 s  .c om

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

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

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

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

    // browse the first message
    assertTrue("should have received the first message", enumeration.hasMoreElements());
    assertEquals(outbound[0], (Message) enumeration.nextElement());

    // Receive the first message.
    assertEquals(outbound[0], consumer.receive(1000));
    consumer.close();
    browser.close();
    producer.close();

}

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

public void testQueueBrowserWith2Consumers() throws Exception {
    final int numMessages = 1000;
    //        connection.setAlwaysSyncSend(false);
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    ActiveMQQueue destinationPrefetch10 = new ActiveMQQueue("TEST?jms.prefetchSize=10");
    ActiveMQQueue destinationPrefetch1 = new ActiveMQQueue("TEST?jms.prefetchsize=1");
    connection.start();//w w w . ja  v a2s . c  o  m

    Connection connection2 = factory.createConnection(userName, password);
    connection2.start();
    connections.add(connection2);
    Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);

    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destinationPrefetch10);

    for (int i = 0; i < numMessages; i++) {
        TextMessage message = session.createTextMessage("Message: " + i);
        producer.send(message);
    }

    QueueBrowser browser = session2.createBrowser(destinationPrefetch1);
    Enumeration<Message> browserView = browser.getEnumeration();

    List<Message> messages = new ArrayList<Message>();
    for (int i = 0; i < numMessages; i++) {
        Message m1 = consumer.receive(5000);
        assertNotNull("m1 is null for index: " + i, m1);
        messages.add(m1);
    }

    int i = 0;
    for (; i < numMessages && browserView.hasMoreElements(); i++) {
        Message m1 = messages.get(i);
        Message m2 = browserView.nextElement();
        assertNotNull("m2 is null for index: " + i, m2);
        assertEquals(m1.getJMSMessageID(), m2.getJMSMessageID());
    }

    // currently browse max page size is ignored for a queue browser consumer
    // only guarantee is a page size - but a snapshot of pagedinpending is
    // used so it is most likely more
    assertTrue("got at least our expected minimum in the browser: ", i > 200);

    assertFalse("nothing left in the browser", browserView.hasMoreElements());
    assertNull("consumer finished", consumer.receiveNoWait());
}

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  a2s .  c o m

    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:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java

public void dotestJAASSecurityManagerAuthorizationPositive(String jaasConfigScope, String artemisRoleName)
        throws Exception {

    createArtemisServer(jaasConfigScope);

    Set<Role> roles = new HashSet<>();
    roles.add(new Role(artemisRoleName, true, true, true, true, true, true, true, true, true, true));
    server.getConfiguration().putSecurityRoles(QUEUE_NAME, roles);
    server.start();/*from  w w w  .ja v  a2  s  . com*/

    JmsConnectionFactory jmsConnectionFactory = new JmsConnectionFactory(
            "amqp://localhost:5672?amqp.saslMechanisms=GSSAPI");
    Connection connection = jmsConnectionFactory.createConnection("client", null);

    try {
        connection.start();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        javax.jms.Queue queue = session.createQueue(QUEUE_NAME);

        // PRODUCE
        final String text = RandomUtil.randomString();

        try {
            MessageProducer producer = session.createProducer(queue);
            producer.send(session.createTextMessage(text));
        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail("should not throw exception here");
        }

        // CONSUME
        try {
            MessageConsumer consumer = session.createConsumer(queue);
            TextMessage m = (TextMessage) consumer.receive(1000);
            Assert.assertNotNull(m);
            Assert.assertEquals(text, m.getText());
        } catch (Exception e) {
            Assert.fail("should not throw exception here");
        }
    } finally {
        connection.close();
    }
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testQueueLargeMessageSize() throws Exception {

    ActiveMQConnectionFactory acf = (ActiveMQConnectionFactory) cf;
    acf.setMinLargeMessageSize(1000);// w  ww  .  j  ava  2s  . co  m
    Connection connection = cf.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    String testText = StringUtils.repeat("t", 5000);
    ActiveMQTextMessage message = (ActiveMQTextMessage) session.createTextMessage(testText);
    session.createProducer(session.createQueue(defaultQueueName)).send(message);

    verifyPendingStats(defaultQueueName, 1, message.getCoreMessage().getPersistentSize());
    verifyPendingDurableStats(defaultQueueName, 1, message.getCoreMessage().getPersistentSize());

    connection.close();

    this.killServer();
    this.restartServer();

    verifyPendingStats(defaultQueueName, 1, message.getCoreMessage().getPersistentSize());
    verifyPendingDurableStats(defaultQueueName, 1, message.getCoreMessage().getPersistentSize());

}