Java Code Examples for javax.jms.BytesMessage#writeBytes()

The following examples show how to use javax.jms.BytesMessage#writeBytes() . 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: NIOSSLWindowSizeTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void testLargePayload() throws Exception {
   Queue dest = session.createQueue("TEST");
   MessageProducer prod = null;
   try {
      prod = session.createProducer(dest);
      BytesMessage msg = session.createBytesMessage();
      msg.writeBytes(messageData);
      prod.send(msg);
   } finally {
      prod.close();
   }
   MessageConsumer cons = null;
   try {
      cons = session.createConsumer(dest);
      assertNotNull(cons.receive(30000L));
   } finally {
      cons.close();
   }
}
 
Example 2
Source File: AdvisoryTempDestinationTests.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void testSlowConsumerAdvisory() throws Exception {
   Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   TemporaryQueue queue = s.createTemporaryQueue();
   MessageConsumer consumer = s.createConsumer(queue);
   assertNotNull(consumer);

   Topic advisoryTopic = AdvisorySupport.getSlowConsumerAdvisoryTopic((ActiveMQDestination) queue);
   s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic);
   // start throwing messages at the consumer
   MessageProducer producer = s.createProducer(queue);
   for (int i = 0; i < MESSAGE_COUNT; i++) {
      BytesMessage m = s.createBytesMessage();
      m.writeBytes(new byte[1024]);
      producer.send(m);
   }
   Message msg = advisoryConsumer.receive(1000);
   assertNotNull(msg);
}
 
Example 3
Source File: LargeMessageTestSupport.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void testLargeMessages() throws Exception {
   for (int i = 0; i < MESSAGE_COUNT; i++) {
      LOG.info("Sending message: " + i);
      BytesMessage msg = producerSession.createBytesMessage();
      msg.writeBytes(largeMessageData);
      producer.send(msg);
   }
   long now = System.currentTimeMillis();
   synchronized (messageCount) {
      while (now + 60000 > System.currentTimeMillis() && messageCount.get() < MESSAGE_COUNT) {
         LOG.info("message count = " + messageCount);
         messageCount.wait(1000);
      }
   }
   LOG.info("Finished count = " + messageCount);
   assertTrue("Not enough messages - expected " + MESSAGE_COUNT + " but got " + messageCount, messageCount.get() == MESSAGE_COUNT);
   assertTrue("received messages are not valid", validMessageConsumption);
   Thread.sleep(1000);
   LOG.info("FINAL count = " + messageCount);
}
 
Example 4
Source File: GeneralInteropTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void sendBytesMessageUsingOpenWire(byte[] bytesData) throws Exception {
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE);

   final ActiveMQMessageProducer producer = (ActiveMQMessageProducer) session.createProducer(destination);

   BytesMessage bytesMessage = session.createBytesMessage();
   bytesMessage.writeBytes(bytesData);
   bytesMessage.writeBoolean(true);
   bytesMessage.writeLong(99999L);
   bytesMessage.writeChar('h');
   bytesMessage.writeInt(987);
   bytesMessage.writeShort((short) 1099);
   bytesMessage.writeUTF("hellobytes");

   producer.send(bytesMessage);
}
 
Example 5
Source File: AdvisoryTempDestinationTests.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void testTempMessageConsumedAdvisory() throws Exception {
   Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   TemporaryQueue queue = s.createTemporaryQueue();
   MessageConsumer consumer = s.createConsumer(queue);

   Topic advisoryTopic = AdvisorySupport.getMessageConsumedAdvisoryTopic((ActiveMQDestination) queue);
   MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic);
   //start throwing messages at the consumer
   MessageProducer producer = s.createProducer(queue);

   BytesMessage m = s.createBytesMessage();
   m.writeBytes(new byte[1024]);
   producer.send(m);
   String id = m.getJMSMessageID();
   Message msg = consumer.receive(1000);
   assertNotNull(msg);

   msg = advisoryConsumer.receive(1000);
   assertNotNull(msg);

   ActiveMQMessage message = (ActiveMQMessage) msg;
   ActiveMQMessage payload = (ActiveMQMessage) message.getDataStructure();
   String originalId = payload.getJMSMessageID();
   assertEquals(originalId, id);
}
 
