Example usage for javax.jms ObjectMessage getObject

List of usage examples for javax.jms ObjectMessage getObject

Introduction

In this page you can find the example usage for javax.jms ObjectMessage getObject.

Prototype


Serializable getObject() throws JMSException;

Source Link

Document

Gets the serializable object containing this message's data.

Usage

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

public boolean handleRequest(MessageContext messageContext) throws JAXRPCException, SOAPFaultException {
    /*/*from  www  .  jav a  2s .c  o m*/
     * WSEE 1.1 section 6.2.2.1: If Handler instances are pooled, they must be pooled by Port
     * component. This is because Handlers may retain non-client specific state across method calls
     * that are specific to the Port component.
     */
    if (integrationControl == null) {
        /*
         * COMPLIANCE NOTE: the state initialized in this call is port-component specific, but
         * non-client specific
         */
        lookupEndpointMetadata(messageContext);
    }

    JbpmContext jbpmContext = integrationControl.getIntegrationServiceFactory().getJbpmConfiguration()
            .createJbpmContext();
    try {
        Session jmsSession = integrationControl.createJmsSession();
        try {
            SOAPMessage soapMessage = ((SOAPMessageContext) messageContext).getMessage();
            ObjectMessage jmsRequest = sendRequest(soapMessage, jmsSession, jbpmContext);

            Destination replyTo = jmsRequest.getJMSReplyTo();
            if (replyTo != null) {
                ObjectMessage jmsResponse = receiveResponse(jmsSession, replyTo, jmsRequest.getJMSMessageID(),
                        jbpmContext);

                // remember operation name and message parts for handling response
                messageContext.setProperty(OPERATION_NAME_PROP,
                        jmsRequest.getStringProperty(IntegrationConstants.OPERATION_NAME_PROP));
                messageContext.setProperty(MESSAGE_PARTS_PROP, jmsResponse.getObject());

                // is response a fault?
                String faultName = jmsResponse.getStringProperty(IntegrationConstants.FAULT_NAME_PROP);
                if (faultName != null) {
                    // remember fault name for handling fault
                    messageContext.setProperty(FAULT_NAME_PROP, faultName);
                    throw new SOAPFaultException(SoapBindConstants.CLIENT_FAULTCODE,
                            SoapBindConstants.BUSINESS_FAULTSTRING, null, null);
                }
            }
        } finally {
            jmsSession.close();
        }
    }
    /*
     * NO need to set jbpm context as rollback only for any exception, since operations in try-block
     * only read definitions from database
     */
    catch (SOAPFaultException e) {
        log.debug("request caused a fault", e);
        messageContext.setProperty(FAULT_EXCEPTION_PROP, e);
    } catch (SOAPException e) {
        /*
         * BP 1.2 R2724: If an INSTANCE receives an envelope that is inconsistent with its WSDL
         * description, it SHOULD generate a soap:Fault with a faultcode of "Client", unless a
         * "MustUnderstand" or "VersionMismatch" fault is generated.
         */
        log.debug("incoming soap message carries invalid content", e);
        messageContext.setProperty(FAULT_EXCEPTION_PROP,
                new SOAPFaultException(SoapBindConstants.CLIENT_FAULTCODE, e.getMessage(), null, null));
    } catch (JMSException e) {
        throw new JAXRPCException("message delivery failed", e);
    } finally {
        jbpmContext.close();
    }
    return true;
}

From source file:org.jbpm.ejb.CommandListenerBean.java

/**
 * Retrieves a {@link Command} instance from the given message, which is assumed to be an
 * {@link ObjectMessage}.//from   w  ww . j  a  v  a2s .  com
 * <p>
 * Subclasses may override this method to materialize the command in some other way.
 * </p>
 */
protected Command extractCommand(Message message) throws JMSException {
    if (message instanceof ObjectMessage) {
        ObjectMessage objectMessage = (ObjectMessage) message;
        Serializable object = objectMessage.getObject();
        if (object instanceof Command) {
            return (Command) object;
        } else {
            log.warn(object + " is not a command");
        }
    } else {
        log.warn(message + " is not an object message");
    }
    return null;
}

From source file:org.jbpm.ejb.impl.CommandListenerBean.java

