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

The following examples show how to use javax.jms.ObjectMessage#getObject() . 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: ChangeSentMessageTest.java    From activemq-artemis with Apache License 2.0 7 votes vote down vote up
/**
 * test Object messages can be changed after sending with no side-affects
 *
 * @throws Exception
 */
@SuppressWarnings("rawtypes")
public void testDoChangeSentMessage() throws Exception {
   Destination destination = createDestination("test-" + ChangeSentMessageTest.class.getName());
   Connection connection = createConnection();
   connection.start();
   Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer consumer = consumerSession.createConsumer(destination);
   Session publisherSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = publisherSession.createProducer(destination);
   HashMap<String, Integer> map = new HashMap<>();
   ObjectMessage message = publisherSession.createObjectMessage();
   for (int i = 0; i < COUNT; i++) {
      map.put(VALUE_NAME, Integer.valueOf(i));
      message.setObject(map);
      producer.send(message);
      assertTrue(message.getObject() == map);
   }
   for (int i = 0; i < COUNT; i++) {
      ObjectMessage msg = (ObjectMessage) consumer.receive();
      HashMap receivedMap = (HashMap) msg.getObject();
      Integer intValue = (Integer) receivedMap.get(VALUE_NAME);
      assertTrue(intValue.intValue() == i);
   }
}
 
Example 2
Source File: RiksdagenApiAgentWorkConsumerImpl.java    From cia with Apache License 2.0 6 votes vote down vote up
@Override
public void onMessage(final Message message) {
	try {
		configureAuthentication();
		final ObjectMessage msg = (ObjectMessage) message;
		LOGGER.info("Consumed message:{}", msg.getObject());
		final RiksdagenDataSources dataSource = (RiksdagenDataSources) msg.getObject();

		final Collection<RiksdagenDataSourcesWorkGenerator> values = beansOfType.values();

		for (final RiksdagenDataSourcesWorkGenerator riksdagenDataSourcesWorkGenerator : values) {
			if (riksdagenDataSourcesWorkGenerator.matches(dataSource)) {
				riksdagenDataSourcesWorkGenerator.generateWorkOrders();
				return;
			}
		}
	} catch (final JMSException exception) {
		LOGGER.warn("jms", exception);
	} finally {
		clearAuthentication();			
	}
}
 
Example 3
Source File: WorldBankApiAgentWorkConsumerImpl.java    From cia with Apache License 2.0 6 votes vote down vote up
@Override
public void onMessage(final Message message) {
	try {
		configureAuthentication();
		final ObjectMessage msg = (ObjectMessage) message;
		LOGGER.info("Consumed message:{}", msg.getObject());
		final WorldBankDataSources dataSource = (WorldBankDataSources) msg.getObject();
		final Collection<WorldBankDataSourcesWorkGenerator> values = beansOfType.values();

		for (final WorldBankDataSourcesWorkGenerator worldBankDataSourcesWorkGenerator : values) {
			if (worldBankDataSourcesWorkGenerator.matches(dataSource)) {
				worldBankDataSourcesWorkGenerator.generateWorkOrders();
			}
		}
	} catch (final JMSException exception) {
		LOGGER.warn("jms", exception);
	} finally {
		clearAuthentication();
	}
}
 
Example 4
Source File: JMSSink.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public final void onMessage(final Message message) {

      try {
         if (message instanceof ObjectMessage) {
            final ObjectMessage objectMessage = (ObjectMessage) message;
            final LoggingEvent event = (LoggingEvent) objectMessage.getObject();
            final Logger remoteLogger = Logger.getLogger(event.getLoggerName());
            remoteLogger.callAppenders(event);
         } else {
            logger.warn("Received message is of type " + message.getJMSType()
                    + ", was expecting ObjectMessage.");
         }
      } catch (final JMSException e) {
         logger.error("Exception thrown while processing incoming message.",
                 e);
      }
   }
 
Example 5
Source File: TopicTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void onMessage(final Message m) {
   ObjectMessage om = (ObjectMessage) m;

   try {
      Wibble2 w = (Wibble2) om.getObject();
   } catch (Exception e) {
      failed = true;
   }

   count++;

   if (count == num) {
      notify();
   }
}
 
