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:com.inkubator.hrm.service.impl.TempJadwalKaryawanServiceImpl.java

@Override
public 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
    SimpleDateFormat jsonDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm");
    JsonObject jsonObject = (JsonObject) jsonConverter.getClassFromJson(appActivity.getPendingData(),
            JsonObject.class);
    Date createdOn = jsonDateFormat.parse(jsonObject.get("createDate").getAsString());

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

    final JSONObject jsonObj = new JSONObject();
    try {
        jsonObj.put("approvalActivityId", appActivity.getId());
        jsonObj.put("ccEmailAddresses", ccEmailAddresses);
        jsonObj.put("locale", appActivity.getLocale());
        jsonObj.put("proposeDate", new SimpleDateFormat("dd-MMMM-yyyy").format(createdOn));
        jsonObj.put("urlLinkToApprove",
                FacesUtil.getRequest().getContextPath() + "" + HRMConstant.EMP_WORK_SCHEDULE_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.datatorrent.lib.io.jms.JMSStringInputOperatorTest.java

private void produceMsg(int numMessages) throws Exception {
    // Create a ConnectionFactory
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");

    // Create a Connection
    Connection connection = connectionFactory.createConnection();
    connection.start();// w w  w  .j  a v  a  2s  . co m

    // Create a Session
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

    // Create the destination (Topic or Queue)
    Destination destination = session.createQueue("TEST.FOO");

    // Create a MessageProducer from the Session to the Topic or Queue
    MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

    // Create a messages
    String text = "Hello world! From tester producer";
    TextMessage message = session.createTextMessage(text);
    for (int i = 0; i < numMessages; i++) {
        producer.send(message);
    }

    // Clean up
    session.close();
    connection.close();

}

From source file:de.klemp.middleware.controller.Controller.java

/**
 * This method creates a connection to the message broker Active MQ and
 * sends the message to the given topic. The method is used by all methods
 * of the second component./*  w  ww.j a va 2  s. c  o  m*/
 * 
 * @param message
 *            send to the output device
 * @param topic
 *            of the message broker
 */
public static void sendMessage(String message, String topic) {
    String url = ActiveMQConnection.DEFAULT_BROKER_URL;
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);

    // Create a Connection
    Connection connection;
    try {
        connection = connectionFactory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // Create the destination (Topic or Queue)
        Destination destination = session.createTopic(topic);
        // Create a MessageProducer from the Session to the Topic or Queue
        MessageProducer producer = session.createProducer(destination);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        // Create a messages
        TextMessage message1 = session.createTextMessage(message);
        // Tell the producer to send the message
        producer.send(message1);
        session.close();
        connection.close();
    } catch (JMSException e) {
        logger.error("Message could not be sended to activemq", e);
    }

}

From source file:de.klemp.middleware.controller.Controller.java

public static void sendMessageFast(String message, String topic) {
    String url = ActiveMQConnection.DEFAULT_BROKER_URL;
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);

    // Create a Connection
    Connection connection;//w w  w .  jav  a  2  s. co  m
    try {
        connectionFactory.setOptimizeAcknowledge(true);
        connectionFactory.setUseAsyncSend(true);
        connection = connectionFactory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // Create the destination (Topic or Queue)
        Destination destination = session.createTopic(topic);
        // Create a MessageProducer from the Session to the Topic or Queue
        MessageProducer producer = session.createProducer(destination);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        // Create a messages
        TextMessage message1 = session.createTextMessage(message);
        // Tell the producer to send the message
        producer.send(message1);
        session.close();
        connection.close();
    } catch (JMSException e) {
        logger.error("Message could not be sended to activemq", e);
    }

}

From source file:fr.xebia.springframework.jms.ManagedCachingConnectionFactoryTest.java

