1
|
package eu.etaxonomy.cdm.jaxb;
|
2
|
|
3
|
import java.io.File;
|
4
|
import java.io.FileOutputStream;
|
5
|
import java.io.IOException;
|
6
|
import java.io.Writer;
|
7
|
|
8
|
import javax.xml.XMLConstants;
|
9
|
import javax.xml.bind.JAXBContext;
|
10
|
import javax.xml.bind.JAXBException;
|
11
|
import javax.xml.bind.Marshaller;
|
12
|
import javax.xml.transform.Source;
|
13
|
import javax.xml.transform.stream.StreamSource;
|
14
|
import javax.xml.validation.Schema;
|
15
|
import javax.xml.validation.SchemaFactory;
|
16
|
|
17
|
import org.apache.commons.logging.Log;
|
18
|
import org.apache.commons.logging.LogFactory;
|
19
|
import org.xml.sax.SAXException;
|
20
|
|
21
|
import eu.etaxonomy.cdm.model.DataSet;
|
22
|
import eu.etaxonomy.cdm.strategy.cache.reference.BookDefaultCacheStrategy;
|
23
|
|
24
|
/*
|
25
|
Initializes a JaxbContext with one class (eu.etaxonomy.cdm.model.DataSet)
|
26
|
Binds it to XML schemas found in /src/main/resources/schema/cdm (cdm.xsd, common.xsd, name.xsd).
|
27
|
There is a bit of magic with a resource resolver in eu.etaxonomy.cdm.jaxb
|
28
|
which allows to package the schemas into a jar file.
|
29
|
*/
|
30
|
public class CdmDocumentBuilder {
|
31
|
private static Log log = LogFactory.getLog(CdmDocumentBuilder.class);
|
32
|
|
33
|
private JAXBContext jaxbContext;
|
34
|
private Marshaller marshaller;
|
35
|
|
36
|
public static String CDM_NAMESPACE = "eu.etaxonomy.cdm.model";
|
37
|
public static String[] CDM_SCHEMA_FILES = { "/schema/cdm/common.xsd",
|
38
|
"/schema/cdm/name.xsd",
|
39
|
"/schema/cdm/cdm.xsd" };
|
40
|
|
41
|
public CdmDocumentBuilder() throws SAXException, JAXBException, IOException {
|
42
|
// SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
|
43
|
// schemaFactory.setResourceResolver(new CdmResourceResolver());
|
44
|
// Source[] sources = new Source[CdmDocumentBuilder.CDM_SCHEMA_FILES.length];
|
45
|
//
|
46
|
// for(int i = 0; i < CdmDocumentBuilder.CDM_SCHEMA_FILES.length; i++) {
|
47
|
// String schemaName = CdmDocumentBuilder.CDM_SCHEMA_FILES[i];
|
48
|
// sources[i] = new StreamSource(this.getClass().getResourceAsStream(schemaName));
|
49
|
// }
|
50
|
// Schema cdmSchema = schemaFactory.newSchema(sources);
|
51
|
|
52
|
jaxbContext = JAXBContext.newInstance(new Class[] {DataSet.class, BookDefaultCacheStrategy.class});
|
53
|
|
54
|
marshaller = jaxbContext.createMarshaller();
|
55
|
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
|
56
|
|
57
|
// validate with explicit schema
|
58
|
//marshaller.setSchema(cdmSchema);
|
59
|
}
|
60
|
|
61
|
public void write(DataSet dataSet, Writer writer) throws JAXBException {
|
62
|
marshaller.marshal(dataSet, writer);
|
63
|
}
|
64
|
|
65
|
// public void writeFile(DataSet dataSet, File file) throws JAXBException {
|
66
|
// marshaller.marshal(dataSet, file);
|
67
|
// }
|
68
|
|
69
|
}
|
70
|
|
71
|
|