1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.batch.core.repository.dao;
18
19 import java.io.BufferedReader;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.InputStreamReader;
23 import java.io.OutputStream;
24
25 import org.springframework.batch.core.repository.ExecutionContextSerializer;
26 import org.springframework.beans.factory.InitializingBean;
27 import org.springframework.core.serializer.Deserializer;
28 import org.springframework.core.serializer.Serializer;
29 import org.springframework.util.Assert;
30
31 import com.thoughtworks.xstream.XStream;
32 import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
33 import com.thoughtworks.xstream.io.HierarchicalStreamDriver;
34 import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
35
36
37
38
39
40
41
42
43
44 public class XStreamExecutionContextStringSerializer implements ExecutionContextSerializer, InitializingBean {
45
46 private ReflectionProvider reflectionProvider = null;
47
48 private HierarchicalStreamDriver hierarchicalStreamDriver;
49
50 private XStream xstream;
51
52 public void setReflectionProvider(ReflectionProvider reflectionProvider) {
53 this.reflectionProvider = reflectionProvider;
54 }
55
56 public void setHierarchicalStreamDriver(HierarchicalStreamDriver hierarchicalStreamDriver) {
57 this.hierarchicalStreamDriver = hierarchicalStreamDriver;
58 }
59
60 @Override
61 public void afterPropertiesSet() throws Exception {
62 init();
63 }
64
65 public synchronized void init() throws Exception {
66 if (hierarchicalStreamDriver == null) {
67 this.hierarchicalStreamDriver = new JettisonMappedXmlDriver();
68 }
69 if (reflectionProvider == null) {
70 xstream = new XStream(hierarchicalStreamDriver);
71 }
72 else {
73 xstream = new XStream(reflectionProvider, hierarchicalStreamDriver);
74 }
75 }
76
77
78
79
80
81
82
83
84 @Override
85 public void serialize(Object context, OutputStream out) throws IOException {
86 Assert.notNull(context);
87 Assert.notNull(out);
88
89 out.write(xstream.toXML(context).getBytes());
90 }
91
92
93
94
95
96
97
98
99 @Override
100 public Object deserialize(InputStream in) throws IOException {
101 BufferedReader br = new BufferedReader(new InputStreamReader(in));
102
103 StringBuilder sb = new StringBuilder();
104
105 String line;
106 while ((line = br.readLine()) != null) {
107 sb.append(line);
108 }
109
110 return xstream.fromXML(sb.toString());
111 }
112 }