KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > freemarker > ext > dom > Transform


1 /*
2  * Copyright (c) 2003 The Visigoth Software Society. All rights
3  * reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  * notice, this list of conditions and the following disclaimer in
14  * the documentation and/or other materials provided with the
15  * distribution.
16  *
17  * 3. The end-user documentation included with the redistribution, if
18  * any, must include the following acknowledgement:
19  * "This product includes software developed by the
20  * Visigoth Software Society (http://www.visigoths.org/)."
21  * Alternately, this acknowledgement may appear in the software itself,
22  * if and wherever such third-party acknowledgements normally appear.
23  *
24  * 4. Neither the name "FreeMarker", "Visigoth", nor any of the names of the
25  * project contributors may be used to endorse or promote products derived
26  * from this software without prior written permission. For written
27  * permission, please contact visigoths@visigoths.org.
28  *
29  * 5. Products derived from this software may not be called "FreeMarker" or "Visigoth"
30  * nor may "FreeMarker" or "Visigoth" appear in their names
31  * without prior written permission of the Visigoth Software Society.
32  *
33  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
34  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
36  * DISCLAIMED. IN NO EVENT SHALL THE VISIGOTH SOFTWARE SOCIETY OR
37  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
38  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
39  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
40  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
41  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
42  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
43  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
44  * SUCH DAMAGE.
45  * ====================================================================
46  *
47  * This software consists of voluntary contributions made by many
48  * individuals on behalf of the Visigoth Software Society. For more
49  * information on the Visigoth Software Society, please see
50  * http://www.visigoths.org/
51  */

52  
53 package freemarker.ext.dom;
54
55
56 import java.io.*;
57 import java.util.*;
58 import freemarker.template.*;
59
60 /**
61  * A class that contains a main() method for command-line invocation
62  * of a FreeMarker XML transformation.
63  *
64  * $id$
65  */

