Java Code Examples for javax.jms.Message#setBooleanProperty()

The following examples show how to use javax.jms.Message#setBooleanProperty() . 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: StubRunnerJmsTransformer.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
private void setHeaders(Message message, Map<String, Object> headers) {
	for (Map.Entry<String, Object> entry : headers.entrySet()) {
		String key = entry.getKey();
		Object value = entry.getValue();
		try {
			if (value instanceof String) {
				message.setStringProperty(key, (String) value);
			}
			else if (value instanceof Boolean) {
				message.setBooleanProperty(key, (Boolean) value);
			}
			else {
				message.setObjectProperty(key, value);
			}
		}
		catch (JMSException ex) {
			throw new IllegalStateException(ex);
		}
	}
}
 
Example 2
Source File: JmsStubMessages.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
private void setHeaders(Message message, Map<String, Object> headers) {
	for (Map.Entry<String, Object> entry : headers.entrySet()) {
		String key = entry.getKey();
		Object value = entry.getValue();
		try {
			if (value instanceof String) {
				message.setStringProperty(key, (String) value);
			}
			else if (value instanceof Boolean) {
				message.setBooleanProperty(key, (Boolean) value);
			}
			else {
				message.setObjectProperty(key, value);
			}
		}
		catch (JMSException ex) {
			throw new IllegalStateException(ex);
		}
	}
}
 
Example 3
Source File: SelectorTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
protected Message createMessage() throws JMSException {
   Message message = createMessage("FOO.BAR");
   message.setJMSType("selector-test");
   message.setJMSMessageID("connection:1:1:1:1");
   message.setObjectProperty("name", "James");
   message.setObjectProperty("location", "London");

   message.setByteProperty("byteProp", (byte) 123);
   message.setByteProperty("byteProp2", (byte) 33);
   message.setShortProperty("shortProp", (short) 123);
   message.setIntProperty("intProp", 123);
   message.setLongProperty("longProp", 123);
   message.setFloatProperty("floatProp", 123);
   message.setDoubleProperty("doubleProp", 123);

   message.setIntProperty("rank", 123);
   message.setIntProperty("version", 2);
   message.setStringProperty("quote", "'In God We Trust'");
   message.setStringProperty("foo", "_foo");
   message.setStringProperty("punctuation", "!#$&()*+,-./:;<=>?@[\\]^`{|}~");
   message.setBooleanProperty("trueProp", true);
   message.setBooleanProperty("falseProp", false);
   return message;
}
 
Example 4
Source File: DurableSubProcessMultiRestartTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void send() throws JMSException {

         LOG.info("Sending ... ");

         Connection con = cf.createConnection();

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

         MessageProducer prod = sess.createProducer(null);
         Message message = sess.createMessage();
         message.setIntProperty("ID", ++messageRover);
         message.setBooleanProperty("COMMIT", true);
         prod.send(topic, message);

         msgCount++;
         LOG.info("Message Sent.");

         sess.close();
         con.close();
      }
 
Example 5
Source File: MessageProvider.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
protected void setCustomProperty(Message message, String propertyName, Object propertyValue) throws JMSException
{
    if (propertyValue instanceof Integer)
    {
        message.setIntProperty(propertyName, ((Integer) propertyValue).intValue());
    }
    else if (propertyValue instanceof Long)
    {
        message.setLongProperty(propertyName, ((Long) propertyValue).longValue());
    }
    else if (propertyValue instanceof Boolean)
    {
        message.setBooleanProperty(propertyName, ((Boolean) propertyValue).booleanValue());
    }
    else if (propertyValue instanceof Byte)
    {
        message.setByteProperty(propertyName, ((Byte) propertyValue).byteValue());
    }
    else if (propertyValue instanceof Double)
    {
        message.setDoubleProperty(propertyName, ((Double) propertyValue).doubleValue());
    }
    else if (propertyValue instanceof Float)
    {
        message.setFloatProperty(propertyName, ((Float) propertyValue).floatValue());
    }
    else if (propertyValue instanceof Short)
    {
        message.setShortProperty(propertyName, ((Short) propertyValue).shortValue());
    }
    else if (propertyValue instanceof String)
    {
        message.setStringProperty(propertyName, (String) propertyValue);
    }
    else
    {
        message.setObjectProperty(propertyName, propertyValue);
    }
}
 
