KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > caucho > xsl > Xsl


1 /*
2  * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
3  *
4  * This file is part of Resin(R) Open Source
5  *
6  * Each copy or derived work must preserve the copyright notice and this
7  * notice unmodified.
8  *
9  * Resin Open Source is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * Resin Open Source is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
17  * of NON-INFRINGEMENT. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with Resin Open Source; if not, write to the
22  *
23  * Free Software Foundation, Inc.
24  * 59 Temple Place, Suite 330
25  * Boston, MA 02111-1307 USA
26  *
27  * @author Scott Ferguson
28  */

29
30 package com.caucho.xsl;
31
32 import com.caucho.log.Log;
33 import com.caucho.server.util.CauchoSystem;
34 import com.caucho.util.ExceptionWrapper;
35 import com.caucho.vfs.MergePath;
36 import com.caucho.vfs.Path;
37 import com.caucho.vfs.ReadStream;
38 import com.caucho.vfs.Vfs;
39 import com.caucho.vfs.WriteStream;
40 import com.caucho.xml.Html;
41 import com.caucho.xml.Xml;
42 import com.caucho.xml.XmlParser;
43
44 import org.w3c.dom.Document JavaDoc;
45
46 import javax.xml.transform.Templates JavaDoc;
47 import javax.xml.transform.TransformerConfigurationException JavaDoc;
48 import java.io.IOException JavaDoc;
49 import java.util.ArrayList JavaDoc;
50 import java.util.HashMap JavaDoc;
51 import java.util.Properties JavaDoc;
52 import java.util.logging.Logger JavaDoc;
53
54 /**
55  * Public facade for creating stylesheets. The Xsl factory
56  * creates standard XSL stylesheets. A Stylesheet object represents
57  * a compiled stylesheet. You'll need to create a Transformer to
58  * actually perform any transformations.
59  *
60  * <code><pre>
61  * import java.io.*;
62  * import javax.xml.transform.*;
63  * import javax.xml.transform.stream.*;
64  * import org.xml.sax.*;
65  *
66  * import com.caucho.xsl.*;
67  *
68  * ...
69  *
70  * TransformerFactory factory = new Xsl();
71  * StreamSource xslSource = new StreamSource("mystyle.xsl");
72  * Transformer transformer = factory.newTransformer(xslSource);
73  *
74  * StreamSource xmlSource = new StreamSource("test.xml");
75  * StreamResult htmlResult = new StreamResult("test.html");
76  *
77  * transformer.transform(xmlSource, htmlResult);
78  * </pre></code>
79  */

