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:io.fabric8.msg.gateway.TestGateway.java

/**
 * TODO - lets figure out a way of mocking kubernetes, running a ZK ensemble, an Artemis broker and testing it!
 * @throws Exception/*from  w  w w .ja  v a 2  s  .c  om*/
 */
@Ignore
public void simpleTest() throws Exception {
    int numberOfMessages = 10;
    String destinationName = "jms.queue.test.foo";
    String brokerURL = "tcp://0.0.0.0:61616";
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL);

    Connection consumerConnection = factory.createConnection();
    consumerConnection.start();
    Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination consumerDestination = consumerSession.createQueue(destinationName);
    MessageConsumer messageConsumer = consumerSession.createConsumer(consumerDestination);

    Connection producerConnection = factory.createConnection();
    producerConnection.start();
    Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = producerSession.createQueue(destinationName);
    MessageProducer producer = producerSession.createProducer(destination);

    for (int i = 0; i < numberOfMessages; i++) {
        Message message = producerSession.createTextMessage("test message: " + i);
        producer.send(message);
        //System.err.println("Sent message " + message);

    }

    Message message;

    for (int i = 0; i < numberOfMessages; i++) {
        message = messageConsumer.receive(5000);
        Assert.assertNotNull(message);
        //System.err.println("Got Message " + message);

    }
    messageConsumer.close();

}

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  . j a v  a 2 s.  co m*/
        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:ca.uhn.hunit.iface.AbstractJmsInterfaceImpl.java

@Override
protected TestMessage<T> internalSendMessage(final TestMessage<T> theMessage) throws TestFailureException {
    LogFactory.INSTANCE.get(this).info("Sending message (" + theMessage.getRawMessage().length() + " bytes)");

    try {//w  ww  .  j a  va  2  s.  com
        MessageCreator mc = new MessageCreator() {
            @Override
            public javax.jms.Message createMessage(Session theSession) throws JMSException {
                TextMessage textMessage = theSession.createTextMessage(theMessage.getRawMessage());

                for (int i = 0; i < myMessagePropertyTableModel.getRowCount(); i++) {
                    if (java.lang.String.class.equals(myMessagePropertyTableModel.getArgType(i))) {
                        textMessage.setStringProperty(myMessagePropertyTableModel.getName(i),
                                (String) myMessagePropertyTableModel.getArg(i));
                    } else if (java.lang.Integer.class.equals(myMessagePropertyTableModel.getArgType(i))) {
                        textMessage.setIntProperty(myMessagePropertyTableModel.getName(i),
                                (Integer) myMessagePropertyTableModel.getArg(i));
                    } else if (int.class.equals(myMessagePropertyTableModel.getArgType(i))) {
                        textMessage.setIntProperty(myMessagePropertyTableModel.getName(i),
                                (Integer) myMessagePropertyTableModel.getArg(i));
                    }
                }

                return textMessage;
            }
        };

        myJmsTemplate.send(myQueueName, mc);
        LogFactory.INSTANCE.get(this).info("Sent message");

    } catch (JmsException e) {
        throw new InterfaceWontSendException(this, e.getMessage(), e);
    }

    return null;
}

From source file:org.wildfly.camel.test.jms.TransactedJMSIntegrationTest.java

private void sendMessage(Connection connection, String jndiName, String message) throws Exception {
    InitialContext initialctx = new InitialContext();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = (Destination) initialctx.lookup(jndiName);
    MessageProducer producer = session.createProducer(destination);
    TextMessage msg = session.createTextMessage(message);
    producer.send(msg);/*from  w  ww.  jav a2  s . com*/
    connection.start();
}

From source file:com.kinglcc.spring.jms.core.converter.Jackson2JmsMessageConverter.java

/**
 * Map the given object to a {@link TextMessage}.
 * @param object the object to be mapped
 * @param session current JMS session/*  w w  w  . ja  v a  2  s .  c  om*/
 * @param objectMapper the mapper to use
 * @return the resulting message
 * @throws JMSException if thrown by JMS methods
 * @throws IOException in case of I/O errors
 * @see Session#createBytesMessage
 */
protected TextMessage mapToTextMessage(Object object, Session session, ObjectMapper objectMapper)
        throws JMSException, IOException {

    StringWriter writer = new StringWriter();
    objectMapper.writeValue(writer, object);
    return session.createTextMessage(writer.toString());
}

From source file:com.datatorrent.lib.io.jms.JMSTestBase.java