Example 6
Source File: Server.java    From hazelcast-simulator with Apache License 2.0 5 votes vote down vote up
@Override
public void answer(Object o) {
    if (replyTo == null) {
        return;
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(format("Sending reply [%s] for [%s] to %s", o, op, replyTo));
    }

    try {
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Message message = session.createMessage();
        message.setJMSCorrelationID(correlationId);
        message.setStringProperty("source", selfAddressString);

        if (o instanceof Throwable) {
            Throwable throwable = (Throwable) o;
            message.setBooleanProperty("error", true);
            message.setStringProperty("message", throwable.getMessage());
        } else {
            message.setBooleanProperty("error", false);
            // hack
            message.setStringProperty("payload", "" + o);
        }

        MessageProducer producer = session.createProducer(replyTo);
        producer.send(message);
        session.close();
    } catch (JMSException e) {
        LOGGER.error(e);
    }
}
 
Example 7
Source File: InterceptorMdbBean.java    From tomee with Apache License 2.0 5 votes vote down vote up
@AroundInvoke
public Object aroundInvoke(final InvocationContext ctx) throws Exception {
    final Object[] objArr = ctx.getParameters();
    final Message msg = (Message) objArr[0];
    msg.setBooleanProperty("MethodLevelBusinessMethodInterception", true);
    ctx.setParameters(objArr);
    return ctx.proceed();
}
 
Example 8
Source File: JMSCacheableMailQueue.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public long flush() throws MailQueueException {
    boolean first = true;
    long count = 0;
    try (Session session = connection.createSession(true, Session.SESSION_TRANSACTED)) {
        Queue queue = session.createQueue(queueName.asString());
        try (MessageConsumer consumer = session.createConsumer(queue)) {
            try (MessageProducer producer = session.createProducer(queue)) {

                Message message = null;
                while (first || message != null) {
                    if (first) {
                        // give the consumer 2000 ms to receive messages
                        message = consumer.receive(2000);
                    } else {
                        message = consumer.receiveNoWait();
                    }
                    first = false;

                    if (message != null) {
                        Message m = copy(session, message);
                        m.setBooleanProperty(FORCE_DELIVERY, true);
                        producer.send(m, message.getJMSDeliveryMode(), message.getJMSPriority(), message.getJMSExpiration());
                        count++;
                    }
                }
                session.commit();
                return count;
            }
        }
    } catch (Exception e) {
        LOGGER.error("Unable to flush mail", e);
        throw new MailQueueException("Unable to get size of queue " + queueName.asString(), e);
    }
}
 
Example 9
Source File: MessageTestBase.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
protected void prepareMessage(final Message m) throws JMSException {
   m.setBooleanProperty("booleanProperty", true);
   m.setByteProperty("byteProperty", (byte) 3);
   m.setDoubleProperty("doubleProperty", 4.0);
   m.setFloatProperty("floatProperty", 5.0f);
   m.setIntProperty("intProperty", 6);
   m.setLongProperty("longProperty", 7);
   m.setShortProperty("shortProperty", (short) 8);
   m.setStringProperty("stringProperty", "this is a String property");

   m.setJMSCorrelationID("this is the correlation ID");
   m.setJMSReplyTo(ActiveMQServerTestCase.topic1);
   m.setJMSType("someArbitraryType");
}
 
