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.IOException;
23
24 import org.apache.commons.jcs3.engine.behavior.IElementSerializer;
25 import org.apache.commons.jcs3.utils.zip.CompressionUtil;
26
27 /**
28 * Performs default serialization and de-serialization. It gzips the value.
29 */
30 public class CompressingSerializer extends StandardSerializer
31 {
32 /** Wrapped serializer */
33 private final IElementSerializer serializer;
34
35
36 /**
37 * Default constructor
38 */
39 public CompressingSerializer()
40 {
41 this(new StandardSerializer());
42 }
43
44 /**
45 * Wrapper constructor
46 *
47 * @param serializer the wrapped serializer
48 * @since 3.1
49 */
50 public CompressingSerializer(IElementSerializer serializer)
51 {
52 this.serializer = serializer;
53 }
54
55 /**
56 * Serializes an object using default serialization. Compresses the byte array.
57 * <p>
58 * @param obj object
59 * @return byte[]
60 * @throws IOException on i/o problem
61 */
62 @Override
63 public <T> byte[] serialize( final T obj )
64 throws IOException
65 {
66 final byte[] uncompressed = serializer.serialize(obj);
67 return CompressionUtil.compressByteArray( uncompressed );
68 }
69
70 /**
71 * Uses default de-serialization to turn a byte array into an object. Decompresses the value
72 * first. All exceptions are converted into IOExceptions.
73 * <p>
74 * @param data data bytes
75 * @param loader class loader to use
76 * @return Object
77 * @throws IOException on i/o problem
78 * @throws ClassNotFoundException if class is not found during deserialization
79 */
80 @Override
81 public <T> T deSerialize( final byte[] data, final ClassLoader loader )
82 throws IOException, ClassNotFoundException
83 {
84 if ( data == null )
85 {
86 return null;
87 }
88
89 final byte[] decompressedByteArray = CompressionUtil.decompressByteArray( data );
90 return serializer.deSerialize(decompressedByteArray, loader);
91 }
92 }