Example 6
Source File: JmsWSConnectionTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
protected void doSendLargeMessageViaOpenWire(Connection connection) throws Exception {
    try {
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(getQueueName());
        MessageProducer producer = session.createProducer(queue);

        byte[] payload = new byte[1024 * 1024];
        for (int i = 0; i < payload.length; ++i) {
            payload[i] = (byte) (i % 256);
        }
        BytesMessage message = session.createBytesMessage();
        message.writeBytes(payload);

        producer.send(message);
    } finally {
        connection.close();
    }
}
 
Example 7
Source File: MessageConverterImpl.java    From message-queue-client-framework with Apache License 2.0 5 votes vote down vote up
@Override
  public Message toMessage(Object obj, Session session) throws JMSException,
          MessageConversionException {

      logger.debug("Method : toMessage");

      if (!(obj instanceof MessageBeanImpl)) {

          throw new MessageConversionException("Obj is not MessageBeanImpl.");
      }

/* Jms字节类型消息 */
      BytesMessage bytesMessage = session.createBytesMessage();

      MessageBeanImpl messageBean = (MessageBeanImpl) obj;

      bytesMessage.setStringProperty("MessageType",
              messageBean.getMessageType());
      bytesMessage.setStringProperty("MessageAckNo",
              messageBean.getMessageAckNo());
      bytesMessage.setStringProperty("MessageNo", messageBean.getMessageNo());
      bytesMessage.setLongProperty("MessageDate",
              messageBean.getMessageDate());

      bytesMessage.writeBytes(messageBean.getMessageContent());

      logger.debug("Convert Success, The Send Message No is "
              + messageBean.getMessageNo());

      return bytesMessage;
  }
 
Example 8
Source File: MappingJackson2MessageConverter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Map the given object to a {@link BytesMessage}.
 * @param object the object to be mapped
 * @param session current JMS session
 * @param objectMapper the mapper to use
 * @return the resulting message
 * @throws JMSException if thrown by JMS methods
 * @throws IOException in case of I/O errors
 * @see Session#createBytesMessage
 */
protected BytesMessage mapToBytesMessage(Object object, Session session, ObjectMapper objectMapper)
		throws JMSException, IOException {

	ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
	OutputStreamWriter writer = new OutputStreamWriter(bos, this.encoding);
	objectMapper.writeValue(writer, object);

	BytesMessage message = session.createBytesMessage();
	message.writeBytes(bos.toByteArray());
	if (this.encodingPropertyName != null) {
		message.setStringProperty(this.encodingPropertyName, this.encoding);
	}
	return message;
}
 
Example 9
Source File: JmsPoolJMSProducer.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Override
public JMSProducer send(Destination destination, byte[] body) {
    try {
        BytesMessage message = session.createBytesMessage();
        message.writeBytes(body);
        doSend(destination, message);
    } catch (JMSException jmse) {
        throw JMSExceptionSupport.createRuntimeException(jmse);
    }

    return this;
}
 
Example 10
Source File: AmqpEventChannel.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public void triggerEvent(Object event) {
    try {
        Class type = event.getClass();
        MessageProducer producer = null;
        synchronized (producers) {
            producer = producers.get(type);
            Destination address = null;
            switch (mode) {
            case QUEUE: {
                // TODO 需要防止路径冲突
                address = session.createQueue(name + StringUtility.DOT + type.getName());
                break;
            }
            case TOPIC: {
                // TODO 需要防止路径冲突
                address = session.createTopic(name + StringUtility.DOT + type.getName());
                break;
            }
            }
            producer = session.createProducer(address);
            producers.put(type, producer);
        }
        byte[] bytes = codec.encode(type, event);
        BytesMessage message = session.createBytesMessage();
        message.writeBytes(bytes);
        producer.send(message);
    } catch (Exception exception) {
        throw new RuntimeException(exception);
    }
}
 
Example 11
Source File: OpenTypeSupportTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private static void sendMessage() throws JMSException {
   Connection conn = connectionFactory.createConnection();
   try {
      conn.start();
      Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Destination queue = session.createQueue(TESTQUEUE);
      BytesMessage toSend = session.createBytesMessage();
      toSend.writeBytes(BYTESMESSAGE_TEXT.getBytes());
      MessageProducer producer = session.createProducer(queue);
      producer.send(queue, toSend);
   } finally {
      conn.close();
   }
}
 