Example 6
Source File: HandlingEventRegistrationAttemptConsumer.java    From pragmatic-microservices-lab with MIT License 6 votes vote down vote up
@Override
    public void onMessage(Message message) {
        try {
            ObjectMessage objectMessage = (ObjectMessage) message;
            HandlingEventRegistrationAttempt attempt
                    = (HandlingEventRegistrationAttempt) objectMessage.getObject();
            handlingEventService.registerHandlingEvent(
                    attempt.getCompletionTime(),
                    attempt.getTrackingId(),
                    attempt.getVoyageNumber(),
                    attempt.getUnLocode(),
                    attempt.getType());
        } catch (JMSException | CannotCreateHandlingEventException e) {
            // Poison messages will be placed on dead-letter queue.
            throw new RuntimeException("Error occurred processing message", e);
//        } catch (JMSException e) {
            // logger.log(Level.SEVERE, e.getMessage(), e);
        }
    }
 
Example 7
Source File: MessageDrivenBean.java    From wildfly-cookbook with Apache License 2.0 6 votes vote down vote up
public void onMessage(Message message) {
	int count = 1;
	try {
		ObjectMessage objectMessage = (ObjectMessage) message;
		Serializable object = objectMessage.getObject();
		@SuppressWarnings("unchecked")
		HashMap<String, Serializable> map = (HashMap<String, Serializable>) object;
		String text = (String) map.get("message");
		count = (Integer) map.get("count");
		long delay = (Long) map.get("delay");
		System.out.println(count + ": " + text);
		Thread.sleep(delay);
	} catch (Exception e) {
		System.out.println("handle message " + count + " met " + e.getMessage());
	} 
}
 
Example 8
Source File: ObjectMessageClassWhitelistingTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testWhiteListedClassByConnectionUrlObjectMessage() throws Exception
{
    Queue destination = createQueue(getTestName());
    final Connection c =
            getConnectionBuilder().setDeserializationPolicyWhiteList("java.util.HashMap,java.lang").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;

        @SuppressWarnings("unchecked")
        HashMap<String, Integer> object = (HashMap<String, Integer>) receivedObjectMessage.getObject();
        assertEquals("Unexpected value", (Integer) TEST_VALUE, object.get("value"));
    }
    finally
    {
        c.close();
    }
}
 
Example 9
Source File: SQSMessageConsumerPrefetchTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Test ConvertToJMSMessage with an object message that contains illegal sqs message body
 */
@Test
public void testConvertToJMSMessageObjectIllegalBody() throws JMSException, IOException {

    /*
     * Set up consumer prefetch and mocks
     */

    Map<String,MessageAttributeValue> mapMessageAttributes = new HashMap<String, MessageAttributeValue>();

    MessageAttributeValue messageAttributeValue = new MessageAttributeValue();
    messageAttributeValue.setStringValue(SQSMessage.OBJECT_MESSAGE_TYPE);
    messageAttributeValue.setDataType(SQSMessagingClientConstants.STRING);
    mapMessageAttributes.put(SQSMessage.JMS_SQS_MESSAGE_TYPE, messageAttributeValue);

    Map<String, String> mapAttributes = new HashMap<String, String>();
    mapAttributes.put(SQSMessagingClientConstants.APPROXIMATE_RECEIVE_COUNT, "1");

    com.amazonaws.services.sqs.model.Message message = mock(com.amazonaws.services.sqs.model.Message.class);
    // Return message attributes with message type 'OBJECT'
    when(message.getMessageAttributes()).thenReturn(mapMessageAttributes);
    when(message.getAttributes()).thenReturn(mapAttributes);
    when(message.getBody()).thenReturn("Some text that does not represent an object");

    /*
     * Convert the SQS message to JMS Message
     */
    ObjectMessage jsmMessage = (ObjectMessage) consumerPrefetch.convertToJMSMessage(message);

    /*
     * Verify results
     */
    try {
        jsmMessage.getObject();
        fail("Expect JMSException");
    } catch (JMSException jmse) {
        // Expected JMS exception
    }
}
 
Example 10
Source File: JmsTransactionTestSupport.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected List<String> assertReceivedObjectMessageWithListBody(Message message) throws JMSException {
   assertNotNull("Should have received a message!", message);
   assertEquals("foo header", "abc", message.getStringProperty("foo"));

   assertTrue("Should be an object message but was: " + message, message instanceof ObjectMessage);
   ObjectMessage objectMessage = (ObjectMessage) message;
   List<String> body = (List<String>) objectMessage.getObject();
   LOG.info("Received body: " + body);

   assertEquals("Size of list should be 1", 1, body.size());
   assertEquals("element 0 of list", "First", body.get(0));
   return body;
}
 
Example 11
Source File: JmsTransactionalStorage.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Override
public S getMessage(String messageId) throws ListenerException {
	try {
		ObjectMessage msg=getJmsMessage(messageId);
	return (S)msg.getObject();
	} catch (JMSException e) {
		throw new ListenerException(e);
	}
}
 
