001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.camel.dataformat.xstream;
018    
019    import java.io.InputStream;
020    import java.io.OutputStream;
021    import java.lang.reflect.Constructor;
022    import java.lang.reflect.Method;
023    import java.util.List;
024    import java.util.Map;
025    import java.util.Map.Entry;
026    
027    import javax.xml.stream.XMLStreamException;
028    
029    import com.thoughtworks.xstream.XStream;
030    import com.thoughtworks.xstream.converters.Converter;
031    import com.thoughtworks.xstream.io.HierarchicalStreamDriver;
032    import com.thoughtworks.xstream.io.HierarchicalStreamReader;
033    import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
034    
035    import org.apache.camel.Exchange;
036    import org.apache.camel.converter.jaxp.StaxConverter;
037    import org.apache.camel.spi.ClassResolver;
038    import org.apache.camel.spi.DataFormat;
039    import org.apache.camel.util.ObjectHelper;
040    
041    /**
042     * An abstract class which implement <a href="http://camel.apache.org/data-format.html">data format</a>
043     * ({@link DataFormat}) interface which leverage the XStream library for XML or JSON's marshaling and unmarshaling
044     *
045     * @version 
046     */
047    public abstract class AbstractXStreamWrapper implements DataFormat {
048        
049        private XStream xstream;
050        private HierarchicalStreamDriver xstreamDriver;
051        private StaxConverter staxConverter;
052        private List<String> converters;
053        private Map<String, String> aliases;
054        private Map<String, String[]> omitFields;
055        private Map<String, String[]> implicitCollections;
056    
057        public AbstractXStreamWrapper() {
058        }
059        
060        public AbstractXStreamWrapper(XStream xstream) {
061            this.xstream = xstream;
062        }
063        
064        public XStream getXStream(ClassResolver resolver) {
065            if (xstream == null) {
066                xstream = createXStream(resolver);
067            }
068            return xstream;
069        }
070    
071        public void setXStream(XStream xstream) {
072            this.xstream = xstream;
073        }
074    
075        protected XStream createXStream(ClassResolver resolver) {
076            if (xstreamDriver != null) {
077                xstream = new XStream(xstreamDriver);
078            } else {
079                xstream = new XStream();
080            }
081    
082            try {
083                if (this.implicitCollections != null) {
084                    for (Entry<String, String[]> entry : this.implicitCollections.entrySet()) {
085                        for (String name : entry.getValue()) {
086                            xstream.addImplicitCollection(resolver.resolveMandatoryClass(entry.getKey()), name);
087                        }
088                    }
089                }
090    
091                if (this.aliases != null) {
092                    for (Entry<String, String> entry : this.aliases.entrySet()) {
093                        xstream.alias(entry.getKey(), resolver.resolveMandatoryClass(entry.getValue()));
094                    }
095                }
096    
097                if (this.omitFields != null) {
098                    for (Entry<String, String[]> entry : this.omitFields.entrySet()) {
099                        for (String name : entry.getValue()) {
100                            xstream.omitField(resolver.resolveMandatoryClass(entry.getKey()), name);
101                        }
102                    }
103                }
104    
105                if (this.converters != null) {
106                    for (String name : this.converters) {
107                        Class<Converter> converterClass = resolver.resolveMandatoryClass(name, Converter.class);
108                        Converter converter;
109    
110                        Constructor con = null;
111                        try {
112                            con = converterClass.getDeclaredConstructor(new Class[] {XStream.class});
113                        } catch (Exception e) {
114                             //swallow as we null check in a moment.
115                        }
116                        if (con != null) {
117                            converter = (Converter) con.newInstance(xstream);
118                        } else {
119                            converter = converterClass.newInstance();
120                            try { 
121                                Method method = converterClass.getMethod("setXStream", new Class[] {XStream.class});
122                                if (method != null) {
123                                    ObjectHelper.invokeMethod(method, converter, xstream);
124                                }
125                            } catch (Throwable e) {
126                                // swallow, as it just means the user never add an XStream setter, which is optional
127                            }
128                        }
129    
130                        xstream.registerConverter(converter);
131                    }
132                }
133            } catch (Exception e) {
134                throw new RuntimeException("Unable to build XStream instance", e);
135            }
136    
137            return xstream;
138        }    
139    
140        public StaxConverter getStaxConverter() {
141            if (staxConverter == null) {
142                staxConverter = new StaxConverter();
143            }
144            return staxConverter;
145        }
146    
147        public void setStaxConverter(StaxConverter staxConverter) {
148            this.staxConverter = staxConverter;
149        }
150    
151        public List<String> getConverters() {
152            return converters;
153        }
154    
155        public void setConverters(List<String> converters) {
156            this.converters = converters;
157        }
158    
159        public Map<String, String> getAliases() {
160            return aliases;
161        }
162    
163        public void setAliases(Map<String, String> aliases) {
164            this.aliases = aliases;
165        }
166    
167        public Map<String, String[]> getImplicitCollections() {
168            return implicitCollections;
169        }
170    
171        public void setImplicitCollections(Map<String, String[]> implicitCollections) {
172            this.implicitCollections = implicitCollections;
173        }
174    
175        public Map<String, String[]> getOmitFields() {
176            return omitFields;
177        }
178    
179        public void setOmitFields(Map<String, String[]> omitFields) {
180            this.omitFields = omitFields;
181        }
182    
183        public HierarchicalStreamDriver getXstreamDriver() {
184            return xstreamDriver;
185        }
186    
187        public void setXstreamDriver(HierarchicalStreamDriver xstreamDriver) {
188            this.xstreamDriver = xstreamDriver;
189        }
190    
191        public XStream getXstream() {
192            return xstream;
193        }
194    
195        public void setXstream(XStream xstream) {
196            this.xstream = xstream;
197        }
198    
199        public void marshal(Exchange exchange, Object body, OutputStream stream) throws Exception {
200            HierarchicalStreamWriter writer = createHierarchicalStreamWriter(exchange, body, stream);
201            try {
202                getXStream(exchange.getContext().getClassResolver()).marshal(body, writer);
203            } finally {
204                writer.close();
205            }
206        }
207    
208        public Object unmarshal(Exchange exchange, InputStream stream) throws Exception {
209            HierarchicalStreamReader reader = createHierarchicalStreamReader(exchange, stream);
210            try {
211                return getXStream(exchange.getContext().getClassResolver()).unmarshal(reader);
212            } finally {
213                reader.close();
214            }
215        }
216    
217        protected abstract HierarchicalStreamWriter createHierarchicalStreamWriter(
218                Exchange exchange, Object body, OutputStream stream) throws XMLStreamException;
219    
220        protected abstract HierarchicalStreamReader createHierarchicalStreamReader(
221                Exchange exchange, InputStream stream) throws XMLStreamException;
222    }