80 public class Xsl extends AbstractStylesheetFactory {
81   static final Logger JavaDoc log = Log.open(Xsl.class);
82
83   public Xsl() {}
84
85   /**
86    * Parses the XSL into a DOM document.
87    *
88    * @param rs the input stream.
89    */

90   protected Document JavaDoc parseXSL(ReadStream rs)
91     throws TransformerConfigurationException JavaDoc
92   {
93     try {
94       Xml parser = new Xml();
95
96       return parser.parseDocument(rs);
97     } catch (Exception JavaDoc e) {
98       throw new XslParseException(e);
99     }
100   }
101
102   public static void main(String JavaDoc []args)
103   {
104     String JavaDoc xslName = "default.xsl";
105     String JavaDoc dest = null;
106     String JavaDoc suffix = null;
107     String JavaDoc toc = "";
108     int i = 0;
109     String JavaDoc conf = CauchoSystem.getResinConfig();
110     boolean isStrict = true;
111     ArrayList JavaDoc<String JavaDoc> argList = new ArrayList JavaDoc<String JavaDoc>();
112     ArrayList JavaDoc<String JavaDoc> keyList = new ArrayList JavaDoc<String JavaDoc>();
113     ArrayList JavaDoc<String JavaDoc> valueList = new ArrayList JavaDoc<String JavaDoc>();
114
115     while (i < args.length) {
116       if (args[i].equals("-xsl")) {
117     xslName = args[i + 1];
118     i += 2;
119       }
120       else if (args[i].equals("-lite") ||
121                args[i].equals("-stylescript")) {
122     isStrict = false;
123     i += 1;
124       }
125       else if (args[i].equals("-o")) {
126     dest = args[i + 1];
127     i += 2;
128       }
129       else if (args[i].equals("-suffix")) {
130     suffix = args[i + 1];
131     i += 2;
132       }
133       else if (args[i].startsWith("-A")) {
134     argList.add(args[i].substring(2));
135     i += 1;
136       }
137       else if (args[i].startsWith("-P")) {
138         String JavaDoc v = args[i].substring(2);
139         int p = v.indexOf('=');
140         String JavaDoc key;
141         String JavaDoc value;
142
143         if (p >= 0) {
144           key = v.substring(0, p);
145           value = v.substring(p + 1);
146         }
147         else {
148           key = v;
149           value = "";
150         }
151
152         keyList.add(key);
153         valueList.add(value);
154
155     i += 1;
156       }
157       else if (args[i].equals("-conf")) {
158     conf = args[i + 1];
159     i += 2;
160       }
161       else if (args[i].equals("-h") || args[i].equals("-help")) {
162     usage();
163     return;
164       } else
165     break;
166     }
167
168     /*
169     Path cfg = CauchoSystem.getResinHome().lookup(conf);
170     if (cfg.exists()) {
171       try {
172     Registry.setRegistry(Registry.parse(cfg));
173       } catch (IOException e) {
174       } catch (SAXException e) {
175       }
176     }
177     */

178
179     Path destDir = null;
180     if (dest != null)
181       destDir = Vfs.lookup(dest);
182     else if (suffix == null)
183       destDir = Vfs.lookup("stdout:");
184
185     if (args.length - i > 1 && (dest == null || destDir.isFile()) &&
186     suffix == null) {
187       System.err.println("multiple sources require a destination directory");
188       System.exit(1);
189     }
190
191     try {
192       MergePath stylePath = new MergePath();
193       stylePath.addMergePath(Vfs.lookup(xslName).getParent());
194       stylePath.addMergePath(Vfs.lookup());
195       stylePath.addMergePath(CauchoSystem.getResinHome().lookup("xsl"));
196       stylePath.addClassPath(Thread.currentThread().getContextClassLoader());
197
198       /*
199         Path []stylePath = new Path[] {
200         Pwd.lookup(xslName).getParent(),
201         Pwd.lookup(),
202         CauchoSystem.getResinHome().lookup("xsl")};
203       */

204       Path []scriptPath = new Path[] {
205         Vfs.lookup(),
206         Vfs.lookup(xslName).getParent(),
207         CauchoSystem.getResinHome().lookup("scripts")
208       };
209
210       Path xslPath = stylePath.lookup(xslName);
211       if (xslPath == null) {
212         System.out.println("can't find `" + xslName + "'");
213         System.exit(1);
214       }
215
216       AbstractStylesheetFactory xsl;
217
218       if (isStrict)
219         xsl = new Xsl();
220       else
221         xsl = new StyleScript();
222
223       xsl.setStylePath(stylePath);
224
225       Templates JavaDoc stylesheet;
226
227       stylesheet = xsl.newTemplates(xslName);
228
229       for (; i < args.length; i++) {
230         String JavaDoc name = args[i];
231
232         Path xmlPath = Vfs.lookup(name);
233
234         HashMap JavaDoc<String JavaDoc,Object JavaDoc> argMap = new HashMap JavaDoc<String JavaDoc,Object JavaDoc>();
235
236         String JavaDoc []childArgs = new String JavaDoc[argList.size() + 1];
237         argList.toArray(childArgs);
238         childArgs[childArgs.length - 1] = name;
239
240         argMap.put("arguments", childArgs);
241         argMap.put("File", Vfs.lookup());
242
243         ReadStream is = xmlPath.openRead();
244         Document JavaDoc doc = null;
245         try {
246           if (isStrict)
247             doc = new Xml().parseDocument(is);
248           else {
249             XmlParser parser = new Html();
250             parser.setEntitiesAsText(true);
251             doc = parser.parseDocument(is);
252           }
253         } finally {
254           is.close();
255         }
256
257         //Document result = xsl.transform(doc, argMap);
258
Document JavaDoc result = null;
259
260         Path destPath = null;
261         if (dest != null)
262           destPath = Vfs.lookup(dest);
263         else if (suffix != null)
264           destPath = xmlPath.getParent();
265         else
266           destPath = Vfs.lookup("stdout:");
267
268         if (suffix != null) {
269           int p = name.lastIndexOf('.');
270           if (p == -1) {
271             System.err.println("suffix missing for `" + name + "'");
272             System.exit(1);
273           }
274
275           String JavaDoc destName = name.substring(0, p);
276           if (dest == null) {
277             p = destName.lastIndexOf('/');
278             if (p >= 0)
279               destName = destName.substring(p + 1);
280           }
281
282           if (! destPath.isFile())
283             destPath = destPath.lookup(destName + '.' + suffix);
284           else {
285             System.err.println("illegal output combination");
286             System.exit(1);
287           }
288         }
289         else if (destPath.isDirectory())
290           destPath = destPath.lookup(name);
291
292         try {
293           destPath.getParent().mkdirs();
294         } catch (IOException JavaDoc e) {
295         }
296
297         WriteStream os = destPath.openWrite();
298
299         try {
300           Properties JavaDoc output = stylesheet.getOutputProperties();
301
302           String JavaDoc encoding = (String JavaDoc) output.get("encoding");
303           String JavaDoc mimeType = (String JavaDoc) output.get("mime-type");
304           String JavaDoc method = (String JavaDoc) output.get("method");
305
306           if (encoding == null && (method == null || ! method.equals("html")))
307             encoding = "UTF-8";
308
309           TransformerImpl transformer =
310             (TransformerImpl) stylesheet.newTransformer();
311
312           if (encoding != null)
313             os.setEncoding(encoding);
314
315           transformer.setProperty("caucho.pwd", Vfs.lookup());
316
317           for (int j = 0; j < keyList.size(); j++) {
318             String JavaDoc key = (String JavaDoc) keyList.get(j);
319             String JavaDoc value = (String JavaDoc) valueList.get(j);
320
321             transformer.setParameter(key, value);
322           }
323
324           transformer.transform(doc, os);
325         } finally {
326           os.close();
327         }
328       }
329     } catch (Throwable JavaDoc e) {
330       while ((e instanceof ExceptionWrapper) &&
331              ((ExceptionWrapper) e).getRootCause() != null)
332         e = ((ExceptionWrapper) e).getRootCause();
333
334       e.printStackTrace();
335     } finally {
336       System.exit(0);
337     }
338   }
339
340   private static void usage()
341   {
342     System.err.println("xsl [-xsl stylesheet] file1 file2 ...");
343     System.err.println(" -xsl stylesheet : select a stylesheet");
344     System.err.println(" -o filename : output filename/directory");
345     System.err.println(" -suffix suffix : replacement suffix");
346     System.err.println(" -stylescript : StyleScript");
347     System.err.println(" -Pkey=value : template parameter");
348     System.err.println(" -h : this help message");
349   }
350 }
351
Popular Tags