Example 12
Source File: QueryMetricMessage.java    From datawave with 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 13
Source File: ObjectMessageIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
private void doTestReceiveSerializedContentPolicyTest(String whiteList, String blackList, boolean succeed) throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        String options = null;
        if(whiteList != null) {
            options = "?jms.deserializationPolicy.whiteList=" + whiteList;
        }

        if(blackList != null) {
            if(options == null) {
                options = "?";
            } else {
                options += "&";
            }

            options +="jms.deserializationPolicy.blackList=" + blackList;
        }

        Connection connection = testFixture.establishConnecton(testPeer, options);

        connection.start();

        testPeer.expectBegin();

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

        MessageAnnotationsDescribedType msgAnnotations = new MessageAnnotationsDescribedType();
        msgAnnotations.setSymbolKeyedAnnotation(AmqpMessageSupport.JMS_MSG_TYPE.toString(), AmqpMessageSupport.JMS_OBJECT_MESSAGE);
        PropertiesDescribedType properties = new PropertiesDescribedType();
        properties.setContentType(AmqpMessageSupport.SERIALIZED_JAVA_OBJECT_CONTENT_TYPE);

        SimplePojo expectedContent = new SimplePojo(UUID.randomUUID());

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

        DescribedType dataContent = new DataDescribedType(new Binary(bytes));

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, msgAnnotations, properties, null, dataContent);
        testPeer.expectDispositionThatIsAcceptedAndSettled();

        MessageConsumer messageConsumer = session.createConsumer(queue);
        Message receivedMessage = messageConsumer.receive(3000);
        testPeer.waitForAllHandlersToComplete(3000);

        assertNotNull(receivedMessage);
        assertTrue(receivedMessage instanceof ObjectMessage);

        ObjectMessage objectMessage = (ObjectMessage) receivedMessage;
        Object received = null;
        try {
            received = objectMessage.getObject();
            if(!succeed) {
                fail("Should not be able to read blocked content");
            }
        } catch (JMSException jmsEx) {
            LOG.debug("Caught: ", jmsEx);
            if(succeed) {
                fail("Should have been able to read blocked content");
            }
        }

        if(succeed) {
            assertEquals("Content not as expected", expectedContent, received);
        }

        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(3000);
    }
}
 
Example 14
Source File: MdbConnectionFactoryTests.java    From tomee with Apache License 2.0 4 votes vote down vote up
public void test02_directRpc() throws Exception {
        final Connection connection = createConnection();
        Session session = null;
        MessageProducer producer = null;
        MessageConsumer consumer = null;
        try {

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

            // initialize session
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            final Destination requestQueue = session.createQueue("BasicMdb");
            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);

//            System.out.println("\n" + "***************************************\n" +
//                    "Sent request message: " + requestMessage + "\n" +
//                    "         request map: " + request + "\n" +
//                    "            to queue: " + requestQueue + "\n" +
//                    "***************************************\n\n");

            // create consumer
            consumer = session.createConsumer(responseQueue);
//            System.out.println("\n" + "***************************************\n" +
//                    "Listening for response at : " + responseQueue + "\n" +
//                    "***************************************\n\n");

            // wait for response mesage
            final Message message = consumer.receive(1000);

            // 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 response = (Map) object;

            // process results
            if (response.containsKey("exception")) {
                throw (Exception) response.get("return");
            }
            final String returnValue = (String) response.get("return");
            assertEquals("eseehc", returnValue);
        } finally {
            MdbUtil.close(producer);
            MdbUtil.close(session);
            MdbUtil.close(connection);
        }
    }
 
