javax.jms.ObjectMessage源码实例Demo

org.apache.log4j.spi.ErrorCode#javax.jms.ObjectMessage源码实例Demo

下面列出了org.apache.log4j.spi.ErrorCode#javax.jms.ObjectMessage 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: activemq-artemis   文件: JMSTest.java
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();
   }
}
 
源代码2 项目: cacheonix-core   文件: JMSAppender.java
/**
    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);
   }
 }
 
源代码3 项目: activemq-artemis   文件: GeneralInteropTest.java
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();
      }
   }

}
 
@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);
  }
}
 
/**
 * 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;
	}
}
 
源代码6 项目: localization_nifi   文件: TestGetJMSQueue.java
@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();
}
 
源代码7 项目: cxf   文件: JMSMessageConverter.java
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[]{};
    }
}
 
源代码8 项目: development   文件: TaskListenerTest.java
@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());
}
 
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);
}
 
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();
   }
}
 
源代码11 项目: solace-integration-guides   文件: XAProducerSB.java
@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();
    }
}
 
源代码12 项目: development   文件: IndexMQSenderTest.java
@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());
}
 
源代码13 项目: oneops   文件: SensorListener.java
/**
 * 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);

	}
}
 
源代码14 项目: dubbox   文件: JmsInvoker.java
@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);
	}
}
 
源代码15 项目: development   文件: TriggerQueueServiceBean.java
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);
    }
}
 
源代码16 项目: learning   文件: Step6Test.java
@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());
}
 
源代码17 项目: tomee   文件: JMSContextImpl.java
@Override
public ObjectMessage createObjectMessage() {
    try {
        return wrap(session().createObjectMessage());
    } catch (final JMSException e) {
        throw toRuntimeException(e);
    }
}
 
/**
 * 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();
}
 
/**
 * 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();
}
 
源代码20 项目: cia   文件: RiksdagenVoteDataWorkConsumerImpl.java
@Override
public void onMessage(final Message message) {
	try {
		updateBallot((String) ((ObjectMessage) message).getObject());
	} catch (final JMSException e) {
		LOGGER.warn("No Valid input", e);
	}
}
 
@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();
    }
}
 
源代码22 项目: learning   文件: PreQualJMSClient.java
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();
    }
}
 
@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);
}
 
源代码24 项目: activemq-artemis   文件: ObjectMessageTest.java
@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());
}
 
源代码25 项目: cia   文件: WorldbankDataWorkConsumerImplITest.java
/**
 * 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();
}
 
@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);
}
 
/**
 * 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);
}
 
源代码28 项目: datawave   文件: QueryMetricMessage.java
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());
}
 
@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);
        }
    });
}
 
源代码30 项目: localization_nifi   文件: JmsFactory.java
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];
}