public void produceMsg(String text) throws Exception {
    // Create a ConnectionFactory
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");

    // Create a Connection
    Connection connection = connectionFactory.createConnection();
    connection.start();/* ww  w .  java2  s .  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
    TextMessage message = session.createTextMessage(text);
    producer.send(message);

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

From source file:fr.xebia.springframework.jms.support.converter.JaxbMessageConverter.java

/**
 * <p>/*from   www  .  ja  va  2 s  .co  m*/
 * Marshal the given <code>object</code> into a text message.
 * </p>
 * 
 * <p>
 * This method ensures that the message encoding supported by the underlying JMS provider is in sync with the encoding used to generate
 * the XML message.
 * </p>
 * 
 * @param object
 *            Object to marshal, MUST be supported by the jaxb context used by this converter (see {@link #setJaxbContext(JAXBContext)}).
 * @see org.springframework.jms.support.converter.MessageConverter#toMessage(java.lang.Object, javax.jms.Session)
 */
public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
    StringWriter out = new StringWriter();
    jaxb2Marshaller.marshal(object, new StreamResult(out));

    // create TextMessage result
    String text = out.toString();
    TextMessage textMessage = session.createTextMessage(text);

    postProcessResponseMessage(textMessage);

    return textMessage;
}

From source file:org.globus.crux.messaging.utils.JAXBMessageConverter.java

/**
 * <p>/*from w  w  w  .j  a va2 s  .c  o m*/
 * Marshal the given <code>object</code> into a text message.
 * </p>
 *
 * <p>
 * This method ensures that the message encoding supported by the underlying JMS provider is in sync with the encoding used to generate
 * the XML message.
 * </p>
 *
 * @param object
 * @see org.springframework.jms.support.converter.MessageConverter#toMessage(java.lang.Object, javax.jms.Session)
 */
public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
    StringWriter out = new StringWriter();
    try {
        context.createMarshaller().marshal(object, new StreamResult(out));
    } catch (JAXBException e) {
        throw new MessageConversionException("Error marshalling object to Text", e);
    }

    // create TextMessage result
    String text = out.toString();
    TextMessage textMessage = session.createTextMessage(text);

    postProcessResponseMessage(textMessage);

    return textMessage;
}

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

@Override
@Transactional(readOnly = false, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void saveMassPenempatanJadwal(List<Long> data, long groupWorkingId, Date createdOn, String createdBy)
        throws Exception {
    WtGroupWorking groupWorking = wtGroupWorkingDao.getEntiyByPK(groupWorkingId);
    groupWorking.setIsActive(Boolean.TRUE);
    wtGroupWorkingDao.update(groupWorking);

    for (Long empDataId : data) {
        EmpData empData = empDataDao.getEntiyByPK(empDataId);
        empData.setWtGroupWorking(wtGroupWorkingDao.getEntiyByPK(groupWorkingId));
        this.empDataDao.update(empData);
    }/*from  w  w w .  jav  a  2s.co m*/

    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm");
    String dataToJson = jsonConverter.getJson(data.toArray(new Long[data.size()]));
    final JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("listEmpId", dataToJson);
    jsonObject.addProperty("groupWorkingId", groupWorkingId);
    jsonObject.addProperty("createDate", dateFormat.format(createdOn));
    jsonObject.addProperty("createBy", createdBy);
    jsonObject.addProperty("locale", FacesUtil.getFacesContext().getViewRoot().getLocale().toString());

    this.jmsTemplateMassJadwalKerja.send(new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createTextMessage(jsonObject.toString());
        }
    });
}

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

@Override
@Transactional(readOnly = false, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void saveMassPenempatanJadwalException(List<EmpData> data, long groupWorkingId, Date startDate,
        Date endDate) throws Exception {
    List<Long> listIdEmp = Lambda.extract(data, Lambda.on(EmpData.class).getId());
    WtGroupWorking groupWorking = wtGroupWorkingDao.getEntiyByPK(groupWorkingId);
    groupWorking.setIsActive(Boolean.TRUE);
    wtGroupWorkingDao.update(groupWorking);

    for (Long empDataId : listIdEmp) {
        EmpData empData = empDataDao.getEntiyByPK(empDataId);
        empData.setWtGroupWorking(wtGroupWorkingDao.getEntiyByPK(groupWorkingId));
        this.empDataDao.update(empData);
    }//from  www .  jav a2 s.  co m

    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm");
    String dataToJson = jsonConverter.getJson(listIdEmp.toArray(new Long[listIdEmp.size()]));
    final JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("listEmpId", dataToJson);
    jsonObject.addProperty("groupWorkingId", groupWorkingId);
    jsonObject.addProperty("createDate", dateFormat.format(new Date()));
    jsonObject.addProperty("createBy", UserInfoUtil.getUserName());
    jsonObject.addProperty("startDate", dateFormat.format(startDate));
    jsonObject.addProperty("endDate", dateFormat.format(endDate));
    jsonObject.addProperty("locale", FacesUtil.getFacesContext().getViewRoot().getLocale().toString());

    this.jmsTemplateMassJadwalKerjaExcection.send(new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createTextMessage(jsonObject.toString());
        }
    });
}