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.IOException;
020import java.util.Iterator;
021import java.util.LinkedHashMap;
022import java.util.LinkedList;
023import java.util.Map;
024
025import javax.jms.JMSException;
026
027import org.apache.activemq.command.ActiveMQBytesMessage;
028import org.apache.activemq.command.ActiveMQDestination;
029import org.apache.activemq.command.ActiveMQMessage;
030import org.apache.activemq.command.ConsumerInfo;
031import org.apache.activemq.command.MessageAck;
032import org.apache.activemq.command.MessageDispatch;
033import org.apache.activemq.command.MessageId;
034import org.apache.activemq.command.TransactionId;
035import org.apache.activemq.util.IdGenerator;
036import org.slf4j.Logger;
037import org.slf4j.LoggerFactory;
038
039/**
040 * Keeps track of the STOMP subscription so that acking is correctly done.
041 *
042 * @author <a href="http://hiramchirino.com">chirino</a>
043 */
044public class StompSubscription {
045
046    private static final Logger LOG = LoggerFactory.getLogger(StompSubscription.class);
047
048    private static final IdGenerator ACK_ID_GENERATOR = new IdGenerator();
049
050    public static final String AUTO_ACK = Stomp.Headers.Subscribe.AckModeValues.AUTO;
051    public static final String CLIENT_ACK = Stomp.Headers.Subscribe.AckModeValues.CLIENT;
052    public static final String INDIVIDUAL_ACK = Stomp.Headers.Subscribe.AckModeValues.INDIVIDUAL;
053
054    protected final ProtocolConverter protocolConverter;
055    protected final String subscriptionId;
056    protected final ConsumerInfo consumerInfo;
057
058    protected final Map<MessageId, StompAckEntry> dispatchedMessage = new LinkedHashMap<>();
059    protected final Map<String, StompAckEntry> pendingAcks; // STOMP v1.2 requires ACK ID tracking
060    protected final LinkedList<StompAckEntry> transactedMessages = new LinkedList<>();
061
062    protected String ackMode = AUTO_ACK;
063    protected ActiveMQDestination destination;
064    protected String transformation;
065
066    public StompSubscription(ProtocolConverter stompTransport, String subscriptionId, ConsumerInfo consumerInfo, String transformation, Map<String, StompAckEntry> pendingAcks) {
067        this.protocolConverter = stompTransport;
068        this.subscriptionId = subscriptionId;
069        this.consumerInfo = consumerInfo;
070        this.transformation = transformation;
071        this.pendingAcks = pendingAcks;
072    }
073
074    void onMessageDispatch(MessageDispatch md) throws IOException, JMSException {
075        ActiveMQMessage message = (ActiveMQMessage)md.getMessage();
076
077        String ackId = null;
078        if (isClientAck() || isIndividualAck()) {
079            ackId = ACK_ID_GENERATOR.generateId();
080            StompAckEntry pendingAck = new StompAckEntry(md, ackId, this);
081
082            synchronized (this) {
083                dispatchedMessage.put(message.getMessageId(), pendingAck);
084            }
085            if (protocolConverter.isStomp12()) {
086                this.pendingAcks.put(ackId, pendingAck);
087            }
088        } else if (isAutoAck()) {
089            MessageAck ack = new MessageAck(md, MessageAck.STANDARD_ACK_TYPE, 1);
090            protocolConverter.getStompTransport().sendToActiveMQ(ack);
091        }
092
093        boolean ignoreTransformation = false;
094
095        if (transformation != null && !( message instanceof ActiveMQBytesMessage ) ) {
096            message.setReadOnlyProperties(false);
097            message.setStringProperty(Stomp.Headers.TRANSFORMATION, transformation);
098        } else {
099            if (message.getStringProperty(Stomp.Headers.TRANSFORMATION) != null) {
100                ignoreTransformation = true;
101            }
102        }
103
104        StompFrame command = protocolConverter.convertMessage(message, ignoreTransformation);
105
106        command.setAction(Stomp.Responses.MESSAGE);
107        if (subscriptionId != null) {
108            command.getHeaders().put(Stomp.Headers.Message.SUBSCRIPTION, subscriptionId);
109        }
110
111        if (protocolConverter.isStomp12() && ackId != null) {
112            command.getHeaders().put(Stomp.Headers.Message.ACK_ID, ackId);
113        }
114
115        try {
116            protocolConverter.getStompTransport().sendToStomp(command);
117        } catch (IOException ex) {
118            if (ackId != null) {
119                pendingAcks.remove(ackId);
120            }
121            throw ex;
122        }
123    }
124
125    synchronized void onStompAbort(TransactionId transactionId) {
126        // Restore the pending ACKs so that their ACK IDs are again valid for a client
127        // to operate on.
128        LOG.trace("Transaction Abort restoring {} pending ACKs to valid state.", transactedMessages.size());
129        for (StompAckEntry ackEntry : transactedMessages) {
130            if (protocolConverter.isStomp12()) {
131                pendingAcks.put(ackEntry.getAckId(), ackEntry);
132            }
133        }
134        transactedMessages.clear();
135    }
136
137    void onStompCommit(TransactionId transactionId) {
138        MessageAck ack = null;
139        synchronized (this) {
140            for (Iterator<StompAckEntry> iterator = dispatchedMessage.values().iterator(); iterator.hasNext();) {
141                StompAckEntry ackEntry = iterator.next();
142                if (transactedMessages.contains(ackEntry)) {
143                    iterator.remove();
144                }
145            }
146
147            // For individual Ack we already sent an Ack that will be applied on commit
148            // we don't send a second standard Ack as that would produce an error.
149            if (!transactedMessages.isEmpty() && isClientAck()) {
150                ack = new MessageAck(transactedMessages.getLast().getMessageDispatch(), MessageAck.STANDARD_ACK_TYPE, transactedMessages.size());
151                ack.setTransactionId(transactionId);
152                transactedMessages.clear();
153            }
154        }
155        // avoid contention with onMessageDispatch
156        if (ack != null) {
157            protocolConverter.getStompTransport().sendToActiveMQ(ack);
158        }
159    }
160
161    synchronized MessageAck onStompMessageAck(String messageId, TransactionId transactionId) {
162        MessageId msgId = new MessageId(messageId);
163
164        final StompAckEntry ackEntry = dispatchedMessage.get(msgId);
165        if (ackEntry == null) {
166            return null;
167        }
168
169        MessageAck ack = new MessageAck();
170        ack.setDestination(consumerInfo.getDestination());
171        ack.setConsumerId(consumerInfo.getConsumerId());
172
173        if (isClientAck()) {
174            if (transactionId == null) {
175                ack.setAckType(MessageAck.STANDARD_ACK_TYPE);
176            } else {
177                ack.setAckType(MessageAck.DELIVERED_ACK_TYPE);
178            }
179            int count = 0;
180            for (Iterator<StompAckEntry> iterator = dispatchedMessage.values().iterator(); iterator.hasNext();) {
181                StompAckEntry entry = iterator.next();
182                MessageId current = entry.getMessageId();
183
184                if (entry.getAckId() != null) {
185                    pendingAcks.remove(entry.getAckId());
186                }
187
188                if (transactionId != null) {
189                    if (!transactedMessages.contains(entry)) {
190                        transactedMessages.add(entry);
191                        count++;
192                    }
193                } else {
194                    iterator.remove();
195                    count++;
196                }
197
198                if (current.equals(msgId)) {
199                    ack.setLastMessageId(current);
200                    break;
201                }
202            }
203            ack.setMessageCount(count);
204            if (transactionId != null) {
205                ack.setTransactionId(transactionId);
206            }
207        } else if (isIndividualAck()) {
208            if (ackEntry.getAckId() != null) {
209                pendingAcks.remove(ackEntry.getAckId());
210            }
211            ack.setAckType(MessageAck.INDIVIDUAL_ACK_TYPE);
212            ack.setMessageID(msgId);
213            ack.setMessageCount(1);
214            if (transactionId != null) {
215                transactedMessages.add(dispatchedMessage.get(msgId));
216                ack.setTransactionId(transactionId);
217            } else {
218                dispatchedMessage.remove(msgId);
219            }
220        }
221
222        return ack;
223    }
224
225    public MessageAck onStompMessageNack(String messageId, TransactionId transactionId) throws ProtocolException {
226        MessageId msgId = new MessageId(messageId);
227
228        if (!dispatchedMessage.containsKey(msgId)) {
229            return null;
230        }
231
232        final StompAckEntry ackEntry = dispatchedMessage.get(msgId);
233
234        if (ackEntry.getAckId() != null) {
235            pendingAcks.remove(ackEntry.getAckId());
236        }
237
238        MessageAck ack = new MessageAck();
239        ack.setDestination(consumerInfo.getDestination());
240        ack.setConsumerId(consumerInfo.getConsumerId());
241        ack.setAckType(MessageAck.POSION_ACK_TYPE);
242        ack.setMessageID(msgId);
243        if (transactionId != null) {
244            transactedMessages.add(ackEntry);
245            ack.setTransactionId(transactionId);
246        } else {
247            dispatchedMessage.remove(msgId);
248        }
249
250        return ack;
251    }
252
253    public String getAckMode() {
254        return ackMode;
255    }
256
257    public void setAckMode(String ackMode) {
258        this.ackMode = ackMode;
259    }
260
261    public boolean isAutoAck() {
262        return ackMode.equals(AUTO_ACK);
263    }
264
265    public boolean isClientAck() {
266        return ackMode.equals(CLIENT_ACK);
267    }
268
269    public boolean isIndividualAck() {
270        return ackMode.equals(INDIVIDUAL_ACK);
271    }
272
273    public String getSubscriptionId() {
274        return subscriptionId;
275    }
276
277    public void setDestination(ActiveMQDestination destination) {
278        this.destination = destination;
279    }
280
281    public ActiveMQDestination getDestination() {
282        return destination;
283    }
284
285    public ConsumerInfo getConsumerInfo() {
286        return consumerInfo;
287    }
288}