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.stomp;
018
019import java.io.BufferedReader;
020import java.io.IOException;
021import java.io.InputStream;
022import java.io.InputStreamReader;
023import java.io.OutputStreamWriter;
024import java.io.PrintWriter;
025import java.util.Collections;
026import java.util.HashMap;
027import java.util.Iterator;
028import java.util.Map;
029import java.util.concurrent.ConcurrentHashMap;
030import java.util.concurrent.ConcurrentMap;
031import java.util.concurrent.atomic.AtomicBoolean;
032
033import javax.jms.JMSException;
034
035import org.apache.activemq.ActiveMQPrefetchPolicy;
036import org.apache.activemq.advisory.AdvisorySupport;
037import org.apache.activemq.broker.BrokerContext;
038import org.apache.activemq.broker.BrokerContextAware;
039import org.apache.activemq.command.ActiveMQDestination;
040import org.apache.activemq.command.ActiveMQMessage;
041import org.apache.activemq.command.ActiveMQTempQueue;
042import org.apache.activemq.command.ActiveMQTempTopic;
043import org.apache.activemq.command.Command;
044import org.apache.activemq.command.CommandTypes;
045import org.apache.activemq.command.ConnectionError;
046import org.apache.activemq.command.ConnectionId;
047import org.apache.activemq.command.ConnectionInfo;
048import org.apache.activemq.command.ConsumerControl;
049import org.apache.activemq.command.ConsumerId;
050import org.apache.activemq.command.ConsumerInfo;
051import org.apache.activemq.command.DestinationInfo;
052import org.apache.activemq.command.ExceptionResponse;
053import org.apache.activemq.command.LocalTransactionId;
054import org.apache.activemq.command.MessageAck;
055import org.apache.activemq.command.MessageDispatch;
056import org.apache.activemq.command.MessageId;
057import org.apache.activemq.command.ProducerId;
058import org.apache.activemq.command.ProducerInfo;
059import org.apache.activemq.command.RemoveSubscriptionInfo;
060import org.apache.activemq.command.Response;
061import org.apache.activemq.command.SessionId;
062import org.apache.activemq.command.SessionInfo;
063import org.apache.activemq.command.ShutdownInfo;
064import org.apache.activemq.command.TransactionId;
065import org.apache.activemq.command.TransactionInfo;
066import org.apache.activemq.util.ByteArrayOutputStream;
067import org.apache.activemq.util.FactoryFinder;
068import org.apache.activemq.util.IOExceptionSupport;
069import org.apache.activemq.util.IdGenerator;
070import org.apache.activemq.util.IntrospectionSupport;
071import org.apache.activemq.util.LongSequenceGenerator;
072import org.slf4j.Logger;
073import org.slf4j.LoggerFactory;
074
075/**
076 * @author <a href="http://hiramchirino.com">chirino</a>
077 */
078public class ProtocolConverter {
079
080    private static final Logger LOG = LoggerFactory.getLogger(ProtocolConverter.class);
081
082    private static final IdGenerator CONNECTION_ID_GENERATOR = new IdGenerator();
083
084    private static final String BROKER_VERSION;
085    private static final StompFrame ping = new StompFrame(Stomp.Commands.KEEPALIVE);
086
087    static {
088        String version = "5.6.0";
089        try(InputStream in = ProtocolConverter.class.getResourceAsStream("/org/apache/activemq/version.txt")) {
090            if (in != null) {
091                try(InputStreamReader isr = new InputStreamReader(in);
092                    BufferedReader reader = new BufferedReader(isr)) {
093                    version = reader.readLine();
094                }
095            }
096        }catch(Exception e) {
097        }
098
099        BROKER_VERSION = version;
100    }
101
102    private final ConnectionId connectionId = new ConnectionId(CONNECTION_ID_GENERATOR.generateId());
103    private final SessionId sessionId = new SessionId(connectionId, -1);
104    private final ProducerId producerId = new ProducerId(sessionId, 1);
105
106    private final LongSequenceGenerator consumerIdGenerator = new LongSequenceGenerator();
107    private final LongSequenceGenerator messageIdGenerator = new LongSequenceGenerator();
108    private final LongSequenceGenerator transactionIdGenerator = new LongSequenceGenerator();
109    private final LongSequenceGenerator tempDestinationGenerator = new LongSequenceGenerator();
110
111    private final ConcurrentMap<Integer, ResponseHandler> resposeHandlers = new ConcurrentHashMap<>();
112    private final ConcurrentMap<ConsumerId, StompSubscription> subscriptionsByConsumerId = new ConcurrentHashMap<>();
113    private final ConcurrentMap<String, StompSubscription> subscriptions = new ConcurrentHashMap<>();
114    private final ConcurrentMap<String, ActiveMQDestination> tempDestinations = new ConcurrentHashMap<>();
115    private final ConcurrentMap<String, String> tempDestinationAmqToStompMap = new ConcurrentHashMap<>();
116    private final Map<String, LocalTransactionId> transactions = new ConcurrentHashMap<>();
117    private final StompTransport stompTransport;
118
119    // Global Map shared with all subscriptions to allow finding the sub associated with an ACK Id
120    private final ConcurrentMap<String, StompAckEntry> pendingAcksTracker = new ConcurrentHashMap<>();
121    // Read-Only view used in this class to enforce the separation of read vs update of the global index.
122    private final Map<String, StompAckEntry> pendingAcks = Collections.unmodifiableMap(pendingAcksTracker);
123
124    private final Object commnadIdMutex = new Object();
125    private int lastCommandId;
126    private final AtomicBoolean connected = new AtomicBoolean(false);
127    private final FrameTranslator frameTranslator = new LegacyFrameTranslator();
128    private final FactoryFinder FRAME_TRANSLATOR_FINDER = new FactoryFinder("META-INF/services/org/apache/activemq/transport/frametranslator/");
129    private final BrokerContext brokerContext;
130    private String version = "1.0";
131    private long hbReadInterval;
132    private long hbWriteInterval;
133    private float hbGracePeriodMultiplier = 1.0f;
134    private String defaultHeartBeat = Stomp.DEFAULT_HEART_BEAT;
135
136    public ProtocolConverter(StompTransport stompTransport, BrokerContext brokerContext) {
137        this.stompTransport = stompTransport;
138        this.brokerContext = brokerContext;
139    }
140
141    protected int generateCommandId() {
142        synchronized (commnadIdMutex) {
143            return lastCommandId++;
144        }
145    }
146
147    protected ResponseHandler createResponseHandler(final StompFrame command) {
148        final String receiptId = command.getHeaders().get(Stomp.Headers.RECEIPT_REQUESTED);
149        if (receiptId != null) {
150            return new ResponseHandler() {
151                @Override
152                public void onResponse(ProtocolConverter converter, Response response) throws IOException {
153                    if (response.isException()) {
154                        // Generally a command can fail.. but that does not invalidate the connection.
155                        // We report back the failure but we don't close the connection.
156                        Throwable exception = ((ExceptionResponse)response).getException();
157                        handleException(exception, command);
158                    } else {
159                        StompFrame sc = new StompFrame();
160                        sc.setAction(Stomp.Responses.RECEIPT);
161                        sc.setHeaders(new HashMap<String, String>(1));
162                        sc.getHeaders().put(Stomp.Headers.Response.RECEIPT_ID, receiptId);
163                        stompTransport.sendToStomp(sc);
164                    }
165                }
166            };
167        }
168        return null;
169    }
170
171    protected void sendToActiveMQ(Command command, ResponseHandler handler) {
172        command.setCommandId(generateCommandId());
173        if (handler != null) {
174            command.setResponseRequired(true);
175            resposeHandlers.put(Integer.valueOf(command.getCommandId()), handler);
176        }
177        stompTransport.sendToActiveMQ(command);
178    }
179
180    protected void sendToStomp(StompFrame command) throws IOException {
181        stompTransport.sendToStomp(command);
182    }
183
184    protected FrameTranslator findTranslator(String header) {
185        return findTranslator(header, null, false);
186    }
187
188    protected FrameTranslator findTranslator(String header, ActiveMQDestination destination, boolean advisory) {
189        FrameTranslator translator = frameTranslator;
190        try {
191            if (header != null) {
192                translator = (FrameTranslator) FRAME_TRANSLATOR_FINDER.newInstance(header);
193            } else {
194                if (destination != null && (advisory || AdvisorySupport.isAdvisoryTopic(destination))) {
195                    translator = new JmsFrameTranslator();
196                }
197            }
198        } catch (Exception ignore) {
199            // if anything goes wrong use the default translator
200        }
201
202        if (translator instanceof BrokerContextAware) {
203            ((BrokerContextAware)translator).setBrokerContext(brokerContext);
204        }
205
206        return translator;
207    }
208
209    /**
210     * Convert a STOMP command
211     *
212     * @param command
213     */
214    public void onStompCommand(StompFrame command) throws IOException, JMSException {
215        try {
216
217            if (command.getClass() == StompFrameError.class) {
218                throw ((StompFrameError)command).getException();
219            }
220
221            String action = command.getAction();
222            if (action.startsWith(Stomp.Commands.SEND)) {
223                onStompSend(command);
224            } else if (action.startsWith(Stomp.Commands.ACK)) {
225                onStompAck(command);
226            } else if (action.startsWith(Stomp.Commands.NACK)) {
227                onStompNack(command);
228            } else if (action.startsWith(Stomp.Commands.BEGIN)) {
229                onStompBegin(command);
230            } else if (action.startsWith(Stomp.Commands.COMMIT)) {
231                onStompCommit(command);
232            } else if (action.startsWith(Stomp.Commands.ABORT)) {
233                onStompAbort(command);
234            } else if (action.startsWith(Stomp.Commands.SUBSCRIBE_PREFIX)) {
235                onStompSubscribe(command);
236            } else if (action.startsWith(Stomp.Commands.UNSUBSCRIBE_PREFIX)) {
237                onStompUnsubscribe(command);
238            } else if (action.startsWith(Stomp.Commands.CONNECT) ||
239                       action.startsWith(Stomp.Commands.STOMP)) {
240                onStompConnect(command);
241            } else if (action.startsWith(Stomp.Commands.DISCONNECT)) {
242                onStompDisconnect(command);
243            } else {
244                throw new ProtocolException("Unknown STOMP action: " + action, true);
245            }
246
247        } catch (ProtocolException e) {
248            handleException(e, command);
249            // Some protocol errors can cause the connection to get closed.
250            if (e.isFatal()) {
251               getStompTransport().onException(e);
252            }
253        }
254    }
255
256    protected void handleException(Throwable exception, StompFrame command) throws IOException {
257        if (command == null) {
258            LOG.warn("Exception occurred while processing a command: {}", exception.toString());
259        } else {
260            LOG.warn("Exception occurred processing: {} -> {}", safeGetAction(command), exception.toString());
261        }
262
263        if (LOG.isDebugEnabled()) {
264            LOG.debug("Exception detail", exception);
265        }
266
267        if (command != null && LOG.isTraceEnabled()) {
268            LOG.trace("Command that caused the error: {}", command);
269        }
270
271        // Let the stomp client know about any protocol errors.
272        ByteArrayOutputStream baos = new ByteArrayOutputStream();
273        PrintWriter stream = new PrintWriter(new OutputStreamWriter(baos, "UTF-8"));
274        exception.printStackTrace(stream);
275        stream.close();
276
277        HashMap<String, String> headers = new HashMap<>();
278        headers.put(Stomp.Headers.Error.MESSAGE, exception.getMessage());
279        headers.put(Stomp.Headers.CONTENT_TYPE, "text/plain");
280
281        if (command != null) {
282            final String receiptId = command.getHeaders().get(Stomp.Headers.RECEIPT_REQUESTED);
283            if (receiptId != null) {
284                headers.put(Stomp.Headers.Response.RECEIPT_ID, receiptId);
285            }
286        }
287
288        StompFrame errorMessage = new StompFrame(Stomp.Responses.ERROR, headers, baos.toByteArray());
289        sendToStomp(errorMessage);
290    }
291
292    protected void onStompSend(StompFrame command) throws IOException, JMSException {
293        checkConnected();
294
295        Map<String, String> headers = command.getHeaders();
296        String destination = headers.get(Stomp.Headers.Send.DESTINATION);
297        if (destination == null) {
298            throw new ProtocolException("SEND received without a Destination specified!");
299        }
300
301        String stompTx = headers.get(Stomp.Headers.TRANSACTION);
302        headers.remove("transaction");
303
304        ActiveMQMessage message = convertMessage(command);
305
306        message.setProducerId(producerId);
307        MessageId id = new MessageId(producerId, messageIdGenerator.getNextSequenceId());
308        message.setMessageId(id);
309
310        if (stompTx != null) {
311            TransactionId activemqTx = transactions.get(stompTx);
312            if (activemqTx == null) {
313                throw new ProtocolException("Invalid transaction id: " + stompTx);
314            }
315            message.setTransactionId(activemqTx);
316        }
317
318        message.onSend();
319        message.beforeMarshall(null);
320        sendToActiveMQ(message, createResponseHandler(command));
321    }
322
323    protected void onStompNack(StompFrame command) throws ProtocolException {
324
325        checkConnected();
326
327        if (this.version.equals(Stomp.V1_0)) {
328            throw new ProtocolException("NACK received but connection is in v1.0 mode.");
329        }
330
331        Map<String, String> headers = command.getHeaders();
332
333        String subscriptionId = headers.get(Stomp.Headers.Ack.SUBSCRIPTION);
334        if (subscriptionId == null && !this.version.equals(Stomp.V1_2)) {
335            throw new ProtocolException("NACK received without a subscription id for acknowledge!");
336        }
337
338        String messageId = headers.get(Stomp.Headers.Ack.MESSAGE_ID);
339        if (messageId == null && !this.version.equals(Stomp.V1_2)) {
340            throw new ProtocolException("NACK received without a message-id to acknowledge!");
341        }
342
343        String ackId = headers.get(Stomp.Headers.Ack.ACK_ID);
344        if (ackId == null && this.version.equals(Stomp.V1_2)) {
345            throw new ProtocolException("NACK received without an ack header to acknowledge!");
346        }
347
348        TransactionId activemqTx = null;
349        String stompTx = headers.get(Stomp.Headers.TRANSACTION);
350        if (stompTx != null) {
351            activemqTx = transactions.get(stompTx);
352            if (activemqTx == null) {
353                throw new ProtocolException("Invalid transaction id: " + stompTx);
354            }
355        }
356
357        boolean nacked = false;
358
359        if (ackId != null) {
360            StompAckEntry pendingAck = this.pendingAcks.get(ackId);
361            if (pendingAck != null) {
362                messageId = pendingAck.getMessageId().toString();
363                MessageAck ack = pendingAck.onMessageNack(activemqTx);
364                if (ack != null) {
365                    sendToActiveMQ(ack, createResponseHandler(command));
366                    nacked = true;
367                }
368            }
369        } else if (subscriptionId != null) {
370            StompSubscription sub = this.subscriptions.get(subscriptionId);
371            if (sub != null) {
372                MessageAck ack = sub.onStompMessageNack(messageId, activemqTx);
373                if (ack != null) {
374                    sendToActiveMQ(ack, createResponseHandler(command));
375                    nacked = true;
376                }
377            }
378        }
379
380        if (!nacked) {
381            throw new ProtocolException("Unexpected NACK received for message-id [" + messageId + "]");
382        }
383    }
384
385    protected void onStompAck(StompFrame command) throws ProtocolException {
386        checkConnected();
387
388        Map<String, String> headers = command.getHeaders();
389        String messageId = headers.get(Stomp.Headers.Ack.MESSAGE_ID);
390        if (messageId == null && !(this.version.equals(Stomp.V1_2))) {
391            throw new ProtocolException("ACK received without a message-id to acknowledge!");
392        }
393
394        String subscriptionId = headers.get(Stomp.Headers.Ack.SUBSCRIPTION);
395        if (subscriptionId == null && this.version.equals(Stomp.V1_1)) {
396            throw new ProtocolException("ACK received without a subscription id for acknowledge!");
397        }
398
399        String ackId = headers.get(Stomp.Headers.Ack.ACK_ID);
400        if (ackId == null && this.version.equals(Stomp.V1_2)) {
401            throw new ProtocolException("ACK received without a ack id for acknowledge!");
402        }
403
404        TransactionId activemqTx = null;
405        String stompTx = headers.get(Stomp.Headers.TRANSACTION);
406        if (stompTx != null) {
407            activemqTx = transactions.get(stompTx);
408            if (activemqTx == null) {
409                throw new ProtocolException("Invalid transaction id: " + stompTx);
410            }
411        }
412
413        boolean acked = false;
414
415        if (ackId != null) {
416            StompAckEntry pendingAck = this.pendingAcks.get(ackId);
417            if (pendingAck != null) {
418                messageId = pendingAck.getMessageId().toString();
419                MessageAck ack = pendingAck.onMessageAck(activemqTx);
420                if (ack != null) {
421                    sendToActiveMQ(ack, createResponseHandler(command));
422                    acked = true;
423                }
424            }
425
426        } else if (subscriptionId != null) {
427            StompSubscription sub = this.subscriptions.get(subscriptionId);
428            if (sub != null) {
429                MessageAck ack = sub.onStompMessageAck(messageId, activemqTx);
430                if (ack != null) {
431                    sendToActiveMQ(ack, createResponseHandler(command));
432                    acked = true;
433                }
434            }
435        } else {
436            // STOMP v1.0: acking with just a message id is very bogus since the same message id
437            // could have been sent to 2 different subscriptions on the same Stomp connection.
438            // For example, when 2 subs are created on the same topic.
439            for (StompSubscription sub : subscriptionsByConsumerId.values()) {
440                MessageAck ack = sub.onStompMessageAck(messageId, activemqTx);
441                if (ack != null) {
442                    sendToActiveMQ(ack, createResponseHandler(command));
443                    acked = true;
444                    break;
445                }
446            }
447        }
448
449        if (!acked) {
450            throw new ProtocolException("Unexpected ACK received for message-id [" + messageId + "]");
451        }
452    }
453
454    protected void onStompBegin(StompFrame command) throws ProtocolException {
455        checkConnected();
456
457        Map<String, String> headers = command.getHeaders();
458
459        String stompTx = headers.get(Stomp.Headers.TRANSACTION);
460
461        if (!headers.containsKey(Stomp.Headers.TRANSACTION)) {
462            throw new ProtocolException("Must specify the transaction you are beginning");
463        }
464
465        if (transactions.get(stompTx) != null) {
466            throw new ProtocolException("The transaction was already started: " + stompTx);
467        }
468
469        LocalTransactionId activemqTx = new LocalTransactionId(connectionId, transactionIdGenerator.getNextSequenceId());
470        transactions.put(stompTx, activemqTx);
471
472        TransactionInfo tx = new TransactionInfo();
473        tx.setConnectionId(connectionId);
474        tx.setTransactionId(activemqTx);
475        tx.setType(TransactionInfo.BEGIN);
476
477        sendToActiveMQ(tx, createResponseHandler(command));
478    }
479
480    protected void onStompCommit(StompFrame command) throws ProtocolException {
481        checkConnected();
482
483        Map<String, String> headers = command.getHeaders();
484
485        String stompTx = headers.get(Stomp.Headers.TRANSACTION);
486        if (stompTx == null) {
487            throw new ProtocolException("Must specify the transaction you are committing");
488        }
489
490        TransactionId activemqTx = transactions.remove(stompTx);
491        if (activemqTx == null) {
492            throw new ProtocolException("Invalid transaction id: " + stompTx);
493        }
494
495        for (StompSubscription sub : subscriptionsByConsumerId.values()) {
496            sub.onStompCommit(activemqTx);
497        }
498
499        TransactionInfo tx = new TransactionInfo();
500        tx.setConnectionId(connectionId);
501        tx.setTransactionId(activemqTx);
502        tx.setType(TransactionInfo.COMMIT_ONE_PHASE);
503
504        sendToActiveMQ(tx, createResponseHandler(command));
505    }
506
507    protected void onStompAbort(StompFrame command) throws ProtocolException {
508        checkConnected();
509        Map<String, String> headers = command.getHeaders();
510
511        String stompTx = headers.get(Stomp.Headers.TRANSACTION);
512        if (stompTx == null) {
513            throw new ProtocolException("Must specify the transaction you are committing");
514        }
515
516        TransactionId activemqTx = transactions.remove(stompTx);
517        if (activemqTx == null) {
518            throw new ProtocolException("Invalid transaction id: " + stompTx);
519        }
520        for (StompSubscription sub : subscriptionsByConsumerId.values()) {
521            try {
522                sub.onStompAbort(activemqTx);
523            } catch (Exception e) {
524                throw new ProtocolException("Transaction abort failed", false, e);
525            }
526        }
527
528        TransactionInfo tx = new TransactionInfo();
529        tx.setConnectionId(connectionId);
530        tx.setTransactionId(activemqTx);
531        tx.setType(TransactionInfo.ROLLBACK);
532
533        sendToActiveMQ(tx, createResponseHandler(command));
534    }
535
536    protected void onStompSubscribe(StompFrame command) throws ProtocolException {
537        checkConnected();
538        FrameTranslator translator = findTranslator(command.getHeaders().get(Stomp.Headers.TRANSFORMATION));
539        Map<String, String> headers = command.getHeaders();
540
541        String subscriptionId = headers.get(Stomp.Headers.Subscribe.ID);
542        String destination = headers.get(Stomp.Headers.Subscribe.DESTINATION);
543
544        if (!this.version.equals(Stomp.V1_0) && subscriptionId == null) {
545            throw new ProtocolException("SUBSCRIBE received without a subscription id!");
546        }
547
548        final ActiveMQDestination actualDest = translator.convertDestination(this, destination, true);
549
550        if (actualDest == null) {
551            throw new ProtocolException("Invalid 'null' Destination.");
552        }
553
554        final ConsumerId id = new ConsumerId(sessionId, consumerIdGenerator.getNextSequenceId());
555        ConsumerInfo consumerInfo = new ConsumerInfo(id);
556        consumerInfo.setPrefetchSize(actualDest.isQueue() ?
557                ActiveMQPrefetchPolicy.DEFAULT_QUEUE_PREFETCH :
558                headers.containsKey("activemq.subscriptionName") ?
559                        ActiveMQPrefetchPolicy.DEFAULT_DURABLE_TOPIC_PREFETCH : ActiveMQPrefetchPolicy.DEFAULT_TOPIC_PREFETCH);
560        consumerInfo.setDispatchAsync(true);
561
562        String browser = headers.get(Stomp.Headers.Subscribe.BROWSER);
563        if (browser != null && browser.equals(Stomp.TRUE)) {
564
565            if (this.version.equals(Stomp.V1_0)) {
566                throw new ProtocolException("Queue Browser feature only valid for Stomp v1.1+ clients!");
567            }
568
569            consumerInfo.setBrowser(true);
570            consumerInfo.setPrefetchSize(ActiveMQPrefetchPolicy.DEFAULT_QUEUE_BROWSER_PREFETCH);
571        }
572
573        String selector = headers.remove(Stomp.Headers.Subscribe.SELECTOR);
574        if (selector != null) {
575            consumerInfo.setSelector("convert_string_expressions:" + selector);
576        }
577
578        IntrospectionSupport.setProperties(consumerInfo, headers, "activemq.");
579
580        if (actualDest.isQueue() && consumerInfo.getSubscriptionName() != null) {
581            throw new ProtocolException("Invalid Subscription: cannot durably subscribe to a Queue destination!");
582        }
583
584        consumerInfo.setDestination(actualDest);
585        consumerInfo.setDispatchAsync(true);
586
587        StompSubscription stompSubscription;
588        if (!consumerInfo.isBrowser()) {
589            stompSubscription = new StompSubscription(this, subscriptionId, consumerInfo, headers.get(Stomp.Headers.TRANSFORMATION), pendingAcksTracker);
590        } else {
591            stompSubscription = new StompQueueBrowserSubscription(this, subscriptionId, consumerInfo, headers.get(Stomp.Headers.TRANSFORMATION), pendingAcksTracker);
592        }
593        stompSubscription.setDestination(actualDest);
594
595        String ackMode = headers.get(Stomp.Headers.Subscribe.ACK_MODE);
596        if (Stomp.Headers.Subscribe.AckModeValues.CLIENT.equals(ackMode)) {
597            stompSubscription.setAckMode(StompSubscription.CLIENT_ACK);
598        } else if (Stomp.Headers.Subscribe.AckModeValues.INDIVIDUAL.equals(ackMode)) {
599            stompSubscription.setAckMode(StompSubscription.INDIVIDUAL_ACK);
600        } else {
601            stompSubscription.setAckMode(StompSubscription.AUTO_ACK);
602        }
603
604        subscriptionsByConsumerId.put(id, stompSubscription);
605        // Stomp v1.0 doesn't need to set this header so we avoid an NPE if not set.
606        if (subscriptionId != null) {
607            subscriptions.put(subscriptionId, stompSubscription);
608        }
609
610        final String receiptId = command.getHeaders().get(Stomp.Headers.RECEIPT_REQUESTED);
611        if (receiptId != null && consumerInfo.getPrefetchSize() > 0) {
612
613            final StompFrame cmd = command;
614            final int prefetch = consumerInfo.getPrefetchSize();
615
616            // Since dispatch could beat the receipt we set prefetch to zero to start and then
617            // once we've sent our Receipt we are safe to turn on dispatch if the response isn't
618            // an error message.
619            consumerInfo.setPrefetchSize(0);
620
621            final ResponseHandler handler = new ResponseHandler() {
622                @Override
623                public void onResponse(ProtocolConverter converter, Response response) throws IOException {
624                    if (response.isException()) {
625                        // Generally a command can fail.. but that does not invalidate the connection.
626                        // We report back the failure but we don't close the connection.
627                        Throwable exception = ((ExceptionResponse)response).getException();
628                        handleException(exception, cmd);
629                    } else {
630                        StompFrame sc = new StompFrame();
631                        sc.setAction(Stomp.Responses.RECEIPT);
632                        sc.setHeaders(new HashMap<String, String>(1));
633                        sc.getHeaders().put(Stomp.Headers.Response.RECEIPT_ID, receiptId);
634                        stompTransport.sendToStomp(sc);
635
636                        ConsumerControl control = new ConsumerControl();
637                        control.setPrefetch(prefetch);
638                        control.setDestination(actualDest);
639                        control.setConsumerId(id);
640
641                        sendToActiveMQ(control, null);
642                    }
643                }
644            };
645
646            sendToActiveMQ(consumerInfo, handler);
647        } else {
648            sendToActiveMQ(consumerInfo, createResponseHandler(command));
649        }
650    }
651
652    protected void onStompUnsubscribe(StompFrame command) throws ProtocolException {
653        checkConnected();
654        Map<String, String> headers = command.getHeaders();
655
656        ActiveMQDestination destination = null;
657        Object o = headers.get(Stomp.Headers.Unsubscribe.DESTINATION);
658        if (o != null) {
659            destination = findTranslator(command.getHeaders().get(Stomp.Headers.TRANSFORMATION)).convertDestination(this, (String)o, true);
660        }
661
662        String subscriptionId = headers.get(Stomp.Headers.Unsubscribe.ID);
663        if (!this.version.equals(Stomp.V1_0) && subscriptionId == null) {
664            throw new ProtocolException("UNSUBSCRIBE received without a subscription id!");
665        }
666
667        if (subscriptionId == null && destination == null) {
668            throw new ProtocolException("Must specify the subscriptionId or the destination you are unsubscribing from");
669        }
670
671        // check if it is a durable subscription
672        String durable = command.getHeaders().get("activemq.subscriptionName");
673        String clientId = durable;
674        if (!this.version.equals(Stomp.V1_0)) {
675            clientId = connectionInfo.getClientId();
676        }
677
678        if (durable != null) {
679            RemoveSubscriptionInfo info = new RemoveSubscriptionInfo();
680            info.setClientId(clientId);
681            info.setSubscriptionName(durable);
682            info.setConnectionId(connectionId);
683            sendToActiveMQ(info, createResponseHandler(command));
684            return;
685        }
686
687        if (subscriptionId != null) {
688            StompSubscription sub = this.subscriptions.remove(subscriptionId);
689            if (sub != null) {
690                sendToActiveMQ(sub.getConsumerInfo().createRemoveCommand(), createResponseHandler(command));
691                return;
692            }
693        } else {
694            // Unsubscribing using a destination is a bit weird if multiple subscriptions
695            // are created with the same destination.
696            for (Iterator<StompSubscription> iter = subscriptionsByConsumerId.values().iterator(); iter.hasNext();) {
697                StompSubscription sub = iter.next();
698                if (destination != null && destination.equals(sub.getDestination())) {
699                    sendToActiveMQ(sub.getConsumerInfo().createRemoveCommand(), createResponseHandler(command));
700                    iter.remove();
701                    return;
702                }
703            }
704        }
705
706        throw new ProtocolException("No subscription matched.");
707    }
708
709    ConnectionInfo connectionInfo = new ConnectionInfo();
710
711    protected void onStompConnect(final StompFrame command) throws ProtocolException {
712
713        if (connected.get()) {
714            throw new ProtocolException("Already connected.");
715        }
716
717        final Map<String, String> headers = command.getHeaders();
718
719        // allow anyone to login for now
720        String login = headers.get(Stomp.Headers.Connect.LOGIN);
721        String passcode = headers.get(Stomp.Headers.Connect.PASSCODE);
722        String clientId = headers.get(Stomp.Headers.Connect.CLIENT_ID);
723        String heartBeat = headers.get(Stomp.Headers.Connect.HEART_BEAT);
724
725        if (heartBeat == null) {
726            heartBeat = defaultHeartBeat;
727        }
728
729        this.version = StompCodec.detectVersion(headers);
730
731        configureInactivityMonitor(heartBeat.trim());
732
733        IntrospectionSupport.setProperties(connectionInfo, headers, "activemq.");
734        connectionInfo.setConnectionId(connectionId);
735        if (clientId != null) {
736            connectionInfo.setClientId(clientId);
737        } else {
738            connectionInfo.setClientId("" + connectionInfo.getConnectionId().toString());
739        }
740
741        connectionInfo.setResponseRequired(true);
742        connectionInfo.setUserName(login);
743        connectionInfo.setPassword(passcode);
744        connectionInfo.setTransportContext(command.getTransportContext());
745
746        sendToActiveMQ(connectionInfo, new ResponseHandler() {
747            @Override
748            public void onResponse(ProtocolConverter converter, Response response) throws IOException {
749
750                if (response.isException()) {
751                    // If the connection attempt fails we close the socket.
752                    Throwable exception = ((ExceptionResponse)response).getException();
753                    handleException(exception, command);
754                    getStompTransport().onException(IOExceptionSupport.create(exception));
755                    return;
756                }
757
758                final SessionInfo sessionInfo = new SessionInfo(sessionId);
759                sendToActiveMQ(sessionInfo, null);
760
761                final ProducerInfo producerInfo = new ProducerInfo(producerId);
762                sendToActiveMQ(producerInfo, new ResponseHandler() {
763                    @Override
764                    public void onResponse(ProtocolConverter converter, Response response) throws IOException {
765
766                        if (response.isException()) {
767                            // If the connection attempt fails we close the socket.
768                            Throwable exception = ((ExceptionResponse)response).getException();
769                            handleException(exception, command);
770                            getStompTransport().onException(IOExceptionSupport.create(exception));
771                        }
772
773                        connected.set(true);
774                        HashMap<String, String> responseHeaders = new HashMap<>();
775
776                        responseHeaders.put(Stomp.Headers.Connected.SESSION, connectionInfo.getClientId());
777                        String requestId = headers.get(Stomp.Headers.Connect.REQUEST_ID);
778                        if (requestId == null) {
779                            // TODO legacy
780                            requestId = headers.get(Stomp.Headers.RECEIPT_REQUESTED);
781                        }
782                        if (requestId != null) {
783                            // TODO legacy
784                            responseHeaders.put(Stomp.Headers.Connected.RESPONSE_ID, requestId);
785                            responseHeaders.put(Stomp.Headers.Response.RECEIPT_ID, requestId);
786                        }
787
788                        responseHeaders.put(Stomp.Headers.Connected.VERSION, version);
789                        responseHeaders.put(Stomp.Headers.Connected.HEART_BEAT,
790                                            String.format("%d,%d", hbWriteInterval, hbReadInterval));
791                        responseHeaders.put(Stomp.Headers.Connected.SERVER, "ActiveMQ/"+BROKER_VERSION);
792
793                        StompFrame sc = new StompFrame();
794                        sc.setAction(Stomp.Responses.CONNECTED);
795                        sc.setHeaders(responseHeaders);
796                        sendToStomp(sc);
797
798                        StompWireFormat format = stompTransport.getWireFormat();
799                        if (format != null) {
800                            format.setStompVersion(version);
801                        }
802                    }
803                });
804            }
805        });
806    }
807
808    protected void onStompDisconnect(StompFrame command) throws ProtocolException {
809        if (connected.get()) {
810            LOG.trace("Connection closed with {} pending ACKs still being tracked.", pendingAcks.size());
811            sendToActiveMQ(connectionInfo.createRemoveCommand(), createResponseHandler(command));
812            sendToActiveMQ(new ShutdownInfo(), createResponseHandler(command));
813            connected.set(false);
814        }
815    }
816
817    protected void checkConnected() throws ProtocolException {
818        if (!connected.get()) {
819            throw new ProtocolException("Not connected.");
820        }
821    }
822
823    /**
824     * Dispatch a ActiveMQ command
825     *
826     * @param command
827     * @throws IOException
828     */
829    public void onActiveMQCommand(Command command) throws IOException, JMSException {
830        if (command.isResponse()) {
831            Response response = (Response)command;
832            ResponseHandler rh = resposeHandlers.remove(Integer.valueOf(response.getCorrelationId()));
833            if (rh != null) {
834                rh.onResponse(this, response);
835            } else {
836                // Pass down any unexpected errors. Should this close the connection?
837                if (response.isException()) {
838                    Throwable exception = ((ExceptionResponse)response).getException();
839                    handleException(exception, null);
840                }
841            }
842        } else if (command.isMessageDispatch()) {
843            MessageDispatch md = (MessageDispatch)command;
844            StompSubscription sub = subscriptionsByConsumerId.get(md.getConsumerId());
845            if (sub != null) {
846                sub.onMessageDispatch(md);
847            }
848        } else if (command.getDataStructureType() == CommandTypes.KEEP_ALIVE_INFO) {
849            stompTransport.sendToStomp(ping);
850        } else if (command.getDataStructureType() == ConnectionError.DATA_STRUCTURE_TYPE) {
851            // Pass down any unexpected async errors. Should this close the connection?
852            Throwable exception = ((ConnectionError)command).getException();
853            handleException(exception, null);
854        }
855    }
856
857    public ActiveMQMessage convertMessage(StompFrame command) throws IOException, JMSException {
858        ActiveMQMessage msg = findTranslator(command.getHeaders().get(Stomp.Headers.TRANSFORMATION)).convertFrame(this, command);
859        return msg;
860    }
861
862    public StompFrame convertMessage(ActiveMQMessage message, boolean ignoreTransformation) throws IOException, JMSException {
863        if (ignoreTransformation == true) {
864            return frameTranslator.convertMessage(this, message);
865        } else {
866            FrameTranslator translator = findTranslator(
867                message.getStringProperty(Stomp.Headers.TRANSFORMATION), message.getDestination(), message.isAdvisory());
868            return translator.convertMessage(this, message);
869        }
870    }
871
872    public StompTransport getStompTransport() {
873        return stompTransport;
874    }
875
876    public ActiveMQDestination createTempDestination(String name, boolean topic) {
877        ActiveMQDestination rc = tempDestinations.get(name);
878        if( rc == null ) {
879            if (topic) {
880                rc = new ActiveMQTempTopic(connectionId, tempDestinationGenerator.getNextSequenceId());
881            } else {
882                rc = new ActiveMQTempQueue(connectionId, tempDestinationGenerator.getNextSequenceId());
883            }
884            sendToActiveMQ(new DestinationInfo(connectionId, DestinationInfo.ADD_OPERATION_TYPE, rc), null);
885            tempDestinations.put(name, rc);
886            tempDestinationAmqToStompMap.put(rc.getQualifiedName(), name);
887        }
888        return rc;
889    }
890
891    public String getCreatedTempDestinationName(ActiveMQDestination destination) {
892        return tempDestinationAmqToStompMap.get(destination.getQualifiedName());
893    }
894
895    public String getDefaultHeartBeat() {
896        return defaultHeartBeat;
897    }
898
899    public void setDefaultHeartBeat(String defaultHeartBeat) {
900        this.defaultHeartBeat = defaultHeartBeat;
901    }
902
903    /**
904     * @return the hbGracePeriodMultiplier
905     */
906    public float getHbGracePeriodMultiplier() {
907        return hbGracePeriodMultiplier;
908    }
909
910    /**
911     * @param hbGracePeriodMultiplier the hbGracePeriodMultiplier to set
912     */
913    public void setHbGracePeriodMultiplier(float hbGracePeriodMultiplier) {
914        this.hbGracePeriodMultiplier = hbGracePeriodMultiplier;
915    }
916
917    protected void configureInactivityMonitor(String heartBeatConfig) throws ProtocolException {
918
919        String[] keepAliveOpts = heartBeatConfig.split(Stomp.COMMA);
920
921        if (keepAliveOpts == null || keepAliveOpts.length != 2) {
922            throw new ProtocolException("Invalid heart-beat header:" + heartBeatConfig, true);
923        } else {
924
925            try {
926                hbReadInterval = (Long.parseLong(keepAliveOpts[0]));
927                hbWriteInterval = Long.parseLong(keepAliveOpts[1]);
928            } catch(NumberFormatException e) {
929                throw new ProtocolException("Invalid heart-beat header:" + heartBeatConfig, true);
930            }
931
932            try {
933                StompInactivityMonitor monitor = this.stompTransport.getInactivityMonitor();
934                monitor.setReadCheckTime((long) (hbReadInterval * hbGracePeriodMultiplier));
935                monitor.setInitialDelayTime(Math.min(hbReadInterval, hbWriteInterval));
936                monitor.setWriteCheckTime(hbWriteInterval);
937                monitor.startMonitoring();
938            } catch(Exception ex) {
939                hbReadInterval = 0;
940                hbWriteInterval = 0;
941            }
942
943            if (LOG.isDebugEnabled()) {
944                LOG.debug("Stomp Connect heartbeat conf RW[{},{}]", hbReadInterval, hbWriteInterval);
945            }
946        }
947    }
948
949    protected void sendReceipt(StompFrame command) {
950        final String receiptId = command.getHeaders().get(Stomp.Headers.RECEIPT_REQUESTED);
951        if (receiptId != null) {
952            StompFrame sc = new StompFrame();
953            sc.setAction(Stomp.Responses.RECEIPT);
954            sc.setHeaders(new HashMap<String, String>(1));
955            sc.getHeaders().put(Stomp.Headers.Response.RECEIPT_ID, receiptId);
956            try {
957                sendToStomp(sc);
958            } catch (IOException e) {
959                LOG.warn("Could not send a receipt for {}", command, e);
960            }
961        }
962    }
963
964    /**
965     * Retrieve the STOMP action value from a frame if the value is valid, otherwise
966     * return an unknown string to allow for safe log output.
967     *
968     * @param command
969     *      The STOMP command to fetch an action from.
970     *
971     * @return the command action or a safe string to use in logging.
972     */
973    protected Object safeGetAction(StompFrame command) {
974        String result = "<Unknown>";
975        if (command != null && command.getAction() != null) {
976            String action = command.getAction().trim();
977
978            if (action != null) {
979                switch (action) {
980                    case Stomp.Commands.SEND:
981                    case Stomp.Commands.ACK:
982                    case Stomp.Commands.NACK:
983                    case Stomp.Commands.BEGIN:
984                    case Stomp.Commands.COMMIT:
985                    case Stomp.Commands.ABORT:
986                    case Stomp.Commands.SUBSCRIBE:
987                    case Stomp.Commands.UNSUBSCRIBE:
988                    case Stomp.Commands.CONNECT:
989                    case Stomp.Commands.STOMP:
990                    case Stomp.Commands.DISCONNECT:
991                        result = action;
992                        break;
993                    case Stomp.Commands.SUBSCRIBE_PREFIX:
994                        result = Stomp.Commands.SUBSCRIBE;
995                    case Stomp.Commands.UNSUBSCRIBE_PREFIX:
996                        result = Stomp.Commands.UNSUBSCRIBE;
997                    default:
998                        break;
999                }
1000            }
1001        }
1002
1003        return result;
1004    }
1005
1006    boolean isStomp10() {
1007        return version.equals(Stomp.V1_0);
1008    }
1009
1010    boolean isStomp11() {
1011        return version.equals(Stomp.V1_1);
1012    }
1013
1014    boolean isStomp12() {
1015        return version.equals(Stomp.V1_2);
1016    }
1017}