Example usage for javax.jms Session createObjectMessage

List of usage examples for javax.jms Session createObjectMessage

Introduction

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

Prototype


ObjectMessage createObjectMessage() throws JMSException;

Source Link

Document

Creates an ObjectMessage object.

Usage

From source file:org.apache.servicemix.audit.async.AbstractJmsExchangeListener.java

public void exchangeAccepted(final ExchangeEvent event) {
    jmsTemplate.send(new MessageCreator() {

        public Message createMessage(Session session) throws JMSException {
            createConfigNodeForNamespace(event.getExchange());
            ObjectMessage message = session.createObjectMessage();
            message.setStringProperty(EVENT, Event.Accepted.name());
            message.setObject((Serializable) getSerializer(event.getExchange().getService().getNamespaceURI())
                    .serialize(event.getExchange()));
            return message;
        }/*from w w  w . ja  va2 s. co  m*/

    });
}

From source file:org.apache.servicemix.audit.async.AbstractJmsExchangeListener.java

public void exchangeSent(final ExchangeEvent event) {
    jmsTemplate.send(new MessageCreator() {

        public Message createMessage(Session session) throws JMSException {
            createConfigNodeForNamespace(event.getExchange());
            ObjectMessage message = session.createObjectMessage();
            message.setObjectProperty(EVENT, Event.Sent.name());
            message.setObject((Serializable) getSerializer(event.getExchange().getService().getNamespaceURI())
                    .serialize(event.getExchange()));
            return message;
        }/*  w w  w .ja v  a  2  s.  c om*/

    });
}

From source file:com.mirth.connect.connectors.jms.JmsMessageUtils.java

public static Message getMessageForObject(Object object, Session session) throws JMSException {
    if (object instanceof Message) {
        return (Message) object;
    } else if (object instanceof String) {
        TextMessage text = session.createTextMessage((String) object);
        return text;
    } else if (object instanceof Map) {
        MapMessage map = session.createMapMessage();
        Map.Entry entry = null;//from   w w w .jav  a  2 s.  c  o m
        Map temp = (Map) object;

        for (Iterator i = temp.entrySet().iterator(); i.hasNext();) {
            entry = (Map.Entry) i.next();
            map.setObject(entry.getKey().toString(), entry.getValue());
        }

        return map;
    } else if (object instanceof InputStream) {
        StreamMessage stream = session.createStreamMessage();
        InputStream temp = (InputStream) object;

        byte[] buffer = new byte[1024 * 4];
        int len = 0;
        try {
            while ((len = temp.read(buffer)) != -1) {
                stream.writeBytes(buffer, 0, len);
            }
        } catch (IOException e) {
            throw new JMSException("Failed to read input stream to create a stream message: " + e);
        }

        return stream;
    } else if (object instanceof byte[]) {
        BytesMessage bytes = session.createBytesMessage();
        byte[] buf = (byte[]) object;
        for (int i = 0; i < buf.length; i++) {
            bytes.writeByte(buf[i]);
        }

        return bytes;
    } else if (object instanceof Serializable) {
        ObjectMessage oMsg = session.createObjectMessage();
        oMsg.setObject((Serializable) object);
        return oMsg;
    } else {
        throw new JMSException(
                "Source was not a supported type, data must be Serializable, String, byte[], Map or InputStream");
    }
}

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;//from w w  w.j  a va 2  s  .  c om

    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.exist.messaging.JmsMessageSender.java

private Message createMessage(Session session, Item item, MessagingMetadata mdd, XQueryContext xqcontext)
        throws JMSException, XPathException {

    Message message = null;/*from   w w w  .  j a v  a 2s  .  c o  m*/

    mdd.add("exist.datatype", Type.getTypeName(item.getType()));

    if (item.getType() == Type.ELEMENT || item.getType() == Type.DOCUMENT) {
        LOG.debug("Streaming element or document node");

        if (item instanceof NodeProxy) {
            NodeProxy np = (NodeProxy) item;
            String uri = np.getDocument().getBaseURI();
            LOG.debug("Document detected, adding URL " + uri);
            mdd.add("exist.document-uri", uri);
        }

        // Node provided
        Serializer serializer = xqcontext.getBroker().newSerializer();

        NodeValue node = (NodeValue) item;
        InputStream is = new NodeInputStream(serializer, node);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            IOUtils.copy(is, baos);
        } catch (IOException ex) {
            LOG.error(ex);
            throw new XPathException(ex);
        }
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(baos);

        BytesMessage bytesMessage = session.createBytesMessage();
        bytesMessage.writeBytes(baos.toByteArray());

        message = bytesMessage;

    } else if (item.getType() == Type.BASE64_BINARY || item.getType() == Type.HEX_BINARY) {
        LOG.debug("Streaming base64 binary");

        if (item instanceof Base64BinaryDocument) {
            Base64BinaryDocument b64doc = (Base64BinaryDocument) item;
            String uri = b64doc.getUrl();
            LOG.debug("Base64BinaryDocument detected, adding URL " + uri);
            mdd.add("exist.document-uri", uri);
        }

        BinaryValue binary = (BinaryValue) item;

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream is = binary.getInputStream();

        //TODO consider using BinaryValue.getInputStream()
        //byte[] data = (byte[]) binary.toJavaObject(byte[].class);

        try {
            IOUtils.copy(is, baos);
        } catch (IOException ex) {
            LOG.error(ex);
            throw new XPathException(ex);
        }
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(baos);

        BytesMessage bytesMessage = session.createBytesMessage();
        bytesMessage.writeBytes(baos.toByteArray());

        message = bytesMessage;
    } else if (item.getType() == Type.STRING) {
        TextMessage textMessage = session.createTextMessage();
        textMessage.setText(item.getStringValue());
        message = textMessage;

    } else {
        ObjectMessage objectMessage = session.createObjectMessage();
        //objectMessage.setObject(item.toJavaObject(Object.class)); TODO hmmmm
        message = objectMessage;
    }

    return message;
}

