Changes related to refactoring of Auditing info (#630)
[cdmlib.git] / cdmlib-io / src / main / java / eu / etaxonomy / cdm / io / jaxb / CdmDocumentBuilder.java
1 /**
2 * Copyright (C) 2008 EDIT
3 * European Distributed Institute of Taxonomy
4 * http://www.e-taxonomy.eu
5 *
6 * The contents of this file are subject to the Mozilla Public License Version 1.1
7 * See LICENSE.TXT at the top of this package for the full license terms.
8 */
9
10 package eu.etaxonomy.cdm.io.jaxb;
11
12 import java.io.File;
13 import java.io.FileInputStream;
14 import java.io.FileNotFoundException;
15 import java.io.IOException;
16 import java.io.InputStreamReader;
17 import java.io.Reader;
18 import java.io.UnsupportedEncodingException;
19 import java.io.Writer;
20
21 import javax.xml.XMLConstants;
22 import javax.xml.bind.JAXBContext;
23 import javax.xml.bind.JAXBException;
24 import javax.xml.bind.Marshaller;
25 import javax.xml.bind.Unmarshaller;
26 import javax.xml.bind.UnmarshallerHandler;
27 import javax.xml.parsers.ParserConfigurationException;
28 import javax.xml.parsers.SAXParser;
29 import javax.xml.parsers.SAXParserFactory;
30 import javax.xml.transform.Source;
31 import javax.xml.transform.sax.SAXSource;
32 import javax.xml.transform.stream.StreamSource;
33 import javax.xml.validation.Schema;
34 import javax.xml.validation.SchemaFactory;
35
36 import org.apache.log4j.Logger;
37 import org.apache.xml.resolver.tools.CatalogResolver;
38 import org.xml.sax.InputSource;
39 import org.xml.sax.SAXException;
40 import org.xml.sax.XMLReader;
41
42 import eu.etaxonomy.cdm.jaxb.CdmNamespacePrefixMapper;
43 import eu.etaxonomy.cdm.jaxb.FormattedText;
44 import eu.etaxonomy.cdm.jaxb.MultilanguageTextElement;
45 import eu.etaxonomy.cdm.model.agent.Person;
46
47 /**
48 * Initializes a JaxbContext with one class (eu.etaxonomy.cdm.model.DataSet).
49 *
50 * @author a.babadshanjan
51 */
52 //Binds it to XML schemas found in /src/main/resources/schema/cdm (cdm.xsd, common.xsd, name.xsd).
53 //There is a bit of magic with a resource resolver in eu.etaxonomy.cdm.io.jaxb
54 //which allows to package the schemas into a jar file.
55 public class CdmDocumentBuilder {
56
57 private static final Logger logger = Logger.getLogger(CdmDocumentBuilder.class);
58
59 private JAXBContext jaxbContext;
60 private boolean formattedOutput = Boolean.TRUE;
61 private String encoding = "UTF-8";
62 private Schema schema;
63 private Marshaller marshaller;
64 private Unmarshaller unmarshaller;
65 private XMLReader xmlReader;
66
67 public static String CDM_NAMESPACE = "eu.etaxonomy.cdm.model";
68 public static String[] CDM_SCHEMA_FILES = { "/schema/cdm/agent.xsd",
69 "/schema/cdm/cdm.xsd",
70 "/schema/cdm/common.xsd",
71 "/schema/cdm/description.xsd",
72 "/schema/cdm/location.xsd",
73 "/schema/cdm/media.xsd",
74 "/schema/cdm/molecular.xsd",
75 "/schema/cdm/name.xsd",
76 "/schema/cdm/occurrence.xsd",
77 "/schema/cdm/reference.xsd",
78 "/schema/cdm/taxon.xsd"};
79 public static Class[] CONTEXT_CLASSES = {DataSet.class,FormattedText.class,MultilanguageTextElement.class};
80
81 protected String[] getSchemaFiles() {
82 return CDM_SCHEMA_FILES;
83 }
84
85 protected Class[] getContextClasses() {
86 return CONTEXT_CLASSES;
87 }
88
89 protected void constructSchema() throws IOException, SAXException {
90 SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
91 schemaFactory.setResourceResolver(new CdmResourceResolver());
92 String[] schemaFiles = getSchemaFiles();
93
94 Source[] sources = new Source[schemaFiles.length];
95
96 for(int i = 0; i < schemaFiles.length; i++) {
97 String schemaName = schemaFiles[i];
98 sources[i] = new StreamSource(this.getClass().getResourceAsStream(schemaName));
99 }
100
101 schema = schemaFactory.newSchema(sources);
102 }
103
104 protected void contstructUnmarshaller() throws ParserConfigurationException, SAXException, JAXBException {
105 unmarshaller = jaxbContext.createUnmarshaller();
106 unmarshaller.setSchema(schema);
107
108 SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
109
110 saxParserFactory.setNamespaceAware(true);
111 saxParserFactory.setXIncludeAware(true);
112 saxParserFactory.setValidating(true);
113
114 SAXParser saxParser = saxParserFactory.newSAXParser();
115 saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
116 "http://www.w3.org/2001/XMLSchema");
117 xmlReader = saxParser.getXMLReader();
118 xmlReader.setEntityResolver(new CatalogResolver());
119 xmlReader.setErrorHandler(new DefaultErrorHandler());
120 unmarshaller.setEventHandler(new WarningTolerantValidationEventHandler());
121 }
122
123 public CdmDocumentBuilder() throws SAXException, JAXBException, IOException, ParserConfigurationException {
124 constructSchema();
125
126 jaxbContext = JAXBContext.newInstance(getContextClasses());
127
128 contstructUnmarshaller();
129 constructMarshaller();
130 }
131
132 protected void constructMarshaller() throws JAXBException {
133 marshaller = jaxbContext.createMarshaller();
134 marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new CdmNamespacePrefixMapper() );
135 marshaller.setSchema(schema);
136
137 // For test purposes insert newlines to make the XML output readable
138 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formattedOutput);
139 marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION,"http://etaxonomy.eu/cdm/model/1.0 schema/cdm/cdm.xsd");
140 marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
141
142 CdmMarshallerListener marshallerListener = new CdmMarshallerListener();
143 marshaller.setListener(marshallerListener);
144 marshaller.setEventHandler(new WarningTolerantValidationEventHandler());
145 }
146
147 public CdmDocumentBuilder(boolean formattedOutput, String encoding) throws SAXException, JAXBException, IOException, ParserConfigurationException {
148 this.formattedOutput = formattedOutput;
149 this.encoding = encoding;
150 constructSchema();
151
152 jaxbContext = JAXBContext.newInstance(getContextClasses());
153
154 contstructUnmarshaller();
155 constructMarshaller();
156 }
157
158 public void marshal(DataSet dataSet, Writer writer) throws JAXBException {
159
160 logger.info("Start marshalling");
161 marshaller.marshal(dataSet, writer);
162
163 }
164
165 public <T> T unmarshal(Class<T> clazz,Reader reader) throws JAXBException {
166 InputSource input = new InputSource(reader);
167 SAXSource saxSource = new SAXSource( xmlReader, input);
168 logger.info("Start unmarshalling");
169 T t = (T) unmarshaller.unmarshal(saxSource);
170 return t;
171 }
172
173 public <T> T unmarshal(Class<T> clazz,Reader reader, String systemId) throws JAXBException {
174 InputSource input = new InputSource(reader);
175 input.setSystemId(systemId);
176 SAXSource saxSource = new SAXSource( xmlReader, input);
177 logger.info("Start unmarshalling");
178 T t = (T) unmarshaller.unmarshal(saxSource);
179 return t;
180 }
181
182 public <T> T unmarshal(Class<T> clazz, File file) throws JAXBException, UnsupportedEncodingException, FileNotFoundException {
183
184 InputSource input = new InputSource(new InputStreamReader(new FileInputStream(file),encoding));
185 input.setSystemId(file.toURI().toString());
186 SAXSource saxSource = new SAXSource( xmlReader, input);
187 logger.info("Start unmarshalling");
188 T t = (T) unmarshaller.unmarshal(saxSource);
189 return t;
190
191 }
192
193 // can only be used with JAXB 2.1
194 // public void writeFile(DataSet dataSet, File file) throws JAXBException {
195 // marshaller.marshal(dataSet, file);
196 // }
197
198 }
199
200