Java Code Examples for javax.jms.ObjectMessage#setObject()

The following examples show how to use javax.jms.ObjectMessage#setObject() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JMSPublisherConsumerIT.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testObjectMessage() throws Exception {
    final String destinationName = "testObjectMessage";

    MessageCreator messageCreator = session -> {
        ObjectMessage message = session.createObjectMessage();

        message.setObject("stringAsObject");

        return message;
    };

    ConsumerCallback responseChecker = response -> {
        assertEquals(
            "stringAsObject",
            SerializationUtils.deserialize(response.getMessageBody())
        );
    };

    testMessage(destinationName, messageCreator, responseChecker);
}
 
Example 2
Source File: JMSAppender.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
    This method called by {@link AppenderSkeleton#doAppend} method to
    do most of the real appending work.  */
 public void append(LoggingEvent event) {
   if(!checkEntryConditions()) {
     return;
   }

   try {
     ObjectMessage msg = topicSession.createObjectMessage();
     if(locationInfo) {
event.getLocationInformation();
     }
     msg.setObject(event);
     topicPublisher.publish(msg);
   } catch(Exception e) {
     errorHandler.error("Could not publish message in JMSAppender ["+name+"].", e,
		 ErrorCode.GENERIC_FAILURE);
   }
 }
 
Example 3
Source File: XAProducerSB.java    From solace-integration-guides with Apache License 2.0 6 votes vote down vote up
@TransactionAttribute(value = TransactionAttributeType.NOT_SUPPORTED)
   @Override
   public void sendMessage() throws JMSException {

System.out.println("Sending reply message");
Connection conn = null;
Session session = null;
MessageProducer prod = null;

try {
    conn = myCF.createConnection();
    session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    prod = session.createProducer(myReplyQueue);

    ObjectMessage msg = session.createObjectMessage();
    msg.setObject("Hello world!");
    prod.send(msg, DeliveryMode.PERSISTENT, 0, 0);
} finally {
    if (prod != null)
	prod.close();
    if (session != null)
	session.close();
    if (conn != null)
	conn.close();
}
   }
 
Example 4
Source File: ProducerSB.java    From solace-integration-guides with Apache License 2.0 6 votes vote down vote up
@Override
public void sendMessage() throws JMSException {

    Connection conn = null;
    Session session = null;
    MessageProducer prod = null;

    try {
        conn = myCF.createConnection();
        session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        prod = session.createProducer(myReplyQueue);

        ObjectMessage msg = session.createObjectMessage();
        msg.setObject("Hello world!");
        prod.send(msg, DeliveryMode.PERSISTENT, 0, 0);
    } finally {
        if (prod != null)
            prod.close();
        if (session != null)
            session.close();
        if (conn != null)
            conn.close();
    }
}
 
Example 5
Source File: XAProducerSB.java    From solace-integration-guides with Apache License 2.0 6 votes vote down vote up
@TransactionAttribute(value = TransactionAttributeType.REQUIRED)
@Override
public void sendMessage() throws JMSException {

    Connection conn = null;
    Session session = null;
    MessageProducer prod = null;

    try {
        conn = myCF.createConnection();
        session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        prod = session.createProducer(myReplyQueue);

        ObjectMessage msg = session.createObjectMessage();
        msg.setObject("Hello world!");
        prod.send(msg, DeliveryMode.PERSISTENT, 0, 0);
    } finally {
        if (prod != null)
            prod.close();
        if (session != null)
            session.close();
        if (conn != null)
            conn.close();
    }
}
 
Example 6
Source File: EmbeddedTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public static void publish(String destination, Serializable object, String contentType) throws Exception {
   ConnectionFactory factory = ActiveMQJMSClient.createConnectionFactory("vm://0","cf");
   Connection conn = factory.createConnection();
   Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Destination dest = session.createQueue(destination);

   try {
      Assert.assertNotNull("Destination was null", dest);
      MessageProducer producer = session.createProducer(dest);
      ObjectMessage message = session.createObjectMessage();

      if (contentType != null) {
         message.setStringProperty(HttpHeaderProperty.CONTENT_TYPE, contentType);
      }
      message.setObject(object);

      producer.send(message);
   } finally {
      conn.close();
   }
}
 
Example 7
Source File: SelectorTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public static void publish(String dest, Serializable object, String contentType, String tag) throws Exception {
   Connection conn = connectionFactory.createConnection();
   try {
      Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Destination destination = createDestination(dest);
      MessageProducer producer = session.createProducer(destination);
      ObjectMessage message = session.createObjectMessage();

      if (contentType != null) {
         message.setStringProperty(HttpHeaderProperty.CONTENT_TYPE, contentType);
      }
      if (tag != null) {
         message.setStringProperty("MyTag", tag);
      }
      message.setObject(object);

      producer.send(message);
   } finally {
      conn.close();
   }
}
 
Example 8
Source File: MessageTypeTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Send an <code>ObjectMessage</code> with a <code>Vector</code> (composed of a <code>
 * String</code> and a <code>double</code>) in its body.
 * <br />
 * Receive it and test that the values of the primitives of the body are correct
 */
@Test
public void testObjectMessage_2() {
   try {
      Vector<Object> vector = new Vector<>();
      vector.add("pi");
      vector.add(new Double(3.14159));

      ObjectMessage message = senderSession.createObjectMessage();
      message.setObject(vector);
      sender.send(message);

      Message m = receiver.receive(TestConfig.TIMEOUT);
      Assert.assertTrue("The message should be an instance of ObjectMessage.\n", m instanceof ObjectMessage);
      ObjectMessage msg = (ObjectMessage) m;
      Assert.assertEquals(vector, msg.getObject());
   } catch (JMSException e) {
      fail(e);
   }
}
 
Example 9
Source File: EmbeddedJMSResource.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public ObjectMessage createMessage(Serializable body, Map<String, Object> properties) {
   ObjectMessage message = this.createObjectMessage();

   if (body != null) {
      try {
         message.setObject(body);
      } catch (JMSException jmsEx) {
         throw new EmbeddedJMSResourceException(String.format("Failed to set body {%s} on ObjectMessage", body.toString()), jmsEx);
      }
   }

   setMessageProperties(message, properties);

   return message;
}
 
Example 10
Source File: JmsSend.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
   ConnectionFactory factory = new ActiveMQJMSConnectionFactory("tcp://localhost:61616");
   Destination destination = ActiveMQDestination.fromPrefixedName("queue://orders");

   try (Connection conn = factory.createConnection()) {
      Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = session.createProducer(destination);
      ObjectMessage message = session.createObjectMessage();

      Order order = new Order("Bill", "$199.99", "iPhone4");
      message.setObject(order);
      producer.send(message);
   }
}
 