Example 12
Source File: JAXRSJmsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void postBook(Session session, Destination destination, Destination replyTo)
    throws Exception {
    MessageProducer producer = session.createProducer(destination);
    byte[] payload = writeBook(new Book("JMS", 3L));
    BytesMessage message = session.createBytesMessage();
    message.writeBytes(payload);
    message.setJMSReplyTo(replyTo);
    // or, if oneway,
    // message.setStringProperty("OnewayRequest", "true");
    // we could've set this header in JMSDestination if no replyTo were set
    // but in CXF one could also provide the replyTo in the configuration
    // so it is just simpler to set this header if needed to avoid some
    // complex logic on the server side

    // all these properties are optional
    // CXF JAXRS and JMS Transport will default to
    // Content-Type : text/xml
    // Accept : */*
    // POST
    // Message.REQUEST_URI : "/"

    message.setStringProperty("Content-Type", "application/xml");
    message.setStringProperty("Accept", "text/xml");
    message.setStringProperty(org.apache.cxf.message.Message.REQUEST_URI, "/bookstore/books");
    message.setStringProperty(org.apache.cxf.message.Message.HTTP_REQUEST_METHOD, "POST");
    message.setStringProperty("custom.protocol.header", "custom.value");

    producer.send(message);
    producer.close();
}
 
Example 13
Source File: TestGetJMSQueue.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendBytesToQueue() throws Exception {
    PutJMS putJms = new PutJMS();
    TestRunner putRunner = TestRunners.newTestRunner(putJms);
    putRunner.setProperty(JmsProperties.JMS_PROVIDER, JmsProperties.ACTIVEMQ_PROVIDER);
    putRunner.setProperty(JmsProperties.URL, "vm://localhost?broker.persistent=false");
    putRunner.setProperty(JmsProperties.DESTINATION_TYPE, JmsProperties.DESTINATION_TYPE_QUEUE);
    putRunner.setProperty(JmsProperties.DESTINATION_NAME, "queue.testing");
    putRunner.setProperty(JmsProperties.ACKNOWLEDGEMENT_MODE, JmsProperties.ACK_MODE_AUTO);
    WrappedMessageProducer wrappedProducer = JmsFactory.createMessageProducer(putRunner.getProcessContext(), true);
    final Session jmsSession = wrappedProducer.getSession();
    final MessageProducer producer = wrappedProducer.getProducer();
    final BytesMessage message = jmsSession.createBytesMessage();
    message.writeBytes("Hello Bytes".getBytes());

    producer.send(message);
    jmsSession.commit();

    GetJMSQueue getJmsQueue = new GetJMSQueue();
    TestRunner runner = TestRunners.newTestRunner(getJmsQueue);
    runner.setProperty(JmsProperties.JMS_PROVIDER, JmsProperties.ACTIVEMQ_PROVIDER);
    runner.setProperty(JmsProperties.URL, "vm://localhost?broker.persistent=false");
    runner.setProperty(JmsProperties.DESTINATION_NAME, "queue.testing");
    runner.setProperty(JmsProperties.ACKNOWLEDGEMENT_MODE, JmsProperties.ACK_MODE_AUTO);

    runner.run();

    List<MockFlowFile> flowFiles = runner
            .getFlowFilesForRelationship(new Relationship.Builder().name("success").build());

    assertTrue(flowFiles.size() == 1);
    MockFlowFile successFlowFile = flowFiles.get(0);
    successFlowFile.assertContentEquals("Hello Bytes");
    successFlowFile.assertAttributeEquals("jms.JMSDestination", "queue.testing");
    producer.close();
    jmsSession.close();
}
 
Example 14
Source File: MessageCompressionTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void sendTestBytesMessage(ActiveMQConnectionFactory factory,
                                  String message) throws JMSException, UnsupportedEncodingException {
   ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(queue);
   BytesMessage bytesMessage = session.createBytesMessage();
   bytesMessage.writeBytes(message.getBytes(StandardCharsets.UTF_8));
   producer.send(bytesMessage);
   connection.close();
}
 
