下面列出了javax.jms.Message#setObjectProperty ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void doSend(Destination destination, Message message) throws JMSException {
if (message == null) {
throw new MessageFormatException("Message must not be null");
}
for (Map.Entry<String, Object> entry : messageProperties.entrySet()) {
message.setObjectProperty(entry.getKey(), entry.getValue());
}
if (correlationId != null) {
message.setJMSCorrelationID(correlationId);
}
if (correlationIdBytes != null) {
message.setJMSCorrelationIDAsBytes(correlationIdBytes);
}
if (type != null) {
message.setJMSType(type);
}
if (replyTo != null) {
message.setJMSReplyTo(replyTo);
}
session.send(producer, destination, message, deliveryMode, priority, timeToLive, disableMessageId, disableTimestamp, deliveryDelay, completionListener);
}
private static void setProperties(final MessageDescription messageDescription,
final Message message)
{
final HashMap<String, Serializable> properties = messageDescription.getProperties();
if (properties == null)
{
return;
}
for (Map.Entry<String, Serializable> entry : properties.entrySet())
{
try
{
message.setObjectProperty(entry.getKey(), entry.getValue());
}
catch (JMSException e)
{
throw new RuntimeException(String.format("Could not set message property '%s' to this value: %s",
entry.getKey(),
String.valueOf(entry.getValue())), e);
}
}
}
private void doSend(Destination destination, Message message) throws JMSException {
if (message == null) {
throw new MessageFormatException("Message must not be null");
}
for (Map.Entry<String, Object> entry : messageProperties.entrySet()) {
message.setObjectProperty(entry.getKey(), entry.getValue());
}
if (correlationId != null) {
message.setJMSCorrelationID(correlationId);
}
if (correlationIdBytes != null) {
message.setJMSCorrelationIDAsBytes(correlationIdBytes);
}
if (type != null) {
message.setJMSType(type);
}
if (replyTo != null) {
message.setJMSReplyTo(replyTo);
}
session.send(producer, destination, message, deliveryMode, priority, timeToLive, disableMessageId, disableTimestamp, deliveryDelay, completionListener);
}
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);
}
}
}
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", "!#$&()*+,-./:;<=>[email protected][\\]^`{|}~");
message.setBooleanProperty("trueProp", true);
message.setBooleanProperty("falseProp", false);
return message;
}
@Override
protected Message createMessage(int index) throws JMSException {
Message answer = session.createMessage();
answer.setStringProperty("textField", data[index]);
Map<String, Object> grandChildMap = new HashMap<>();
grandChildMap.put("x", "abc");
grandChildMap.put("y", Arrays.asList(new Object[]{"a", "b", "c"}));
Map<String, Object> nestedMap = new HashMap<>();
nestedMap.put("a", "foo");
nestedMap.put("b", new Integer(23));
nestedMap.put("c", new Long(45));
nestedMap.put("d", grandChildMap);
answer.setObjectProperty("mapField", nestedMap);
answer.setObjectProperty("listField", Arrays.asList(new Object[]{"a", "b", "c"}));
answer.setStringProperty("JMSXUserID", "JohnDoe");
return answer;
}
@Test
public void testResetToNull() throws JMSException {
Message m1 = queueProducerSession.createMessage();
m1.setStringProperty("key", "fish");
m1.setBooleanProperty("key", true);
m1.setStringProperty("key2", "fish");
m1.setStringProperty("key2", null);
m1.setStringProperty("key3", "fish");
m1.setObjectProperty("key3", null);
queueProducer.send(m1);
Message m2 = queueConsumer.receive(1000);
Assert.assertEquals("key should be true", m2.getObjectProperty("key"), Boolean.TRUE);
Assert.assertEquals("key2 should be null", null, m2.getObjectProperty("key2"));
Assert.assertEquals("key3 should be null", null, m2.getObjectProperty("key3"));
}
@SuppressWarnings("unchecked")
public void setHeadersFromContext(Message message, Context context) throws JMSException {
Map<String, Object> headers = (Map<String, Object>) context.get(HEADERS_KEY);
if (headers == null) {
return;
}
Map<String, Object> outHeaders = (Map<String, Object>) headers.get(HEADERS_OUT_KEY);
if (outHeaders == null) {
return;
}
for (Map.Entry<String, Object> entry : outHeaders.entrySet()) {
message.setObjectProperty(entry.getKey(), entry.getValue());
}
}
private void doSend(Destination destination, Message message) throws JMSException {
if (message == null) {
throw new MessageFormatException("Message must not be null");
}
for (Map.Entry<String, Object> entry : messageProperties.entrySet()) {
message.setObjectProperty(entry.getKey(), entry.getValue());
}
if (correlationId != null) {
message.setJMSCorrelationID(correlationId);
}
if (correlationIdBytes != null) {
message.setJMSCorrelationIDAsBytes(correlationIdBytes);
}
if (type != null) {
message.setJMSType(type);
}
if (replyTo != null) {
message.setJMSReplyTo(replyTo);
}
if (completionListener != null) {
producer.send(destination, message, deliveryMode, priority, timeToLive, completionListener);
} else {
producer.send(destination, message, deliveryMode, priority, timeToLive);
}
}
private void applyMessageProperties(Message destinationMessage, Map<String, Object> properties) throws JMSException {
if (properties == null) {
return;
}
for (Map.Entry<String, Object> entry : properties.entrySet()) {
destinationMessage.setObjectProperty(entry.getKey(), entry.getValue());
}
}
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);
}
}
@Test
public void unsupportedObjectPropertyValue() 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();
try
{
message.setObjectProperty("invalidObject", new Exception());
}
catch (MessageFormatException e)
{
// pass
}
String validValue = "validValue";
message.setObjectProperty("validObject", validValue);
producer.send(message);
final MessageConsumer consumer = session.createConsumer(queue);
connection.start();
final Message receivedMessage = consumer.receive(getReceiveTimeout());
assertNotNull(receivedMessage);
assertFalse("Unexpected property found", message.propertyExists("invalidObject"));
assertEquals("Unexpected property value", validValue, message.getObjectProperty("validObject"));
}
finally
{
connection.close();
}
}
private void setMessageProperties(Message message, Map<String, Object> msgProperties) throws JMSException
{
if (msgProperties != null && !msgProperties.isEmpty())
{
Set<Map.Entry<String, Object>> entries = msgProperties.entrySet();
for(Map.Entry<String, Object> it: entries)
{
message.setObjectProperty(it.getKey(), it.getValue());
}
}
}
public static void setMessageProperties(Message message, Map<String, Object> properties) {
if (properties != null && properties.size() > 0) {
for (Map.Entry<String, Object> property : properties.entrySet()) {
try {
message.setObjectProperty(property.getKey(), property.getValue());
} catch (JMSException jmsEx) {
throw new EmbeddedJMSResourceException(String.format("Failed to set property {%s = %s}", property.getKey(), property.getValue().toString()), jmsEx);
}
}
}
}
/**
* 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;
}
}
}
/**
* if a property is set as a <code>Float</code> with the <code>Message.setObjectProperty()</code>
* method, it can be retrieve directly as a <code>double</code> by <code>Message.getFloatProperty()</code>
*/
@Test
public void testSetObjectProperty_1() {
try {
Message message = senderSession.createMessage();
message.setObjectProperty("pi", new Float(3.14159f));
Assert.assertEquals(3.14159f, message.getFloatProperty("pi"), 0);
} catch (JMSException e) {
fail(e);
}
}
/**
* 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});
}
}
}
}
/**
* 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});
}
}
}
}
/**
* Sends a request for an operation.
*
* @param operation The name of the operation to invoke or {@code null} if the message
* should not have a subject.
* @param applicationProperties Application properties to set on the request message or
* {@code null} if no properties should be set.
* @param payload Payload to include or {@code null} if the message should have no body.
* @return A future indicating the outcome of the operation.
*/
public Future<CredentialsObject> sendRequest(
final String operation,
final Map<String, Object> applicationProperties,
final Buffer payload) {
try {
final Message request = createMessage(payload);
if (operation != null) {
request.setJMSType(operation);
}
if (applicationProperties != null) {
for (Map.Entry<String, Object> entry : applicationProperties.entrySet()) {
if (entry.getValue() instanceof String) {
request.setStringProperty(entry.getKey(), (String) entry.getValue());
} else {
request.setObjectProperty(entry.getKey(), entry.getValue());
}
}
}
return send(request)
.compose(credentialsResult -> {
final Promise<CredentialsObject> result = Promise.promise();
switch (credentialsResult.getStatus()) {
case HttpURLConnection.HTTP_OK:
case HttpURLConnection.HTTP_CREATED:
result.complete(credentialsResult.getPayload());
break;
case HttpURLConnection.HTTP_NOT_FOUND:
result.fail(new ClientErrorException(credentialsResult.getStatus(), "no such credentials"));
break;
default:
result.fail(StatusCodeMapper.from(credentialsResult));
}
return result.future();
});
} catch (JMSException e) {
return Future.failedFuture(getServiceInvocationException(e));
}
}
@Test
public void testNullProperties() throws Exception {
conn = cf.createConnection();
Queue queue = createQueue("testQueue");
Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer prod = sess.createProducer(queue);
MessageConsumer cons = sess.createConsumer(queue);
conn.start();
Message msg = sess.createMessage();
msg.setStringProperty("Test", "SomeValue");
assertEquals("SomeValue", msg.getStringProperty("Test"));
msg.setStringProperty("Test", null);
assertEquals(null, msg.getStringProperty("Test"));
msg.setObjectProperty(MessageTest.propName1, null);
msg.setObjectProperty(MessageUtil.JMSXGROUPID, null);
msg.setObjectProperty(MessageUtil.JMSXUSERID, null);
msg.setStringProperty(MessageTest.propName2, null);
msg.getStringProperty(MessageTest.propName1);
msg.setStringProperty("Test", null);
Message received = sendAndConsumeMessage(msg, prod, cons);
Assert.assertNotNull(received);
checkProperties(received);
}