Example 11
Source File: JMSTopicProducer.java    From flex-blazeds with Apache License 2.0 5 votes vote down vote up
void sendObjectMessage(Serializable obj, Map properties) throws JMSException
{
    if (obj == null)
        return;

    ObjectMessage message = session.createObjectMessage();
    message.setObject(obj);
    copyHeadersToProperties(properties, message);
    publisher.publish(message, getDeliveryMode(), messagePriority, getTimeToLive(properties));
}
 
Example 12
Source File: IndexRequestListener.java    From development with Apache License 2.0 5 votes vote down vote up
private boolean putBackMessageOnIndexerQueue(Message message) {
    if (message instanceof ObjectMessage) {
        Session session = null;
        Connection conn = null;
        try {
            Context jndiContext = getContext();
            ConnectionFactory qFactory = (ConnectionFactory) jndiContext
                    .lookup("jms/bss/indexerQueueFactory");
            conn = qFactory.createConnection();
            Queue queue = (Queue) jndiContext
                    .lookup("jms/bss/indexerQueue");
            session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer producer = session.createProducer(queue);
            ObjectMessage msg = session.createObjectMessage();
            msg.setObject(((ObjectMessage) message).getObject());
            producer.send(msg);
            return true;
        } catch (Throwable e) {
            // This should not happen because the indexer queue is in the
            // local server. If it happens, than there's something terribly
            // wrong.
            throw new SaaSSystemException(e);
        } finally {
            closeSession(session);
            closeConnection(conn);
        }
    } else {
        return false;
    }
}
 
Example 13
Source File: SQSObjectMessageTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Test set object
 */
@Test
public void testSetObject() throws JMSException {
    Map<String, String> expectedPayload = new HashMap<String, String>();
    expectedPayload.put("testKey", "testValue");

    ObjectMessage objectMessage = new SQSObjectMessage();
    objectMessage.setObject((Serializable) expectedPayload);
    
    Map<String, String> actualPayload = (HashMap<String, String>) objectMessage.getObject();
    assertEquals(expectedPayload, actualPayload);
}
 
