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 javax.xml.bind.JAXBContext;
020 import javax.xml.bind.JAXBException;
021 import javax.xml.bind.Marshaller;
022 import javax.xml.bind.annotation.XmlRootElement;
023 import javax.xml.bind.util.JAXBSource;
024 import javax.xml.parsers.ParserConfigurationException;
025
026 import org.w3c.dom.Document;
027
028 import org.apache.camel.converter.HasAnnotation;
029 import org.apache.camel.converter.jaxp.XmlConverter;
030
031 /**
032 * @version $Revision: 563665 $
033 */
034 public class JaxbConverter {
035 private XmlConverter jaxbConverter;
036
037 public XmlConverter getJaxbConverter() {
038 if (jaxbConverter == null) {
039 jaxbConverter = new XmlConverter();
040 }
041 return jaxbConverter;
042 }
043
044 public void setJaxbConverter(XmlConverter jaxbConverter) {
045 this.jaxbConverter = jaxbConverter;
046 }
047
048 public static JAXBSource toSource(@HasAnnotation(XmlRootElement.class)Object value) throws JAXBException {
049 JAXBContext context = createJaxbContext(value);
050 return new JAXBSource(context, value);
051 }
052
053 public Document toDocument(@HasAnnotation(XmlRootElement.class)Object value) throws JAXBException, ParserConfigurationException {
054 JAXBContext context = createJaxbContext(value);
055 Marshaller marshaller = context.createMarshaller();
056
057 Document doc = getJaxbConverter().createDocument();
058 marshaller.marshal(value, doc);
059 return doc;
060 }
061
062 protected static JAXBContext createJaxbContext(Object value) throws JAXBException {
063 if (value == null) {
064 throw new IllegalArgumentException("Cannot convert from null value to JAXBSource");
065 }
066 JAXBContext context = JAXBContext.newInstance(value.getClass());
067 return context;
068 }
069
070 // public void write(OutputStream out, Object value) throws JAXBException {
071 // JAXBContext context = JAXBContext.newInstance(value.getClass());
072 // Marshaller marshaller = context.createMarshaller();
073 // marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
074 // marshaller.marshal(value, out);
075 // }
076
077 }