リスト9 DocumentTransformer.java

 1 package com.netpotlet.test;
 2
 3 import java.io.File;
 4 import java.io.FileNotFoundException;
 5 import java.io.FileOutputStream;
 6 import java.io.OutputStreamWriter;
 7 import java.io.StringReader;
 8 import java.io.UnsupportedEncodingException;
 9 import java.io.IOException;
10 import java.net.URL;
11
12 import javax.xml.parsers.FactoryConfigurationError;
13 import javax.xml.parsers.ParserConfigurationException;
14 import javax.xml.transform.OutputKeys;
15 import javax.xml.transform.Result;
16 import javax.xml.transform.Source;
17 import javax.xml.transform.Transformer;
18 import javax.xml.transform.TransformerFactory;
19 import javax.xml.transform.TransformerConfigurationException;
20 import javax.xml.transform.TransformerException;
21 import javax.xml.transform.stream.StreamResult;
22 import javax.xml.transform.stream.StreamSource;
23
24 class DocumentTransformer {
25     private String encoding;
26     private TransformerFactory factory;
27     private String xsltfile;
28     private Source source = null;
29     private Result result = null;
30
31     DocumentTransformer(String encoding, String xsltfile)
32         throws IOException {
33         this.encoding = encoding;
34         factory = TransformerFactory.newInstance();
35         this.xsltfile = xsltfile;
36     }
37
38     void transformDocument()
39         throws
40             IOException,
41             FactoryConfigurationError,
42             ParserConfigurationException,
43             TransformerConfigurationException,
44             TransformerException {
45         URL url = new File(xsltfile).toURL();
46         Source xsltSource = new StreamSource(url.toExternalForm());
47         Transformer transformer = factory.newTransformer(xsltSource);
48         if ((source != null) && (result != null)) {
49             transform(transformer);
50         }
51     }
52
53     void setSource(String document) {
54         StringReader reader = new StringReader(document);
55         source = new StreamSource(reader);
56     }
57     
58     void setResult(String filename)
59         throws UnsupportedEncodingException,
60                FileNotFoundException {
61         OutputStreamWriter writer =
62             new OutputStreamWriter(new FileOutputStream(filename),
63                                    encoding);
64         result = new StreamResult(writer);
65     }
66
67     private void transform(Transformer transformer)
68         throws TransformerException {
69         transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
70         transformer.setOutputProperty(OutputKeys.INDENT, "yes");
71         transformer.transform(source, result);
72     }
73 }