1 package org.apache.commons.jcs.utils.serialization;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import org.apache.commons.jcs.engine.CacheElement;
23 import org.apache.commons.jcs.engine.CacheElementSerialized;
24 import org.apache.commons.jcs.engine.behavior.ICacheElement;
25 import org.apache.commons.jcs.engine.behavior.ICacheElementSerialized;
26 import org.apache.commons.jcs.engine.behavior.IElementSerializer;
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29
30 import java.io.IOException;
31
32
33
34
35
36
37 public class SerializationConversionUtil
38 {
39
40 private static final Log log = LogFactory.getLog( SerializationConversionUtil.class );
41
42
43
44
45
46
47
48
49
50
51
52 public static <K, V> ICacheElementSerialized<K, V> getSerializedCacheElement( ICacheElement<K, V> element,
53 IElementSerializer elementSerializer )
54 throws IOException
55 {
56 if ( element == null )
57 {
58 return null;
59 }
60
61 byte[] serializedValue = null;
62
63
64 if ( element instanceof ICacheElementSerialized )
65 {
66 serializedValue = ( (ICacheElementSerialized<K, V>) element ).getSerializedValue();
67 }
68 else
69 {
70 if ( elementSerializer != null )
71 {
72 try
73 {
74 serializedValue = elementSerializer.serialize( element.getVal() );
75 }
76 catch ( IOException e )
77 {
78 log.error( "Problem serializing object.", e );
79 throw e;
80 }
81 }
82 else
83 {
84
85 log.warn( "ElementSerializer is null. Could not serialize object." );
86 throw new IOException( "Could not serialize object. The ElementSerializer is null." );
87 }
88 }
89 ICacheElementSerialized<K, V> serialized = new CacheElementSerialized<K, V>(
90 element.getCacheName(), element.getKey(), serializedValue, element.getElementAttributes() );
91
92 return serialized;
93 }
94
95
96
97
98
99
100
101
102
103
104
105
106 public static <K, V> ICacheElement<K, V> getDeSerializedCacheElement( ICacheElementSerialized<K, V> serialized,
107 IElementSerializer elementSerializer )
108 throws IOException, ClassNotFoundException
109 {
110 if ( serialized == null )
111 {
112 return null;
113 }
114
115 V deSerializedValue = null;
116
117 if ( elementSerializer != null )
118 {
119 try
120 {
121 try
122 {
123 deSerializedValue = elementSerializer.deSerialize( serialized.getSerializedValue(), null );
124 }
125 catch ( ClassNotFoundException e )
126 {
127 log.error( "Problem de-serializing object.", e );
128 throw e;
129 }
130 }
131 catch ( IOException e )
132 {
133 log.error( "Problem de-serializing object.", e );
134 throw e;
135 }
136 }
137 else
138 {
139
140 log.warn( "ElementSerializer is null. Could not serialize object." );
141 }
142 ICacheElement<K, V> deSerialized = new CacheElement<K, V>( serialized.getCacheName(), serialized.getKey(), deSerializedValue );
143 deSerialized.setElementAttributes( serialized.getElementAttributes() );
144
145 return deSerialized;
146 }
147 }