Java Code Examples for javax.jms.Session#createObjectMessage()

The following examples show how to use javax.jms.Session#createObjectMessage() . 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: ObjectMessageClassWhitelistingTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
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 2
Source File: JMSMessageConverter.java    From cxf with Apache License 2.0 6 votes vote down vote up
public Message toMessage(Object object, Session session) throws JMSException {
    if (object instanceof Message) {
        return (Message)object;
    } else if (object instanceof String) {
        return session.createTextMessage((String)object);
    } else if (object instanceof byte[]) {
        BytesMessage message = session.createBytesMessage();
        message.writeBytes((byte[])object);
        return message;
    } else if (object instanceof Serializable) {
        return session.createObjectMessage((Serializable)object);
    } else {
        throw new IllegalArgumentException("Unsupported type " + nullSafeClassName(object) + "."
                                           + " Valid types are: String, byte[], Serializable object.");
    }
}
 
Example 3
Source File: TestGetJMSQueue.java    From localization_nifi with 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 4
Source File: TestGetJMSQueue.java    From nifi with 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 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: JmsTransactionalStorage.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Override
public String storeMessage(String messageId, String correlationId, Date receivedDate, String comments, String label, S message) throws SenderException {
	Session session=null;
	try {
		session = createSession();
		ObjectMessage msg = session.createObjectMessage(message);
		msg.setStringProperty(FIELD_TYPE,getType());
		msg.setStringProperty(FIELD_ORIGINAL_ID,messageId);
		msg.setJMSCorrelationID(correlationId);
		msg.setLongProperty(FIELD_RECEIVED_DATE,receivedDate.getTime());
		msg.setStringProperty(FIELD_COMMENTS,comments);
		if (StringUtils.isNotEmpty(getSlotId())) {
			msg.setStringProperty(FIELD_SLOTID,getSlotId());
		}
		msg.setStringProperty(FIELD_LABEL,label);
		return send(session,getDestination(),msg);
	} catch (Exception e) {
		throw new SenderException(e);
	} finally {
		closeSession(session);
	}
}
 
Example 7
Source File: InvokeMessageConverter.java    From DWSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
public Message toMessage(Object obj, Session session) throws JMSException,
			MessageConversionException {

		if (obj instanceof InvokeMessage) {
			ActiveMQObjectMessage objMsg = (ActiveMQObjectMessage) session
					.createObjectMessage();
			long delay=5*1000;
        	System.out.println("延时:"+delay/1000+"秒");
        	System.out.println("msgId:"+objMsg.getJMSMessageID());
        	objMsg.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
//        	objMsg.setExpiration(2000);
        	
			Map<String, byte[]> map = new HashMap<String, byte[]>();
			try {
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				ObjectOutputStream oos = new ObjectOutputStream(bos);
				oos.writeObject(obj);
				map.put("InvokeMessage", bos.toByteArray());
			} catch (IOException e) {
				e.printStackTrace();
			}
			objMsg.setObjectProperty("Map", map);
			return objMsg;
		} else {
			throw new JMSException("Object:[" + obj + "] is not InvokeMessage");
		}
	}
 
Example 8
Source File: ObjectMessageTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetObjectPropertyForDouble() throws Exception
{
    Queue queue = createQueue(getTestName());
    Connection connection = getConnection();
    try
    {
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        ObjectMessage msg = session.createObjectMessage("test");
        msg.setObjectProperty("TestDoubleProperty", Double.MAX_VALUE);
        assertEquals(Double.MAX_VALUE, msg.getObjectProperty("TestDoubleProperty"));

        MessageProducer producer = session.createProducer(queue);
        producer.send(msg);

        MessageConsumer consumer = session.createConsumer(queue);
        connection.start();
        Message receivedMessage = consumer.receive(getReceiveTimeout());

        assertTrue("ObjectMessage should be received", receivedMessage instanceof ObjectMessage);
        assertEquals("Unexpected received property",
                     Double.MAX_VALUE,
                     receivedMessage.getObjectProperty("TestDoubleProperty"));
    }
    finally
    {
        connection.close();
    }
}
 