66
67 public class Transform {
68     
69     private File inputFile, ftlFile, outputFile;
70     private String JavaDoc encoding;
71     private Locale locale;
72     private Configuration cfg;
73     
74     /**
75      * A convenient main() method for command-line invocation.
76      */

77     static public void main(String JavaDoc[] args) {
78         try {
79             Transform proc = transformFromArgs(args);
80             proc.transform();
81         } catch (IllegalArgumentException JavaDoc iae) {
82             System.err.println(iae.getMessage());
83             usage();
84         } catch (Exception JavaDoc e) {
85             e.printStackTrace();
86         }
87     }
88     
89     /**
90      * @param inputFile The file from which to read the XML input
91      * @param ftlFile The file containing the template
92      * @param outputFile The file to which to output. If this is null, we use stdout.
93      * @param locale The locale to use. If this is null, we use the platform default.
94      * @param encoding The character encoding to use for output, if this is null, we use the platform default
95      */

96     
97     Transform(File inputFile, File ftlFile, File outputFile, Locale locale, String JavaDoc encoding) throws IOException {
98         if (encoding == null) {
99             encoding = System.getProperty("file.encoding");
100         }
101         if (locale == null) {
102             locale = Locale.getDefault();
103         }
104         this.encoding = encoding;
105         this.locale = locale;
106         this.inputFile = inputFile;
107         this.ftlFile = ftlFile;
108         this.outputFile = outputFile;
109         File ftlDirectory = ftlFile.getAbsoluteFile().getParentFile();
110         cfg = new Configuration();
111         cfg.setDirectoryForTemplateLoading(ftlDirectory);
112     }
113     
114     /**
115      * Performs the transformation.
116      */

117     void transform() throws Exception JavaDoc {
118         String JavaDoc templateName = ftlFile.getName();
119         Template template = cfg.getTemplate(templateName, locale);
120         NodeModel rootNode = NodeModel.parse(inputFile);
121         OutputStream outputStream = System.out;
122         if (outputFile != null) {
123             outputStream = new FileOutputStream(outputFile);
124         }
125         Writer outputWriter = new OutputStreamWriter(outputStream, encoding);
126         try {
127             template.process(null, outputWriter, null, rootNode);
128         } finally {
129             if (outputFile != null)
130                 outputWriter.close();
131         }
132     }
133     
134     static Transform transformFromArgs(String JavaDoc[] args) throws IOException {
135         int i=0;
136         String JavaDoc input = null, output=null, ftl = null, loc = null, enc = null;
137         while (i<args.length) {
138             String JavaDoc dashArg = args[i++];
139             if (i>=args.length) {
140                 throw new IllegalArgumentException JavaDoc("");
141             }
142             String JavaDoc arg = args[i++];
143             if (dashArg.equals("-in")) {
144                 if (input != null) {
145                     throw new IllegalArgumentException JavaDoc("The input file should only be specified once");
146                 }
147                 input = arg;
148             } else if (dashArg.equals("-ftl")) {
149                 if (ftl != null) {
150                     throw new IllegalArgumentException JavaDoc("The ftl file should only be specified once");
151                 }
152                 ftl = arg;
153             } else if (dashArg.equals("-out")) {
154                 if (output != null) {
155                     throw new IllegalArgumentException JavaDoc("The output file should only be specified once");
156                 }
157                 output = arg;
158             } else if (dashArg.equals("-locale")) {
159                 if (loc != null) {
160                     throw new IllegalArgumentException JavaDoc("The locale should only be specified once");
161                 }
162                 loc = arg;
163             } else if (dashArg.equals("-encoding")) {
164                 if (enc != null) {
165                     throw new IllegalArgumentException JavaDoc("The encoding should only be specified once");
166                 }
167                 enc = arg;
168             } else {
169                 throw new IllegalArgumentException JavaDoc("Unknown input argument: " + dashArg);
170             }
171         }
172         if (input == null) {
173             throw new IllegalArgumentException JavaDoc("No input file specified.");
174         }
175         if (ftl == null) {
176             throw new IllegalArgumentException JavaDoc("No ftl file specified.");
177         }
178         File inputFile = new File(input).getAbsoluteFile();
179         File ftlFile = new File(ftl).getAbsoluteFile();
180         if (!inputFile.exists()) {
181             throw new IllegalArgumentException JavaDoc("Input file does not exist: " + input);
182         }
183         if (!ftlFile.exists()) {
184             throw new IllegalArgumentException JavaDoc("FTL file does not exist: " + ftl);
185         }
186         if (!inputFile.isFile() || !inputFile.canRead()) {
187             throw new IllegalArgumentException JavaDoc("Input file must be a readable file: " + input);
188         }
189         if (!ftlFile.isFile() || !ftlFile.canRead()) {
190             throw new IllegalArgumentException JavaDoc("FTL file must be a readable file: " + ftl);
191         }
192         File outputFile = null;
193         if (output != null) {
194             outputFile = new File(output).getAbsoluteFile();
195             File outputDirectory = outputFile.getParentFile();
196             if (!outputDirectory.exists() || !outputDirectory.canWrite()) {
197                 throw new IllegalArgumentException JavaDoc("The output directory must exist and be writable: " + outputDirectory);
198             }
199         }
200         Locale locale = Locale.getDefault();
201         if (loc != null) {
202             locale = localeFromString(loc);
203         }
204         return new Transform(inputFile, ftlFile, outputFile, locale, enc);
205     }
206     
207     static Locale localeFromString(String JavaDoc ls) {
208         if (ls == null) ls = "";
209         String JavaDoc lang="", country="", variant="";
210         StringTokenizer st = new StringTokenizer(ls, "_-,");
211         if (st.hasMoreTokens()) {
212             lang = st.nextToken();
213             if (st.hasMoreTokens()) {
214                 country = st.nextToken();
215                 if (st.hasMoreTokens()) {
216                     variant = st.nextToken();
217                 }
218             }
219             return new Locale(lang, country, variant);
220         } else {
221             return Locale.getDefault();
222         }
223     }
224     
225     static void usage() {
226         System.err.println("Usage: java freemarker.ext.dom.Transform -in <xmlfile> -ftl <ftlfile> [-out <outfile>] [-locale <locale>] [-encoding <encoding>]");
227         System.exit(-1);
228     }
229 }
230
Popular Tags