Java Code Examples for javax.jms.ObjectMessage

The following examples show how to use javax.jms.ObjectMessage. These examples are extracted from open source projects. 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 Project: activemq-artemis   Source File: JMSTest.java    License: Apache License 2.0 6 votes vote down vote up
public static void publish(String dest, Serializable object, String contentType) 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);
      }
      message.setObject(object);

      producer.send(message);
   } finally {
      conn.close();
   }
}
 
Example 2
/**
    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 Project: activemq-artemis   Source File: GeneralInteropTest.java    License: Apache License 2.0 6 votes vote down vote up
private void sendObjectMessageUsingCoreJms(String queueName, Serializable object) throws Exception {
   Connection jmsConn = null;
   try {
      jmsConn = coreCf.createConnection();
      Session session = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      ObjectMessage objectMessage = session.createObjectMessage(object);

      Queue queue = session.createQueue(queueName);
      MessageProducer producer = session.createProducer(queue);

      producer.send(objectMessage);
   } finally {
      if (jmsConn != null) {
         jmsConn.close();
      }
   }

}
 
Example 4
@Override
public void onMessage(final Message message) {
  try {
    final ObjectMessage om = (ObjectMessage) message;
    HandlingEventRegistrationAttempt attempt = (HandlingEventRegistrationAttempt) om.getObject();
    handlingEventService.registerHandlingEvent(
      attempt.getCompletionTime(),
      attempt.getTrackingId(),
      attempt.getVoyageNumber(),
      attempt.getUnLocode(),
      attempt.getType()
    );
  } catch (Exception e) {
    logger.error(e, e);
  }
}
 
Example 5
/**
 * This implementation converts a TextMessage back to a String, a
 * ByteMessage back to a byte array, a MapMessage back to a Map,
 * and an ObjectMessage back to a Serializable object. Returns
 * the plain Message object in case of an unknown message type.
 * @see #extractStringFromMessage
 * @see #extractByteArrayFromMessage
 * @see #extractMapFromMessage
 * @see #extractSerializableFromMessage
 */
@Override
public Object fromMessage(Message message) throws JMSException, MessageConversionException {
	if (message instanceof TextMessage) {
		return extractStringFromMessage((TextMessage) message);
	}
	else if (message instanceof BytesMessage) {
		return extractByteArrayFromMessage((BytesMessage) message);
	}
	else if (message instanceof MapMessage) {
		return extractMapFromMessage((MapMessage) message);
	}
	else if (message instanceof ObjectMessage) {
		return extractSerializableFromMessage((ObjectMessage) message);
	}
	else {
		return message;
	}
}
 
Example 6
Source Project: localization_nifi   Source File: TestGetJMSQueue.java    License: Apache License 2.0 6 votes vote down vote up
@org.junit.Ignore
public void testSendObjectToQueue() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(GetJMSQueue.class);
    runner.setProperty(JmsProperties.JMS_PROVIDER, JmsProperties.ACTIVEMQ_PROVIDER);
    runner.setProperty(JmsProperties.URL, "tcp://localhost:61616");
    runner.setProperty(JmsProperties.DESTINATION_TYPE, JmsProperties.DESTINATION_TYPE_QUEUE);
    runner.setProperty(JmsProperties.DESTINATION_NAME, "queue.testing");
    runner.setProperty(JmsProperties.ACKNOWLEDGEMENT_MODE, JmsProperties.ACK_MODE_AUTO);
    WrappedMessageProducer wrappedProducer = JmsFactory.createMessageProducer(runner.getProcessContext(), true);
    final Session jmsSession = wrappedProducer.getSession();
    final MessageProducer producer = wrappedProducer.getProducer();

    // Revision class is used because test just needs any Serializable class in core NiFi
    final ObjectMessage message = jmsSession.createObjectMessage(new Revision(1L, "ID", "COMP_ID"));

    producer.send(message);
    jmsSession.commit();
    producer.close();
    jmsSession.close();
}
 
Example 7
Source Project: cxf   Source File: JMSMessageConverter.java    License: Apache License 2.0 6 votes vote down vote up
public Object fromMessage(Message message) throws JMSException {
    if (message instanceof TextMessage) {
        return ((TextMessage)message).getText();
    } else if (message instanceof BytesMessage) {
        BytesMessage message1 = (BytesMessage)message;
        byte[] bytes = new byte[(int)message1.getBodyLength()];
        message1.readBytes(bytes);
        return bytes;
    } else if (message instanceof ObjectMessage) {
        return ((ObjectMessage)message).getObject();
    } else if (message instanceof StreamMessage) {
        StreamMessage streamMessage = (StreamMessage)message;
        return streamMessage.readObject();
    } else {
        return new byte[]{};
    }
}
 
