View Javadoc

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