View Javadoc

1   package org.apache.jcs.utils.serialization;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import java.io.BufferedInputStream;
23  import java.io.ByteArrayInputStream;
24  import java.io.ByteArrayOutputStream;
25  import java.io.IOException;
26  import java.io.ObjectInputStream;
27  import java.io.ObjectOutputStream;
28  import java.io.Serializable;
29  
30  import org.apache.jcs.engine.behavior.IElementSerializer;
31  
32  /***
33   * Performs default serialization and de-serialization.
34   * <p>
35   * @author Aaron Smuts
36   */
37  public class StandardSerializer
38      implements IElementSerializer
39  {
40      /***
41       * Serializes an object using default serilaization.
42       */
43      public byte[] serialize( Serializable obj )
44          throws IOException
45      {
46          ByteArrayOutputStream baos = new ByteArrayOutputStream();
47          ObjectOutputStream oos = new ObjectOutputStream( baos );
48          try
49          {
50              oos.writeObject( obj );
51          }
52          finally
53          {
54              oos.close();
55          }
56          return baos.toByteArray();
57      }
58  
59      /***
60       * Uses default de-serialization to turn a byte array into an object. All
61       * exceptions are converted into IOExceptions.
62       */
63      public Object deSerialize( byte[] data )
64          throws IOException, ClassNotFoundException
65      {
66          ByteArrayInputStream bais = new ByteArrayInputStream( data );
67          BufferedInputStream bis = new BufferedInputStream( bais );
68          ObjectInputStream ois = new ObjectInputStream( bis );
69          try
70          {
71              try
72              {
73                  return ois.readObject();
74              }
75              catch ( IOException e )
76              {
77                  throw e;
78              }
79              catch ( ClassNotFoundException e )
80              {
81                  throw e;
82              }
83          }
84          finally
85          {
86              ois.close();
87          }
88      }
89  }