001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.activemq.transport.amqp.message;
018
019import static org.apache.activemq.transport.amqp.message.AmqpMessageSupport.JMS_AMQP_CONTENT_ENCODING;
020import static org.apache.activemq.transport.amqp.message.AmqpMessageSupport.JMS_AMQP_CONTENT_TYPE;
021import static org.apache.activemq.transport.amqp.message.AmqpMessageSupport.JMS_AMQP_FIRST_ACQUIRER;
022import static org.apache.activemq.transport.amqp.message.AmqpMessageSupport.JMS_AMQP_FOOTER_PREFIX;
023import static org.apache.activemq.transport.amqp.message.AmqpMessageSupport.JMS_AMQP_HEADER;
024import static org.apache.activemq.transport.amqp.message.AmqpMessageSupport.JMS_AMQP_MESSAGE_ANNOTATION_PREFIX;
025import static org.apache.activemq.transport.amqp.message.AmqpMessageSupport.JMS_AMQP_PROPERTIES;
026import static org.apache.activemq.transport.amqp.message.AmqpMessageSupport.JMS_AMQP_REPLYTO_GROUP_ID;
027
028import java.nio.charset.StandardCharsets;
029import java.util.Map;
030import java.util.Set;
031
032import javax.jms.JMSException;
033import javax.jms.Message;
034
035import org.apache.activemq.ScheduledMessage;
036import org.apache.activemq.command.ActiveMQDestination;
037import org.apache.activemq.command.ActiveMQMessage;
038import org.apache.activemq.transport.amqp.AmqpProtocolException;
039import org.apache.qpid.proton.amqp.Binary;
040import org.apache.qpid.proton.amqp.Decimal128;
041import org.apache.qpid.proton.amqp.Decimal32;
042import org.apache.qpid.proton.amqp.Decimal64;
043import org.apache.qpid.proton.amqp.Symbol;
044import org.apache.qpid.proton.amqp.UnsignedByte;
045import org.apache.qpid.proton.amqp.UnsignedInteger;
046import org.apache.qpid.proton.amqp.UnsignedLong;
047import org.apache.qpid.proton.amqp.UnsignedShort;
048import org.apache.qpid.proton.amqp.messaging.ApplicationProperties;
049import org.apache.qpid.proton.amqp.messaging.Footer;
050import org.apache.qpid.proton.amqp.messaging.Header;
051import org.apache.qpid.proton.amqp.messaging.MessageAnnotations;
052import org.apache.qpid.proton.amqp.messaging.Properties;
053
054public abstract class InboundTransformer {
055
056    public static final String TRANSFORMER_NATIVE = "native";
057    public static final String TRANSFORMER_RAW = "raw";
058    public static final String TRANSFORMER_JMS = "jms";
059
060    public abstract String getTransformerName();
061
062    public abstract InboundTransformer getFallbackTransformer();
063
064    public final ActiveMQMessage transform(EncodedMessage amqpMessage) throws Exception {
065        InboundTransformer transformer = this;
066        ActiveMQMessage message = null;
067
068        while (transformer != null) {
069            try {
070                message = transformer.doTransform(amqpMessage);
071                break;
072            } catch (Exception e) {
073                transformer = transformer.getFallbackTransformer();
074            }
075        }
076
077        if (message == null) {
078            throw new AmqpProtocolException("Failed to transform incoming delivery, skipping.", false);
079        }
080
081        return message;
082    }
083
084    protected abstract ActiveMQMessage doTransform(EncodedMessage amqpMessage) throws Exception;
085
086    @SuppressWarnings("unchecked")
087    protected void populateMessage(ActiveMQMessage jms, org.apache.qpid.proton.message.Message amqp) throws Exception {
088        Header header = amqp.getHeader();
089        if (header != null) {
090            jms.setBooleanProperty(JMS_AMQP_HEADER, true);
091
092            if (header.getDurable() != null) {
093                jms.setPersistent(header.getDurable().booleanValue());
094            }
095
096            if (header.getPriority() != null) {
097                jms.setJMSPriority(header.getPriority().intValue());
098            } else {
099                jms.setPriority((byte) Message.DEFAULT_PRIORITY);
100            }
101
102            if (header.getFirstAcquirer() != null) {
103                jms.setBooleanProperty(JMS_AMQP_FIRST_ACQUIRER, header.getFirstAcquirer());
104            }
105
106            if (header.getDeliveryCount() != null) {
107                jms.setRedeliveryCounter(header.getDeliveryCount().intValue());
108            }
109        } else {
110            jms.setPriority((byte) Message.DEFAULT_PRIORITY);
111            jms.setPersistent(false);
112        }
113
114        final MessageAnnotations ma = amqp.getMessageAnnotations();
115        if (ma != null) {
116            for (Map.Entry<?, ?> entry : ma.getValue().entrySet()) {
117                String key = entry.getKey().toString();
118                if ("x-opt-delivery-time".equals(key) && entry.getValue() != null) {
119                    long deliveryTime = ((Number) entry.getValue()).longValue();
120                    long delay = deliveryTime - System.currentTimeMillis();
121                    if (delay > 0) {
122                        jms.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
123                    }
124                } else if ("x-opt-delivery-delay".equals(key) && entry.getValue() != null) {
125                    long delay = ((Number) entry.getValue()).longValue();
126                    if (delay > 0) {
127                        jms.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
128                    }
129                } else if ("x-opt-delivery-repeat".equals(key) && entry.getValue() != null) {
130                    int repeat = ((Number) entry.getValue()).intValue();
131                    if (repeat > 0) {
132                        jms.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, repeat);
133                    }
134                } else if ("x-opt-delivery-period".equals(key) && entry.getValue() != null) {
135                    long period = ((Number) entry.getValue()).longValue();
136                    if (period > 0) {
137                        jms.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, period);
138                    }
139                } else if ("x-opt-delivery-cron".equals(key) && entry.getValue() != null) {
140                    String cronEntry = (String) entry.getValue();
141                    if (cronEntry != null) {
142                        jms.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_CRON, cronEntry);
143                    }
144                }
145
146                setProperty(jms, JMS_AMQP_MESSAGE_ANNOTATION_PREFIX + key, entry.getValue());
147            }
148        }
149
150        final ApplicationProperties ap = amqp.getApplicationProperties();
151        if (ap != null) {
152            for (Map.Entry<String, Object> entry : ((Map<String, Object>) ap.getValue()).entrySet()) {
153                setProperty(jms,  entry.getKey(), entry.getValue());
154            }
155        }
156
157        final Properties properties = amqp.getProperties();
158        if (properties != null) {
159            jms.setBooleanProperty(JMS_AMQP_PROPERTIES, true);
160            if (properties.getMessageId() != null) {
161                jms.setJMSMessageID(AMQPMessageIdHelper.INSTANCE.toBaseMessageIdString(properties.getMessageId()));
162            }
163            Binary userId = properties.getUserId();
164            if (userId != null) {
165                jms.setUserID(new String(userId.getArray(), userId.getArrayOffset(), userId.getLength(), StandardCharsets.UTF_8));
166            }
167            if (properties.getTo() != null) {
168                jms.setDestination((ActiveMQDestination.createDestination(properties.getTo(), ActiveMQDestination.QUEUE_TYPE)));
169            }
170            if (properties.getSubject() != null) {
171                jms.setType(properties.getSubject());
172            }
173            if (properties.getReplyTo() != null) {
174                jms.setReplyTo((ActiveMQDestination.createDestination(properties.getReplyTo(), ActiveMQDestination.QUEUE_TYPE)));
175            }
176            if (properties.getCorrelationId() != null) {
177                jms.setCorrelationId(AMQPMessageIdHelper.INSTANCE.toBaseMessageIdString(properties.getCorrelationId()));
178            }
179            if (properties.getContentType() != null) {
180                jms.setStringProperty(JMS_AMQP_CONTENT_TYPE, properties.getContentType().toString());
181            }
182            if (properties.getContentEncoding() != null) {
183                jms.setStringProperty(JMS_AMQP_CONTENT_ENCODING, properties.getContentEncoding().toString());
184            }
185            if (properties.getCreationTime() != null) {
186                jms.setTimestamp(properties.getCreationTime().getTime());
187            }
188            if (properties.getGroupId() != null) {
189                jms.setGroupID(properties.getGroupId());
190            }
191            if (properties.getGroupSequence() != null) {
192                jms.setGroupSequence(properties.getGroupSequence().intValue());
193            }
194            if (properties.getReplyToGroupId() != null) {
195                jms.setStringProperty(JMS_AMQP_REPLYTO_GROUP_ID, properties.getReplyToGroupId());
196            }
197            if (properties.getAbsoluteExpiryTime() != null) {
198                jms.setExpiration(properties.getAbsoluteExpiryTime().getTime());
199            }
200        }
201
202        // If the jms expiration has not yet been set...
203        if (header != null && jms.getJMSExpiration() == 0) {
204            // Then lets try to set it based on the message ttl.
205            long ttl = Message.DEFAULT_TIME_TO_LIVE;
206            if (header.getTtl() != null) {
207                ttl = header.getTtl().longValue();
208            }
209
210            if (ttl != javax.jms.Message.DEFAULT_TIME_TO_LIVE) {
211                jms.setExpiration(System.currentTimeMillis() + ttl);
212            }
213        }
214
215        final Footer fp = amqp.getFooter();
216        if (fp != null) {
217            for (Map.Entry<Object, Object> entry : (Set<Map.Entry<Object, Object>>) fp.getValue().entrySet()) {
218                String key = entry.getKey().toString();
219                setProperty(jms, JMS_AMQP_FOOTER_PREFIX + key, entry.getValue());
220            }
221        }
222    }
223
224    private void setProperty(Message msg, String key, Object value) throws JMSException {
225        if (value instanceof UnsignedLong) {
226            long v = ((UnsignedLong) value).longValue();
227            msg.setLongProperty(key, v);
228        } else if (value instanceof UnsignedInteger) {
229            long v = ((UnsignedInteger) value).longValue();
230            if (Integer.MIN_VALUE <= v && v <= Integer.MAX_VALUE) {
231                msg.setIntProperty(key, (int) v);
232            } else {
233                msg.setLongProperty(key, v);
234            }
235        } else if (value instanceof UnsignedShort) {
236            int v = ((UnsignedShort) value).intValue();
237            if (Short.MIN_VALUE <= v && v <= Short.MAX_VALUE) {
238                msg.setShortProperty(key, (short) v);
239            } else {
240                msg.setIntProperty(key, v);
241            }
242        } else if (value instanceof UnsignedByte) {
243            short v = ((UnsignedByte) value).shortValue();
244            if (Byte.MIN_VALUE <= v && v <= Byte.MAX_VALUE) {
245                msg.setByteProperty(key, (byte) v);
246            } else {
247                msg.setShortProperty(key, v);
248            }
249        } else if (value instanceof Symbol) {
250            msg.setStringProperty(key, value.toString());
251        } else if (value instanceof Decimal128) {
252            msg.setDoubleProperty(key, ((Decimal128) value).doubleValue());
253        } else if (value instanceof Decimal64) {
254            msg.setDoubleProperty(key, ((Decimal64) value).doubleValue());
255        } else if (value instanceof Decimal32) {
256            msg.setFloatProperty(key, ((Decimal32) value).floatValue());
257        } else if (value instanceof Binary) {
258            msg.setStringProperty(key, value.toString());
259        } else {
260            msg.setObjectProperty(key, value);
261        }
262    }
263}