cleanup
[cdmlib.git] / cdmlib-print / src / main / java / eu / etaxonomy / cdm / print / Transformator.java
1 /**
2 * Copyright (C) 2007 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 package eu.etaxonomy.cdm.print;
10
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.net.URL;
14
15 import javax.xml.transform.Templates;
16 import javax.xml.transform.Transformer;
17 import javax.xml.transform.TransformerException;
18 import javax.xml.transform.TransformerFactory;
19 import javax.xml.transform.stream.StreamSource;
20
21 import org.apache.logging.log4j.LogManager;
22 import org.apache.logging.log4j.Logger;
23 import org.jdom.Document;
24 import org.jdom.transform.JDOMResult;
25 import org.jdom.transform.JDOMSource;
26 import org.jdom.transform.XSLTransformException;
27
28 /**
29 * Perform XSL transformations.
30 *
31 * Note: This class provides access to the JAXP XSL transformer currently active.
32 *
33 * @author n.hoffmann
34 * @since Apr 20, 2010
35 */
36 public class Transformator {
37
38 private static final Logger logger = LogManager.getLogger();
39
40 private Transformer transformer;
41
42 public Transformator(InputStream stylesheet) throws XSLTransformException{
43 if(stylesheet == null){
44 throw new IllegalArgumentException("Stylsheet may not be null");
45 }
46
47 try {
48 TransformerFactory transformerFactory = TransformerFactory.newInstance();
49 Templates templates = transformerFactory.newTemplates(new StreamSource(stylesheet));
50 transformer = templates.newTransformer();
51 }
52 catch (TransformerException e) {
53 throw new XSLTransformException("Could not construct XSLTransformer", e);
54
55 }
56 }
57
58
59 public Transformator(URL stylesheet) throws XSLTransformException, IOException {
60 this(stylesheet.openStream());
61 }
62
63 /**
64 * Transforms the given document to an output document.
65 *
66 * @param inputDoc input document
67 * @param resolver entity resolver for the input document
68 * @return transformed output document
69 * @throws XSLTransformException if there's a problem in the transformation
70 */
71 public Document transform(org.jdom.Document inputDocument) throws XSLTransformException {
72 JDOMSource source = new JDOMSource(inputDocument);
73 JDOMResult result = new JDOMResult();
74 try {
75 logger.trace("Transforming input document: " + inputDocument);
76
77 transformer.transform(source, result);
78 Document resultDocument = result.getDocument();
79
80 resultDocument.getContent();
81 return resultDocument;
82 }
83 catch (TransformerException e) {
84 logger.error(e);
85 throw new XSLTransformException("Could not perform transformation", e);
86 }
87 }
88 }