1 package org.apache.commons.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 org.apache.commons.jcs.engine.behavior.IElementSerializer;
23 import org.apache.commons.jcs.io.ObjectInputStreamClassLoaderAware;
24
25 import java.io.BufferedInputStream;
26 import java.io.ByteArrayInputStream;
27 import java.io.ByteArrayOutputStream;
28 import java.io.IOException;
29 import java.io.ObjectInputStream;
30 import java.io.ObjectOutputStream;
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 serialization.
42 * <p>
43 * @param obj
44 * @return byte[]
45 * @throws IOException
46 */
47 @Override
48 public <T> byte[] serialize( T obj )
49 throws IOException
50 {
51 ByteArrayOutputStream baos = new ByteArrayOutputStream();
52 ObjectOutputStream oos = new ObjectOutputStream( baos );
53 try
54 {
55 oos.writeObject( obj );
56 }
57 finally
58 {
59 oos.close();
60 }
61 return baos.toByteArray();
62 }
63
64 /**
65 * Uses default de-serialization to turn a byte array into an object. All exceptions are
66 * converted into IOExceptions.
67 * <p>
68 * @param data
69 * @return Object
70 * @throws IOException
71 * @throws ClassNotFoundException
72 */
73 @Override
74 public <T> T deSerialize( byte[] data, ClassLoader loader )
75 throws IOException, ClassNotFoundException
76 {
77 ByteArrayInputStream bais = new ByteArrayInputStream( data );
78 BufferedInputStream bis = new BufferedInputStream( bais );
79 ObjectInputStream ois = new ObjectInputStreamClassLoaderAware( bis, loader );
80 try
81 {
82 @SuppressWarnings("unchecked") // Need to cast from Object
83 T readObject = (T) ois.readObject();
84 return readObject;
85 }
86 finally
87 {
88 ois.close();
89 }
90 }
91 }