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