Example 9
Source File: ObjectMessageClassWhitelistingTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private void sendTestObjectMessage(final Session s, final MessageProducer producer) throws JMSException
{
    HashMap<String, Integer> messageContent = new HashMap<>();
    messageContent.put("value", TEST_VALUE);
    Message objectMessage = s.createObjectMessage(messageContent);
    producer.send(objectMessage);
}
 
Example 10
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 11
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 12
Source File: ActiveMQRASession.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Create an object message
 *
 * @param object The object
 * @return The message
 * @throws JMSException Thrown if an error occurs
 */
@Override
public ObjectMessage createObjectMessage(final Serializable object) throws JMSException {
   Session session = getSessionInternal();

   if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
      ActiveMQRALogger.LOGGER.trace("createObjectMessage(" + object + ")" + session);
   }

   return session.createObjectMessage(object);
}
 
Example 13
Source File: CloudstreetApiWCI.java    From cloudstreetmarket.com with GNU General Public License v3.0 5 votes vote down vote up
public MessageCreator messageCreator(Serializable payload){
	return new MessageCreator() {
		@Override
		public Message createMessage(Session session) throws JMSException {
			return session.createObjectMessage(payload);
		}
    };
}
 
Example 14
Source File: JmsStubMessages.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private Message createMessage(Session session, Object payload) throws JMSException {
	if (payload instanceof String) {
		return session.createTextMessage((String) payload);
	}
	else if (payload instanceof byte[]) {
		BytesMessage bytesMessage = session.createBytesMessage();
		bytesMessage.writeBytes((byte[]) payload);
		return bytesMessage;
	}
	else if (payload instanceof Serializable) {
		return session.createObjectMessage((Serializable) payload);
	}
	return session.createMessage();
}
 
Example 15
Source File: SearchClientProxy.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * Uses Request/reply mechanism for synchronous operation.
 * 
 */
public SearchResults doSearch(final String queryString, final List<String> condQueries, final Identity identity, final Roles roles, final int firstResult,
        final int maxResults, final boolean doHighlighting) throws ServiceNotAvailableException, ParseException, QueryException {
    if (log.isDebugEnabled()) {
        log.debug("STARTqueryString=" + queryString);
    }
    final SearchRequest searchRequest = new SearchRequest(queryString, condQueries, identity.getKey(), roles, firstResult, maxResults, doHighlighting);
    Session session = null;
    try {
        session = acquireSession();
        if (log.isDebugEnabled()) {
            log.debug("doSearch session=" + session);
        }
        final Message requestMessage = session.createObjectMessage(searchRequest);
        final Message returnedMessage = doSearchRequest(session, requestMessage);
        queryCount_++;
        if (returnedMessage != null) {
            final String responseStatus = returnedMessage.getStringProperty(JMS_RESPONSE_STATUS_PROPERTY_NAME);
            if (responseStatus.equalsIgnoreCase(JMS_RESPONSE_STATUS_OK)) {
                final SearchResults searchResult = (SearchResults) ((ObjectMessage) returnedMessage).getObject();
                if (log.isDebugEnabled()) {
                    log.debug("ENDqueryString=" + queryString);
                }
                return searchResult;
            } else if (responseStatus.equalsIgnoreCase(JMS_RESPONSE_STATUS_PARSE_EXCEPTION)) {
                throw new ParseException("can not parse query=" + queryString);
            } else if (responseStatus.equalsIgnoreCase(JMS_RESPONSE_STATUS_QUERY_EXCEPTION)) {
                throw new QueryException("invalid query=" + queryString);
            } else if (responseStatus.equalsIgnoreCase(JMS_RESPONSE_STATUS_SERVICE_NOT_AVAILABLE_EXCEPTION)) {
                throw new ServiceNotAvailableException("Remote search service not available" + queryString);
            } else {
                log.warn("doSearch: receive unkown responseStatus=" + responseStatus);
                return null;
            }
        } else {
            // null returnedMessage
            throw new ServiceNotAvailableException("communication error with JMS - cannot receive messages!!!");
        }
    } catch (final JMSException e) {
        log.error("Search failure I", e);
        throw new ServiceNotAvailableException("communication error with JMS - cannot send messages!!!");
    } finally {
        releaseSession(session);
    }
}
 
