/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 org.apache.camel.component.krati.serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.Serializable;
import krati.io.SerializationException;
import krati.io.Serializer;
import org.apache.camel.util.IOHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class KratiDefaultSerializer<T extends Serializable> implements Serializer<T> {

    private static final Logger LOG = LoggerFactory.getLogger(KratiDefaultSerializer.class);

    /**
     * Serialize an object into a byte array.
     *
     * @param object - an object to be serialized by this Serializer.
     * @return a byte array which is the raw representation of an object.
     */
    public byte[] serialize(T object) throws SerializationException {
        byte[] result = null;

        if (object == null) {
            return null;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            result = baos.toByteArray();
        } catch (IOException e) {
            LOG.warn("Error while serializing object. Null will be used.", e);
        } finally {
            IOHelper.close(oos, baos);
        }
        return result;
    }

    /**
     * Deserialize an object from its raw bytes generated by {{@link #serialize(Object)}.
     *
     * @param binary - the raw bytes from which an object is constructed.
     * @return an object constructed from the raw bytes.
     * @throws SerializationException if the object cannot be constructed from the raw bytes.
     */
    @SuppressWarnings("unchecked")
    public T deserialize(byte[] binary) throws SerializationException {
        T result = null;
        ObjectInputStream ois = null;

        if (binary == null) {
            return null;
        }

        // TODO: should use Camel's ClassResolver for classloading
        ByteArrayInputStream bais = new ByteArrayInputStream(binary);
        final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        try {
            ois = new ObjectInputStream(bais) {
                @Override
                public Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
                    try {
                        return classLoader.loadClass(desc.getName());
                    } catch (Exception e) {
                    }
                    return super.resolveClass(desc);
                }
            };
            result = (T) ois.readObject();
        } catch (IOException e) {
            LOG.warn("Error while deserializing object. Null will be used.", e);
        } catch (ClassNotFoundException e) {
            LOG.warn("Could not find class while deserializing object. Null will be used.", e);
        } finally {
            IOHelper.close(ois, bais);
        }
        return result;
    }
}