protected Command extractCommand(Message message) throws JMSException {
    Command command = null;/*from  w  ww  . j a  v  a 2  s .c  om*/
    if (message instanceof ObjectMessage) {
        log.debug("deserializing command from jms message...");
        ObjectMessage objectMessage = (ObjectMessage) message;
        Serializable object = objectMessage.getObject();
        if (object instanceof Command) {
            command = (Command) object;
        } else {
            log.warn("ignoring object message cause it isn't a command '" + object + "'"
                    + (object != null ? " (" + object.getClass().getName() + ")" : ""));
        }
    } else {
        log.warn("ignoring message '" + message + "' cause it isn't an ObjectMessage ("
                + message.getClass().getName() + ")");
    }
    return command;
}

From source file:org.logicblaze.lingo.jmx.remote.jms.activemq.ActiveMQServerListenerInfo.java

/**
 * MessageListener implementation/*from  w  w w  . jav  a  2  s. c o  m*/
 *
 * @param message
 */
public void onMessage(Message message) {
    try {
        if (message != null && message instanceof ObjectMessage) {
            ObjectMessage objMsg = (ObjectMessage) message;
            Object obj = objMsg.getObject();
            if (obj != null && obj instanceof RemoveInfo) {
                close();
            }
        } else {
            if (message instanceof ActiveMQMessage) {
                ActiveMQMessage amqMsg = (ActiveMQMessage) message;
                if (amqMsg.getDataStructure() instanceof RemoveInfo) {
                    close();
                }
            }
        }
    } catch (JMSException e) {
        log.warn("Failed to process onMessage", e);
    }
}

From source file:org.logicblaze.lingo.jmx.remote.jms.MBeanJmsServerConnectionClient.java

/**
 * MessageListener implementation//from  w  w  w.  jav  a2s  .c  o  m
 * @param msg 
 */
public void onMessage(Message msg) {
    ObjectMessage objMsg = (ObjectMessage) msg;
    try {
        Notification notification = (Notification) objMsg.getObject();
        localNotifier.sendNotification(notification);
    } catch (JMSException jmsEx) {
        log.error("Failed to send Notification", jmsEx);
    }
}

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

/**
 * @param message the message to receive the bytes from. Note this only works for
 *                TextMessge, ObjectMessage, StreamMessage and BytesMessage.
 * @param jmsSpec indicates the JMS API version, either
 *                {@link JmsConstants#JMS_SPECIFICATION_102B} or
 *                {@link JmsConstants#JMS_SPECIFICATION_11}. Any other value
 *                including <code>null</code> is treated as fallback to
 *                {@link JmsConstants#JMS_SPECIFICATION_102B}.
 * @return a byte array corresponding with the message payload
 * @throws JMSException        if the message can't be read or if the message passed is
 *                             a MapMessage
 * @throws java.io.IOException if a failure occurs while reading the stream and
 *                             converting the message data
 *//* w w  w.  j  a  v a  2  s.  c o  m*/
