001/*
002 * Copyright 2002-2012 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.remoting.support;
018
019import org.apache.commons.logging.Log;
020import org.apache.commons.logging.LogFactory;
021
022import org.springframework.beans.factory.BeanClassLoaderAware;
023import org.springframework.util.ClassUtils;
024
025/**
026 * Generic support base class for remote accessor and exporters,
027 * providing common bean ClassLoader handling.
028 *
029 * @author Juergen Hoeller
030 * @since 2.5.2
031 */
032public abstract class RemotingSupport implements BeanClassLoaderAware {
033
034        /** Logger available to subclasses */
035        protected final Log logger = LogFactory.getLog(getClass());
036
037        private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
038
039
040        @Override
041        public void setBeanClassLoader(ClassLoader classLoader) {
042                this.beanClassLoader = classLoader;
043        }
044
045        /**
046         * Return the ClassLoader that this accessor operates in,
047         * to be used for deserializing and for generating proxies.
048         */
049        protected ClassLoader getBeanClassLoader() {
050                return this.beanClassLoader;
051        }
052
053
054        /**
055         * Override the thread context ClassLoader with the environment's bean ClassLoader
056         * if necessary, i.e. if the bean ClassLoader is not equivalent to the thread
057         * context ClassLoader already.
058         * @return the original thread context ClassLoader, or {@code null} if not overridden
059         */
060        protected ClassLoader overrideThreadContextClassLoader() {
061                return ClassUtils.overrideThreadContextClassLoader(getBeanClassLoader());
062        }
063
064        /**
065         * Reset the original thread context ClassLoader if necessary.
066         * @param original the original thread context ClassLoader,
067         * or {@code null} if not overridden (and hence nothing to reset)
068         */
069        protected void resetThreadContextClassLoader(ClassLoader original) {
070                if (original != null) {
071                        Thread.currentThread().setContextClassLoader(original);
072                }
073        }
074
075}