KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > bsf > util > CodeBuffer


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

55
56 package org.apache.bsf.util;
57
58 import java.io.StringReader JavaDoc;
59 import java.io.StringWriter JavaDoc;
60 import java.io.PrintWriter JavaDoc;
61 import java.util.Hashtable JavaDoc;
62 import java.util.Stack JavaDoc;
63 import java.util.Vector JavaDoc;
64
65 import org.apache.bsf.util.cf.CodeFormatter;
66
67 /**
68  * A <code>CodeBuffer</code> object is used as a code repository for generated Java code.
69  * It provides buffers which correspond to the various sections of a Java class.
70  *
71  * @author Matthew J. Duftler
72  */

73 public class CodeBuffer
74 {
75   private StringWriter JavaDoc fieldDeclSW = new StringWriter JavaDoc(),
76                        methodDeclSW = new StringWriter JavaDoc(),
77                        initializerSW = new StringWriter JavaDoc(),
78                        constructorSW = new StringWriter JavaDoc(),
79                        serviceMethodSW = new StringWriter JavaDoc();
80
81   private PrintWriter JavaDoc fieldDeclPW = new PrintWriter JavaDoc(fieldDeclSW),
82                        methodDeclPW = new PrintWriter JavaDoc(methodDeclSW),
83                        initializerPW = new PrintWriter JavaDoc(initializerSW),
84                        constructorPW = new PrintWriter JavaDoc(constructorSW),
85                        serviceMethodPW = new PrintWriter JavaDoc(serviceMethodSW);
86
87   private Stack JavaDoc symbolTableStack = new Stack JavaDoc();
88   private Hashtable JavaDoc symbolTable = new Hashtable JavaDoc(),
89                        usedSymbolIndices = new Hashtable JavaDoc();
90
91   private ObjInfo finalStatementInfo;
92   private CodeBuffer parent;
93
94
95   {
96     symbolTableStack.push(symbolTable);
97   }
98
99   // New stuff...
100
private Vector JavaDoc imports = new Vector JavaDoc(),
101                  constructorArguments = new Vector JavaDoc(),
102                  constructorExceptions = new Vector JavaDoc(),
103                  serviceMethodExceptions = new Vector JavaDoc(),
104                  implementsVector = new Vector JavaDoc();
105   private String JavaDoc packageName = null,
106                  className = "Test",
107                  serviceMethodName = "exec",
108                  extendsName = null;
109   private Class JavaDoc serviceMethodReturnType = void.class;
110
111   public CodeBuffer()
112   {
113   }
114   public CodeBuffer(CodeBuffer parent)
115   {
116     this.parent = parent;
117   }
118   public void addConstructorArgument(ObjInfo arg)
119   {
120     constructorArguments.addElement(arg);
121   }
122   public void addConstructorException(String JavaDoc exceptionName)
123   {
124     if (!constructorExceptions.contains(exceptionName))
125     {
126       constructorExceptions.addElement(exceptionName);
127     }
128   }
129   public void addConstructorStatement(String JavaDoc statement)
130   {
131     constructorPW.println(statement);
132   }
133   public void addFieldDeclaration(String JavaDoc statement)
134   {
135     fieldDeclPW.println(statement);
136   }
137   public void addImplements(String JavaDoc importName)
138   {
139     if (!implementsVector.contains(importName))
140     {
141       implementsVector.addElement(importName);
142     }
143   }
144   public void addImport(String JavaDoc importName)
145   {
146     if (!imports.contains(importName))
147     {
148       imports.addElement(importName);
149     }
150   }
151   public void addInitializerStatement(String JavaDoc statement)
152   {
153     initializerPW.println(statement);
154   }
155   public void addMethodDeclaration(String JavaDoc statement)
156   {
157     methodDeclPW.println(statement);
158   }
159   public void addServiceMethodException(String JavaDoc exceptionName)
160   {
161     if (!serviceMethodExceptions.contains(exceptionName))
162     {
163       serviceMethodExceptions.addElement(exceptionName);
164     }
165   }
166   public void addServiceMethodStatement(String JavaDoc statement)
167   {
168     serviceMethodPW.println(statement);
169   }
170   // Used internally by merge(...).
171
private void appendIfNecessary(PrintWriter JavaDoc pw, StringBuffer JavaDoc buf)
172   {
173     if (buf.length() > 0)
174     {
175       pw.print(buf.toString());
176     }
177   }
178   public String JavaDoc buildNewSymbol(String JavaDoc prefix)
179   {
180     Integer JavaDoc nextNum = getSymbolIndex(prefix);
181
182     if (nextNum == null)
183     {
184       nextNum = new Integer JavaDoc(0);
185     }
186
187     int iNextNum = nextNum.intValue();
188     String JavaDoc symbol = prefix + "_" + iNextNum;
189
190     while (getSymbol(symbol) != null)
191     {
192       iNextNum++;
193       symbol = prefix + "_" + iNextNum;
194     }
195
196     putSymbolIndex(prefix, new Integer JavaDoc(iNextNum + 1));
197
198     return symbol;
199   }
200   public void clearSymbolTable()
201   {
202     symbolTable = new Hashtable JavaDoc();
203     symbolTableStack = new Stack JavaDoc();
204     symbolTableStack.push(symbolTable);
205
206     usedSymbolIndices = new Hashtable JavaDoc();
207   }
208   public String JavaDoc getClassName()
209   {
210     return className;
211   }
212   public Vector JavaDoc getConstructorArguments()
213   {
214     return constructorArguments;
215   }
216   public StringBuffer JavaDoc getConstructorBuffer()
217   {
218     constructorPW.flush();
219
220     return constructorSW.getBuffer();
221   }
222   public Vector JavaDoc getConstructorExceptions()
223   {
224     return constructorExceptions;
225   }
226   public String JavaDoc getExtends()
227   {
228     return extendsName;
229   }
230   public StringBuffer JavaDoc getFieldBuffer()
231   {
232     fieldDeclPW.flush();
233
234     return fieldDeclSW.getBuffer();
235   }
236   public ObjInfo getFinalServiceMethodStatement()
237   {
238     return finalStatementInfo;
239   }
240   public Vector JavaDoc getImplements()
241   {
242     return implementsVector;
243   }
244   public Vector JavaDoc getImports()
245   {
246     return imports;
247   }
248   public StringBuffer JavaDoc getInitializerBuffer()
249   {
250     initializerPW.flush();
251
252     return initializerSW.getBuffer();
253   }
254   public StringBuffer JavaDoc getMethodBuffer()
255   {
256     methodDeclPW.flush();
257
258     return methodDeclSW.getBuffer();
259   }
260   public String JavaDoc getPackageName()
261   {
262     return packageName;
263   }
264   public StringBuffer JavaDoc getServiceMethodBuffer()
265   {
266     serviceMethodPW.flush();
267
268     return serviceMethodSW.getBuffer();
269   }
270   public Vector JavaDoc getServiceMethodExceptions()
271   {
272     return serviceMethodExceptions;
273   }
274   public String JavaDoc getServiceMethodName()
275   {
276     return serviceMethodName;
277   }
278   public Class JavaDoc getServiceMethodReturnType()
279   {
280     if (finalStatementInfo != null)
281     {
282       return finalStatementInfo.objClass;
283     }
284     else if (serviceMethodReturnType != null)
285     {
286       return serviceMethodReturnType;
287     }
288     else
289     {
290       return void.class;
291     }
292   }
293   public ObjInfo getSymbol(String JavaDoc symbol)
294   {
295     ObjInfo ret = (ObjInfo)symbolTable.get(symbol);
296
297     if (ret == null && parent != null)
298       ret = parent.getSymbol(symbol);
299
300     return ret;
301   }
302   Integer JavaDoc getSymbolIndex(String JavaDoc prefix)
303   {
304     if (parent != null)
305     {
306       return parent.getSymbolIndex(prefix);
307     }
308     else
309     {
310       return (Integer JavaDoc)usedSymbolIndices.get(prefix);
311     }
312   }
313   public Hashtable JavaDoc getSymbolTable()
314   {
315     return symbolTable;
316   }
317   public void merge(CodeBuffer otherCB)
318   {
319     Vector JavaDoc otherImports = otherCB.getImports();
320
321     for (int i = 0; i < otherImports.size(); i++)
322     {
323       addImport((String JavaDoc)otherImports.elementAt(i));
324     }
325
326     appendIfNecessary(fieldDeclPW, otherCB.getFieldBuffer());
327     appendIfNecessary(methodDeclPW, otherCB.getMethodBuffer());
328     appendIfNecessary(initializerPW, otherCB.getInitializerBuffer());
329     appendIfNecessary(constructorPW, otherCB.getConstructorBuffer());
330     appendIfNecessary(serviceMethodPW, otherCB.getServiceMethodBuffer());
331
332     ObjInfo oldRet = getFinalServiceMethodStatement();
333
334     if (oldRet != null && oldRet.isExecutable())
335     {
336       addServiceMethodStatement(oldRet.objName + ";");
337     }
338
339     setFinalServiceMethodStatement(otherCB.getFinalServiceMethodStatement());
340   }
341   public void popSymbolTable()
342   {
343     symbolTableStack.pop();
344     symbolTable = (Hashtable JavaDoc)symbolTableStack.peek();
345   }
346   public void print(PrintWriter JavaDoc out, boolean formatOutput)
347   {
348     if (formatOutput)
349     {
350       new CodeFormatter().formatCode(new StringReader JavaDoc(toString()), out);
351     }
352     else
353     {
354       out.print(toString());
355     }
356
357     out.flush();
358   }
359   public void pushSymbolTable()
360   {
361     symbolTable = (Hashtable JavaDoc)symbolTableStack.push(new ScriptSymbolTable(symbolTable));
362   }
363   public void putSymbol(String JavaDoc symbol, ObjInfo obj)
364   {
365     symbolTable.put(symbol, obj);
366   }
367   void putSymbolIndex(String JavaDoc prefix, Integer JavaDoc index)
368   {
369     if (parent != null)
370     {
371       parent.putSymbolIndex(prefix, index);
372     }
373     else
374     {
375       usedSymbolIndices.put(prefix, index);
376     }
377   }
378   public void setClassName(String JavaDoc className)
379   {
380     this.className = className;
381   }
382   public void setExtends(String JavaDoc extendsName)
383   {
384     this.extendsName = extendsName;
385   }
386   public void setFinalServiceMethodStatement(ObjInfo finalStatementInfo)
387   {
388     this.finalStatementInfo = finalStatementInfo;
389   }
390   public void setPackageName(String JavaDoc packageName)
391   {
392     this.packageName = packageName;
393   }
394   public void setServiceMethodName(String JavaDoc serviceMethodName)
395   {
396     this.serviceMethodName = serviceMethodName;
397   }
398   public void setServiceMethodReturnType(Class JavaDoc serviceMethodReturnType)
399   {
400     this.serviceMethodReturnType = serviceMethodReturnType;
401   }
402   public void setSymbolTable(Hashtable JavaDoc symbolTable)
403   {
404     this.symbolTable = symbolTable;
405   }
406   public boolean symbolTableIsStacked()
407   {
408     return (symbolTable instanceof ScriptSymbolTable);
409   }
410   public String JavaDoc toString()
411   {
412     StringWriter JavaDoc sw = new StringWriter JavaDoc();
413     PrintWriter JavaDoc pw = new PrintWriter JavaDoc(sw);
414     ObjInfo ret = finalStatementInfo;
415
416     if (packageName != null && !packageName.equals(""))
417     {
418       pw.println("package " + packageName + ";");
419       pw.println();
420     }
421
422     if (imports.size() > 0)
423     {
424       for (int i = 0; i < imports.size(); i++)
425       {
426         pw.println("import " + imports.elementAt(i) + ";");
427       }
428
429       pw.println();
430     }
431
432     pw.println("public class " + className +
433                (extendsName != null && !extendsName.equals("")
434                 ? " extends " + extendsName
435                 : "") +
436                (implementsVector.size() > 0
437                 ? " implements " +
438                   StringUtils.getCommaListFromVector(implementsVector)
439                 : "")
440               );
441     pw.println("{");
442
443     pw.print(getFieldBuffer().toString());
444
445     StringBuffer JavaDoc buf = getInitializerBuffer();
446
447     if (buf.length() > 0)
448     {
449       pw.println();
450       pw.println("{");
451       pw.print(buf.toString());
452       pw.println("}");
453     }
454
455     buf = getConstructorBuffer();
456
457     if (buf.length() > 0)
458     {
459       pw.println();
460       pw.println("public " + className + "(" +
461                  (constructorArguments.size() > 0
462                   ? StringUtils.getCommaListFromVector(constructorArguments)
463                   : ""
464                  ) + ")" +
465                  (constructorExceptions.size() > 0
466                   ? " throws " +
467                     StringUtils.getCommaListFromVector(constructorExceptions)
468                   : ""
469                  )
470                 );
471       pw.println("{");
472       pw.print(buf.toString());
473       pw.println("}");
474     }
475
476     buf = getServiceMethodBuffer();
477
478     if (buf.length() > 0 || ret != null)
479     {
480       pw.println();
481       pw.println("public " +
482                   StringUtils.getClassName(getServiceMethodReturnType()) + " " +
483                   serviceMethodName + "()" +
484                  (serviceMethodExceptions.size() > 0
485                   ? " throws " +
486                     StringUtils.getCommaListFromVector(serviceMethodExceptions)
487                   : ""
488                  )
489                 );
490       pw.println("{");
491
492       pw.print(buf.toString());
493
494       if (ret != null)
495       {
496         if (ret.isValueReturning())
497         {
498           pw.println();
499           pw.println("return " + ret.objName + ";");
500         }
501         else if (ret.isExecutable())
502         {
503           pw.println(ret.objName + ";");
504         }
505       }
506
507       pw.println("}");
508     }
509
510     pw.print(getMethodBuffer().toString());
511
512     pw.println("}");
513
514     pw.flush();
515
516     return sw.toString();
517   }
518 }
519
Popular Tags