01: /*
02: * XsltTransformer.java
03: *
04: * This file is part of SQL Workbench/J, http://www.sql-workbench.net
05: *
06: * Copyright 2002-2008, Thomas Kellerer
07: * No part of this code maybe reused without the permission of the author
08: *
09: * To contact the author please send an email to: support@sql-workbench.net
10: *
11: */
12: package workbench.util;
13:
14: import java.io.BufferedInputStream;
15: import java.io.BufferedOutputStream;
16: import java.io.File;
17: import java.io.FileInputStream;
18: import java.io.FileNotFoundException;
19: import java.io.FileOutputStream;
20: import java.io.IOException;
21: import java.io.InputStream;
22: import java.io.OutputStream;
23:
24: import javax.xml.transform.Source;
25: import javax.xml.transform.Transformer;
26: import javax.xml.transform.TransformerException;
27: import javax.xml.transform.TransformerFactory;
28: import javax.xml.transform.stream.StreamResult;
29: import javax.xml.transform.stream.StreamSource;
30:
31: /**
32: * Xslt transformer using the JDK built-in XSLT stuff
33: */
34: public class XsltTransformer {
35: private Transformer transformer;
36:
37: public XsltTransformer(File xslfile) throws IOException,
38: TransformerException {
39: if (!xslfile.exists()) {
40: throw new FileNotFoundException("File "
41: + xslfile.getAbsolutePath() + " doesn't exist");
42: }
43: Source sxslt = new StreamSource(new FileInputStream(xslfile));
44: sxslt.setSystemId(xslfile.getName());
45: TransformerFactory factory = TransformerFactory.newInstance();
46: this .transformer = factory.newTransformer(sxslt);
47: }
48:
49: public void transform(InputStream inXml, OutputStream out)
50: throws TransformerException {
51: Source xmlSource = new StreamSource(inXml);
52: StreamResult res = new StreamResult(out);
53: transformer.transform(xmlSource, res);
54: FileUtil.closeQuitely(inXml);
55: FileUtil.closeQuitely(out);
56: }
57:
58: public static void transformFile(String inputFileName,
59: String outputFilename, String xsltFile)
60: throws TransformerException, IOException {
61: File f = new File(xsltFile);
62: XsltTransformer trans = new XsltTransformer(f);
63: InputStream in = null;
64: OutputStream out = null;
65: try {
66: in = new BufferedInputStream(new FileInputStream(
67: inputFileName), 32 * 1024);
68: out = new BufferedOutputStream(new FileOutputStream(
69: outputFilename), 32 * 1024);
70: trans.transform(in, out);
71: } finally {
72: FileUtil.closeQuitely(in);
73: FileUtil.closeQuitely(out);
74: }
75: }
76:
77: public static void main(String args[]) {
78: try {
79: if (args.length != 3) {
80: System.out
81: .println("Call with: XsltTransformer inputfile outputfile stylesheet");
82: } else {
83: transformFile(args[0], args[1], args[2]);
84: System.out.println(args[0]
85: + " has been successfully transformed into "
86: + args[1]);
87: }
88: } catch (Exception e) {
89: e.printStackTrace();
90: System.exit(1);
91: }
92: }
93:
94: }
|