Example 10
Source File: MdbInterceptor.java    From tomee with Apache License 2.0 5 votes vote down vote up
@AroundInvoke
public Object mdbInterceptor(final InvocationContext ctx) throws Exception {
    final Object[] objArr = ctx.getParameters();
    final Message msg = (Message) objArr[0];
    msg.clearProperties();
    msg.setBooleanProperty("ClassLevelBusinessMethodInterception", true);
    ctx.setParameters(objArr);
    return ctx.proceed();
}
 
Example 11
Source File: AutoAckMessageListenerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testAutoAckMsgListenerQueue() throws Exception {
   Connection conn = null;

   try {
      CountDownLatch latch = new CountDownLatch(1);

      conn = createConnection();
      Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = session.createProducer(queue1);
      MessageConsumer consumer = session.createConsumer(queue1);
      AutoAckMsgListener listener = new AutoAckMsgListener(latch, session);
      consumer.setMessageListener(listener);

      // create and send messages
      log.debug("Send and receive two message");
      Message messageSent = session.createMessage();
      messageSent.setBooleanProperty("last", false);
      producer.send(messageSent);
      messageSent.setBooleanProperty("last", true);
      producer.send(messageSent);

      conn.start();

      // wait until message is received
      log.debug("waiting until message has been received by message listener...");
      latch.await(10, TimeUnit.SECONDS);

      // check message listener status
      if (listener.getPassed() == false) {
         throw new Exception("failed");
      }
   } finally {
      if (conn != null) {
         conn.close();
      }
   }
}
 
Example 12
Source File: MessagePropertyConversionTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * if a property is set as a <code>boolean</code>,
 * it can also be read as a <code>boolean</code>.
 */
@Test
public void testBoolean2Boolean() {
   try {
      Message message = senderSession.createMessage();
      message.setBooleanProperty("prop", true);
      Assert.assertEquals(true, message.getBooleanProperty("prop"));
   } catch (JMSException e) {
      fail(e);
   }
}
 
Example 13
Source File: MessagePropertyConversionTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * if a property is set as a <code>boolean</code>,
 * it can also be read as a <code>String</code>.
 */
@Test
public void testBoolean2String() {
   try {
      Message message = senderSession.createMessage();
      message.setBooleanProperty("prop", true);
      Assert.assertEquals("true", message.getStringProperty("prop"));
   } catch (JMSException e) {
      fail(e);
   }
}
 
Example 14
Source File: AndesJMSPublisher.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Set JMS Headers to the message according to publisher configuration
 *
 * @param message message to set properties
 */
private void setMessageProperties(Message message) throws JMSException {

    List<JMSHeaderProperty> headerPropertyList = publisherConfig.getJMSHeaderProperties();

    for (JMSHeaderProperty jmsHeaderProperty : headerPropertyList) {
        JMSHeaderPropertyType type = jmsHeaderProperty.getType();
        String propertyKey = jmsHeaderProperty.getKey();
        Object propertyValue = jmsHeaderProperty.getValue();
        switch (type) {
            case OBJECT:
                message.setObjectProperty(propertyKey, propertyValue);
                break;
            case BYTE:
                message.setByteProperty(propertyKey, (Byte) propertyValue);
                break;
            case BOOLEAN:
                message.setBooleanProperty(propertyKey, (Boolean) propertyValue);
                break;
            case DOUBLE:
                message.setDoubleProperty(propertyKey, (Double) propertyValue);
                break;
            case FLOAT:
                message.setFloatProperty(propertyKey, (Float) propertyValue);
                break;
            case SHORT:
                message.setShortProperty(propertyKey, (Short) propertyValue);
                break;
            case STRING:
                message.setStringProperty(propertyKey, (String) propertyValue);
                break;
            case INTEGER:
                message.setIntProperty(propertyKey, (Integer) propertyValue);
                break;
            case LONG:
                message.setLongProperty(propertyKey, (Long) propertyValue);
                break;
        }
    }
}
 
