001/*
002 * Copyright 2002-2018 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.lang.Nullable;
024import org.springframework.util.ClassUtils;
025
026/**
027 * Generic support base class for remote accessor and exporters,
028 * providing common bean ClassLoader handling.
029 *
030 * @author Juergen Hoeller
031 * @since 2.5.2
032 */
033public abstract class RemotingSupport implements BeanClassLoaderAware {
034
035        /** Logger available to subclasses. */
036        protected final Log logger = LogFactory.getLog(getClass());
037
038        private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
039
040
041        @Override
042        public void setBeanClassLoader(ClassLoader classLoader) {
043                this.beanClassLoader = classLoader;
044        }
045
046        /**
047         * Return the ClassLoader that this accessor operates in,
048         * to be used for deserializing and for generating proxies.
049         */
050        protected ClassLoader getBeanClassLoader() {
051                return this.beanClassLoader;
052        }
053
054
055        /**
056         * Override the thread context ClassLoader with the environment's bean ClassLoader
057         * if necessary, i.e. if the bean ClassLoader is not equivalent to the thread
058         * context ClassLoader already.
059         * @return the original thread context ClassLoader, or {@code null} if not overridden
060         */
061        @Nullable
062        protected ClassLoader overrideThreadContextClassLoader() {
063                return ClassUtils.overrideThreadContextClassLoader(getBeanClassLoader());
064        }
065
066        /**
067         * Reset the original thread context ClassLoader if necessary.
068         * @param original the original thread context ClassLoader,
069         * or {@code null} if not overridden (and hence nothing to reset)
070         */
071        protected void resetThreadContextClassLoader(@Nullable ClassLoader original) {
072                if (original != null) {
073                        Thread.currentThread().setContextClassLoader(original);
074                }
075        }
076
077}