Example 14
Source File: ActiveMQConnectionFactoryTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void sendObjectMessage(String qname, Serializable obj) throws Exception {
   ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://0");
   Connection connection = factory.createConnection();
   try {
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Queue q = session.createQueue(qname);
      MessageProducer producer = session.createProducer(q);
      ObjectMessage objMessage = session.createObjectMessage();
      objMessage.setObject(obj);
      producer.send(objMessage);
   } finally {
      connection.close();
   }
}
 
Example 15
Source File: MockJMSProducer.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Override
public JMSProducer send(Destination destination, Serializable body) {
    try {
        ObjectMessage message = session.createObjectMessage();
        message.setObject(body);
        doSend(destination, message);
    } catch (JMSException jmse) {
        throw JMSExceptionSupport.createRuntimeException(jmse);
    }

    return this;
}
 
Example 16
Source File: JmsProducer.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Override
public JMSProducer send(Destination destination, Serializable body) {
    try {
        ObjectMessage message = session.createObjectMessage();
        message.setObject(body);
        doSend(destination, message);
    } catch (JMSException jmse) {
        throw JmsExceptionSupport.createRuntimeException(jmse);
    }

    return this;
}
 
Example 17
Source File: ForeignMessageTest.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Test
public void testSendForeignMessage() throws Exception
{
    final Destination replyTo = createQueue(getTestName() + "_replyTo");
    final Queue queue = createQueue(getTestName());
    final Connection connection = getConnection();
    try
    {
        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final String jmsType = "TestJmsType";
        final String correlationId = "testCorrelationId";
        final ObjectMessage message = session.createObjectMessage();
        final ObjectMessage foreignMessage =
                Reflection.newProxy(ObjectMessage.class, new AbstractInvocationHandler()
                {
                    @Override
                    protected Object handleInvocation(final Object proxy, final Method method, final Object[] args)
                            throws Throwable
                    {
                        return method.invoke(message, args);
                    }
                });

        foreignMessage.setJMSCorrelationID(correlationId);
        foreignMessage.setJMSType(jmsType);
        foreignMessage.setJMSReplyTo(replyTo);
        Serializable payload = UUID.randomUUID();
        foreignMessage.setObject(payload);

        final MessageConsumer consumer = session.createConsumer(queue);
        final MessageProducer producer = session.createProducer(queue);
        producer.send(foreignMessage);

        connection.start();

        Message receivedMessage = consumer.receive(getReceiveTimeout());
        assertTrue("ObjectMessage was not received ", receivedMessage instanceof ObjectMessage);
        assertEquals("JMSCorrelationID mismatch",
                     foreignMessage.getJMSCorrelationID(),
                     receivedMessage.getJMSCorrelationID());
        assertEquals("JMSType mismatch", foreignMessage.getJMSType(), receivedMessage.getJMSType());
        assertEquals("JMSReply To mismatch", foreignMessage.getJMSReplyTo(), receivedMessage.getJMSReplyTo());
        assertEquals("JMSMessageID mismatch", foreignMessage.getJMSMessageID(), receivedMessage.getJMSMessageID());
        assertEquals("JMS Default priority should be default",
                     Message.DEFAULT_PRIORITY,
                     receivedMessage.getJMSPriority());
        assertEquals("Message payload not as expected", payload, ((ObjectMessage) receivedMessage).getObject());
    }
    finally
    {
        connection.close();
    }
}
 