Example 15
Source File: JMSHeadersAndPropertiesTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void propertyValues() throws Exception
{
    Queue queue = createQueue(getTestName());
    Connection connection = getConnection();
    try
    {
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(queue);
        Message message = session.createMessage();

        message.setBooleanProperty("boolean", true);
        message.setByteProperty("byte", Byte.MAX_VALUE);
        message.setShortProperty("short", Short.MAX_VALUE);
        message.setIntProperty("int", Integer.MAX_VALUE);
        message.setFloatProperty("float", Float.MAX_VALUE);
        message.setDoubleProperty("double", Double.MAX_VALUE);

        producer.send(message);

        final MessageConsumer consumer = session.createConsumer(queue);
        connection.start();

        final Message receivedMessage = consumer.receive(getReceiveTimeout());
        assertNotNull(receivedMessage);

        assertEquals("Unexpected boolean property value", Boolean.TRUE, message.getBooleanProperty("boolean"));
        assertEquals("Unexpected byte property value", Byte.MAX_VALUE, message.getByteProperty("byte"));
        assertEquals("Unexpected short property value", Short.MAX_VALUE, message.getShortProperty("short"));
        assertEquals("Unexpected int property value", Integer.MAX_VALUE, message.getIntProperty("int"));
        assertEquals("Unexpected float property value", Float.MAX_VALUE, message.getFloatProperty("float"), 0f);
        assertEquals("Unexpected double property value", Double.MAX_VALUE, message.getDoubleProperty("double"), 0d);
    }
    finally
    {
        connection.close();
    }
}
 
Example 16
Source File: LastValueQueueTest.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Override
public void run()
{
    try
    {
        LOGGER.info("Starting to send in background thread");
        final Connection producerConnection = getConnection();
        try
        {
            final Session producerSession = producerConnection.createSession(true, Session.SESSION_TRANSACTED);

            final MessageProducer backgroundProducer = producerSession.createProducer(_queue);
            for (int messageNumber = 0; messageNumber < MSG_COUNT; messageNumber++)
            {

                final Message message = nextMessage(messageNumber, producerSession, _numberOfUniqueKeyValues);
                backgroundProducer.send(message);
                producerSession.commit();

                putMessageInMap(message, _messageSequenceNumbersByKey);
                _quarterOfMessagesSentLatch.countDown();
            }

            Message shutdownMessage = producerSession.createMessage();
            shutdownMessage.setBooleanProperty(SHUTDOWN, true);
            // make sure the shutdown messages have distinct keys because the Qpid Cpp Broker will
            // otherwise consider them to have the same key.
            shutdownMessage.setStringProperty(KEY_PROPERTY, Thread.currentThread().getName());

            backgroundProducer.send(shutdownMessage);
            producerSession.commit();
        }
        finally
        {
            producerConnection.close();
        }

        LOGGER.info("Finished sending in background thread");
    }
    catch (Exception e)
    {
        _exception = e;
        LOGGER.warn("Unexpected exception in publisher", e);
    }
}
 
