KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openlaszlo > xml > internal > XMLCompiler


1 /* ****************************************************************************
2  * XMLCompiler.java
3  * ****************************************************************************/

4
5 /* J_LZ_COPYRIGHT_BEGIN *******************************************************
6 * Copyright 2001-2004 Laszlo Systems, Inc. All Rights Reserved. *
7 * Use is subject to license terms. *
8 * J_LZ_COPYRIGHT_END *********************************************************/

9
10 package org.openlaszlo.xml.internal;
11
12 import java.io.File JavaDoc;
13 import java.io.FileReader JavaDoc;
14 import java.io.FileWriter JavaDoc;
15 import java.io.IOException JavaDoc;
16 import java.io.Reader JavaDoc;
17 import java.io.Writer JavaDoc;
18 import java.io.StringBufferInputStream JavaDoc;
19
20 import java.util.List JavaDoc;
21 import java.util.Stack JavaDoc;
22
23
24 import org.jdom.Attribute;
25 import org.jdom.Comment;
26 import org.jdom.Document;
27 import org.jdom.Element;
28 import org.jdom.JDOMException;
29 import org.jdom.input.SAXBuilder;
30
31 /**
32  * Takes XML in various forms, and serializes it to actionscript, preserving all
33  * heirarchy
34  *
35  * @author Oliver Steele
36  * @author Max Carlson
37  * @version 1.0
38  */

