001    
002    /*
003     * Copyright (C) 2012 Archie L. Cobbs. All rights reserved.
004     *
005     * $Id: SpringDelegate.java 293 2012-02-19 22:07:10Z archie.cobbs $
006     */
007    
008    package org.dellroad.stuff.pobj;
009    
010    import java.io.IOException;
011    
012    import javax.xml.transform.Result;
013    import javax.xml.transform.Source;
014    
015    import org.springframework.beans.factory.InitializingBean;
016    import org.springframework.oxm.Marshaller;
017    import org.springframework.oxm.Unmarshaller;
018    
019    /**
020     * {@link PersistentObjectDelegate} that uses Spring's {@link Marshaller} and {@link Unmarshaller} interfaces
021     * for XML conversion.
022     *
023     * @param <T> type of the root persistent object
024     */
025    public class SpringDelegate<T> extends AbstractDelegate<T> implements InitializingBean {
026    
027        private Marshaller marshaller;
028        private Unmarshaller unmarshaller;
029    
030        /**
031         * Set the {@link Marshaller} used to convert instances to XML. Required property.
032         */
033        public void setMarshaller(Marshaller marshaller) {
034            this.marshaller = marshaller;
035        }
036    
037        /**
038         * Set the {@link Marshaller} used to convert instances to XML. Required property.
039         */
040        public void setUnmarshaller(Unmarshaller unmarshaller) {
041            this.unmarshaller = unmarshaller;
042        }
043    
044        @Override
045        public void afterPropertiesSet() throws Exception {
046            if (this.marshaller == null)
047                throw new Exception("no marshaller configured");
048            if (this.unmarshaller == null)
049                throw new Exception("no unmarshaller configured");
050        }
051    
052        @Override
053        public void serialize(T obj, Result result) throws IOException {
054            try {
055                this.marshaller.marshal(obj, result);
056            } catch (IOException e) {
057                throw e;
058            } catch (Exception e) {
059                throw new PersistentObjectException(e);
060            }
061        }
062    
063        @Override
064        @SuppressWarnings("unchecked")
065        public T deserialize(Source source) throws IOException {
066            try {
067                return (T)this.unmarshaller.unmarshal(source);
068            } catch (IOException e) {
069                throw e;
070            } catch (Exception e) {
071                throw new PersistentObjectException(e);
072            }
073        }
074    }
075