Example usage for javax.jms Session createMapMessage

List of usage examples for javax.jms Session createMapMessage

Introduction

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

Prototype


MapMessage createMapMessage() throws JMSException;

Source Link

Document

Creates a MapMessage object.

Usage

From source file:Supplier.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    Session session = null;
    Destination orderQueue;//www.  ja  va2 s. c om
    try {
        Connection connection = connectionFactory.createConnection();

        session = connection.createSession(true, Session.SESSION_TRANSACTED);
        orderQueue = session.createQueue(QUEUE);
        MessageConsumer consumer = session.createConsumer(orderQueue);

        connection.start();

        while (true) {
            Message message = consumer.receive();
            MessageProducer producer = session.createProducer(message.getJMSReplyTo());
            MapMessage orderMessage;
            if (message instanceof MapMessage) {
                orderMessage = (MapMessage) message;
            } else {
                // End of Stream
                producer.send(session.createMessage());
                session.commit();
                producer.close();
                break;
            }

            int quantity = orderMessage.getInt("Quantity");
            System.out.println(
                    ITEM + " Supplier: Vendor ordered " + quantity + " " + orderMessage.getString("Item"));

            MapMessage outMessage = session.createMapMessage();
            outMessage.setInt("VendorOrderNumber", orderMessage.getInt("VendorOrderNumber"));
            outMessage.setString("Item", ITEM);

            quantity = Math.min(orderMessage.getInt("Quantity"),
                    new Random().nextInt(orderMessage.getInt("Quantity") * 10));
            outMessage.setInt("Quantity", quantity);

            producer.send(outMessage);
            System.out.println(ITEM + " Supplier: Sent " + quantity + " " + ITEM + "(s)");
            session.commit();
            System.out.println(ITEM + " Supplier: committed transaction");
            producer.close();
        }
        connection.close();
    } catch (JMSException e) {
        e.printStackTrace();
    }
}

