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

The following examples show how to use javax.jms.BytesMessage#setStringProperty() . 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: MappingJackson2MessageConverter.java    From spring-analysis-note with MIT License 6 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 objectWriter the writer to use
 * @return the resulting message
 * @throws JMSException if thrown by JMS methods
 * @throws IOException in case of I/O errors
 * @since 4.3
 * @see Session#createBytesMessage
 */
protected BytesMessage mapToBytesMessage(Object object, Session session, ObjectWriter objectWriter)
		throws JMSException, IOException {

	ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
	if (this.encoding != null) {
		OutputStreamWriter writer = new OutputStreamWriter(bos, this.encoding);
		objectWriter.writeValue(writer, object);
	}
	else {
		// Jackson usually defaults to UTF-8 but can also go straight to bytes, e.g. for Smile.
		// We use a direct byte array argument for the latter case to work as well.
		objectWriter.writeValue(bos, object);
	}

	BytesMessage message = session.createBytesMessage();
	message.writeBytes(bos.toByteArray());
	if (this.encodingPropertyName != null) {
		message.setStringProperty(this.encodingPropertyName,
				(this.encoding != null ? this.encoding : DEFAULT_ENCODING));
	}
	return message;
}
 
Example 2
Source File: JmsLargeMessagesInGroupsTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
protected void sendMessagesToBroker(int count, AtomicInteger sequence) throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue(getDestinationName());
    MessageProducer producer = session.createProducer(queue);

    byte[] buffer = new byte[MESSAGE_SIZE];
    for (count = 0; count < MESSAGE_SIZE; count++) {
        String s = String.valueOf(count % 10);
        Character c = s.charAt(0);
        int value = c.charValue();
        buffer[count] = (byte) value;
    }

    LOG.info("Sending {} messages to destination: {}", MESSAGE_COUNT, queue);
    for (int i = 1; i <= MESSAGE_COUNT; i++) {
        BytesMessage message = session.createBytesMessage();
        message.setJMSDeliveryMode(DeliveryMode.PERSISTENT);
        message.setStringProperty("JMSXGroupID", JMSX_GROUP_ID);
        message.setIntProperty("JMSXGroupSeq", sequence.incrementAndGet());
        message.writeBytes(buffer);
        producer.send(message);
    }

    producer.close();
}
 
Example 3
Source File: JMSMessageGroupsTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
protected void sendMessagesToBroker(String queueName, Connection connection, int count, AtomicInteger sequence) throws Exception {
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue queue = session.createQueue(queueName);
   MessageProducer producer = session.createProducer(queue);

   byte[] buffer = new byte[MESSAGE_SIZE];
   for (count = 0; count < MESSAGE_SIZE; count++) {
      String s = String.valueOf(count % 10);
      Character c = s.charAt(0);
      int value = c.charValue();
      buffer[count] = (byte) value;
   }

   LOG.debug("Sending {} messages to destination: {}", MESSAGE_COUNT, queue);
   for (int i = 1; i <= MESSAGE_COUNT; i++) {
      BytesMessage message = session.createBytesMessage();
      message.setJMSDeliveryMode(DeliveryMode.PERSISTENT);
      message.setStringProperty("JMSXGroupID", JMSX_GROUP_ID);
      message.setIntProperty("JMSXGroupSeq", sequence.incrementAndGet());
      message.writeBytes(buffer);
      producer.send(message);
   }

   session.close();
}
 
Example 4
Source File: JmsContextTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void bytesMessage() throws Exception {
   context = cf.createContext();
   try {
      JMSProducer producer = context.createProducer();
      BytesMessage bMsg = context.createBytesMessage();
      bMsg.setStringProperty("COM_SUN_JMS_TESTNAME", "sendAndRecvMsgOfEachTypeCLTest");
      bMsg.writeByte((byte) 1);
      bMsg.writeInt(22);
      CountDownLatch latch = new CountDownLatch(1);
      SimpleCompletionListener listener = new SimpleCompletionListener(latch);
      producer.setAsync(listener);
      producer.send(queue1, bMsg);
      assertTrue(latch.await(5, TimeUnit.SECONDS));
      assertEquals(listener.message.readByte(), (byte) 1);
      assertEquals(listener.message.readInt(), 22);
   } finally {
      context.close();
   }
}
 
