View Javadoc

1   /*
2    * Copyright 2006-2008 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.batch.core.repository.dao;
18  
19  import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
20  import com.thoughtworks.xstream.io.HierarchicalStreamDriver;
21  import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
22  import com.thoughtworks.xstream.XStream;
23  
24  import java.util.Map;
25  
26  import org.springframework.beans.factory.InitializingBean;
27  
28  /**
29   * Implementation that uses XStream and Jettison to provide serialization.
30   * 
31   * @author Thomas Risberg
32   * @since 2.0
33   */
34  public class XStreamExecutionContextStringSerializer implements ExecutionContextStringSerializer, InitializingBean {
35  
36  	private ReflectionProvider reflectionProvider = null;
37  
38  	private HierarchicalStreamDriver hierarchicalStreamDriver;
39  
40  	private XStream xstream;
41  
42  	public String serialize(Map<String, Object> context) {
43  		return xstream.toXML(context);
44  	}
45  
46  	@SuppressWarnings("unchecked")
47  	public Map<String, Object> deserialize(String context) {
48  		return (Map<String, Object>) xstream.fromXML(context);
49  	}
50  
51  	public void setReflectionProvider(ReflectionProvider reflectionProvider) {
52  		this.reflectionProvider = reflectionProvider;
53  	}
54  
55  	public void setHierarchicalStreamDriver(HierarchicalStreamDriver hierarchicalStreamDriver) {
56  		this.hierarchicalStreamDriver = hierarchicalStreamDriver;
57  	}
58  
59  	public void afterPropertiesSet() throws Exception {
60  		init();
61  	}
62  
63  	public synchronized void init() throws Exception {
64  		if (hierarchicalStreamDriver == null) {
65  			this.hierarchicalStreamDriver = new JettisonMappedXmlDriver();
66  		}
67  		if (reflectionProvider == null) {
68  			xstream =  new XStream(hierarchicalStreamDriver);
69  		}
70  		else {
71  			xstream = new XStream(reflectionProvider, hierarchicalStreamDriver);
72  		}
73  	}
74  }