From source file:org.jbpm.bpel.integration.server.SoapHandler.java

protected ObjectMessage sendRequest(SOAPMessage soapMessage, Session jmsSession, JbpmContext jbpmContext)
        throws SOAPException, JMSException {
    // create a jms message to deliver the incoming content
    ObjectMessage jmsRequest = jmsSession.createObjectMessage();

    // put the partner link identified by handle in a jms property
    PartnerLinkEntry partnerLinkEntry = integrationControl.getPartnerLinkEntry(portTypeName, serviceName,
            portName);//from   w  w  w.ja  v  a2 s .  c  o  m
    long partnerLinkId = partnerLinkEntry.getId();
    jmsRequest.setLongProperty(IntegrationConstants.PARTNER_LINK_ID_PROP, partnerLinkId);

    Operation operation = determineOperation(soapMessage);
    if (operation == null)
        throw new SOAPException("could not determine operation to perform");

    // put the operation name in a jms property
    String operationName = operation.getName();
    jmsRequest.setStringProperty(IntegrationConstants.OPERATION_NAME_PROP, operationName);

    log.debug("received request: partnerLink=" + partnerLinkId + ", operation=" + operationName);

    // extract message content
    HashMap requestParts = new HashMap();
    formatter.readMessage(operationName, soapMessage, requestParts, MessageDirection.INPUT);
    jmsRequest.setObject(requestParts);

    // fill message properties
    BpelProcessDefinition process = integrationControl.getDeploymentDescriptor()
            .findProcessDefinition(jbpmContext);
    MessageType requestType = process.getImportDefinition()
            .getMessageType(operation.getInput().getMessage().getQName());
    fillCorrelationProperties(requestParts, jmsRequest, requestType.getPropertyAliases());

    // set up producer
    MessageProducer producer = jmsSession.createProducer(partnerLinkEntry.getDestination());
    try {
        // is the exchange pattern request/response?
        if (operation.getOutput() != null) {
            Destination replyTo = integrationControl.getIntegrationServiceFactory().getResponseDestination();
            jmsRequest.setJMSReplyTo(replyTo);

            // have jms discard request message if response timeout expires
            Number responseTimeout = getResponseTimeout(jbpmContext);
            if (responseTimeout != null)
                producer.setTimeToLive(responseTimeout.longValue());
        } else {
            // have jms discard message if one-way timeout expires
            Number oneWayTimeout = getOneWayTimeout(jbpmContext);
            if (oneWayTimeout != null)
                producer.setTimeToLive(oneWayTimeout.longValue());
        }

        // send request message
        producer.send(jmsRequest);
        log.debug("sent request: " + RequestListener.messageToString(jmsRequest));

        return jmsRequest;
    } finally {
        // release producer resources
        producer.close();
    }
}

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

private static Message serializableToMessage(Serializable value, Session session) throws JMSException {
    ObjectMessage oMsg = session.createObjectMessage();
    oMsg.setObject(value);/*from   w  w w .j  a  v a 2  s. co  m*/

    return oMsg;
}

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

/**
 * Tests that is able to convert a Map which contains a serializable value into
 * an ObjectMessage.//from  w  ww  .j  a  va 2 s.  com
 */
@Test
public void testConvertsMapWithSerializableValueIntoObjectMessage() throws Exception {
    Session session = mock(Session.class);
    when(session.createObjectMessage()).thenReturn(new ActiveMQObjectMessage());

    // Creates a test Map containing a serializable object
    Map data = new HashMap();
    data.put("orange", new Orange());

    Message message = JmsMessageUtils.toMessage(data, session);
    assertTrue(message instanceof ObjectMessage);

    ObjectMessage objectMessage = (ObjectMessage) message;
    Map values = (Map) objectMessage.getObject();
    assertEquals(new Orange(), values.get("orange"));
}

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

/**
 * Tests that trying to convert a Map which contains a non valid non serializable
 * value throws an exception.//from   ww  w .j  a v a2s . co m
 */
@Test
public void testConvertingMapIncludingNotValidNotSerializableValueThrowsException() throws Exception {
    Session session = mock(Session.class);
    when(session.createObjectMessage()).thenReturn(new ActiveMQObjectMessage());

    // Creates a test Map containing a non serializable object
    Map data = new HashMap();
    data.put("notserializable", new BananaFactory());

    try {
        JmsMessageUtils.toMessage(data, session);
        fail("Attempt to send a non-serializable object in a map should fail");
    } catch (Exception expected) {
        assertTrue(expected.getCause() instanceof NotSerializableException);
    }
}

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

@Test
public void testConvertingSerializableToObjectMessage() throws JMSException {
    Session session = mock(Session.class);
    when(session.createObjectMessage()).thenReturn(new ActiveMQObjectMessage());

    final String OBJECT_ID = "id1234";
    ObjectMessage message = (ObjectMessage) JmsMessageUtils.toMessage(new SerializableObject(OBJECT_ID),
            session);//from   w  w  w .ja v a2  s . c o  m

    Serializable serializable = message.getObject();
    assertTrue(serializable instanceof SerializableObject);
    assertEquals(OBJECT_ID, ((SerializableObject) serializable).id);
}