@Test
public void testMessageProducer() throws Exception {
    ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(
            "vm://localhost?broker.persistent=false&broker.useJmx=true");
    ManagedConnectionFactory connectionFactory = new ManagedConnectionFactory(activeMQConnectionFactory);
    Connection connection = null;
    Session session = null;
    MessageProducer messageProducer = null;
    try {/*from w ww.  j av  a2  s  . c  o m*/
        connection = connectionFactory.createConnection();
        assertEquals(1, connectionFactory.getActiveConnectionCount());
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        assertEquals(1, connectionFactory.getActiveSessionCount());
        Destination myQueue = session.createQueue("test-queue");
        messageProducer = session.createProducer(myQueue);

        assertEquals(1, connectionFactory.getActiveMessageProducerCount());

        messageProducer.send(myQueue, session.createTextMessage("test"));

        assertEquals(0, connectionFactory.getActiveMessageConsumerCount());
    } finally {
        JmsUtils.closeMessageProducer(messageProducer);
        assertEquals(0, connectionFactory.getActiveMessageProducerCount());
        JmsUtils.closeSession(session);
        assertEquals(0, connectionFactory.getActiveSessionCount());
        JmsUtils.closeConnection(connection);
        assertEquals(0, connectionFactory.getActiveConnectionCount());
    }
}

From source file:com.moss.veracity.core.cluster.jms.UpdateTransmitterJMSImpl.java

private void sendMessage(Object o) {

    Session session = null;
    MessageProducer producer = null;//from   w w w  .j a  v  a2  s.  c o  m
    try {
        StringWriter writer = new StringWriter();
        Marshaller m = jaxbContext.createMarshaller();
        m.marshal(o, writer);
        String text = writer.getBuffer().toString();

        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic(UpdateTopic.NAME);
        producer = session.createProducer(topic);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);

        TextMessage message = session.createTextMessage(text);
        producer.send(message);

        producer.close();
        session.close();
    } catch (Exception ex) {

        if (producer != null) {
            try {
                producer.close();
            } catch (JMSException e) {
                if (log.isErrorEnabled()) {
                    log.error("Failed to close producer after failure", e);
                } else {
                    ex.printStackTrace();
                }
            }
        }

        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                if (log.isErrorEnabled()) {
                    log.error("Failed to close session after failure", e);
                } else {
                    ex.printStackTrace();
                }
            }
        }

        throw new RuntimeException("Message transmission failed: " + o, ex);
    }
}

From source file:com.mothsoft.alexis.engine.retrieval.DocumentRetrievalTaskImpl.java