Example 17
Source File: MessageIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testSendMessageWithApplicationProperties() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        testPeer.expectBegin();
        testPeer.expectSenderAttach();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        String queueName = "myQueue";
        Queue queue = session.createQueue(queueName);
        MessageProducer producer = session.createProducer(queue);

        ApplicationPropertiesSectionMatcher appPropsMatcher = new ApplicationPropertiesSectionMatcher(true);
        appPropsMatcher.withEntry(NULL_STRING_PROP, nullValue());
        appPropsMatcher.withEntry(STRING_PROP, equalTo(STRING_PROP_VALUE));
        appPropsMatcher.withEntry(BOOLEAN_PROP, equalTo(BOOLEAN_PROP_VALUE));
        appPropsMatcher.withEntry(BYTE_PROP, equalTo(BYTE_PROP_VALUE));
        appPropsMatcher.withEntry(SHORT_PROP, equalTo(SHORT_PROP_VALUE));
        appPropsMatcher.withEntry(INT_PROP, equalTo(INT_PROP_VALUE));
        appPropsMatcher.withEntry(LONG_PROP, equalTo(LONG_PROP_VALUE));
        appPropsMatcher.withEntry(FLOAT_PROP, equalTo(FLOAT_PROP_VALUE));
        appPropsMatcher.withEntry(DOUBLE_PROP, equalTo(DOUBLE_PROP_VALUE));

        MessageHeaderSectionMatcher headersMatcher = new MessageHeaderSectionMatcher(true).withDurable(equalTo(true));

        MessageAnnotationsSectionMatcher msgAnnotationsMatcher = new MessageAnnotationsSectionMatcher(true);

        MessagePropertiesSectionMatcher propsMatcher = new MessagePropertiesSectionMatcher(true).withTo(equalTo(queueName));

        TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher();
        messageMatcher.setHeadersMatcher(headersMatcher);
        messageMatcher.setMessageAnnotationsMatcher(msgAnnotationsMatcher);
        messageMatcher.setPropertiesMatcher(propsMatcher);
        messageMatcher.setApplicationPropertiesMatcher(appPropsMatcher);
        //TODO: currently we aren't sending any body section, decide if this is allowed
        //messageMatcher.setMessageContentMatcher(new EncodedAmqpValueMatcher(null));
        testPeer.expectTransfer(messageMatcher);

        Message message = session.createMessage();
        message.setStringProperty(NULL_STRING_PROP, NULL_STRING_PROP_VALUE);
        message.setStringProperty(STRING_PROP, STRING_PROP_VALUE);
        message.setBooleanProperty(BOOLEAN_PROP, BOOLEAN_PROP_VALUE);
        message.setByteProperty(BYTE_PROP, BYTE_PROP_VALUE);
        message.setShortProperty(SHORT_PROP, SHORT_PROP_VALUE);
        message.setIntProperty(INT_PROP, INT_PROP_VALUE);
        message.setLongProperty(LONG_PROP, LONG_PROP_VALUE);
        message.setFloatProperty(FLOAT_PROP, FLOAT_PROP_VALUE);
        message.setDoubleProperty(DOUBLE_PROP, DOUBLE_PROP_VALUE);

        producer.send(message);

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

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 18
Source File: PutJMS.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Iterates through all of the flow file's metadata and for any metadata key that starts with <code>jms.</code>, the value for the corresponding key is written to the JMS message as a property.
 * The name of this property is equal to the key of the flow file's metadata minus the <code>jms.</code>. For example, if the flowFile has a metadata entry:
 * <br /><br />
 * <code>jms.count</code> = <code>8</code>
 * <br /><br />
 * then the JMS message will have a String property added to it with the property name <code>count</code> and value <code>8</code>.
 *
 * If the flow file also has a metadata key with the name <code>jms.count.type</code>, then the value of that metadata entry will determine the JMS property type to use for the value. For example,
 * if the flow file has the following properties:
 * <br /><br />
 * <code>jms.count</code> = <code>8</code><br />
 * <code>jms.count.type</code> = <code>integer</code>
 * <br /><br />
 * Then <code>message</code> will have an INTEGER property added with the value 8.
 * <br /><br/>
 * If the type is not valid for the given value (e.g., <code>jms.count.type</code> = <code>integer</code> and <code>jms.count</code> = <code>hello</code>, then this JMS property will not be added
 * to <code>message</code>.
 *
 * @param flowFile The flow file whose metadata should be examined for JMS properties.
 * @param message The JMS message to which we want to add properties.
 * @throws JMSException ex
 */
private void copyAttributesToJmsProps(final FlowFile flowFile, final Message message) throws JMSException {
    final ComponentLog logger = getLogger();

    final Map<String, String> attributes = flowFile.getAttributes();
    for (final Entry<String, String> entry : attributes.entrySet()) {
        final String key = entry.getKey();
        final String value = entry.getValue();

        if (key.toLowerCase().startsWith(ATTRIBUTE_PREFIX.toLowerCase()) && !key.toLowerCase().endsWith(ATTRIBUTE_TYPE_SUFFIX.toLowerCase())) {

            final String jmsPropName = key.substring(ATTRIBUTE_PREFIX.length());
            final String type = attributes.get(key + ATTRIBUTE_TYPE_SUFFIX);

            try {
                if (type == null || type.equalsIgnoreCase(PROP_TYPE_STRING)) {
                    message.setStringProperty(jmsPropName, value);
                } else if (type.equalsIgnoreCase(PROP_TYPE_INTEGER)) {
                    message.setIntProperty(jmsPropName, Integer.parseInt(value));
                } else if (type.equalsIgnoreCase(PROP_TYPE_BOOLEAN)) {
                    message.setBooleanProperty(jmsPropName, Boolean.parseBoolean(value));
                } else if (type.equalsIgnoreCase(PROP_TYPE_SHORT)) {
                    message.setShortProperty(jmsPropName, Short.parseShort(value));
                } else if (type.equalsIgnoreCase(PROP_TYPE_LONG)) {
                    message.setLongProperty(jmsPropName, Long.parseLong(value));
                } else if (type.equalsIgnoreCase(PROP_TYPE_BYTE)) {
                    message.setByteProperty(jmsPropName, Byte.parseByte(value));
                } else if (type.equalsIgnoreCase(PROP_TYPE_DOUBLE)) {
                    message.setDoubleProperty(jmsPropName, Double.parseDouble(value));
                } else if (type.equalsIgnoreCase(PROP_TYPE_FLOAT)) {
                    message.setFloatProperty(jmsPropName, Float.parseFloat(value));
                } else if (type.equalsIgnoreCase(PROP_TYPE_OBJECT)) {
                    message.setObjectProperty(jmsPropName, value);
                } else {
                    logger.warn("Attribute key '{}' for {} has value '{}', but expected one of: integer, string, object, byte, double, float, long, short, boolean; not adding this property",
                            new Object[]{key, flowFile, value});
                }
            } catch (NumberFormatException e) {
                logger.warn("Attribute key '{}' for {} has value '{}', but attribute key '{}' has value '{}'. Not adding this JMS property",
                        new Object[]{key, flowFile, value, key + ATTRIBUTE_TYPE_SUFFIX, PROP_TYPE_INTEGER});
            }
        }
    }
}
 
Example 19
Source File: SQSMessageTest.java    From amazon-sqs-java-messaging-lib with Apache License 2.0 4 votes vote down vote up
/**
 * Test setting SQSMessage property
 */
@Test
public void testProperty() throws JMSException {
    when(mockSQSSession.createMessage()).thenReturn(new SQSMessage());
    Message message = mockSQSSession.createMessage();

    message.setBooleanProperty("myTrueBoolean", true);
    message.setBooleanProperty("myFalseBoolean", false);
    message.setIntProperty("myInteger", 100);
    message.setDoubleProperty("myDouble", 2.1768);
    message.setFloatProperty("myFloat", 3.1457f);
    message.setLongProperty("myLong", 1290772974281L);
    message.setShortProperty("myShort", (short) 123);
    message.setByteProperty("myByteProperty", (byte) 'a');
    message.setStringProperty("myString", "StringValue");
    message.setStringProperty("myNumber", "500");

    Assert.assertTrue(message.propertyExists("myTrueBoolean"));
    Assert.assertEquals(message.getObjectProperty("myTrueBoolean"), true);
    Assert.assertEquals(message.getBooleanProperty("myTrueBoolean"), true);
    
    Assert.assertTrue(message.propertyExists("myFalseBoolean"));
    Assert.assertEquals(message.getObjectProperty("myFalseBoolean"), false);
    Assert.assertEquals(message.getBooleanProperty("myFalseBoolean"), false);
    
    Assert.assertTrue(message.propertyExists("myInteger"));
    Assert.assertEquals(message.getObjectProperty("myInteger"), 100);
    Assert.assertEquals(message.getIntProperty("myInteger"), 100);
    
    Assert.assertTrue(message.propertyExists("myDouble"));
    Assert.assertEquals(message.getObjectProperty("myDouble"), 2.1768);
    Assert.assertEquals(message.getDoubleProperty("myDouble"), 2.1768);
    
    Assert.assertTrue(message.propertyExists("myFloat"));
    Assert.assertEquals(message.getObjectProperty("myFloat"), 3.1457f);
    Assert.assertEquals(message.getFloatProperty("myFloat"), 3.1457f);
    
    Assert.assertTrue(message.propertyExists("myLong"));
    Assert.assertEquals(message.getObjectProperty("myLong"), 1290772974281L);
    Assert.assertEquals(message.getLongProperty("myLong"), 1290772974281L);
    
    Assert.assertTrue(message.propertyExists("myShort"));
    Assert.assertEquals(message.getObjectProperty("myShort"), (short) 123);
    Assert.assertEquals(message.getShortProperty("myShort"), (short) 123);
    
    Assert.assertTrue(message.propertyExists("myByteProperty"));
    Assert.assertEquals(message.getObjectProperty("myByteProperty"), (byte) 'a');
    Assert.assertEquals(message.getByteProperty("myByteProperty"), (byte) 'a');
    
    Assert.assertTrue(message.propertyExists("myString"));
    Assert.assertEquals(message.getObjectProperty("myString"), "StringValue");
    Assert.assertEquals(message.getStringProperty("myString"), "StringValue");

    Assert.assertTrue(message.propertyExists("myNumber"));
    Assert.assertEquals(message.getObjectProperty("myNumber"), "500");
    Assert.assertEquals(message.getStringProperty("myNumber"), "500");
    Assert.assertEquals(message.getLongProperty("myNumber"), 500L);
    Assert.assertEquals(message.getFloatProperty("myNumber"), 500f);
    Assert.assertEquals(message.getShortProperty("myNumber"), (short) 500);
    Assert.assertEquals(message.getDoubleProperty("myNumber"), 500d);
    Assert.assertEquals(message.getIntProperty("myNumber"), 500);

    // Validate property names
    Set<String> propertyNamesSet = new HashSet<String>(Arrays.asList(
            "myTrueBoolean",
            "myFalseBoolean",
            "myInteger",
            "myDouble",
            "myFloat",
            "myLong",
            "myShort",
            "myByteProperty",
            "myNumber",
            "myString"));

    Enumeration<String > propertyNames = message.getPropertyNames();
    int counter = 0;
    while (propertyNames.hasMoreElements()) {
        assertTrue(propertyNamesSet.contains(propertyNames.nextElement()));
        counter++;
    }
    assertEquals(propertyNamesSet.size(), counter);
    
    message.clearProperties();
    Assert.assertFalse(message.propertyExists("myTrueBoolean"));
    Assert.assertFalse(message.propertyExists("myInteger"));
    Assert.assertFalse(message.propertyExists("myDouble"));
    Assert.assertFalse(message.propertyExists("myFloat"));
    Assert.assertFalse(message.propertyExists("myLong"));
    Assert.assertFalse(message.propertyExists("myShort"));
    Assert.assertFalse(message.propertyExists("myByteProperty"));
    Assert.assertFalse(message.propertyExists("myString"));
    Assert.assertFalse(message.propertyExists("myNumber"));

    propertyNames = message.getPropertyNames();
    assertFalse(propertyNames.hasMoreElements());
}
 
Example 20
Source File: PutJMS.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Iterates through all of the flow file's metadata and for any metadata key that starts with <code>jms.</code>, the value for the corresponding key is written to the JMS message as a property.
 * The name of this property is equal to the key of the flow file's metadata minus the <code>jms.</code>. For example, if the flowFile has a metadata entry:
 * <br /><br />
 * <code>jms.count</code> = <code>8</code>
 * <br /><br />
 * then the JMS message will have a String property added to it with the property name <code>count</code> and value <code>8</code>.
 *
 * If the flow file also has a metadata key with the name <code>jms.count.type</code>, then the value of that metadata entry will determine the JMS property type to use for the value. For example,
 * if the flow file has the following properties:
 * <br /><br />
 * <code>jms.count</code> = <code>8</code><br />
 * <code>jms.count.type</code> = <code>integer</code>
 * <br /><br />
 * Then <code>message</code> will have an INTEGER property added with the value 8.
 * <br /><br/>
 * If the type is not valid for the given value (e.g., <code>jms.count.type</code> = <code>integer</code> and <code>jms.count</code> = <code>hello</code>, then this JMS property will not be added
 * to <code>message</code>.
 *
 * @param flowFile The flow file whose metadata should be examined for JMS properties.
 * @param message The JMS message to which we want to add properties.
 * @throws JMSException ex
 */
private void copyAttributesToJmsProps(final FlowFile flowFile, final Message message) throws JMSException {
    final ComponentLog logger = getLogger();

    final Map<String, String> attributes = flowFile.getAttributes();
    for (final Entry<String, String> entry : attributes.entrySet()) {
        final String key = entry.getKey();
        final String value = entry.getValue();

        if (key.toLowerCase().startsWith(ATTRIBUTE_PREFIX.toLowerCase()) && !key.toLowerCase().endsWith(ATTRIBUTE_TYPE_SUFFIX.toLowerCase())) {

            final String jmsPropName = key.substring(ATTRIBUTE_PREFIX.length());
            final String type = attributes.get(key + ATTRIBUTE_TYPE_SUFFIX);

            try {
                if (type == null || type.equalsIgnoreCase(PROP_TYPE_STRING)) {
                    message.setStringProperty(jmsPropName, value);
                } else if (type.equalsIgnoreCase(PROP_TYPE_INTEGER)) {
                    message.setIntProperty(jmsPropName, Integer.parseInt(value));
                } else if (type.equalsIgnoreCase(PROP_TYPE_BOOLEAN)) {
                    message.setBooleanProperty(jmsPropName, Boolean.parseBoolean(value));
                } else if (type.equalsIgnoreCase(PROP_TYPE_SHORT)) {
                    message.setShortProperty(jmsPropName, Short.parseShort(value));
                } else if (type.equalsIgnoreCase(PROP_TYPE_LONG)) {
                    message.setLongProperty(jmsPropName, Long.parseLong(value));
                } else if (type.equalsIgnoreCase(PROP_TYPE_BYTE)) {
                    message.setByteProperty(jmsPropName, Byte.parseByte(value));
                } else if (type.equalsIgnoreCase(PROP_TYPE_DOUBLE)) {
                    message.setDoubleProperty(jmsPropName, Double.parseDouble(value));
                } else if (type.equalsIgnoreCase(PROP_TYPE_FLOAT)) {
                    message.setFloatProperty(jmsPropName, Float.parseFloat(value));
                } else if (type.equalsIgnoreCase(PROP_TYPE_OBJECT)) {
                    message.setObjectProperty(jmsPropName, value);
                } else {
                    logger.warn("Attribute key '{}' for {} has value '{}', but expected one of: integer, string, object, byte, double, float, long, short, boolean; not adding this property",
                            new Object[]{key, flowFile, value});
                }
            } catch (NumberFormatException e) {
                logger.warn("Attribute key '{}' for {} has value '{}', but attribute key '{}' has value '{}'. Not adding this JMS property",
                        new Object[]{key, flowFile, value, key + ATTRIBUTE_TYPE_SUFFIX, PROP_TYPE_INTEGER});
            }
        }
    }
}