//   Copyright 2012 Georg-August-Universität Göttingen, Germany
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package de.ugoe.cs.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.io.OutputStream;
import java.io.Serializable;

import org.apache.commons.lang.SerializationException;

/**
 * <p>
 * This class is basically a partial copy of the the
 * {@link org.apache.commons.lang.SerializationUtils}. The difference is that we use the class
 * loader of the current context for the ObjectInputStream for deserialization. This allows the
 * usage of this method in multi-classloader environments, such as application servers.
 * </p>
 * 
 * @author Steffen Herbold
 */
public class SerializationUtils {

    /**
     * @see org.apache.commons.lang.SerializationUtils#serialize(Serializable, OutputStream)
     */
    public static void serialize(final Serializable obj, final OutputStream outputStream) {
        org.apache.commons.lang.SerializationUtils.serialize(obj, outputStream);
    }

    /**
     * @see org.apache.commons.lang.SerializationUtils#serialize(Serializable)
     */
    public static byte[] serialize(final Serializable obj) {
        return org.apache.commons.lang.SerializationUtils.serialize(obj);
    }

    /**
     * @see org.apache.commons.lang.SerializationUtils#deserialize(InputStream)
     */
    public static <T> T deserialize(final InputStream inputStream) {
        if (inputStream == null) {
            throw new IllegalArgumentException("The InputStream must not be null");
        }
        ObjectInputStream in = null;
        try {
            // stream closed in the finally
            in = new ObjectInputStream(inputStream) {
                /*
                 * (non-Javadoc)
                 * 
                 * @see java.io.ObjectInputStream#resolveClass(java.io.ObjectStreamClass)
                 */
                @Override
                protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException,
                    ClassNotFoundException
                {
                    Class<?> clazz =
                        Class.forName(desc.getName(), false, Thread.currentThread()
                            .getContextClassLoader());

                    if (clazz != null) {
                        return clazz;
                    }
                    return super.resolveClass(desc);
                }
            };
            @SuppressWarnings("unchecked")
            // may fail with CCE if serialised form is incorrect
            final T obj = (T) in.readObject();
            return obj;

        }
        catch (final ClassCastException ex) {
            throw new SerializationException(ex);
        }
        catch (final ClassNotFoundException ex) {
            throw new SerializationException(ex);
        }
        catch (final IOException ex) {
            throw new SerializationException(ex);
        }
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            }
            catch (final IOException ex) { // NOPMD
                // ignore close exception
            }
        }
    }

    /**
     * @see org.apache.commons.lang.SerializationUtils#deserialize(byte[])
     */
    public static <T> T deserialize(final byte[] objectData) {
        if (objectData == null) {
            throw new IllegalArgumentException("The byte[] must not be null");
        }
        return SerializationUtils.<T> deserialize(new ByteArrayInputStream(objectData));
    }

}