Example 18
Source File: ObjectMessageIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
private void doSendBasicObjectMessageWithSerializedContentTestImpl(String content, boolean setObjectIfNull) throws JMSException, IOException, InterruptedException, Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        testPeer.expectBegin();
        testPeer.expectSenderAttach();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue("myQueue");
        MessageProducer producer = session.createProducer(queue);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(content);
        oos.flush();
        oos.close();
        byte[] bytes = baos.toByteArray();

        MessageHeaderSectionMatcher headersMatcher = new MessageHeaderSectionMatcher(true).withDurable(equalTo(true));
        MessageAnnotationsSectionMatcher msgAnnotationsMatcher = new MessageAnnotationsSectionMatcher(true);
        msgAnnotationsMatcher.withEntry(AmqpMessageSupport.JMS_MSG_TYPE, equalTo(AmqpMessageSupport.JMS_OBJECT_MESSAGE));
        MessagePropertiesSectionMatcher propertiesMatcher = new MessagePropertiesSectionMatcher(true);
        propertiesMatcher.withContentType(equalTo(AmqpMessageSupport.SERIALIZED_JAVA_OBJECT_CONTENT_TYPE));
        TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher();
        messageMatcher.setHeadersMatcher(headersMatcher);
        messageMatcher.setMessageAnnotationsMatcher(msgAnnotationsMatcher);
        messageMatcher.setPropertiesMatcher(propertiesMatcher);
        messageMatcher.setMessageContentMatcher(new EncodedDataMatcher(new Binary(bytes)));

        testPeer.expectTransfer(messageMatcher);
        testPeer.expectClose();

        ObjectMessage message = session.createObjectMessage();
        if (content != null || setObjectIfNull) {
            message.setObject(content);
        }

        producer.send(message);

        if (content == null) {
            assertTrue(message.isBodyAssignableTo(String.class));
            assertTrue(message.isBodyAssignableTo(Serializable.class));
            assertTrue(message.isBodyAssignableTo(Object.class));
            assertTrue(message.isBodyAssignableTo(Boolean.class));
            assertTrue(message.isBodyAssignableTo(byte[].class));
        } else {
            assertTrue(message.isBodyAssignableTo(String.class));
            assertTrue(message.isBodyAssignableTo(Serializable.class));
            assertTrue(message.isBodyAssignableTo(Object.class));
            assertFalse(message.isBodyAssignableTo(Boolean.class));
            assertFalse(message.isBodyAssignableTo(byte[].class));
        }

        if (content == null) {
            assertNull(message.getBody(Object.class));
            assertNull(message.getBody(Serializable.class));
            assertNull(message.getBody(String.class));
            assertNull(message.getBody(byte[].class));
        } else {
            assertNotNull(message.getBody(Object.class));
            assertNotNull(message.getBody(Serializable.class));
            assertNotNull(message.getBody(String.class));
            try {
                message.getBody(byte[].class);
                fail("Cannot read TextMessage with this type.");
            } catch (MessageFormatException mfe) {
            }
        }

        connection.close();

        testPeer.waitForAllHandlersToComplete(3000);
    }
}
 
Example 19
Source File: ObjectMessageTest.java    From activemq-artemis with Apache License 2.0 3 votes vote down vote up
@Test
public void testClassLoaderIsolation() throws Exception {

   ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
   try {
      queueProd.setDeliveryMode(DeliveryMode.PERSISTENT);

      ObjectMessage om = (ObjectMessage) message;

      SomeObject testObject = new SomeObject(3, 7);

      ClassLoader testClassLoader = ObjectMessageTest.newClassLoader(testObject.getClass());

      om.setObject(testObject);

      queueProd.send(message);

      Thread.currentThread().setContextClassLoader(testClassLoader);

      ObjectMessage r = (ObjectMessage) queueCons.receive();

      Object testObject2 = r.getObject();

      ProxyAssertSupport.assertEquals("org.apache.activemq.artemis.jms.tests.message.SomeObject", testObject2.getClass().getName());
      ProxyAssertSupport.assertNotSame(testObject, testObject2);
      ProxyAssertSupport.assertNotSame(testObject.getClass(), testObject2.getClass());
      ProxyAssertSupport.assertNotSame(testObject.getClass().getClassLoader(), testObject2.getClass().getClassLoader());
      ProxyAssertSupport.assertSame(testClassLoader, testObject2.getClass().getClassLoader());
   } finally {
      Thread.currentThread().setContextClassLoader(originalClassLoader);
   }

}
 
Example 20
Source File: MessageWithReadResolveTest.java    From activemq-artemis with Apache License 2.0 3 votes vote down vote up
@Test
public void testSendReceiveMessage() throws Exception {
   Connection conn = createConnection();

   Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

   MessageProducer prod = sess.createProducer(queue1);

   // Make persistent to make sure message gets serialized
   prod.setDeliveryMode(DeliveryMode.PERSISTENT);

   MessageConsumer cons = sess.createConsumer(queue1);

   TestMessage tm = new TestMessage(123, false);

   ObjectMessage om = sess.createObjectMessage();

   om.setObject(tm);

   conn.start();

   prod.send(om);

   ObjectMessage om2 = (ObjectMessage) cons.receive(1000);

   ProxyAssertSupport.assertNotNull(om2);

   TestMessage tm2 = (TestMessage) om2.getObject();

   ProxyAssertSupport.assertEquals(123, tm2.getID());

   conn.close();
}