Example 16
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 17
Source File: JmsTest.java    From tomee with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private synchronized void createSender(final Connection connection, final Destination requestQueue) throws JMSException {
    Session session = null;
    MessageProducer producer = null;
    MessageConsumer consumer = null;
    try {
        // create request
        final Map<String, Object> request = new TreeMap<>();
        request.put("args", new Object[]{"cheese"});

        // create a new temp response queue
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final Destination responseQueue = session.createTemporaryQueue();

        // Create a request messages
        final ObjectMessage requestMessage = session.createObjectMessage();
        requestMessage.setJMSReplyTo(responseQueue);
        requestMessage.setObject((Serializable) request);

        // Send the request message
        producer = session.createProducer(requestQueue);
        producer.send(requestMessage);

        // wait for the response message
        consumer = session.createConsumer(responseQueue);
        final Message message = consumer.receive(30000);

        // verify message
        assertNotNull("Did not get a response message", message);
        assertTrue("Response message is not an ObjectMessage", message instanceof ObjectMessage);
        final ObjectMessage responseMessage = (ObjectMessage) message;
        final Serializable object = responseMessage.getObject();
        assertNotNull("Response ObjectMessage contains a null object");
        assertTrue("Response ObjectMessage does not contain an instance of Map", object instanceof Map);
        final Map<String, String> response = (Map<String, String>) object;

        // process results
        final String returnValue = response.get("return");
        assertEquals("test-cheese", returnValue);
    } finally {
        MdbUtil.close(consumer);
        MdbUtil.close(producer);
        MdbUtil.close(session);
    }
}
 
Example 18
Source File: MdbTest.java    From tomee with Apache License 2.0 4 votes vote down vote up
private void createSender() throws JMSException {
    Connection connection = null;
    Session session = null;
    MessageProducer producer = null;
    MessageConsumer consumer = null;
    try {
        connection = connectionFactory.createConnection();
        connection.start();

        // create request
        final Map<String, Object> request = new TreeMap<>();
        request.put("args", new Object[]{"cheese"});

        // create a new temp response queue
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final Destination responseQueue = session.createTemporaryQueue();

        // Create a request messages
        final ObjectMessage requestMessage = session.createObjectMessage();
        requestMessage.setJMSReplyTo(responseQueue);
        requestMessage.setObject((Serializable) request);

        // Send the request message
        producer = session.createProducer(session.createQueue(REQUEST_QUEUE_NAME));
        producer.send(requestMessage);

        // wait for the response message
        consumer = session.createConsumer(responseQueue);
        final Message message = consumer.receive(30000);

        // verify message
        assertNotNull("Did not get a response message", message);
        assertTrue("Response message is not an ObjectMessage", message instanceof ObjectMessage);
        final ObjectMessage responseMessage = (ObjectMessage) message;
        final Serializable object = responseMessage.getObject();
        assertNotNull("Response ObjectMessage contains a null object");
        assertTrue("Response ObjectMessage does not contain an instance of Map", object instanceof Map);
        final Map<String, String> response = (Map<String, String>) object;

        // process results
        final String returnValue = (String) response.get("return");
        assertEquals("test-cheese", returnValue);
    } finally {
        MdbUtil.close(consumer);
        MdbUtil.close(producer);
        MdbUtil.close(session);
        MdbUtil.close(connection);
    }
}
 
Example 19
Source File: SimpleMessageConverter.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Create a JMS ObjectMessage for the given Serializable object.
 * @param object the Serializable object to convert
 * @param session current JMS session
 * @return the resulting message
 * @throws JMSException if thrown by JMS methods
 * @see javax.jms.Session#createObjectMessage
 */
protected ObjectMessage createMessageForSerializable(Serializable object, Session session) throws JMSException {
	return session.createObjectMessage(object);
}
 
Example 20
Source File: SimpleMessageConverter.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Create a JMS ObjectMessage for the given Serializable object.
 * @param object the Serializable object to convert
 * @param session current JMS session
 * @return the resulting message
 * @throws JMSException if thrown by JMS methods
 * @see javax.jms.Session#createObjectMessage
 */
protected ObjectMessage createMessageForSerializable(Serializable object, Session session) throws JMSException {
	return session.createObjectMessage(object);
}