Example 5
Source File: StompV11Test.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendContentType() 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(org.apache.activemq.artemis.api.core.Message.HDR_CONTENT_TYPE.toString(), "text/plain");
   message.writeBytes("Hello World".getBytes(StandardCharsets.UTF_8));
   producer.send(message);

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

   Assert.assertEquals("text/plain", frame.getHeader(Stomp.Headers.CONTENT_TYPE));

   conn.disconnect();
}
 
Example 6
Source File: MappingJackson2MessageConverter.java    From java-technology-stack with MIT License 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 objectWriter the writer to use
 * @return the resulting message
 * @throws JMSException if thrown by JMS methods
 * @throws IOException in case of I/O errors
 * @since 4.3
 * @see Session#createBytesMessage
 */
protected BytesMessage mapToBytesMessage(Object object, Session session, ObjectWriter objectWriter)
		throws JMSException, IOException {

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

	BytesMessage message = session.createBytesMessage();
	message.writeBytes(bos.toByteArray());
	if (this.encodingPropertyName != null) {
		message.setStringProperty(this.encodingPropertyName, this.encoding);
	}
	return message;
}
 
Example 7
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 8
Source File: JAXRSJmsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void postOneWayBook(Session session, Destination destination)
    throws Exception {
    MessageProducer producer = session.createProducer(destination);

    byte[] payload = writeBook(new Book("JMS OneWay", 125L));
    BytesMessage message = session.createBytesMessage();
    message.writeBytes(payload);
    message.setStringProperty("Content-Type", "application/xml");
    message.setStringProperty(org.apache.cxf.message.Message.REQUEST_URI, "/bookstore/oneway");
    message.setStringProperty(org.apache.cxf.message.Message.HTTP_REQUEST_METHOD, "PUT");

    producer.send(message);
    producer.close();
}
 
Example 9
Source File: BridgeTestBase.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
protected void sendMessages(final ConnectionFactory cf,
                            final Destination dest,
                            final int start,
                            final int numMessages,
                            final boolean persistent,
                            final boolean largeMessage) throws Exception {
   Connection conn = null;

   try {
      conn = cf.createConnection();

      Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

      MessageProducer prod = sess.createProducer(dest);

      prod.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);

      for (int i = start; i < start + numMessages; i++) {
         if (largeMessage) {
            BytesMessage msg = sess.createBytesMessage();
            ((ActiveMQMessage) msg).setInputStream(ActiveMQTestBase.createFakeLargeStream(1024L * 1024L));
            msg.setStringProperty("msg", "message" + i);
            prod.send(msg);
         } else {
            TextMessage tm = sess.createTextMessage("message" + i);
            prod.send(tm);
         }

      }
   } finally {
      if (conn != null) {
         conn.close();
      }
   }
}
 
Example 10
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 11
Source File: StompTestBase.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void sendJmsMessage(byte[] data,
                           String propertyName,
                           String propertyValue,
                           Destination destination) throws Exception {
   MessageProducer producer = session.createProducer(destination);
   BytesMessage message = session.createBytesMessage();
   message.setStringProperty(propertyName, propertyValue);
   message.writeBytes(data);
   producer.send(message);
}
 