Example 15
Source File: StompV12Test.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubscribeWithMessageSentWithProperties() throws Exception {
   conn.connect(defUser, defPass);

   subscribe(conn, "sub1", Stomp.Headers.Subscribe.AckModeValues.AUTO);

   MessageProducer producer = session.createProducer(queue);
   BytesMessage message = session.createBytesMessage();
   message.setStringProperty("S", "value");
   message.setBooleanProperty("n", false);
   message.setByteProperty("byte", (byte) 9);
   message.setDoubleProperty("d", 2.0);
   message.setFloatProperty("f", (float) 6.0);
   message.setIntProperty("i", 10);
   message.setLongProperty("l", 121);
   message.setShortProperty("s", (short) 12);
   message.writeBytes("Hello World".getBytes(StandardCharsets.UTF_8));
   producer.send(message);

   ClientStompFrame frame = conn.receiveFrame();
   Assert.assertNotNull(frame);

   Assert.assertTrue(frame.getHeader("S") != null);
   Assert.assertTrue(frame.getHeader("n") != null);
   Assert.assertTrue(frame.getHeader("byte") != null);
   Assert.assertTrue(frame.getHeader("d") != null);
   Assert.assertTrue(frame.getHeader("f") != null);
   Assert.assertTrue(frame.getHeader("i") != null);
   Assert.assertTrue(frame.getHeader("l") != null);
   Assert.assertTrue(frame.getHeader("s") != null);
   Assert.assertEquals("Hello World", frame.getBody());

   conn.disconnect();
}
 
Example 16
Source File: JmsMessageProducerTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void testSendMultipleMessagesPersistent() throws Exception {
    connection = createAmqpConnection();
    assertNotNull(connection);

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    assertNotNull(session);
    Queue queue = session.createQueue(name.getMethodName());
    MessageProducer producer = session.createProducer(queue);

    final int MSG_COUNT = 100;

    QueueViewMBean proxy = getProxyToQueue(name.getMethodName());
    assertEquals(0, proxy.getQueueSize());

    producer.setDeliveryMode(DeliveryMode.PERSISTENT);

    byte[] payload = new byte[1024];
    Arrays.fill(payload, (byte) 255);

    for (int i = 0; i < MSG_COUNT; ++i) {
        BytesMessage message = session.createBytesMessage();
        message.writeBytes(payload);
        LOG.trace("sending message: {}", i);
        producer.send(message);
        LOG.trace("sent message: {}", i);
    }

    producer.close();

    assertEquals(MSG_COUNT, proxy.getQueueSize());
}
 
Example 17
Source File: IMSSender.java    From iaf with Apache License 2.0 4 votes vote down vote up
@Override
public javax.jms.Message createMessage(Session session, String correlationID, String message) throws NamingException, JMSException {
	
	BytesMessage bytesMessage = null;
	bytesMessage = session.createBytesMessage();
	
	setMessageCorrelationID(bytesMessage, correlationID);
	
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	
	try {
		bos.write(IIH_HEADER_STRUCT_ID.getBytes(CHARSET));
		bos.write(intToBytes(IIH_HEADER_VERSION));
		bos.write(intToBytes(IIH_HEADER_LENGTH));
		bos.write(intToBytes(IIH_HEADER_ENCODING));
		bos.write(intToBytes(IIH_HEADER_CODECHARSET));
		bos.write(IIH_HEADER_FORMAT.getBytes(CHARSET));
		bos.write(intToBytes(IIH_HEADER_FLAGS));
		bos.write(IIH_HEADER_LTERM_OR.getBytes(CHARSET));
		bos.write(IIH_HEADER_MFS_MAPNAME.getBytes(CHARSET));
		bos.write(IIH_HEADER_REPLY_FORMAT.getBytes(CHARSET));
		bos.write(IIH_HEADER_MFS_AUTH.getBytes(CHARSET));
		bos.write(IIH_HEADER_TRAN_INSTANCE);
		bos.write(IIH_HEADER_TRAN_STATE.getBytes(CHARSET));
		bos.write(IIH_HEADER_COMMIT_MODE.getBytes(CHARSET));
		bos.write(IIH_HEADER_SECURITY_SCOPE.getBytes(CHARSET));
		bos.write(IIH_HEADER_RESERVED.getBytes(CHARSET));
		
		byte[] data = message.getBytes(CHARSET);

		bos.write(shortToBytes(data.length + 13)); //LL, +13 is for LL, ZZ and transaction code bytes
		bos.write(new byte[2]); //ZZ
		bos.write((transactionCode + " ").getBytes(CHARSET));
		
		bos.write(data);
		
		bos.toByteArray();
	} catch (IOException e) {
		// Should never happen
		throw new RuntimeException(e);
	}
	
	bytesMessage.writeBytes(bos.toByteArray());
	
	// Set Properties
	bytesMessage.setIntProperty("JMS_IBM_Encoding", MQENC_NATIVE);
	bytesMessage.setIntProperty("JMS_IBM_Character_Set", CCSID_ISO_8859_1);	
	bytesMessage.setStringProperty("JMS_IBM_Format", MQC_MQFMT_IMS);	

	return bytesMessage;
}
 
