001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one
003     * or more contributor license agreements.  See the NOTICE file
004     * distributed with this work for additional information
005     * regarding copyright ownership.  The ASF licenses this file
006     * to you under the Apache License, Version 2.0 (the
007     * "License"); you may not use this file except in compliance
008     * with the License.  You may obtain a copy of the License at
009     *
010     *     http://www.apache.org/licenses/LICENSE-2.0
011     *
012     * Unless required by applicable law or agreed to in writing,
013     * software distributed under the License is distributed on an
014     * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015     * KIND, either express or implied.  See the License for the
016     * specific language governing permissions and limitations
017     * under the License.
018     */
019    package org.apache.shiro.io;
020    
021    import org.apache.shiro.util.ClassUtils;
022    import org.apache.shiro.util.UnknownClassException;
023    
024    import java.io.IOException;
025    import java.io.InputStream;
026    import java.io.ObjectInputStream;
027    import java.io.ObjectStreamClass;
028    
029    /**
030     * Enables correct ClassLoader lookup in various environments (e.g. JEE Servers, etc).
031     *
032     * @since 1.2
033     * @see <a href="https://issues.apache.org/jira/browse/SHIRO-334">SHIRO-334</a>
034     */
035    public class ClassResolvingObjectInputStream extends ObjectInputStream {
036    
037        public ClassResolvingObjectInputStream(InputStream inputStream) throws IOException {
038            super(inputStream);
039        }
040    
041        /**
042         * Resolves an {@link ObjectStreamClass} by delegating to Shiro's 
043         * {@link ClassUtils#forName(String)} utility method, which is known to work in all ClassLoader environments.
044         * 
045         * @param osc the ObjectStreamClass to resolve the class name.
046         * @return the discovered class
047         * @throws IOException never - declaration retained for subclass consistency
048         * @throws ClassNotFoundException if the class could not be found in any known ClassLoader
049         */
050        @Override
051        protected Class<?> resolveClass(ObjectStreamClass osc) throws IOException, ClassNotFoundException {
052            try {
053                return ClassUtils.forName(osc.getName());
054            } catch (UnknownClassException e) {
055                throw new ClassNotFoundException("Unable to load ObjectStreamClass [" + osc + "]: ", e);
056            }
057        }
058    }