View Javadoc
1   package org.apache.commons.jcs3.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.ByteArrayInputStream;
23  import java.io.ByteArrayOutputStream;
24  import java.io.IOException;
25  import java.io.ObjectInputStream;
26  import java.io.ObjectOutputStream;
27  
28  import org.apache.commons.jcs3.engine.behavior.IElementSerializer;
29  import org.apache.commons.jcs3.io.ObjectInputStreamClassLoaderAware;
30  
31  /**
32   * Performs default serialization and de-serialization.
33   */
34  public class StandardSerializer
35      implements IElementSerializer
36  {
37      /**
38       * Serializes an object using default serialization.
39       * <p>
40       * @param obj
41       * @return byte[]
42       * @throws IOException
43       */
44      @Override
45      public <T> byte[] serialize(final T obj)
46          throws IOException
47      {
48          final ByteArrayOutputStream baos = new ByteArrayOutputStream();
49  
50          try (ObjectOutputStream oos = new ObjectOutputStream(baos))
51          {
52              oos.writeUnshared(obj);
53          }
54  
55          return baos.toByteArray();
56      }
57  
58      /**
59       * Uses default de-serialization to turn a byte array into an object. All exceptions are
60       * converted into IOExceptions.
61       * <p>
62       * @param data data bytes
63       * @param loader class loader to use
64       * @return Object
65       * @throws IOException
66       * @throws ClassNotFoundException
67       */
68      @Override
69      public <T> T deSerialize(final byte[] data, final ClassLoader loader)
70          throws IOException, ClassNotFoundException
71      {
72          try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
73               ObjectInputStream ois = new ObjectInputStreamClassLoaderAware(bais, loader))
74          {
75              @SuppressWarnings("unchecked") // Need to cast from Object
76              final
77              T readObject = (T) ois.readObject();
78              return readObject;
79          }
80      }
81  }