001    /** 
002     * 
003     * Copyright 2004 Protique Ltd
004     * 
005     * Licensed under the Apache License, Version 2.0 (the "License"); 
006     * you may not use this file except in compliance with the License. 
007     * 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     * 
017     **/
018    package org.activemq.ra;
019    
020    /**
021     * A helper class used to provide access to the current active
022     * {@link SessionAndProducer} instance being used to process a message
023     * in the current thread so that messages can be produced using the same
024     * session.
025     *
026     * @version $Revision: 1.1.1.1 $
027     */
028    public class SessionAndProducerHelper {
029        private static final ThreadLocal threadLocal = new ThreadLocal();
030    
031        /**
032         * Returns the current {@link SessionAndProducer} used by the current thread which is processing a message.
033         * This allows us to access the current Session to send a message using the same underlying
034         * session to avoid unnecessary XA or to use regular JMS transactions while using message driven POJOs.
035         *
036         * @return
037         */
038        public static SessionAndProducer getActiveSessionAndProducer() {
039            return (SessionAndProducer) threadLocal.get();
040        }
041    
042    
043        /**
044         * Registers the session and producer which should be called before the
045         * {@link javax.resource.spi.endpoint.MessageEndpoint#beforeDelivery(java.lang.reflect.Method)}
046         * method is called.
047         *
048         * @param sessionAndProducer
049         */
050        public static void register(SessionAndProducer sessionAndProducer) {
051            threadLocal.set(sessionAndProducer);
052        }
053    
054        /**
055         * Unregisters the session and producer which should be called after the
056         * {@link javax.resource.spi.endpoint.MessageEndpoint#afterDelivery()}
057         * method is called.
058         *
059         * @param sessionAndProducer
060         */
061        public static void unregister(SessionAndProducer sessionAndProducer) {
062            threadLocal.set(null);
063        }
064    }