View Javadoc

1   /**
2    * Copyright 2005-2012 The Kuali Foundation
3    *
4    * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
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  package org.kuali.rice.krad.service.impl;
17  
18  import com.thoughtworks.xstream.XStream;
19  import com.thoughtworks.xstream.converters.MarshallingContext;
20  import com.thoughtworks.xstream.converters.reflection.ObjectAccessException;
21  import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;
22  import com.thoughtworks.xstream.converters.reflection.ReflectionConverter;
23  import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
24  import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
25  import com.thoughtworks.xstream.mapper.Mapper;
26  import org.apache.commons.logging.Log;
27  import org.apache.commons.logging.LogFactory;
28  import org.apache.ojb.broker.core.proxy.ListProxyDefaultImpl;
29  import org.kuali.rice.krad.service.KRADServiceLocator;
30  import org.kuali.rice.krad.service.PersistenceService;
31  import org.kuali.rice.krad.service.XmlObjectSerializerService;
32  
33  import java.lang.reflect.Field;
34  import java.util.ArrayList;
35  import java.util.Iterator;
36  
37  
38  /**
39   * This class is the service implementation for the XmlObjectSerializer structure. This is the default implementation that gets
40   * delivered with Kuali. It utilizes the XStream open source libraries and framework.
41   * 
42   * 
43   */
44  public class XmlObjectSerializerServiceImpl implements XmlObjectSerializerService {
45  	private static final Log LOG = LogFactory.getLog(XmlObjectSerializerServiceImpl.class);
46  	
47  	private PersistenceService persistenceService;
48  	
49  	private XStream xstream;
50  	
51  	public XmlObjectSerializerServiceImpl() {
52  		xstream = new XStream(new ProxyAwareJavaReflectionProvider());
53  
54          // See http://xstream.codehaus.org/faq.html#Serialization_CGLIB
55          // To use a newer version of XStream we may need to do something like this:
56  //        xstream = new XStream() {
57  //
58  //            @Override
59  //            public ReflectionProvider getReflectionProvider() {
60  //                return new ProxyAwareJavaReflectionProvider();
61  //            }
62  //
63  //            protected MapperWrapper wrapMapper(MapperWrapper next) {
64  //                return new CGLIBMapper(next);
65  //            }
66  //        };
67  //        xstream.registerConverter(new CGLIBEnhancedConverter(xstream.getMapper(), xstream.getReflectionProvider()));
68  
69  		xstream.registerConverter(new ProxyConverter(xstream.getMapper(), xstream.getReflectionProvider() ));
70  		xstream.addDefaultImplementation(ArrayList.class, ListProxyDefaultImpl.class);
71  	}
72  	
73      /**
74       * @see org.kuali.rice.krad.service.XmlObjectSerializer#toXml(java.lang.Object)
75       */
76      public String toXml(Object object) {
77      	if ( LOG.isDebugEnabled() ) {
78      		LOG.debug( "toXml(" + object + ") : \n" + xstream.toXML(object) );
79      	}
80          return xstream.toXML(object);
81      }
82  
83      /**
84       * @see org.kuali.rice.krad.service.XmlObjectSerializer#fromXml(java.lang.String)
85       */
86      public Object fromXml(String xml) {
87      	if ( LOG.isDebugEnabled() ) {
88      		LOG.debug( "fromXml() : \n" + xml );
89      	}
90      	if ( xml != null ) {
91      		xml = xml.replaceAll( "--EnhancerByCGLIB--[0-9a-f]{0,8}", "" );
92      	}
93          return xstream.fromXML(xml);
94      }
95  
96      /**
97       * This custom converter only handles proxies for BusinessObjects.  List-type proxies are handled by configuring XStream to treat
98       * ListProxyDefaultImpl as ArrayLists (see constructor for this service). 
99       */
100     public class ProxyConverter extends ReflectionConverter {
101         public ProxyConverter(Mapper mapper, ReflectionProvider reflectionProvider) {
102             super(mapper, reflectionProvider);
103         }
104         
105         @Override
106         // since the ReflectionConverter supertype defines canConvert without using a parameterized Class type, we must declare
107         // the overridden version the same way
108         @SuppressWarnings("unchecked")
109         public boolean canConvert(Class clazz) {
110             return clazz.getName().contains("CGLIB");
111         }
112 
113         @Override
114         public void marshal(Object obj, HierarchicalStreamWriter writer, MarshallingContext context) {
115             super.marshal(getPersistenceService().resolveProxy(obj), writer, context);
116         }
117         
118         // we shouldn't need an unmarshal method because all proxy metadata is taken out of the XML, so we'll reserialize as a base BO. 
119     }
120     
121     public class ProxyAwareJavaReflectionProvider extends PureJavaReflectionProvider {
122 
123     	public ProxyAwareJavaReflectionProvider() {
124     		super();
125     	}
126         /**
127          * @see com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider#visitSerializableFields(java.lang.Object, com.thoughtworks.xstream.converters.reflection.ReflectionProvider.Visitor)
128          */
129         @Override
130         public void visitSerializableFields(Object object, Visitor visitor) {
131             for (Iterator iterator = fieldDictionary.serializableFieldsFor(object.getClass()); iterator.hasNext();) {
132                 Field field = (Field) iterator.next();
133                 if (!fieldModifiersSupported(field)) {
134                     continue;
135                 }
136                 validateFieldAccess(field);
137                 Object value = null;
138                 try {
139                     value = field.get(object);
140                     if (value != null && getPersistenceService().isProxied(value)) {
141                         value = getPersistenceService().resolveProxy(value);
142                     }
143                 } catch (IllegalArgumentException e) {
144                     throw new ObjectAccessException("Could not get field " + field.getClass() + "." + field.getName(), e);
145                 } catch (IllegalAccessException e) {
146                     throw new ObjectAccessException("Could not get field " + field.getClass() + "." + field.getName(), e);
147                 }
148                 visitor.visit(field.getName(), field.getType(), field.getDeclaringClass(), value);
149             }
150         }
151         
152     }
153 
154 	public PersistenceService getPersistenceService() {
155 		if ( persistenceService == null ) {
156 			persistenceService = KRADServiceLocator.getPersistenceService();
157 		}
158 		return persistenceService;
159 	}
160     
161 }