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 */
020package org.apache.directory.server.core.avltree;
021
022
023import java.io.ByteArrayInputStream;
024import java.io.ByteArrayOutputStream;
025import java.io.IOException;
026import java.io.ObjectInputStream;
027import java.io.ObjectOutputStream;
028
029import org.apache.directory.server.i18n.I18n;
030
031
032/**
033 * A Marshaller which uses default Java Serialization.
034 *
035 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
036 */
037public class DefaultMarshaller implements Marshaller<Object>
038{
039    public static final DefaultMarshaller INSTANCE = new DefaultMarshaller();
040
041
042    public byte[] serialize( Object object ) throws IOException
043    {
044        try ( ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
045            ObjectOutputStream out = new ObjectOutputStream( byteStream ) )
046        {
047            out.writeObject( object );
048            out.flush();
049            byte[] data = byteStream.toByteArray();
050
051            return data;
052        }
053    }
054
055
056    public Object deserialize( byte[] bytes ) throws IOException
057    {
058        try ( ByteArrayInputStream byteStream = new ByteArrayInputStream( bytes );
059            ObjectInputStream in = new ObjectInputStream( byteStream ) )
060        {
061            return in.readObject();
062        }
063        catch ( ClassNotFoundException e )
064        {
065            IOException ioe = new IOException( I18n.err( I18n.ERR_445 ) );
066            ioe.initCause( e );
067            throw ioe;
068        }
069    }
070}