001    /**
002     * Copyright 2005-2012 The Kuali Foundation
003     *
004     * Licensed under the Educational Community License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.opensource.org/licenses/ecl2.php
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    package org.kuali.rice.krad.service.impl;
017    
018    import com.thoughtworks.xstream.XStream;
019    import com.thoughtworks.xstream.converters.MarshallingContext;
020    import com.thoughtworks.xstream.converters.reflection.ObjectAccessException;
021    import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;
022    import com.thoughtworks.xstream.converters.reflection.ReflectionConverter;
023    import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
024    import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
025    import com.thoughtworks.xstream.mapper.Mapper;
026    import org.apache.commons.logging.Log;
027    import org.apache.commons.logging.LogFactory;
028    import org.apache.ojb.broker.core.proxy.ListProxyDefaultImpl;
029    import org.kuali.rice.krad.service.KRADServiceLocator;
030    import org.kuali.rice.krad.service.PersistenceService;
031    import org.kuali.rice.krad.service.XmlObjectSerializerService;
032    
033    import java.lang.reflect.Field;
034    import java.util.ArrayList;
035    import java.util.Iterator;
036    
037    
038    /**
039     * This class is the service implementation for the XmlObjectSerializer structure. This is the default implementation that gets
040     * delivered with Kuali. It utilizes the XStream open source libraries and framework.
041     * 
042     * 
043     */
044    public class XmlObjectSerializerServiceImpl implements XmlObjectSerializerService {
045            private static final Log LOG = LogFactory.getLog(XmlObjectSerializerServiceImpl.class);
046            
047            private PersistenceService persistenceService;
048            
049            private XStream xstream;
050            
051            public XmlObjectSerializerServiceImpl() {
052                    xstream = new XStream(new ProxyAwareJavaReflectionProvider());
053    
054            // See http://xstream.codehaus.org/faq.html#Serialization_CGLIB
055            // To use a newer version of XStream we may need to do something like this:
056    //        xstream = new XStream() {
057    //
058    //            @Override
059    //            public ReflectionProvider getReflectionProvider() {
060    //                return new ProxyAwareJavaReflectionProvider();
061    //            }
062    //
063    //            protected MapperWrapper wrapMapper(MapperWrapper next) {
064    //                return new CGLIBMapper(next);
065    //            }
066    //        };
067    //        xstream.registerConverter(new CGLIBEnhancedConverter(xstream.getMapper(), xstream.getReflectionProvider()));
068    
069                    xstream.registerConverter(new ProxyConverter(xstream.getMapper(), xstream.getReflectionProvider() ));
070                    xstream.addDefaultImplementation(ArrayList.class, ListProxyDefaultImpl.class);
071            }
072            
073        /**
074         * @see org.kuali.rice.krad.service.XmlObjectSerializer#toXml(java.lang.Object)
075         */
076        public String toXml(Object object) {
077            if ( LOG.isDebugEnabled() ) {
078                    LOG.debug( "toXml(" + object + ") : \n" + xstream.toXML(object) );
079            }
080            return xstream.toXML(object);
081        }
082    
083        /**
084         * @see org.kuali.rice.krad.service.XmlObjectSerializer#fromXml(java.lang.String)
085         */
086        public Object fromXml(String xml) {
087            if ( LOG.isDebugEnabled() ) {
088                    LOG.debug( "fromXml() : \n" + xml );
089            }
090            if ( xml != null ) {
091                    xml = xml.replaceAll( "--EnhancerByCGLIB--[0-9a-f]{0,8}", "" );
092            }
093            return xstream.fromXML(xml);
094        }
095    
096        /**
097         * This custom converter only handles proxies for BusinessObjects.  List-type proxies are handled by configuring XStream to treat
098         * ListProxyDefaultImpl as ArrayLists (see constructor for this service). 
099         */
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    }