From source file:Vendor.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    Session session = null;
    Destination orderQueue;/*  w w  w  . j a v a2  s . co m*/
    Destination monitorOrderQueue;
    Destination storageOrderQueue;
    TemporaryQueue vendorConfirmQueue;
    MessageConsumer orderConsumer = null;
    MessageProducer monitorProducer = null;
    MessageProducer storageProducer = null;

    try {
        Connection connection = connectionFactory.createConnection();

        session = connection.createSession(true, Session.SESSION_TRANSACTED);
        orderQueue = session.createQueue("VendorOrderQueue");
        monitorOrderQueue = session.createQueue("MonitorOrderQueue");
        storageOrderQueue = session.createQueue("StorageOrderQueue");

        orderConsumer = session.createConsumer(orderQueue);
        monitorProducer = session.createProducer(monitorOrderQueue);
        storageProducer = session.createProducer(storageOrderQueue);

        Connection asyncconnection = connectionFactory.createConnection();
        asyncSession = asyncconnection.createSession(true, Session.SESSION_TRANSACTED);

        vendorConfirmQueue = asyncSession.createTemporaryQueue();
        MessageConsumer confirmConsumer = asyncSession.createConsumer(vendorConfirmQueue);
        confirmConsumer.setMessageListener(this);

        asyncconnection.start();

        connection.start();

        while (true) {
            Order order = null;
            try {
                Message inMessage = orderConsumer.receive();
                MapMessage message;
                if (inMessage instanceof MapMessage) {
                    message = (MapMessage) inMessage;

                } else {
                    // end of stream
                    Message outMessage = session.createMessage();
                    outMessage.setJMSReplyTo(vendorConfirmQueue);
                    monitorProducer.send(outMessage);
                    storageProducer.send(outMessage);
                    session.commit();
                    break;
                }

                // Randomly throw an exception in here to simulate a Database error
                // and trigger a rollback of the transaction
                if (new Random().nextInt(3) == 0) {
                    throw new JMSException("Simulated Database Error.");
                }

                order = new Order(message);

                MapMessage orderMessage = session.createMapMessage();
                orderMessage.setJMSReplyTo(vendorConfirmQueue);
                orderMessage.setInt("VendorOrderNumber", order.getOrderNumber());
                int quantity = message.getInt("Quantity");
                System.out.println("Vendor: Retailer ordered " + quantity + " " + message.getString("Item"));

                orderMessage.setInt("Quantity", quantity);
                orderMessage.setString("Item", "Monitor");
                monitorProducer.send(orderMessage);
                System.out.println("Vendor: ordered " + quantity + " Monitor(s)");

                orderMessage.setString("Item", "HardDrive");
                storageProducer.send(orderMessage);
                System.out.println("Vendor: ordered " + quantity + " Hard Drive(s)");

                session.commit();
                System.out.println("Vendor: Comitted Transaction 1");

            } catch (JMSException e) {
                System.out.println("Vendor: JMSException Occured: " + e.getMessage());
                e.printStackTrace();
                session.rollback();
                System.out.println("Vendor: Rolled Back Transaction.");
            }
        }

        synchronized (supplierLock) {
            while (numSuppliers > 0) {
                try {
                    supplierLock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        connection.close();
        asyncconnection.close();

    } catch (JMSException e) {
        e.printStackTrace();
    }

}

From source file:org.apache.camel.component.jms.JmsBinding.java

/**
 * /*from w  ww  .ja v  a 2  s  .  c o  m*/
 * Create the {@link Message} 
 * 
 * @return jmsMessage or null if the mapping was not successfully
 */
protected Message createJmsMessageForType(Exchange exchange, Object body, Map<String, Object> headers,
        Session session, CamelContext context, JmsMessageType type) throws JMSException {
    switch (type) {
    case Text: {
        TextMessage message = session.createTextMessage();
        String payload = context.getTypeConverter().convertTo(String.class, exchange, body);
        message.setText(payload);
        return message;
    }
    case Bytes: {
        BytesMessage message = session.createBytesMessage();
        byte[] payload = context.getTypeConverter().convertTo(byte[].class, exchange, body);
        message.writeBytes(payload);
        return message;
    }
    case Map: {
        MapMessage message = session.createMapMessage();
        Map payload = context.getTypeConverter().convertTo(Map.class, exchange, body);
        populateMapMessage(message, payload, context);
        return message;
    }
    case Object:
        Serializable payload;
        try {
            payload = context.getTypeConverter().mandatoryConvertTo(Serializable.class, exchange, body);
        } catch (NoTypeConversionAvailableException e) {
            // cannot convert to serializable then thrown an exception to avoid sending a null message
            JMSException cause = new MessageFormatException(e.getMessage());
            cause.initCause(e);
            throw cause;
        }
        return session.createObjectMessage(payload);
    default:
        break;
    }
    return null;
}

From source file:org.apache.falcon.messaging.JMSMessageConsumerTest.java

private Message getMockFalconMessage(int i, Session session) throws FalconException, JMSException {
    Map<String, String> message = new HashMap<String, String>();
    message.put(WorkflowExecutionArgs.BRKR_IMPL_CLASS.getName(), BROKER_IMPL_CLASS);
    message.put(WorkflowExecutionArgs.BRKR_URL.getName(), BROKER_URL);
    message.put(WorkflowExecutionArgs.CLUSTER_NAME.getName(), "cluster1");
    message.put(WorkflowExecutionArgs.ENTITY_NAME.getName(), "process1");
    message.put(WorkflowExecutionArgs.ENTITY_TYPE.getName(), "PROCESS");
    message.put(WorkflowExecutionArgs.OUTPUT_FEED_PATHS.getName(), "/clicks/hour/00/0" + i);
    message.put(WorkflowExecutionArgs.OUTPUT_FEED_NAMES.getName(), "clicks");
    message.put(WorkflowExecutionArgs.LOG_FILE.getName(), "/logfile");
    message.put(WorkflowExecutionArgs.LOG_DIR.getName(), "/tmp/falcon-log");
    message.put(WorkflowExecutionArgs.NOMINAL_TIME.getName(), "2012-10-10-10-10");
    message.put(WorkflowExecutionArgs.OPERATION.getName(), "GENERATE");
    message.put(WorkflowExecutionArgs.RUN_ID.getName(), "0");
    message.put(WorkflowExecutionArgs.TIMESTAMP.getName(), "2012-10-10-10-1" + i);
    message.put(WorkflowExecutionArgs.WORKFLOW_ID.getName(), "workflow-" + i);
    message.put(WorkflowExecutionArgs.TOPIC_NAME.getName(), TOPIC_NAME);
    message.put(WorkflowExecutionArgs.STATUS.getName(), i != 15 ? "SUCCEEDED" : "FAILED");
    message.put(WorkflowExecutionArgs.WORKFLOW_USER.getName(), FalconTestUtil.TEST_USER_1);

    String[] args = new String[message.size() * 2];
    int index = 0;
    for (Map.Entry<String, String> entry : message.entrySet()) {
        args[index++] = "-" + entry.getKey();
        args[index++] = entry.getValue();
    }//from   w w  w  .j a v  a  2 s.c  o m

    WorkflowExecutionContext context = WorkflowExecutionContext.create(args,
            WorkflowExecutionContext.Type.POST_PROCESSING);

    MapMessage jmsMessage = session.createMapMessage();
    for (Map.Entry<WorkflowExecutionArgs, String> entry : context.entrySet()) {
        jmsMessage.setString(entry.getKey().getName(), entry.getValue());
    }

    return jmsMessage;
}

From source file:org.apache.qpid.test.utils.QpidBrokerTestCase.java

public Message createMessage(Session session, int messageSize) throws JMSException
{
    String payload = new String(new byte[messageSize]);

    Message message;/*  w  w w  .ja  va2  s. co m*/

    switch (_messageType)
    {
        case BYTES:
            message = session.createBytesMessage();
            ((BytesMessage) message).writeUTF(payload);
            break;
        case MAP:
            message = session.createMapMessage();
            ((MapMessage) message).setString(CONTENT, payload);
            break;
        default: // To keep the compiler happy
        case TEXT:
            message = session.createTextMessage();
            ((TextMessage) message).setText(payload);
            break;
        case OBJECT:
            message = session.createObjectMessage();
            ((ObjectMessage) message).setObject(payload);
            break;
        case STREAM:
            message = session.createStreamMessage();
            ((StreamMessage) message).writeString(payload);
            break;
    }

    return message;
}

From source file:org.gss_project.gss.server.ejb.AdminAPIBean.java

public void indexFile(Long fileId, boolean delete) {
    Connection qConn = null;//ww w  . j  a va  2s .c  o  m
    Session session = null;
    MessageProducer sender = null;
    try {
        Context jndiCtx = new InitialContext();
        ConnectionFactory factory = (QueueConnectionFactory) jndiCtx.lookup("java:/JmsXA");
        Queue queue = (Queue) jndiCtx.lookup("queue/gss-indexingQueue");
        qConn = factory.createConnection();
        session = qConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        sender = session.createProducer(queue);

        MapMessage map = session.createMapMessage();
        map.setObject("id", fileId);
        map.setBoolean("delete", delete);
        sender.send(map);
    } catch (NamingException e) {
        logger.error("Index was not updated: ", e);
    } catch (JMSException e) {
        logger.error("Index was not updated: ", e);
    } finally {
        try {
            if (sender != null)
                sender.close();
            if (session != null)
                session.close();
            if (qConn != null)
                qConn.close();
        } catch (JMSException e) {
            logger.warn(e);
        }
    }
}

From source file:org.gss_project.gss.server.ejb.ExternalAPIBean.java

private void indexFile(Long fileId, boolean delete) {
     Connection qConn = null;/* w w w.  ja va2  s  . c o m*/
     Session session = null;
     MessageProducer sender = null;
     try {
         Context jndiCtx = new InitialContext();
         ConnectionFactory factory = (QueueConnectionFactory) jndiCtx.lookup("java:/JmsXA");
         Queue queue = (Queue) jndiCtx.lookup("queue/gss-indexingQueue");
         qConn = factory.createConnection();
         session = qConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
         sender = session.createProducer(queue);

         MapMessage map = session.createMapMessage();
         map.setObject("id", fileId);
         map.setBoolean("delete", delete);
         sender.send(map);
     } catch (NamingException e) {
         logger.error("Index was not updated: ", e);
     } catch (JMSException e) {
         logger.error("Index was not updated: ", e);
     } finally {
         try {
             if (sender != null)
                 sender.close();
             if (session != null)
                 session.close();
             if (qConn != null)
                 qConn.close();
         } catch (JMSException e) {
             logger.warn(e);
         }
     }
 }

From source file:org.jbpm.bpel.tutorial.invoice.ComputePricePT_Impl.java

protected void sendInvoiceMessage(float shippingPrice) throws JMSException {
    ServletContext servletContext = endpointContext.getServletContext();
    Integer orderId = (Integer) servletContext.getAttribute(ORDER_ID_ATTR);
    Float linePrice = (Float) servletContext.getAttribute(LINE_PRICE_ATTR);
    float amount = linePrice.floatValue() + shippingPrice;

    // create a session
    Session jmsSession = jmsConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    try {/*from ww w  .jav  a2  s  . c  om*/
        // create the message
        MapMessage invoiceMessage = jmsSession.createMapMessage();
        invoiceMessage.setInt("orderId", orderId.intValue());
        invoiceMessage.setFloat("amount", amount);

        // send it!
        MessageProducer producer = jmsSession.createProducer(invoiceDestination);
        producer.send(invoiceMessage);

        log.debug("Sent invoice message: orderId=" + orderId + ", amount=" + amount);
    } finally {
        jmsSession.close();
    }
}

From source file:org.jbpm.bpel.tutorial.shipping.ShippingPT_Impl.java

protected void sendShippingMessage(String customerId) throws JMSException {
    // create a session
    Session jmsSession = jmsConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    try {/*from  w ww. jav  a 2  s  .c om*/
        // create the message
        MapMessage message = jmsSession.createMapMessage();
        message.setString("customerId", customerId);

        // send it!
        MessageProducer producer = jmsSession.createProducer(shippingDestination);
        producer.send(message);

        log.debug("Sent shipping message: customerId=" + customerId);
    } finally {
        jmsSession.close();
    }
}

From source file:org.mule.transport.jms.JmsMessageUtils.java

private static Message mapToMessage(Map<?, ?> value, Session session) throws JMSException {
    MapMessage mMsg = session.createMapMessage();

    for (Iterator<?> i = value.entrySet().iterator(); i.hasNext();) {
        Map.Entry<?, ?> entry = (Map.Entry<?, ?>) i.next();
        mMsg.setObject(entry.getKey().toString(), entry.getValue());
    }// w ww.j  a v  a 2s . c  o m

    return mMsg;
}