public static byte[] toByteArray(Message message, String jmsSpec, String encoding)
        throws JMSException, IOException {
    if (message instanceof BytesMessage) {
        BytesMessage bMsg = (BytesMessage) message;
        bMsg.reset();

        if (JmsConstants.JMS_SPECIFICATION_11.equals(jmsSpec)) {
            long bmBodyLength = bMsg.getBodyLength();
            if (bmBodyLength > Integer.MAX_VALUE) {
                throw new JMSException("Size of BytesMessage exceeds Integer.MAX_VALUE; "
                        + "please consider using JMS StreamMessage instead");
            }

            if (bmBodyLength > 0) {
                byte[] bytes = new byte[(int) bmBodyLength];
                bMsg.readBytes(bytes);
                return bytes;
            } else {
                return ArrayUtils.EMPTY_BYTE_ARRAY;
            }
        } else {
            ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
            byte[] buffer = new byte[4096];
            int len;

            while ((len = bMsg.readBytes(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }

            if (baos.size() > 0) {
                return baos.toByteArray();
            } else {
                return ArrayUtils.EMPTY_BYTE_ARRAY;
            }
        }
    } else if (message instanceof StreamMessage) {
        StreamMessage sMsg = (StreamMessage) message;
        sMsg.reset();

        ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
        byte[] buffer = new byte[4096];
        int len;

        while ((len = sMsg.readBytes(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }

        return baos.toByteArray();
    } else if (message instanceof ObjectMessage) {
        ObjectMessage oMsg = (ObjectMessage) message;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(baos);
        os.writeObject(oMsg.getObject());
        os.flush();
        os.close();
        return baos.toByteArray();
    } else if (message instanceof TextMessage) {
        TextMessage tMsg = (TextMessage) message;
        String tMsgText = tMsg.getText();

        if (null == tMsgText) {
            // Avoid creating new instances of byte arrays, even empty ones. The
            // load on this part of the code can be high.
            return ArrayUtils.EMPTY_BYTE_ARRAY;
        } else {
            return tMsgText.getBytes(encoding);
        }
    } else {
        throw new JMSException("Cannot get bytes from Map Message");
    }
}

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./* www.  j  av  a 2  s  .c  om*/
 */
@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

@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.  jav  a  2s. c o  m

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

From source file:org.opencastproject.message.broker.impl.MessageReceiverImpl.java

protected Serializable getSerializable(String destinationId, DestinationType type) {
    Option<Serializable> messageObject = Option.<Serializable>none();
    do {//w  w  w  . j  a va 2 s  .  c om
        // Wait for a message
        Option<Message> message = waitForMessage(destinationId, type);
        try {
            if (isValidObjectMessage(message)) {
                ObjectMessage objectMessage = (ObjectMessage) message.get();
                messageObject = Option.option(objectMessage.getObject());
            } else {
                logger.debug("Skipping invalid message:" + message);
                messageObject = Option.<Serializable>none();
            }
        } catch (JMSException e) {
            logger.error("Unable to get message {} because {}", message, ExceptionUtils.getStackTrace(e));
            messageObject = Option.<Serializable>none();
        }
    } while (messageObject.isNone());
    return messageObject.get();
}

From source file:org.openengsb.opencit.core.projectmanager.internal.ProjectManagerImpl.java

@Override
public void onMessage(Message message) {
    if (!(message instanceof ObjectMessage)) {
        log.error("Received message is not an instance of ObjectMessage: " + message);
        return;//from   w  w w .j  a va  2 s .  co m
    }
    ObjectMessage objectMessage = (ObjectMessage) message;
    Serializable object;
    try {
        object = objectMessage.getObject();
    } catch (JMSException e) {
        log.error("Failed to de-serialize the JMS object", e);
        return;
    }
    if (!(object instanceof BuildFeedback)) {
        log.error("Received object is not an instance of BuildFeedback: " + object);
        return;
    }

    BuildFeedback feedback = (BuildFeedback) object;
    List<Build> builds = persistence.query(new Build(null, null, feedback.getBuildId()));
    if (builds.size() != 1) {
        log.error("Found " + builds.size() + " builds matching buildID " + feedback.getBuildId());
        return;
    }
    Build build = builds.get(0);
    Project p = getProject(build.getProjectId());

    Notification n = createNotification();
    n.setSubject("Feedback from dependent project: " + feedback.getResult());
    n.setMessage(feedback.formatMessage());
    n.setRecipient(p.getNotificationRecipient());

    WiringService ws = osgiUtilsService.getService(WiringService.class);
    NotificationDomain nd = ws.getDomainEndpoint(NotificationDomain.class, "notification", p.getId());
    nd.notify(n);
    log.trace("Notification sent.");

    if (!(build.getReason() instanceof DepUpdateBuildReason)) {
        return;
    }
    DepUpdateBuildReason update = (DepUpdateBuildReason) build.getReason();

    BuildFeedback newFeedback = new BuildFeedback();
    newFeedback.setBuildId(update.getUpdate().getBuildId());
    if (feedback.getResult() == BuildFeedback.BuildResult.SUCCESS) {
        newFeedback.setResult(BuildFeedback.BuildResult.SUCCESS);
    } else {
        newFeedback.setResult(BuildFeedback.BuildResult.NESTEDFAIL);
    }
    newFeedback.setContactInfo(p.getNotificationRecipient());
    newFeedback.setProjectName(p.getId());
    newFeedback.setNestedFeedback(feedback);
    sendFeedback(update.getUpdate().getFeedbackQueue(), newFeedback);
}