Example 8
Source Project: development   Source File: TaskListenerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void onMessageErrorHandlingFailed() throws Exception {
    // given
    PayloadStub payload = new PayloadStub();
    payload.setExecuteCauseException(true);
    payload.setHandleErrorCauseException(true);
    TaskMessage taskMessage = new TaskMessage(HandlerStub.class, payload);

    ObjectMessage messageMock = mock(ObjectMessage.class);
    when(messageMock.getObject()).thenReturn(taskMessage);

    // when
    listener.onMessage(messageMock);

    // then
    assertTrue(payload.isExecuted());
    assertFalse(payload.isExecutedSuccessfully());
    assertTrue(payload.isErrorHandled());
    assertFalse(payload.isHandledErrorSuccessfully());
}
 
Example 9
private void doTestWhiteListedEnclosedClassTest(Connection c, Serializable content) throws Exception
{
    Queue destination = createQueue(getTestName());
    c.start();
    Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = s.createConsumer(destination);
    MessageProducer producer = s.createProducer(destination);

    final ObjectMessage sendMessage = s.createObjectMessage();
    sendMessage.setObject(content);
    producer.send(sendMessage);

    Message receivedMessage = consumer.receive(getReceiveTimeout());
    assertNotNull("did not receive message within receive timeout", receivedMessage);
    assertTrue("message is of wrong type", receivedMessage instanceof ObjectMessage);
    Object receivedObject = ((ObjectMessage) receivedMessage).getObject();
    assertEquals("Received object has unexpected class", content.getClass(), receivedObject.getClass());
    assertEquals("Received object has unexpected content", content, receivedObject);
}
 