Example 12
Source File: StompV11Test.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 13
Source File: StompTest.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, null, 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(10000);
   Assert.assertNotNull(frame);
   Assert.assertEquals(Stomp.Responses.MESSAGE, frame.getCommand());
   Assert.assertEquals("value", frame.getHeader("S"));
   Assert.assertEquals("false", frame.getHeader("n"));
   Assert.assertEquals("9", frame.getHeader("byte"));
   Assert.assertEquals("2.0", frame.getHeader("d"));
   Assert.assertEquals("6.0", frame.getHeader("f"));
   Assert.assertEquals("10", frame.getHeader("i"));
   Assert.assertEquals("121", frame.getHeader("l"));
   Assert.assertEquals("12", frame.getHeader("s"));
   Assert.assertEquals("Hello World", frame.getBody());

   conn.disconnect();
}
 
Example 14
Source File: JMSTransactionableStore.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
private void writeWindowId(String appId, int operatorId, long windowId) throws JMSException
{
  BytesMessage message = getBase().getSession().createBytesMessage();
  message.setStringProperty(APP_OPERATOR_ID, appId + "_" + operatorId);
  message.writeLong(windowId);
  producer.send(message);
  logger.debug("Message with windowId {} sent", windowId);
}
 
Example 15
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 16
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 17
Source File: SimpleOpenWireTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testSendEmptyMessages() throws Exception {
   Queue dest = new ActiveMQQueue(queueName);

   QueueSession defaultQueueSession =  connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
   QueueSender defaultSender = defaultQueueSession.createSender(dest);
   defaultSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
   connection.start();

   Message msg = defaultQueueSession.createMessage();
   msg.setStringProperty("testName", "testSendEmptyMessages");
   defaultSender.send(msg);

   QueueReceiver queueReceiver = defaultQueueSession.createReceiver(dest);
   assertNotNull("Didn't receive message", queueReceiver.receive(1000));

   //bytes
   BytesMessage bytesMessage = defaultQueueSession.createBytesMessage();
   bytesMessage.setStringProperty("testName", "testSendEmptyMessages");
   defaultSender.send(bytesMessage);
   assertNotNull("Didn't receive message", queueReceiver.receive(1000));

   //map
   MapMessage mapMessage = defaultQueueSession.createMapMessage();
   mapMessage.setStringProperty("testName", "testSendEmptyMessages");
   defaultSender.send(mapMessage);
   assertNotNull("Didn't receive message", queueReceiver.receive(1000));

   //object
   ObjectMessage objMessage = defaultQueueSession.createObjectMessage();
   objMessage.setStringProperty("testName", "testSendEmptyMessages");
   defaultSender.send(objMessage);
   assertNotNull("Didn't receive message", queueReceiver.receive(1000));

   //stream
   StreamMessage streamMessage = defaultQueueSession.createStreamMessage();
   streamMessage.setStringProperty("testName", "testSendEmptyMessages");
   defaultSender.send(streamMessage);
   assertNotNull("Didn't receive message", queueReceiver.receive(1000));

   //text
   TextMessage textMessage = defaultQueueSession.createTextMessage();
   textMessage.setStringProperty("testName", "testSendEmptyMessages");
   defaultSender.send(textMessage);
   assertNotNull("Didn't receive message", queueReceiver.receive(1000));
}
 
Example 18
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 19
Source File: JmsBasedHonoConnection.java    From hono with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Creates a new message for a payload and device ID.
 * <p>
 * The returned message contains the UTF-8 encoding of the given string in its payload.
 * The device ID is put into property {@link MessageHelper#APP_PROPERTY_DEVICE_ID}.
 *
 * @param payload The payload.
 * @param deviceId The identifier of the device that is subject to the message or {@code null}
 *                 if the message is not subjected to a device.
 * @return The message.
 * @throws JMSException if the message could not be created.
 * @throws IllegalStateException if the connection is not established.
 */
public BytesMessage newMessage(final String payload, final String deviceId) throws JMSException {
    final BytesMessage message = newMessage(Buffer.buffer(payload));
    if (deviceId != null) {
        message.setStringProperty(MessageHelper.APP_PROPERTY_DEVICE_ID, deviceId);
    }
    return message;
}