/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2007,2008 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.ejb21.ha.interceptors.iiop;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.omg.CORBA.LocalObject;
import org.ow2.cmi.ha.interceptor.HAContext;

/**
 * Provide marshalling and unmarshalling of an instance of {@link HAContext}.
 * @author Loris Bouzonnet
 */
public abstract class HAInterceptor extends LocalObject {

    /**
     * A unique identifier for HA context
     */
    public static int HA_CTX_ID = 6666;

    /**
     * Marshall an instance of {@link HAContext}.
     * @param haContext a context
     * @return the serialized context
     * @throws IOException if an error occur while marshalling
     */
    protected byte[] marshallHAContext(final HAContext haContext) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream =
            new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream =
            new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(haContext);
        return byteArrayOutputStream.toByteArray();
    }

    /**
     * Unmarshall an instance of {@link HAContext}.
     * @param byteCtx the serialized context
     * @return a context
     * @throws IOException if an error occur while unmarshalling
     * @throws ClassNotFoundException if the type of the context cannot be resolved
     */
    protected HAContext unmarshallHAContext(final byte[] byteCtx)
    throws IOException, ClassNotFoundException {
        ByteArrayInputStream byteArrayInputStream =
            new ByteArrayInputStream(byteCtx);
        ObjectInputStream objectInputStream =
            new ObjectInputStream(byteArrayInputStream);
        return (HAContext) objectInputStream.readObject();
    }
}