Example 10
private static void publish(String destination, Serializable object, String contentType) throws Exception {
   Connection conn = factory.createConnection();
   Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Destination dest = session.createQueue(destination);

   try {
      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 11
Source Project: solace-integration-guides   Source File: XAProducerSB.java    License: 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 12
Source Project: development   Source File: IndexMQSenderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void sendMessage_withJMSResources() throws Exception {
    MockitoAnnotations.initMocks(this);
    doReturn(Boolean.TRUE).when(sender).checkJMSResources();
    Connection conn = mock(Connection.class);
    doReturn(conn).when(factory).createConnection();
    Session session = mock(Session.class);
    doReturn(session).when(conn).createSession(eq(false),
            eq(Session.AUTO_ACKNOWLEDGE));
    MessageProducer producer = mock(MessageProducer.class);
    doReturn(producer).when(session).createProducer(eq(queue));
    ObjectMessage om = mock(ObjectMessage.class);
    doReturn(om).when(session).createObjectMessage();
    doNothing().when(om).setObject(caughtMessage.capture());

    sender.sendMessage(objectMessage);
    verify(factory, times(1)).createConnection();
    verify(session, times(1)).close();
    verify(conn, times(1)).close();
    verify(producer, times(1)).send(eq(om));
    assertEquals(objectMessage, caughtMessage.getValue());
}
 
Example 13
Source Project: oneops   Source File: SensorListener.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * takes the jms message
 */
public void onMessage(Message msg) {
	try {
		
		if (msg instanceof ObjectMessage) {
			BasicEvent event = (BasicEvent)((ObjectMessage)msg).getObject();
			if (logger.isDebugEnabled() || cisToLog.contains(event.getCiId())) {
				logger.info(gson.toJson(event));
			}
			sensorHeartBeat.timeStampIt(event.getChannel());
			sensorHeartBeat.timeStampIt(BasicEvent.DEFAULT_CHANNEL);
			sensor.sendCEPEvent(event);
		}
		msg.acknowledge();
	} catch (JMSException e) {
		logger.info("caught Exception in onMessage",e);

	}
}
 
Example 14
Source Project: dubbox   Source File: JmsInvoker.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Result doInvoke(Invocation invocation) throws Throwable {
	try {
		// transfer a RPC to a jms-requestor and return the call result
		QueueSession session = this.queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
		JmsQueueRequestor requestor = new JmsQueueRequestor(session, queue);
		Message message = session.createObjectMessage((Serializable) invocation);
		message.setJMSRedelivered(false);
		ObjectMessage result = (ObjectMessage) requestor.request(message, timeout);
		if (result == null)
			return new RpcResult(new RpcException("request is timeout in " + timeout + "ms"));
		return (Result) (result.getObject());
	} catch (JMSException e) {
		throw new RpcException(e);
	}
}
 
Example 15
Source Project: development   Source File: TriggerQueueServiceBean.java    License: Apache License 2.0 6 votes vote down vote up
private void sendObjectMsgSingleSession(List<? extends Serializable> objectsToSend) throws JMSException {
    Session session = null;
    Connection conn = null;
    try {
        conn = qFactory.createConnection();
        session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(queue);
        for (Serializable objectToSend : objectsToSend) {
            ObjectMessage msg = session.createObjectMessage();
            msg.setObject(objectToSend);
            producer.send(msg);
        }
    } finally {
        closeSession(session);
        closeConnection(conn);
    }
}
 
Example 16
Source Project: learning   Source File: Step6Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void sendTextMessageToJMSQueue() throws Exception {
    // Mock the qualify service to verify it's invoked
    MockHandler qualifyMock = testKit.replaceService("IntakeJMS");
    
    // Create and send a JMS message with the request XML payload
    MessageProducer producer = hornetQ.getJMSSession().createProducer(
            HornetQMixIn.getJMSQueue(REQUEST_QUEUE));
    ObjectMessage message = hornetQ.getJMSSession().createObjectMessage();
    message.setObject(MockApplication.good());
    producer.send(message);
    
    // Verify that we received the message in the service
    qualifyMock.waitForOKMessage();
    Assert.assertEquals(1, qualifyMock.getMessages().size());
}
 
Example 17
Source Project: tomee   Source File: JMSContextImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ObjectMessage createObjectMessage() {
    try {
        return wrap(session().createObjectMessage());
    } catch (final JMSException e) {
        throw toRuntimeException(e);
    }
}
 
Example 18
/**
 * On message failure test.
 *
 * @throws JMSException
 *             the JMS exception
 */
@Test
public void onMessageFailureTest() throws JMSException {
	final ObjectMessage message = mock(ObjectMessage.class);

	when(message.getObject()).thenThrow(new JMSException("test"));

	messsageListener.onMessage(message);
	verify(message, atLeastOnce()).getObject();
}
 
Example 19
/**
 * On message success test.
 *
 * @throws JMSException
 *             the JMS exception
 */
@Test
@Transactional
public void onMessageSuccessTest() throws JMSException {
	final ObjectMessage message = mock(ObjectMessage.class);

	when(message.getObject()).thenReturn(WorldBankDataSources.COUNTRIES);

	messsageListener.onMessage(message);
	verify(message, atLeastOnce()).getObject();
}
 
Example 20
Source Project: cia   Source File: RiksdagenVoteDataWorkConsumerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(final Message message) {
	try {
		updateBallot((String) ((ObjectMessage) message).getObject());
	} catch (final JMSException e) {
		LOGGER.warn("No Valid input", e);
	}
}
 
Example 21
@Test
public void testNotWhiteListedByConnectionUrlObjectMessage() throws Exception
{
    Queue destination = createQueue(getTestName());
    final Connection c = getConnectionBuilder().setDeserializationPolicyWhiteList("org.apache.qpid").build();
    try
    {
        c.start();
        Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageConsumer consumer = s.createConsumer(destination);
        MessageProducer producer = s.createProducer(destination);

        sendTestObjectMessage(s, producer);
        Message receivedMessage = consumer.receive(getReceiveTimeout());
        assertNotNull("did not receive message within receive timeout", receivedMessage);
        assertTrue("message is of wrong type", receivedMessage instanceof ObjectMessage);
        ObjectMessage receivedObjectMessage = (ObjectMessage) receivedMessage;
        try
        {
            receivedObjectMessage.getObject();
            fail("should not deserialize class");
        }
        catch (MessageFormatException e)
        {
            // pass
        }
    }
    finally
    {
        c.close();
    }
}
 
Example 22
Source Project: learning   Source File: PreQualJMSClient.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
	
    HornetQMixIn hqMixIn = new HornetQMixIn(false)
                                .setUser(USER)
                                .setPassword(PASSWD);
    
    hqMixIn.initialize();

    String requestFile = DEFAULT_REQUEST + SUFFIX;
    if (args.length == 1) {
    	requestFile = args[0] + SUFFIX;
    }

    try {
    	// JMS Client Setup
        Session session = hqMixIn.createJMSSession();
        MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(REQUEST_QUEUE));
        
        // Send the request message
        ObjectMessage request = (ObjectMessage)
        		hqMixIn.createJMSMessageFromResource(requestFile);
        producer.send(request);
        System.out.println("Sent message [\n" + request.getObject() + "\n]");
        
    } finally {
        hqMixIn.uninitialize();
    }
}
 
Example 23
@Test
public void simpleObject() throws Exception {
	Session session = mock(Session.class);
	Serializable payload = mock(Serializable.class);
	ObjectMessage jmsMessage = mock(ObjectMessage.class);
	given(session.createObjectMessage(payload)).willReturn(jmsMessage);

	this.converter.toMessage(MessageBuilder.withPayload(payload).build(), session);
	verify(session).createObjectMessage(payload);
}
 
