View Javadoc

1   package joeq.Main;
2   
3   import java.io.File;
4   import java.io.FileNotFoundException;
5   import java.io.FileOutputStream;
6   import java.io.PrintStream;
7   import java.lang.reflect.Method;
8   import java.lang.reflect.Modifier;
9   import java.util.Collection;
10  import java.util.Iterator;
11  import java.util.LinkedList;
12  import javax.xml.parsers.DocumentBuilder;
13  import javax.xml.parsers.DocumentBuilderFactory;
14  import jwutil.util.Assert;
15  import org.w3c.dom.Document;
16  import org.w3c.dom.Element;
17  import org.w3c.dom.Node;
18  import org.w3c.dom.NodeList;
19  import org.xml.sax.SAXException;
20  import org.xml.sax.SAXParseException;
21  
22  /***
23   * A command-line utility to generate an invocation stub from a web.xml file. 
24   * 
25   * @author V. Benjamin Livshits
26   * @version $Id: GenerateWebRoots.java 2285 2005-06-05 05:31:12Z joewhaley $
27   */
28  public class GenerateWebRoots {
29      private static boolean TRACE = true;
30      private static PrintStream out = System.out;
31      private static final String TAGLIB_BASE = "cls/webapp";
32  
33      public static void main(String[] args) throws FileNotFoundException {
34          String inputFile  = null;
35          String outputFile = null; //"InvokeServlets.java";
36          
37          for(int i = 0; i < args.length; i++){
38              String arg = args[i];
39              
40              if(inputFile == null){
41                  inputFile = arg;
42              }else
43              if(arg.equals("-o")){
44                  outputFile = args[++i];
45              }else
46              if(arg.equals("-v")){
47                  TRACE = true;
48              }
49          }
50          if(inputFile == null){
51              usage(args[0]);
52              System.exit(1);
53          }
54          Document doc            = parseFile(inputFile);
55          
56          // get the interesting tags
57          Collection servlets     = findMatches(doc, "servlet-class");
58          Collection filters      = findMatches(doc, "filter-class");
59          Collection listeners    = findMatches(doc, "listener-class");
60          Collection taglibs      = findMatches(doc, "taglib-location");
61          
62          out = (outputFile != null) ? 
63              new PrintStream(new FileOutputStream(outputFile)) : 
64              System.out;
65          
66          printPreamble();
67          printServlets(servlets);
68          printFilters(filters);
69          printListeners(listeners);
70          printTags(taglibs);
71          printPostamble();       
72      }
73  
74      private static void usage(String prog) {
75          System.err.println("Usage:");
76          System.err.println("\t" + prog + "input-file [-v] [-o output-file]");
77      }
78  
79      private static void printPostamble() {
80          out.println("}\n");        
81      }
82  
83      private static void printTags(Collection taglibs) {
84          out.println("\tpublic static void processTags() {");
85          for(Iterator iter = taglibs.iterator(); iter.hasNext();){
86              String taglib = (String) iter.next();
87              out.println("\t\t// Processing taglib " + taglib + ":");
88              processTaglib(taglib);
89          }
90          out.println("\t}\n");        
91      }
92      
93      static void processTaglib(String taglib) {
94          String taglibFileName = TAGLIB_BASE + File.separator + taglib;
95          Document doc = parseFile(taglibFileName);
96          Collection tags = findMatches(doc, "tag-class");
97          int count = 0;
98          for(Iterator iter = tags.iterator(); iter.hasNext();){
99              String tag = (String) iter.next();
100             
101             out.println("\t\t// " + ++count + ". " + tag);
102             out.println("\t\ttry {");
103             out.println("\t\t\tTagSupport tag = new " + tag + "();");
104             out.println("\t\t\ttag.doStartTag();");
105             out.println("\t\t} catch (JspException e){e.printStackTrace();}");
106         }
107     }
108 
109     private static void printServlets(Collection servletNames) {
110         out.println("\tpublic static void processServlets() {");
111         int count = 0;
112 
113         for(Iterator iter = servletNames.iterator(); iter.hasNext();){
114             String servlet = (String) iter.next();
115             
116             out.println("\t\t// " + ++count + ". " + servlet);
117             out.println("\t\ttry {");
118             out.println("\t\t\tHttpServletRequest request   = new MyHttpServletRequest();");
119             out.println("\t\t\tHttpServletResponse response = new MyHttpServletResponse();" + "\n");
120             out.println("\t\t\tHttpServlet servlet = new " + servlet + "();");
121             
122             if(hasMethod(servlet, "init", true)){
123                 out.println("\t\t\tservlet.init();");    
124             }
125             
126             out.println("\t\t\tservlet.service(request, response);");
127             out.println("\t\t} catch (Exception e) {");
128             out.println("\t\t\te.printStackTrace();");
129             out.println("\t\t}\n");
130         }        
131         out.println("\t}\n\n");
132     }
133 
134     static boolean hasMethod(String className, String methodName, boolean publicOnly) {
135         Class c;
136         try {
137             c = Class.forName(className);
138         } catch (ClassNotFoundException e) {
139             e.printStackTrace();
140             return false;
141         }
142         Method[] methods = c.getDeclaredMethods();
143         for(int i = 0; i < methods.length; i++){
144             Method method = methods[i];
145             
146             if(method.getName().equals(methodName)){
147                 if( publicOnly && (method.getModifiers() | Modifier.PUBLIC) != 0){
148                     return true;
149                 }
150             }
151         }
152         
153         return false;
154     }
155 
156     private static void printFilters(Collection filterNames) {
157         out.println("\tpublic static void processFilters() {");
158         int count = 0;
159         out.println("\t\tFilterChain chain = new FilterChain(){");
160         out.println("\t\t    public void doFilter(ServletRequest req, ServletResponse resp){");
161         out.println("\t\t");
162         out.println("\t\t    }");
163         out.println("\t\t};\n");
164 
165         for(Iterator iter = filterNames.iterator(); iter.hasNext();){
166             String filter = (String) iter.next();
167             
168             out.println("\t\t// " + ++count + ". " + filter);
169             out.println("\t\ttry {");
170             out.println("\t\t\tHttpServletRequest request   = new MyHttpServletRequest();");
171             out.println("\t\t\tHttpServletResponse response = new MyHttpServletResponse();" + "\n");
172             out.println("\t\t\tFilter filter = new " + filter + "();");
173             out.println("\t\t\t//filter.init(...);");
174             out.println("\t\t\tfilter.doFilter(request, response, chain);");
175             out.println("\t\t\t//filter.destroy();");
176             out.println("\t\t} catch (Exception e) {");
177             out.println("\t\t\te.printStackTrace();");
178             out.println("\t\t}\n");
179         }        
180         out.println("\t}\n\n");
181     }
182     
183     private static void printListeners(Collection listenerNames) {
184         out.println("\tpublic static void processListeners() {");
185         int count = 0;
186 
187         for(Iterator iter = listenerNames.iterator(); iter.hasNext();){
188             String listener = (String) iter.next();
189             try {
190                 Class c = Class.forName(listener);
191                 Class httpSessionListener = Class.forName("javax.servlet.http.HttpSessionListener");
192                 Class servletContextListener = Class.forName("javax.servlet.ServletContextListener");
193                 if(httpSessionListener.isAssignableFrom(c)){
194                     out.println("\t\t// " + ++count + ". " + listener);
195                     out.println("\t\ttry {");
196                     out.println("\t\t\tHttpSessionListener listener = new " + listener + "();");
197                     out.println("\t\t\tlistener.sessionCreated(null);");
198                     out.println("\t\t\tlistener.sessionDestroyed(null);");
199                     out.println("\t\t} catch (Exception e) {");
200                     out.println("\t\t\te.printStackTrace();");
201                     out.println("\t\t}\n");        
202                 }else
203                 if(servletContextListener.isAssignableFrom(c)){
204                     out.println("\t\t// " + ++count + ". " + listener);
205                     out.println("\t\ttry {");
206                     out.println("\t\t\tServletContextListener listener = new " + listener + "();");
207                     out.println("\t\t\tlistener.contextInitialized(null);");
208                     out.println("\t\t\tlistener.contextDestroyed(null);");
209                     out.println("\t\t} catch (Exception e) {");
210                     out.println("\t\t\te.printStackTrace();");
211                     out.println("\t\t}\n");        
212                 }
213             } catch (ClassNotFoundException e) {
214                 e.printStackTrace();
215             }
216         }
217         out.println("\t}\n\n");
218     }
219     
220     private static void printPreamble() {
221         out.println("/* Automatically generated by GenerateWebRoots */\n");
222         out.println("import javax.servlet.http.HttpServletRequest;");
223         out.println("import javax.servlet.http.HttpServletResponse;");
224         out.println("import javax.servlet.ServletRequest;");
225         out.println("import javax.servlet.ServletResponse;");        
226         out.println("import javax.servlet.http.HttpServlet;");
227         out.println("import javax.servlet.ServletContextListener;");
228         out.println("import javax.servlet.http.HttpSessionListener;");
229         out.println("import javax.servlet.Filter;");
230         out.println("import javax.servlet.FilterChain;");
231         out.println("import javax.servlet.jsp.JspException;");
232         out.println("import javax.servlet.jsp.tagext.TagSupport;");
233         out.println("import MyMockLib.MyHttpServletRequest;");
234         out.println("import MyMockLib.MyHttpServletResponse;");
235         out.println("import java.io.IOException;\n");
236         
237         out.println("class InvokeServlets {");
238         out.println("\tpublic static void main(String[] args) throws IOException {");
239         out.println("\t\tprocessServlets();");
240         out.println("\t\tprocessFilters();");
241         out.println("\t\tprocessTags();");
242         out.println("\t}\n");
243     }
244 
245     public static Document parseFile(String fileName) {
246         try {
247             DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
248             DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
249             Document doc = docBuilder.parse(new File(fileName));
250 
251             // normalize text representation
252             doc.getDocumentElement().normalize ();
253             return doc;
254         } catch (SAXParseException err) {
255             System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
256             System.out.println(" " + err.getMessage ());
257             return null;
258         } catch (SAXException e) {
259             Exception x = e.getException ();
260             ((x == null) ? e : x).printStackTrace ();
261             return null;
262         } catch (Throwable t) {
263             t.printStackTrace ();
264             return null;  
265         }
266     }
267 
268     public static Collection findMatches(Document doc, String tagName){
269         NodeList servlets = doc.getElementsByTagName(tagName);
270         if(TRACE) System.out.println("Total no of sinks: " + servlets.getLength());
271         Collection result = new LinkedList();
272     
273         for(int s=0; s < servlets.getLength() ; s++){
274             Element servletNode = (Element) servlets.item(s);
275             if(true || servletNode.getNodeType() == Node.TEXT_NODE){                    
276                 Assert._assert(servletNode != null);
277                 String className = servletNode.getChildNodes().item(0).getNodeValue().trim();
278                 
279                 if(TRACE) System.out.println("Found " + tagName + ": " + className);
280                 result.add(className);
281             }//end of if clause
282         }
283         
284         return result;
285     }
286 }