001    // Copyright 2005 The Apache Software Foundation
002    //
003    // Licensed under the Apache License, Version 2.0 (the "License");
004    // you may not use this file except in compliance with the License.
005    // You may obtain a copy of the License at
006    //
007    //     http://www.apache.org/licenses/LICENSE-2.0
008    //
009    // Unless required by applicable law or agreed to in writing, software
010    // distributed under the License is distributed on an "AS IS" BASIS,
011    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012    // See the License for the specific language governing permissions and
013    // limitations under the License.
014    
015    package org.apache.hivemind.internal.ser;
016    
017    import java.lang.ref.WeakReference;
018    
019    import org.apache.commons.logging.Log;
020    import org.apache.commons.logging.LogFactory;
021    import org.apache.hivemind.ApplicationRuntimeException;
022    
023    /**
024     * Class used to hold a <em>global</em> instance of
025     * {@link org.apache.hivemind.internal.ser.ServiceSerializationSupport}, so that
026     * {@link org.apache.hivemind.internal.ser.ServiceToken}s may locate them.
027     * 
028     * @author Howard M. Lewis Ship
029     * @since 1.1
030     */
031    public class ServiceSerializationHelper
032    {
033        private static final Log LOG = LogFactory.getLog(ServiceSerializationHelper.class);
034    
035        private static final ThreadLocal _threadLocal = new ThreadLocal();
036    
037        /**
038         * Returns the previously stored SSS.
039         * 
040         * @throws ApplicationRuntimeException
041         *             if no SSS has been stored.
042         */
043        public static ServiceSerializationSupport getServiceSerializationSupport()
044        {
045            ServiceSerializationSupport result = null;
046    
047            WeakReference reference = (WeakReference) _threadLocal.get();
048            if (reference != null)
049                result = (ServiceSerializationSupport) reference.get();
050    
051            if (result == null)
052                throw new ApplicationRuntimeException(SerMessages.noSupportSet());
053    
054            return result;
055        }
056    
057        /**
058         * Stores the SSS instance for later access; if an existing SSS is already stored, then an error
059         * is logged (should be just one SSS per class loader).
060         */
061    
062        public static void setServiceSerializationSupport(
063                ServiceSerializationSupport serviceSerializationSupport)
064        {
065            WeakReference reference = new WeakReference(serviceSerializationSupport);
066    
067            _threadLocal.set(reference);
068        }
069    }