KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > saxon > Compile


1 package net.sf.saxon;
2 import net.sf.saxon.instruct.TerminationException;
3 import net.sf.saxon.trans.XPathException;
4 import org.xml.sax.InputSource JavaDoc;
5
6 import javax.xml.transform.Source JavaDoc;
7 import javax.xml.transform.Templates JavaDoc;
8 import javax.xml.transform.TransformerFactoryConfigurationError JavaDoc;
9 import javax.xml.transform.sax.SAXSource JavaDoc;
10 import java.io.*;
11 import java.util.Date JavaDoc;
12
13 /**
14  * This <B>Compile</B> class provides a command-line interface allowing a
15  * stylesheet to be compiled.<p>
16  *
17  * @author M.H.Kay
18  */

19
20 public class Compile {
21
22     private TransformerFactoryImpl factory = new TransformerFactoryImpl();
23
24     private boolean showTime = false;
25     private boolean debug = false;
26
27     /**
28      * Main program, can be used directly from the command line.
29      * <p>The format is:</P>
30      * <p>java net.sf.saxon.Compile [options] <I>style-file</I> <I>output-file</I></P>
31      * <p>This program compiles the XSL style sheet in style-file to the output-file.</p>
32      *
33      * @param args Arguments supplied on the command line
34      * @exception java.lang.Exception Any compilation error occurs
35      */

36
37     public static void main (String JavaDoc args[])
38         throws java.lang.Exception JavaDoc
39     {
40         // the real work is delegated to another routine so that it can be used in a subclass
41
(new Compile()).doMain(args);
42     }
43
44     /**
45      * Support method for main program. This support method can also be invoked from subclasses
46      * that support the same command line interface
47      *
48      * @param args the command-line arguments
49      */

50
51     protected void doMain(String JavaDoc args[]) {
52
53         String JavaDoc styleFileName;
54         boolean useURLs = false;
55         String JavaDoc outputFileName;
56
57                 // Check the command-line arguments.
58

59         try {
60             int i = 0;
61             while (true) {
62                 if (i>=args.length) badUsage("No stylesheet file name");
63
64                 if (args[i].charAt(0)=='-') {
65
66                     if (args[i].equals("-u")) {
67                         useURLs = true;
68                         i++;
69                     }
70
71                     else if (args[i].equals("-t")) {
72                         System.err.println(factory.getConfiguration().getProductTitle());
73                         System.err.println("Java version " + System.getProperty("java.version"));
74                         factory.setAttribute(
75                             FeatureKeys.TIMING,
76                             Boolean.TRUE);
77
78                         //Loader.setTracing(true);
79
showTime = true;
80                         i++;
81                     }
82
83                     else if (args[i].equals("-y")) {
84                         i++;
85                         if (args.length < i+2) badUsage("No style parser class");
86                         String JavaDoc styleParserName = args[i++];
87                         factory.setAttribute(
88                                 FeatureKeys.STYLE_PARSER_CLASS,
89                                 styleParserName);
90                     }
91
92                     else if (args[i].equals("-r")) {
93                         i++;
94                         if (args.length < i+2) badUsage("No URIResolver class");
95                         String JavaDoc r = args[i++];
96                         factory.setURIResolver(factory.getConfiguration().makeURIResolver(r));
97                     }
98
99                     else if (args[i].equals("-debug")) {
100                         i++;
101                         debug = true;
102                     }
103
104                     else badUsage("Unknown option " + args[i]);
105                 }
106
107                 else break;
108             }
109
110             if (args.length < i+1 ) badUsage("No stylesheet file name");
111             styleFileName = args[i++];
112
113             if (args.length < i+1 ) badUsage("No output file name");
114             outputFileName = args[i++];
115
116
117             long startTime = (new Date JavaDoc()).getTime();
118
119             Source JavaDoc styleSource;
120             if (useURLs || styleFileName.startsWith("http:")
121                              || styleFileName.startsWith("file:")) {
122                 styleSource = factory.getURIResolver().resolve(styleFileName, null);
123                 if (styleSource == null) {
124                     styleSource = factory.getConfiguration().getSystemURIResolver().resolve(styleFileName, null);
125                 }
126
127             } else {
128                 File sheetFile = new File(styleFileName);
129                 if (!sheetFile.exists()) {
130                     quit("Stylesheet file " + sheetFile + " does not exist", 2);
131                 }
132                 InputSource JavaDoc eis = new InputSource JavaDoc(sheetFile.toURL().toString());
133                 styleSource = new SAXSource JavaDoc(factory.getConfiguration().getStyleParser(), eis);
134             }
135
136             if (styleSource==null) {
137                 quit("URIResolver for stylesheet file must return a Source", 2);
138             }
139
140             Templates JavaDoc sheet = factory.newTemplates(styleSource);
141
142             if (showTime) {
143                 long endTime = (new Date JavaDoc()).getTime();
144                 System.err.println("Stylesheet compilation time: " + (endTime-startTime) + " milliseconds");
145             }
146
147             try {
148                 String JavaDoc msg = ((PreparedStylesheet)sheet).getExecutable().getReasonUnableToCompile();
149                 if (msg != null) {
150                     System.err.println(msg);
151                     quit("Unable to compile stylesheet", 2);
152                 }
153                 System.err.println("Serializing compiled stylesheet");
154                 ((PreparedStylesheet)sheet).setTargetNamePool(
155                         ((PreparedStylesheet)sheet).getConfiguration().getNamePool());
156                 OutputStream fos = new FileOutputStream(outputFileName);
157                 if (debug) {
158                     fos = new TracingObjectOutputStream(fos);
159                 }
160                 ObjectOutputStream oos = new ObjectOutputStream(fos);
161                 oos.writeObject(sheet);
162                 oos.close();
163                 System.err.println("Finished serializing stylesheet");
164             } catch (Exception JavaDoc err) {
165                 err.printStackTrace();
166             }
167
168         } catch (TerminationException err) {
169             quit(err.getMessage(), 1);
170         } catch (XPathException err) {
171             quit("Transformation failed: " + err.getMessage(), 2);
172         } catch (TransformerFactoryConfigurationError JavaDoc err) {
173             quit("Transformation failed: " + err.getMessage(), 2);
174         } catch (Exception JavaDoc err2) {
175             err2.printStackTrace();
176         }
177
178     }
179
180     /**
181      * Exit with a message
182      *
183      * @param message Message to be output
184      * @param code Result code to be returned to the operating system
185      */

186
187     protected static void quit(String JavaDoc message, int code) {
188         System.err.println(message);
189         System.exit(code);
190     }
191
192
193     /** Output error message when incorrect command line options/arguments are used
194      *
195      * @param message Error message to be displayed
196      */

197     protected void badUsage(String JavaDoc message) {
198         System.err.println(message);
199         System.err.println(factory.getConfiguration().getProductTitle());
200         System.err.println("Usage: java net.sf.saxon.Compile [options] stylesheet-file output-file");
201         System.err.println("Options: ");
202         System.err.println(" -r classname Use specified URIResolver class");
203         System.err.println(" -t Display version and timing information");
204         System.err.println(" -u Names are URLs not filenames");
205         System.err.println(" -y classname Use specified SAX parser for stylesheet");
206         System.err.println(" -debug Produce trace output to diagnose failures");
207         System.err.println(" -? Display this message ");
208         System.exit(2);
209     }
210
211     /**
212      * Tracing version of ObjectOutputStream for diagnostics
213      */

214
215     private static class TracingObjectOutputStream extends FilterOutputStream {
216
217         OutputStream oos;
218         public TracingObjectOutputStream(OutputStream oos) {
219             super(oos);
220             this.oos = oos;
221         }
222
223         public void write(byte b[]) throws IOException {
224             char[] chars = new char[b.length];
225             for (int i=0; i<b.length; i++) {
226                 chars[i] = (char)b[i];
227             }
228             String JavaDoc s = new String JavaDoc(chars);
229             if (s.indexOf("saxon") >= 0) {
230                 System.err.println("write byte[]: " + s);
231             }
232             super.write(b);
233         }
234
235         /**
236          * Writes <code>len</code> bytes from the specified
237          * <code>byte</code> array starting at offset <code>off</code> to
238          * this output stream.
239          * <p/>
240          * The <code>write</code> method of <code>FilterOutputStream</code>
241          * calls the <code>write</code> method of one argument on each
242          * <code>byte</code> to output.
243          * <p/>
244          * Note that this method does not call the <code>write</code> method
245          * of its underlying input stream with the same arguments. Subclasses
246          * of <code>FilterOutputStream</code> should provide a more efficient
247          * implementation of this method.
248          *
249          * @param b the data.
250          * @param off the start offset in the data.
251          * @param len the number of bytes to write.
252          * @throws java.io.IOException if an I/O error occurs.
253          * @see java.io.FilterOutputStream#write(int)
254          */

255         public void write(byte b[], int off, int len) throws IOException {
256             char[] chars = new char[len];
257             for (int i=0; i<len; i++) {
258                 chars[i] = (char)b[i+off];
259             }
260             String JavaDoc s = new String JavaDoc(chars);
261             if (s.indexOf("saxon") >= 0) {
262                 System.err.println("write byte[]: " + s);
263             }
264             super.write(b, off, len);
265         }
266
267         /**
268          * Writes the specified <code>byte</code> to this output stream.
269          * <p/>
270          * The <code>write</code> method of <code>FilterOutputStream</code>
271          * calls the <code>write</code> method of its underlying output stream,
272          * that is, it performs <tt>out.write(b)</tt>.
273          * <p/>
274          * Implements the abstract <tt>write</tt> method of <tt>OutputStream</tt>.
275          *
276          * @param b the <code>byte</code>.
277          * @throws java.io.IOException if an I/O error occurs.
278          */

279 // public void write(int b) throws IOException {
280
// char c = (char)b;
281
// System.err.println("write byte: " + c);
282
// super.write(b);
283
// }
284

285     }
286
287 }
288
289 //
290
// The contents of this file are subject to the Mozilla Public License Version 1.0 (the "License");
291
// you may not use this file except in compliance with the License. You may obtain a copy of the
292
// License at http://www.mozilla.org/MPL/
293
//
294
// Software distributed under the License is distributed on an "AS IS" basis,
295
// WITHOUT WARRANTY OF ANY KIND, either express or implied.
296
// See the License for the specific language governing rights and limitations under the License.
297
//
298
// The Original Code is: all this file.
299
//
300
// The Initial Developer of the Original Code is Michael H. Kay.
301
//
302
// Portions created by (your name) are Copyright (C) (your legal entity). All Rights Reserved.
303
//
304
// Contributor(s): none.
305
//
306
Popular Tags