private String requestParse(final Long documentId, final String content) {
    Connection connection = null;
    Session session = null;
    MessageProducer producer = null;/*from   www. j  a  v  a  2s.c  o m*/

    // set up JMS connection, session, consumer, producer
    try {
        connection = this.connectionFactory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producer = session.createProducer(this.requestQueue);

        logger.info("Sending parse request, document ID: " + documentId);
        final TextMessage textMessage = session.createTextMessage(content);
        textMessage.setJMSReplyTo(this.responseQueue);
        textMessage.setLongProperty(DOCUMENT_ID, documentId);

        producer.send(textMessage);
    } catch (JMSException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (producer != null) {
                producer.close();
            }
            if (session != null) {
                session.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }

    return content;
}

From source file:com.inkubator.hrm.service.impl.EmpCareerHistoryServiceImpl.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
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMMM-yyyy", new Locale(appActivity.getLocale()));
    EmpCareerHistoryModel model = this.convertJsonToModel(appActivity.getPendingData());
    EmployeeType beforeEmployeeType = employeeTypeDao
            .getEntiyByPK(model.getEmpData().getEmployeeType().getId());
    Jabatan beforeJabatan = jabatanDao.getEntiyByPK(model.getEmpData().getJabatanByJabatanId().getId());
    EmployeeType afterEmployeeType = employeeTypeDao.getEntiyByPK(model.getEmployeeTypeId());
    Jabatan afterJabatan = jabatanDao.getEntiyByPK(model.getJabatanId());

    //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);

        //jika di approve, maka tambahkan juga tembusanSurat di list CC of EmailAddress
        if (appActivity.getApprovalStatus() == HRMConstant.APPROVAL_STATUS_APPROVED) {
            HrmUser copyOfLetterTo = hrmUserDao.getByEmpDataId(model.getCopyOfLetterTo().getId());
            if (copyOfLetterTo != null) {
                ccEmailAddresses.add(copyOfLetterTo.getEmailAddress());
            }//from  ww  w. j  a v a 2 s  .  c  om
        }
    }

    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(model.getCreatedOn()));
        jsonObj.put("effectiveDate", dateFormat.format(model.getEffectiveDate()));
        jsonObj.put("beforeNik", model.getEmpData().getNik());
        jsonObj.put("beforeJoinDate", dateFormat.format(model.getEmpData().getJoinDate()));
        jsonObj.put("beforeEmployeeType", beforeEmployeeType.getName());
        jsonObj.put("beforeJabatan", beforeJabatan.getName());
        jsonObj.put("beforeDepartment", beforeJabatan.getDepartment().getDepartmentName());
        jsonObj.put("afterNik", model.getNik());
        jsonObj.put("afterJoinDate", dateFormat.format(model.getJoinDate()));
        jsonObj.put("afterEmployeeType", afterEmployeeType.getName());
        jsonObj.put("afterJabatan", afterJabatan.getName());
        jsonObj.put("afterDepartment", afterJabatan.getDepartment().getDepartmentName());

        jsonObj.put("urlLinkToApprove",
                FacesUtil.getRequest().getContextPath() + ""
                        + HRMConstant.EMPLOYEE_CAREER_TRANSITION_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:jenkins.plugins.logstash.persistence.ActiveMqDao.java

@Override
public void push(String data) throws IOException {
    TopicConnection connection = null;/*from ww w  .j a  v  a 2 s  .  c om*/
    Session session = null;
    try {
        // Create a Connection
        connection = connectionFactory.createTopicConnection();

        connection.start();

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

        // Create the destination Queue
        Destination destination = session.createTopic(key);

        // Create the MessageProducer from the Session to the Queue
        MessageProducer producer = session.createProducer(destination);

        producer.setDeliveryMode(DeliveryMode.PERSISTENT);

        // Create the message
        TextMessage message = session.createTextMessage(data);
        message.setJMSType("application/json");
        // Tell the producer to send the message
        producer.send(message);

        //logger.log( Level.FINER, String.format("JMS message sent with ID [%s]", message.getJMSMessageID()));

    } catch (JMSException e) {
        logger.log(Level.SEVERE, null != e.getMessage() ? e.getMessage() : e.getClass().getName());
        throw new IOException(e);
    } finally {
        // Clean up
        try {
            if (null != session)
                session.close();
        } catch (JMSException e) {
            logger.log(Level.WARNING, null != e.getMessage() ? e.getMessage() : e.getClass().getName());
        }
        try {
            if (null != connection)
                connection.close();
        } catch (JMSException e) {
            logger.log(Level.WARNING, null != e.getMessage() ? e.getMessage() : e.getClass().getName());
        }
    }
}

From source file:org.dawnsci.commandserver.core.producer.AliveConsumer.java

protected void startNotifications() throws Exception {

    if (uri == null)
        throw new NullPointerException("Please set the URI before starting notifications!");
    this.cbean = new ConsumerBean();
    cbean.setStatus(ConsumerStatus.STARTING);
    cbean.setName(getName());//w ww  .ja  v a 2  s .co m
    cbean.setConsumerId(consumerId);
    cbean.setVersion(consumerVersion);
    cbean.setStartTime(System.currentTimeMillis());
    try {
        cbean.setHostName(InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
        // Not fatal but would be nice...
        e.printStackTrace();
    }

    System.out.println("Running events on topic " + Constants.ALIVE_TOPIC + " to notify of '" + getName()
            + "' service being available.");

    final Thread aliveThread = new Thread(new Runnable() {
        public void run() {

            try {
                ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
                aliveConnection = connectionFactory.createConnection();
                aliveConnection.start();

                final Session session = aliveConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                final Topic topic = session.createTopic(Constants.ALIVE_TOPIC);
                final MessageProducer producer = session.createProducer(topic);

                final ObjectMapper mapper = new ObjectMapper();

                // Here we are sending the message out to the topic
                while (isActive()) {
                    try {
                        Thread.sleep(Constants.NOTIFICATION_FREQUENCY);

                        TextMessage temp = session.createTextMessage(mapper.writeValueAsString(cbean));
                        producer.send(temp, DeliveryMode.NON_PERSISTENT, 1, 5000);

                        if (ConsumerStatus.STARTING.equals(cbean.getStatus())) {
                            cbean.setStatus(ConsumerStatus.RUNNING);
                        }

                    } catch (InterruptedException ne) {
                        break;
                    } catch (Exception neOther) {
                        neOther.printStackTrace();
                    }
                }
            } catch (Exception ne) {
                ne.printStackTrace();
                setActive(false);
            }
        }
    });
    aliveThread.setName("Alive Notification Topic");
    aliveThread.setDaemon(true);
    aliveThread.setPriority(Thread.MIN_PRIORITY);
    aliveThread.start();
}