1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.proxy2.serialization;
18
19 import static org.junit.Assert.assertEquals;
20 import static org.junit.Assert.assertTrue;
21
22 import java.io.Serializable;
23
24 import org.apache.commons.lang3.SerializationException;
25 import org.apache.commons.lang3.SerializationUtils;
26 import org.apache.commons.proxy2.ProxyFactory;
27 import org.apache.commons.proxy2.interceptor.InterceptorUtils;
28 import org.apache.commons.proxy2.interceptor.SwitchInterceptor;
29 import org.apache.commons.proxy2.interceptor.matcher.invocation.DeclaredByMatcher;
30 import org.apache.commons.proxy2.AbstractProxyFactoryAgnosticTest;
31 import org.junit.After;
32 import org.junit.Before;
33 import org.junit.Test;
34
35 public class SerializationProxyTest extends AbstractProxyFactoryAgnosticTest
36 {
37 public static class NonSerializableStringWrapper
38 {
39 private final String value;
40
41 NonSerializableStringWrapper(String value)
42 {
43 this.value = value;
44 }
45
46 public String getValue()
47 {
48 return value;
49 }
50 }
51
52 public interface Provider
53 {
54 NonSerializableStringWrapper getObject();
55 }
56
57 private static final ThreadLocal<ProxyFactory> PROXY_FACTORY = new ThreadLocal<ProxyFactory>();
58
59 private static SwitchInterceptor implementProvider(String value)
60 {
61 return new SwitchInterceptor().when(new DeclaredByMatcher(Provider.class)).then(
62 InterceptorUtils.constant(new NonSerializableStringWrapper(value)));
63 }
64
65 private static Provider serializableProvider(final String value)
66 {
67 return PROXY_FACTORY.get().createInterceptorProxy(
68 null,
69 implementProvider(value).when(new DeclaredByMatcher(WriteReplace.class)).then(
70 InterceptorUtils.constant(new ReadResolve()
71 {
72 private static final long serialVersionUID = 1L;
73
74 @Override
75 public Object readResolve()
76 {
77 return serializableProvider(value);
78 }
79 })), Provider.class, WriteReplace.class);
80 }
81
82 @Before
83 public void captureProxyFactory()
84 {
85 PROXY_FACTORY.set(proxyFactory);
86 }
87
88 @After
89 public void clearProxyFactory()
90 {
91 PROXY_FACTORY.remove();
92 }
93
94 @Test(expected = SerializationException.class)
95 public void testNaive()
96 {
97 final Provider proxy = proxyFactory.createInterceptorProxy(null, implementProvider("foo"), Provider.class,
98 Serializable.class);
99 assertEquals("foo", proxy.getObject().getValue());
100 assertTrue(Serializable.class.isInstance(proxy));
101 SerializationUtils.roundtrip((Serializable) proxy);
102 }
103
104 @Test
105 public void testSerializationProxy()
106 {
107 final Provider proxy = serializableProvider("foo");
108 assertEquals("foo", proxy.getObject().getValue());
109 assertTrue(Serializable.class.isInstance(proxy));
110 final Provider proxy2 = (Provider) SerializationUtils.roundtrip((Serializable) proxy);
111 assertEquals("foo", proxy2.getObject().getValue());
112 }
113 }