Example 15
Source File: ClusterEventBus.java    From olat with Apache License 2.0 4 votes vote down vote up
void serveMessage(final Message message, final long receiveEnqueueTime) {
    // stats
    final long receiveTime = System.currentTimeMillis();
    if (receiveEnqueueTime > 0) {
        final long diff = receiveTime - receiveEnqueueTime;
        mrtgProbeJMSEnqueueTime_.addMeasurement(diff);
    }
    if (lastOnMessageFinishTime_ != -1) {
        final long waitingTime = receiveTime - lastOnMessageFinishTime_;
        // the waiting time is inverted to represent more like a frequency
        // the values it translates to are the following:
        // 0ms -> 100
        // 1ms -> 66
        // 2ms -> 50
        // 4ms -> 33
        // 6ms -> 25
        // 8ms -> 20
        // 18ms -> 10
        // 20ms -> 9
        // 23ms -> 8
        // 26.5ms -> 7
        // 31ms -> 6
        // 38ms -> 5
        mrtgProbeJMSLoad_.addMeasurement((long) (100.0 / ((waitingTime / 2.0) + 1.0)));
        lastOnMessageFinishTime_ = -1;
    }

    final ObjectMessage om = (ObjectMessage) message;
    try {
        // unpack
        final JMSWrapper jmsWrapper = (JMSWrapper) om.getObject();
        final Integer nodeId = jmsWrapper.getNodeId();
        final MultiUserEvent event = jmsWrapper.getMultiUserEvent();
        final OLATResourceable ores = jmsWrapper.getOres();
        final boolean fromSameNode = clusterConfig.getNodeId().equals(nodeId);

        // update nodeinfo statistics
        final NodeInfo nodeInfo = getNodeInfoFor(nodeId);
        if (!nodeInfo.update(jmsWrapper)) {
            log.warn("onMessage: update failed. clustereventbus: " + this);
        }

        final String recMsg = "received msg: " + (fromSameNode ? "[same node]" : "") + " from node:" + nodeId + ", olat-id:" + jmsWrapper.getMsgId() + ", ores:"
                + ores.getResourceableTypeName() + ":" + ores.getResourceableId() + ", event:" + event + "}";

        // stats
        final long jmsTimestamp = om.getJMSTimestamp();
        if (jmsTimestamp != 0) {
            final long deliveryTime = receiveTime - jmsTimestamp;
            if (deliveryTime > 1500) {
                // then issue a log statement
                log.warn("message received with long delivery time (longer than 1500ms: " + deliveryTime + "): " + recMsg);
            }
            mrtgProbeJMSDeliveryTime_.addMeasurement(deliveryTime);
        }

        addToReceivedScreen(recMsg);
        if (log.isDebugEnabled()) {
            log.debug(recMsg);
        }

        // message with destination and source both having this vm are ignored here, since they were already
        // "inline routed" when having been sent (direct call within the vm).
        if (!fromSameNode) {
            // distribute the unmarshalled event to all JVM wide listeners for this channel.
            doFire(event, ores, eventLogger);
            DBFactory.getInstance(false).commitAndCloseSession();
        } // else message already sent "in-vm"

        // stats
        final long doneTime = System.currentTimeMillis();
        final long processingTime = doneTime - receiveTime;
        if (processingTime > 500) {
            // then issue a log statement
            log.warn("message received with long processing time (longer than 500ms: " + processingTime + "): " + recMsg);
        }
        mrtgProbeJMSProcessingTime_.addMeasurement(processingTime);
    } catch (final Error er) {
        log.error("Uncaught Error in ClusterEventBus.onMessage!", er);
        throw er;
    } catch (final RuntimeException re) {
        log.error("Uncaught RuntimeException in ClusterEventBus.onMessage!", re);
        throw re;
    } catch (final JMSException e) {
        log.warn("JMSException in ClusterEventBus.onMessage", e);
        throw new OLATRuntimeException("error when receiving jms messages", e);
    } catch (final Throwable th) {
        log.error("Uncaught Throwable in ClusterEventBus.onMessage!", th);
    } finally {
        lastOnMessageFinishTime_ = System.currentTimeMillis();
    }
}
 
Example 16
Source File: MimeMessageObjectMessageSource.java    From james-project with Apache License 2.0 4 votes vote down vote up
public MimeMessageObjectMessageSource(ObjectMessage message) throws JMSException {
    this.message = message;
    this.id = message.getJMSMessageID();
    this.content = (byte[]) message.getObject();
    in = new SharedByteArrayInputStream(content);
}
 
Example 17
Source File: CompressedInteropTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
private void receiveObjectMessage(boolean useCore) throws Exception {
   ObjectMessage objectMessage = (ObjectMessage) receiveMessage(useCore);
   Object objectVal = objectMessage.getObject();
   assertEquals(TEXT, objectVal);
}
 
Example 18
Source File: JMSObjectInputOperator.java    From attic-apex-malhar with Apache License 2.0 2 votes vote down vote up
/**
 * Extract a Serializable object from the given {@link ObjectMessage}.
 *
 * @param message the message to convert
 * @return the resulting Serializable object
 * @throws JMSException if thrown by JMS methods
 */
protected Serializable extractSerializableFromMessage(ObjectMessage message) throws JMSException
{
  return message.getObject();
}
 
Example 19
Source File: SimpleMessageConverter.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Extract a Serializable object from the given {@link ObjectMessage}.
 * @param message the message to convert
 * @return the resulting Serializable object
 * @throws JMSException if thrown by JMS methods
 */
protected Serializable extractSerializableFromMessage(ObjectMessage message) throws JMSException {
	return message.getObject();
}