39 public class XMLCompiler {
40     
41     private static Stack JavaDoc counterstack = new Stack JavaDoc();
42     private static Stack JavaDoc basestack = new Stack JavaDoc();
43     
44     private static String JavaDoc bas = "";
45
46     /**
47      * Compile XML to actionscript
48      *
49      * @param XML string to compile
50      * @return Actionscript representation of XML
51      */

52     public static String JavaDoc compile(String JavaDoc x) {
53         // Compile a new element from scratch
54
StringBuffer JavaDoc base = new StringBuffer JavaDoc();
55         StringBufferInputStream JavaDoc sis = new StringBufferInputStream JavaDoc(x);
56         SAXBuilder sb = new SAXBuilder();
57         try {
58             Document doc = sb.build(sis);
59             Element e = doc.getRootElement();
60             return compile(e);
61         } catch (Exception JavaDoc ignored) {}
62         
63         return null;
64     }
65
66     /**
67      * Compile XML to actionscript
68      *
69      * @param Element e JDOM element to compile
70      * @return Actionscript representation of XML
71      */

72     public static String JavaDoc compile(Element e) {
73         return compile(e, Schema.DEFAULT_SCHEMA);
74     }
75
76     /**
77      * Compile XML to actionscript
78      *
79      * @param Element e JDOM element to compile
80      * @param Schema schema Laszlo Schema to follow (what is var, function)
81      * @return Actionscript representation of XML
82      */

83     public static String JavaDoc compile(Element e, Schema schema) {
84         // Compile a new element from scratch
85
StringBuffer JavaDoc base = new StringBuffer JavaDoc();
86         return compile(e, schema, base);
87     }
88     
89     /**
90      * Compile XML to actionscript
91      *
92      * @param Element e JDOM element to compile
93      * @param Schema schema Laszlo Schema to follow (what is var, function)
94      * @param StringBuffer base Base of current element - used when called
95      * recursively
96      * @return Actionscript representation of XML
97      */

98     public static String JavaDoc compile(Element e, Schema schema,
99                                        StringBuffer JavaDoc base) {
100         // Default to an empty string for the variable name - use name node
101
// in XML
102
String JavaDoc varname = "";
103         return compile(e, schema, base, varname);
104     }
105     
106     /**
107      * Compile XML to actionscript
108      *
109      * @param Element e JDOM element to compile
110      * @param Schema schema Laszlo Schema to follow (what is var, function)
111      * @param StringBuffer base Base of current element - used when called
112      * recursively
113      * @param String varname Variable name to use instead of element name
114      * @return Actionscript representation of XML
115      */

116     public static String JavaDoc compile(Element e, Schema schema,
117                                        StringBuffer JavaDoc base, String JavaDoc varname) {
118         StringBuffer JavaDoc out = new StringBuffer JavaDoc();
119         
120         int lastcount = -1;
121         
122         
123         /*
124         // Find shortest available subsring - not necessary because of flash's
125         // name pools
126         String name = (String)shorter.get(nodename);
127         if (name == null) {
128             String chunk = "";
129             for (int i = 1; i < nodename.length(); i++) {
130                 chunk = nodename.substring(0, i);
131                 if (! shorter.containsKey(nodename) && ! used.containsKey(chunk) ) {
132                     shorter.put(nodename, chunk);
133                     used.put(chunk, "shorter");
134                     break;
135                 }
136             }
137             out.append(chunk + " = '" + nodename + "';\n");
138             name = chunk;
139         }
140         */

141         
142         if (base.length() <= 0) {
143             // If we're just starting out, initialize everything
144
counterstack = new Stack JavaDoc();
145             counterstack.push(new Integer JavaDoc(-1));
146             lastcount = counterstack.size();
147
148             basestack = new Stack JavaDoc();
149             basestack.push(base);
150             
151             bas = "";
152             out.append("function x(n, a, t) {\nvar o = {};\no.n = n;\no.a = a;\no.c = [];\nif (t.length) {o.t = t;}\nreturn o;\n}\n");
153         }
154
155         //out.append(counterstack.size() + ", " + lastcount + " > ");
156

157         // Count up one for each unique base name - ensures there is no
158
// namespace collision in Actionscript namespace for elements with same
159
// names
160
Integer JavaDoc in = new Integer JavaDoc(-1);
161         in = (Integer JavaDoc)counterstack.pop();
162         int inum = in.intValue();
163         inum++;
164         in = new Integer JavaDoc(inum);
165         
166         counterstack.push(in);
167         
168         if (base.length() > 0) {
169             base.append("[");
170             // Append the new number to the current base
171
base.append(in);
172             base.append("]");
173         } else {
174             base.append("root");
175         }
176
177         String JavaDoc name = e.getName();
178         // Create an object to hold sub-values
179
out.append(base + "=x('" + name + "'");
180
181         // Add each attribute as an element of the 'attrs' object
182
List JavaDoc attributes = e.getAttributes();
183         //if (attributes.size() > 0) {
184
out.append(",{");
185             for (int i = 0; i < attributes.size(); i++) {
186                 Attribute a = (Attribute)attributes.get(i);
187                 
188                 String JavaDoc val = null;
189                 Schema.Type type = schema.getAttributeType(e, a.getName());
190                 if (type == schema.STRING_TYPE) {
191                     val = "'" + escapeQuote( a.getValue() ) + "'";
192                 } else {
193                     // schema.UNKNOWN_TYPE
194
try {
195                         float v = a.getFloatValue();
196                         val = escapeQuote( a.getValue() );
197                     } catch (Exception JavaDoc ex) {
198                         val = "'" + escapeQuote( a.getValue() ) + "'";
199                     }
200                 }
201                 
202                 out.append(a.getName() + ":" + val);
203     
204                 if (i < attributes.size() - 1) {
205                     out.append(",");
206                 }
207             }
208             out.append("}");
209         //}
210

211
212         // Add textual data to 't' node if available
213
String JavaDoc text = e.getTextTrim();
214         if ((text != null) && (text.length() > 0)) {
215             out.append(",'" + escapeQuote( text ) + "');\n");
216         } else {
217             out.append(");\n");
218         }
219
220         // Add each child element to the children object
221
List JavaDoc nestedElements = e.getChildren();
222         
223         
224         if (nestedElements.size() > 0) {
225             counterstack.push(new Integer JavaDoc(-1));
226         
227             for (int i = 0; i < nestedElements.size(); i++) {
228                 Element c = (Element)nestedElements.get(i);
229                 if (i > 0) {
230                     StringBuffer JavaDoc temp = new StringBuffer JavaDoc(bas);
231                     // compile child recursively, add to children object
232
out.append( compile(c, schema, temp) );
233                 } else {
234                     // Set up initial children object to hold child elements
235
basestack.push(bas + "");
236                     //out.append("in: " + bas + "\n");
237

238                     base.append(".c");
239                     bas = base + "";
240                     out.append( compile(c, schema, base) );
241                 }
242             }
243             
244             if (counterstack.size() != lastcount) {
245                 counterstack.pop();
246                 bas = (String JavaDoc)basestack.pop();
247                 //out.append("out: " + base + " : " + basestack.size() + ", " + lastcount + "\n");
248
lastcount = counterstack.size();
249             }
250         }
251
252         return out.toString();
253     }
254
255 /*
256     /**
257      * A utility class to allow execution from the command line
258      *
259      * @param args[] a series of 3 arguments - [XML input document],
260      * [variable name], [AS output document]
261   public static void main(String[] args) {
262         if (args.length != 3) {
263             System.out.println("Usage: XMLCompiler " +
264                 "[XML input document] " + "[variable name] " + "[AS output document]");
265             System.exit(0);
266         }
267     
268         try {
269             // Create and load properties
270             System.out.println("Reading XML from " + args[0]);
271             
272             // Load XML into JDOM Document
273             SAXBuilder builder = new SAXBuilder();
274             FileReader r = new FileReader(args[0]);
275             Document doc = builder.build( r );
276             
277             System.out.println("\n\n---- Converting to Actionscript ----");
278             
279             Schema schema = Schema.DEFAULT_SCHEMA;
280             StringBuffer out = new StringBuffer();
281             
282             // recurse on children - should be only one root element...
283             List nestedElements = doc.getRootElement().getChildren();
284             for (int i = 0; i < nestedElements.size(); i++) {
285                 Element c = (Element)nestedElements.get(i);
286                 out.append( compile(c, schema, new StringBuffer(), args[1]) );
287             }
288
289
290             System.out.println("\n\n---- Writing to file ----");
291             FileWriter w = new FileWriter(args[2]);
292             w.write(out + "");
293             w.flush();
294             w.close();
295                     
296             System.out.println(out);
297
298         } catch (Exception e) {
299             e.printStackTrace();
300         }
301     }
302  */

303     
304     /**
305      * Escapes strings for inclusion inside actionscript strings,
306      * ex: ' to \'
307      *
308      * @param string to escape
309      * @return an escaped string
310      */

311     private static String JavaDoc escapeQuote(String JavaDoc s) {
312         String JavaDoc retvalue = s;
313         if ( s.indexOf ("'") != -1 || s.indexOf ("\"") != -1 || s.indexOf ("\\") != -1) {
314         StringBuffer JavaDoc hold = new StringBuffer JavaDoc();
315         char c;
316         for ( int i = 0; i < s.length(); i++ ) {
317             if ( (c=s.charAt(i)) == '\'' ) {
318                 hold.append ("\\'");
319             } else if ((c=s.charAt(i)) == '\"') {
320                 hold.append ("\\\"");
321             } else if ((c=s.charAt(i)) == '\\') {
322                 hold.append ("\\\\");
323             } else {
324                 hold.append(c);
325             }
326         }
327         retvalue = hold.toString();
328         }
329         return retvalue;
330     }
331 }
332
Popular Tags