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.converter.jaxb;
018    
019    import java.io.IOException;
020    import java.io.InputStream;
021    import java.io.InputStreamReader;
022    import java.io.OutputStream;
023    import java.io.UnsupportedEncodingException;
024    import javax.xml.bind.JAXBContext;
025    import javax.xml.bind.JAXBElement;
026    import javax.xml.bind.JAXBException;
027    import javax.xml.bind.Marshaller;
028    import javax.xml.bind.Unmarshaller;
029    import javax.xml.namespace.QName;
030    import javax.xml.stream.FactoryConfigurationError;
031    import javax.xml.stream.XMLOutputFactory;
032    import javax.xml.stream.XMLStreamException;
033    import javax.xml.stream.XMLStreamWriter;
034    import javax.xml.transform.Source;
035    import javax.xml.transform.stream.StreamSource;
036    
037    import org.apache.camel.CamelContext;
038    import org.apache.camel.CamelContextAware;
039    import org.apache.camel.Exchange;
040    import org.apache.camel.converter.IOConverter;
041    import org.apache.camel.impl.ServiceSupport;
042    import org.apache.camel.spi.DataFormat;
043    import org.apache.camel.util.IOHelper;
044    import org.apache.camel.util.ObjectHelper;
045    import org.slf4j.Logger;
046    import org.slf4j.LoggerFactory;
047    
048    /**
049     * A <a href="http://camel.apache.org/data-format.html">data format</a> ({@link DataFormat})
050     * using JAXB2 to marshal to and from XML
051     *
052     * @version 
053     */
054    public class JaxbDataFormat extends ServiceSupport implements DataFormat, CamelContextAware {
055    
056        private static final transient Logger LOG = LoggerFactory.getLogger(JaxbDataFormat.class);
057        private CamelContext camelContext;
058        private JAXBContext context;
059        private String contextPath;
060        private boolean prettyPrint = true;
061        private boolean ignoreJAXBElement = true;
062        private boolean filterNonXmlChars;
063        private String encoding;
064        // partial support
065        private QName partNamespace;
066        private String partClass;
067        private Class partialClass;
068    
069        public JaxbDataFormat() {
070        }
071    
072        public JaxbDataFormat(JAXBContext context) {
073            this.context = context;
074        }
075    
076        public JaxbDataFormat(String contextPath) {
077            this.contextPath = contextPath;
078        }
079    
080        public void marshal(Exchange exchange, Object graph, OutputStream stream) throws IOException {
081            try {            
082                // must create a new instance of marshaller as its not thread safe
083                Marshaller marshaller = getContext().createMarshaller();
084                if (isPrettyPrint()) {
085                    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
086                } 
087                // exchange take precedence over encoding option
088                String charset = exchange.getProperty(Exchange.CHARSET_NAME, String.class);
089                if (charset == null) {
090                    charset = encoding;
091                }
092                if (charset != null) {
093                    marshaller.setProperty(Marshaller.JAXB_ENCODING, charset);
094                }
095    
096                marshal(exchange, graph, stream, marshaller);
097    
098            } catch (JAXBException e) {
099                throw new IOException(e);
100            } catch (XMLStreamException e) {
101                throw new IOException(e);
102            }
103        }
104    
105        @SuppressWarnings("unchecked")
106        void marshal(Exchange exchange, Object graph, OutputStream stream, Marshaller marshaller)
107            throws XMLStreamException, JAXBException {
108    
109            Object e = graph;
110            if (partialClass != null && getPartNamespace() != null) {
111                e = new JAXBElement(getPartNamespace(), partialClass, graph);
112            }
113    
114            if (needFiltering(exchange)) {
115                marshaller.marshal(e, createFilteringWriter(stream));
116            } else {
117                marshaller.marshal(e, stream);
118            }
119        }
120    
121        private FilteringXmlStreamWriter createFilteringWriter(OutputStream stream)
122            throws XMLStreamException, FactoryConfigurationError {
123            XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(stream);
124            FilteringXmlStreamWriter filteringWriter = new FilteringXmlStreamWriter(writer);
125            return filteringWriter;
126        }
127    
128        @SuppressWarnings("unchecked")
129        public Object unmarshal(Exchange exchange, InputStream stream) throws IOException {
130            try {
131                // must create a new instance of unmarshaller as its not thread safe
132                Object answer;
133                Unmarshaller unmarshaller = getContext().createUnmarshaller();
134    
135                if (partialClass != null) {
136                    // partial unmarshalling
137                    Source source;
138                    if (needFiltering(exchange)) {
139                        source = new StreamSource(createNonXmlFilterReader(exchange, stream));
140                    } else {
141                        source = new StreamSource(stream);
142                    }
143                    answer = unmarshaller.unmarshal(source, partialClass);
144                } else {
145                    if (needFiltering(exchange)) {
146                        NonXmlFilterReader reader = createNonXmlFilterReader(exchange, stream);
147                        answer = unmarshaller.unmarshal(reader);
148                    } else  {
149                        answer = unmarshaller.unmarshal(stream);
150                    }
151                }
152    
153                if (answer instanceof JAXBElement && isIgnoreJAXBElement()) {
154                    answer = ((JAXBElement<?>)answer).getValue();
155                }
156                return answer;
157            } catch (JAXBException e) {
158                throw new IOException(e);
159            }
160        }
161    
162        private NonXmlFilterReader createNonXmlFilterReader(Exchange exchange, InputStream stream) throws UnsupportedEncodingException {
163            return new NonXmlFilterReader(new InputStreamReader(stream, IOConverter.getCharsetName(exchange)));
164        }
165    
166        protected boolean needFiltering(Exchange exchange) {
167            // exchange property takes precedence over data format property
168            return exchange == null ? filterNonXmlChars : exchange.getProperty(Exchange.FILTER_NON_XML_CHARS, filterNonXmlChars, Boolean.class);
169        }
170    
171        // Properties
172        // -------------------------------------------------------------------------
173        public boolean isIgnoreJAXBElement() {        
174            return ignoreJAXBElement;
175        }
176        
177        public void setIgnoreJAXBElement(boolean flag) {
178            ignoreJAXBElement = flag;
179        }
180        
181        public JAXBContext getContext() {
182            return context;
183        }
184    
185        public void setContext(JAXBContext context) {
186            this.context = context;
187        }
188    
189        public String getContextPath() {
190            return contextPath;
191        }
192    
193        public void setContextPath(String contextPath) {
194            this.contextPath = contextPath;
195        }
196    
197        public boolean isPrettyPrint() {
198            return prettyPrint;
199        }
200    
201        public void setPrettyPrint(boolean prettyPrint) {
202            this.prettyPrint = prettyPrint;
203        }
204    
205        public boolean isFilterNonXmlChars() {
206            return filterNonXmlChars;
207        }
208    
209        public void setFilterNonXmlChars(boolean filterNonXmlChars) {
210            this.filterNonXmlChars = filterNonXmlChars;
211        }
212    
213        public String getEncoding() {
214            return encoding;
215        }
216    
217        public void setEncoding(String encoding) {
218            this.encoding = encoding;
219        }
220    
221        public QName getPartNamespace() {
222            return partNamespace;
223        }
224    
225        public void setPartNamespace(QName partNamespace) {
226            this.partNamespace = partNamespace;
227        }
228    
229        public String getPartClass() {
230            return partClass;
231        }
232    
233        public void setPartClass(String partClass) {
234            this.partClass = partClass;
235        }
236    
237        public CamelContext getCamelContext() {
238            return camelContext;
239        }
240    
241        public void setCamelContext(CamelContext camelContext) {
242            this.camelContext = camelContext;
243        }
244    
245        @Override
246        protected void doStart() throws Exception {
247            ObjectHelper.notNull(camelContext, "CamelContext");
248    
249            if (context == null) {
250                // if context not injected, create one and resolve partial class up front so they are ready to be used
251                context = createContext();
252            }
253            if (partClass != null) {
254                partialClass = camelContext.getClassResolver().resolveMandatoryClass(partClass);
255            }
256        }
257    
258        @Override
259        protected void doStop() throws Exception {
260        }
261    
262        /**
263         * Strategy to create JAXB context
264         */
265        protected JAXBContext createContext() throws JAXBException {
266            if (contextPath != null) {
267                // prefer to use application class loader which is most likely to be able to
268                // load the the class which has been JAXB annotated
269                ClassLoader cl = camelContext.getApplicationContextClassLoader();
270                if (cl != null) {
271                    LOG.info("Creating JAXBContext with contextPath: " + contextPath + " and ApplicationContextClassLoader: " + cl);
272                    return JAXBContext.newInstance(contextPath, cl);
273                } else {
274                    LOG.info("Creating JAXBContext with contextPath: " + contextPath);
275                    return JAXBContext.newInstance(contextPath);
276                }
277            } else {
278                LOG.info("Creating JAXBContext");
279                return JAXBContext.newInstance();
280            }
281        }
282    
283    }