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
015package org.apache.hivemind.internal.ser;
016
017import java.lang.ref.WeakReference;
018
019import org.apache.hivemind.ApplicationRuntimeException;
020
021/**
022 * Class used to hold a <em>global</em> instance of
023 * {@link org.apache.hivemind.internal.ser.ServiceSerializationSupport}, so that
024 * {@link org.apache.hivemind.internal.ser.ServiceToken}s may locate them.
025 * 
026 * @author Howard M. Lewis Ship
027 * @since 1.1
028 */
029public class ServiceSerializationHelper
030{
031    private static final ThreadLocal _threadLocal = new ThreadLocal();
032
033    /**
034     * Returns the previously stored SSS.
035     * 
036     * @throws ApplicationRuntimeException
037     *             if no SSS has been stored.
038     */
039    public static ServiceSerializationSupport getServiceSerializationSupport()
040    {
041        ServiceSerializationSupport result = null;
042
043        WeakReference reference = (WeakReference) _threadLocal.get();
044        if (reference != null)
045            result = (ServiceSerializationSupport) reference.get();
046
047        if (result == null)
048            throw new ApplicationRuntimeException(SerMessages.noSupportSet());
049
050        return result;
051    }
052
053    /**
054     * Stores the SSS instance for later access; if an existing SSS is already stored, then an error
055     * is logged (should be just one SSS per class loader).
056     */
057
058    public static void setServiceSerializationSupport(
059            ServiceSerializationSupport serviceSerializationSupport)
060    {
061        WeakReference reference = new WeakReference(serviceSerializationSupport);
062
063        _threadLocal.set(reference);
064    }
065}