Example 24
Source Project: activemq-artemis   Source File: ObjectMessageTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void assertEquivalent(final Message m, final int mode, final boolean redelivery) throws JMSException {
   super.assertEquivalent(m, mode, redelivery);

   ObjectMessage om = (ObjectMessage) m;
   ProxyAssertSupport.assertEquals("this is the serializable object", om.getObject());
}
 
Example 25
Source Project: cia   Source File: WorldbankDataWorkConsumerImplITest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * On message success test.
 *
 * @throws JMSException
 *             the JMS exception
 */
@Test
@Transactional
public void onMessageSuccessTest() throws JMSException {
	final ObjectMessage message = mock(ObjectMessage.class);

	final ArrayList<String> list = new ArrayList<>();
	list.add("SE");
	list.add("UIS.DR.1.G1.M");

	when(message.getObject()).thenReturn(list);

	messsageListener.onMessage(message);
	verify(message, atLeastOnce()).getObject();
}
 
Example 26
@Test
public void testWithMessageContentsDelegateForObjectMessageWithPlainObject() throws Exception {
	ObjectMessage objectMessage = mock(ObjectMessage.class);
	given(objectMessage.getObject()).willReturn(OBJECT);

	MessageContentsDelegate delegate = mock(MessageContentsDelegate.class);

	MessageListenerAdapter adapter = new MessageListenerAdapter(delegate);
	adapter.onMessage(objectMessage);

	verify(delegate).handleMessage(OBJECT);
}
 
Example 27
/**
 * Test create message with object
 */
@Test
public void testCreateMessageWithObject() throws JMSException {
    Map<String, String> expectedPayload = new HashMap<String, String>();
    expectedPayload.put("testKey", "testValue");

    ObjectMessage objectMessage = new SQSObjectMessage((Serializable) expectedPayload);
    
    Map<String, String> actualPayload = (HashMap<String, String>) objectMessage.getObject();
    assertEquals(expectedPayload, actualPayload);
}
 
Example 28
Source Project: datawave   Source File: QueryMetricMessage.java    License: Apache License 2.0 5 votes vote down vote up
public static QueryMetricMessage fromJMSMessage(ObjectMessage msg) throws JMSException {
    Object o = msg.getObject();
    if (o instanceof QueryMetricMessage)
        return (QueryMetricMessage) o;
    else
        throw new IllegalArgumentException("Object is of wrong type: " + o.getClass());
}
 
Example 29
@Test
public void testFromJmsToAppToJms() {

    MyJmsClient client = new MyJmsClient(jms.createQueue("some-queue"));
    Map<String, Object> map = new HashMap<>();
    map.put("mp.messaging.incoming.source.connector", JmsConnector.CONNECTOR_NAME);
    map.put("mp.messaging.incoming.source.destination", "source");
    map.put("mp.messaging.outgoing.jms.connector", JmsConnector.CONNECTOR_NAME);
    map.put("mp.messaging.outgoing.jms.destination", "should-not-be-used");
    MapBasedConfig config = new MapBasedConfig(map);
    addConfig(config);
    deploy(MyAppProcessingData.class);

    AtomicInteger count = new AtomicInteger();
    JMSProducer producer = jms.createProducer();
    Queue source = jms.createQueue("source");

    for (int i = 0; i < 20; i++) {
        ObjectMessage message = jms.createObjectMessage(count.getAndIncrement());
        producer.send(source, message);
    }

    await().until(() -> client.messages.size() >= 10);
    assertThat(client.messages).allSatisfy(entry -> {
        try {
            assertThat(entry.getBody(String.class)).isNotNull();
            assertThat(entry.getJMSCorrelationID()).startsWith("my-correlation-");
            assertThat(entry.getStringProperty("prop")).isEqualTo("bar");
        } catch (JMSException e) {
            fail("unable to read jms data", e);
        }
    });
}
 
Example 30
Source Project: localization_nifi   Source File: JmsFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static byte[] createByteArray(final Message message) throws JMSException {
    if (message instanceof TextMessage) {
        return getMessageBytes((TextMessage) message);
    } else if (message instanceof BytesMessage) {
        return getMessageBytes((BytesMessage) message);
    } else if (message instanceof StreamMessage) {
        return getMessageBytes((StreamMessage) message);
    } else if (message instanceof MapMessage) {
        return getMessageBytes((MapMessage) message);
    } else if (message instanceof ObjectMessage) {
        return getMessageBytes((ObjectMessage) message);
    }
    return new byte[0];
}