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