Example 18
Source File: MemoryLimitTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 120000)
public void testCursorBatch() throws Exception {

   ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?jms.prefetchPolicy.all=10");
   factory.setOptimizeAcknowledge(true);
   Connection conn = factory.createConnection();
   conn.start();
   Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
   Queue queue = sess.createQueue("STORE");
   final ProducerThread producer = new ProducerThread(sess, queue) {
      @Override
      protected Message createMessage(int i) throws Exception {
         BytesMessage bytesMessage = sess.createBytesMessage();
         bytesMessage.writeBytes(payload);
         return bytesMessage;
      }
   };
   producer.setMessageCount(2000);
   producer.start();
   producer.join();

   Thread.sleep(1000);

   // assert we didn't break high watermark (70%) usage
   final Destination dest = broker.getDestination((ActiveMQQueue) queue);
   LOG.info("Destination usage: " + dest.getMemoryUsage());
   int percentUsage = dest.getMemoryUsage().getPercentUsage();
   assertTrue("Should be less than 70% of limit but was: " + percentUsage, percentUsage <= 71);
   LOG.info("Broker usage: " + broker.getSystemUsage().getMemoryUsage());
   assertTrue(broker.getSystemUsage().getMemoryUsage().getPercentUsage() <= 71);

   // consume one message
   MessageConsumer consumer = sess.createConsumer(queue);
   Message msg = consumer.receive(5000);
   msg.acknowledge();

   // this should free some space and allow us to get new batch of messages in the memory
   // exceeding the limit
   assertTrue("Limit is exceeded", Wait.waitFor(new Wait.Condition() {
      @Override
      public boolean isSatisified() throws Exception {
         LOG.info("Destination usage: " + dest.getMemoryUsage());
         return dest.getMemoryUsage().getPercentUsage() >= 200;
      }
   }));

   LOG.info("Broker usage: " + broker.getSystemUsage().getMemoryUsage());
   assertTrue(broker.getSystemUsage().getMemoryUsage().getPercentUsage() >= 200);

   // let's make sure we can consume all messages
   for (int i = 1; i < 2000; i++) {
      msg = consumer.receive(5000);
      if (msg == null) {
         dumpAllThreads("NoMessage");
      }
      assertNotNull("Didn't receive message " + i, msg);
      msg.acknowledge();
   }
}
 
Example 19
Source File: MarshallingMessageConverter.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * Marshal the given object to a {@link BytesMessage}.
 * @param object the object to be marshalled
 * @param session current JMS session
 * @param marshaller the marshaller to use
 * @return the resulting message
 * @throws JMSException if thrown by JMS methods
 * @throws IOException in case of I/O errors
 * @throws XmlMappingException in case of OXM mapping errors
 * @see Session#createBytesMessage
 * @see Marshaller#marshal(Object, Result)
 */
protected BytesMessage marshalToBytesMessage(Object object, Session session, Marshaller marshaller)
		throws JMSException, IOException, XmlMappingException {

	ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
	StreamResult streamResult = new StreamResult(bos);
	marshaller.marshal(object, streamResult);
	BytesMessage message = session.createBytesMessage();
	message.writeBytes(bos.toByteArray());
	return message;
}
 
Example 20
Source File: SimpleMessageConverter.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Create a JMS BytesMessage for the given byte array.
 * @param bytes the byte array to convert
 * @param session current JMS session
 * @return the resulting message
 * @throws JMSException if thrown by JMS methods
 * @see javax.jms.Session#createBytesMessage
 */
protected BytesMessage createMessageForByteArray(byte[] bytes, Session session) throws JMSException {
	BytesMessage message = session.createBytesMessage();
	message.writeBytes(bytes);
	return message;
}