KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > taskdefs > optional > sun > appserv > SunJspc


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 /*
25  * SunJspc.java
26  *
27  * Created on May 22, 2002, 8:46 PM
28  */

29
30 package org.apache.tools.ant.taskdefs.optional.sun.appserv;
31
32 import org.apache.tools.ant.Project;
33 import org.apache.tools.ant.taskdefs.MatchingTask;
34 import org.apache.tools.ant.types.Reference;
35 import org.apache.tools.ant.DirectoryScanner;
36 import org.apache.tools.ant.BuildException;
37 import org.apache.tools.ant.types.Path;
38 import org.apache.tools.ant.taskdefs.Java;
39
40 import java.io.File JavaDoc;
41 import java.util.StringTokenizer JavaDoc;
42 import java.util.ArrayList JavaDoc;
43
44 /** Ant task to run the jsp compiler.for SunONE Application Server
45  * <p> This task takes the given jsp files and compiles them into java
46  * files. It is then up to the user to compile the java files into classes.
47  *
48  * <p> The task requires the srcdir and destdir attributes to be
49  * set. This Task is a MatchingTask, so the files to be compiled can be
50  * specified using includes/excludes attributes or nested include/exclude
51  * elements. Optional attributes are verbose (set the verbosity level passed
52  * to jasper), package (name of the destination package for generated java
53  * classes and classpath (the classpath to use when running the jsp
54  * compiler).
55  *
56  * <p><h4>Notes</h4>
57  * <p>The includes directive is necessary in the ant targets
58  * <p>The taskdef can contain in its classpath the path to the SunJspc compiled file
59  *
60  * <p><h4>Usage</h4>
61  * <pre>
62  * &lt;taskdef
63  * name="sun-appserv-jspc"
64  * classname="org.apache.tools.ant.taskdefs.optional.sunone.SunJspc"
65  * classpath=&lt;classpath to the compiled file>/&gt;
66  *
67  * &lt;sun-appserv-jspc srcdir="${basedir}/src/war"
68  * destdir="${basedir}/gensrc"
69  * package="com.i3sp.jsp"
70  * verbose="9"&gt;
71  * &lt;include name="**\/*.jsp" /&gt;
72  * &lt;/s1jspc&gt;
73  *
74  *&lt;sun-appserv-jspc
75  * destdir="${basedir}/gensrc"
76  * verbose="9"&gt;
77  * webapp=${basedir}
78  * &lt;/sun-apserv-jspc&gt;
79  * </pre>
80  *
81  * @author <a HREF="mailto:irfan@sun.com">Irfan Ahmed</a>
82  * <p> Large Amount of cutting and pasting from the Javac task...
83  * @since SunONE Application Server 7 SE
84  */

85
86 public class SunJspc extends MatchingTask
87 {
88     private File JavaDoc destDir = null;
89     private File JavaDoc srcDir;
90     private String JavaDoc packageName;
91     private String JavaDoc verboseLevel;
92     private File JavaDoc uriRoot;
93     private File JavaDoc uriBase;
94     private Path classPath;
95     private int compileListLength;
96     private boolean failOnError = true;
97     private File JavaDoc webAppBaseDir;
98     
99     private File JavaDoc sunoneHome;
100     private File JavaDoc asinstalldir;
101
102     /** Appserver runtime Libraries, expressed relative to the installation directory */
103     private static final String JavaDoc[] CLASSPATH_ELEMENTS = {
104                             "lib",
105                             "lib/appserv-rt.jar",
106                             "lib/javaee.jar",
107                             "lib/appserv-ext.jar"};
108     
109     LocalStringsManager lsm = new LocalStringsManager();
110
111     public void setSunonehome(File JavaDoc sunoneHome)
112     {
113         final String JavaDoc msg = lsm.getString("DeprecatedAttribute", new Object JavaDoc[] {"sunonehome",
114          "asinstalldir"});
115         log(msg, Project.MSG_WARN);
116         this.asinstalldir = sunoneHome;
117     }
118
119     
120     /**
121      * Specifies the installation directory for the Sun ONE Application Server
122      * 8. This may be used if the application server is installed on the
123      * local machine.
124      *
125      * @param asinstalldir The home directory for the user's app server
126      * installation.
127      */

128     public void setAsinstalldir(File JavaDoc asinstalldir) {
129         this.asinstalldir = asinstalldir;
130     }
131
132         
133     /**
134      * Returns the asinstalldir attribute specify by in the build script.
135      * If asinstalldir hasn't been explicitly set (using
136      * the <code>setAsinstalldir</code> method), the value stored in the <code>
137      * sunone.home</code> property will be returned.
138      *
139      * @return File representing the app server installation directory. Returns
140      * <code>null</code> if the installation directory hasn't been
141      * explictly set and the <code>sunone.home</code> property isn't set.
142      * @throws ClassNotFoundException if asinstalldir is an invalid directory
143      */

144     protected File JavaDoc getAsinstalldir() throws ClassNotFoundException JavaDoc {
145         if (asinstalldir == null) {
146             String JavaDoc home = getProject().getProperty("asinstall.dir");
147             if (home != null) {
148                 asinstalldir = new File JavaDoc(home);
149             }
150             else {
151                 home = getProject().getProperty("sunone.home");
152                 if (home != null)
153                 {
154                     final String JavaDoc msg = lsm.getString("DeprecatedProperty", new Object JavaDoc[] {"sunone.home", "asinstall.dir"});
155                     log(msg, Project.MSG_WARN);
156                     asinstalldir = new File JavaDoc(home);
157                 }
158                 
159             }
160         }
161         if (asinstalldir!=null) verifyAsinstalldir(asinstalldir);
162         return asinstalldir;
163     }
164
165
166     /**
167      * verify if asinsatlldir attribute is valid.
168      * asinstalldir must be a valid directory and must contain the config directory.
169      *
170      * @return true if asinstalldir is valid
171      * @throws ClassNotFoundException if asinstalldir is an invalid directory
172      */

173     private boolean verifyAsinstalldir(File JavaDoc home) throws ClassNotFoundException JavaDoc{
174         if (home!= null && home.isDirectory()) {
175             if ( new File JavaDoc(home, "config").isDirectory() ) {
176                 return true;
177             }
178         }
179         throw new ClassNotFoundException JavaDoc("ClassCouldNotBeFound");
180     }
181     
182     
183     public void setDestdir(File JavaDoc dest)
184     {
185         destDir = dest;
186     }
187     
188     public File JavaDoc getDestdir()
189     {
190         return destDir;
191     }
192     
193     public void setSrcdir(File JavaDoc src)
194     {
195         srcDir = src;
196     }
197     
198     public File JavaDoc getSrcdir()
199     {
200         return srcDir;
201     }
202     
203     public void setPackage(String JavaDoc name)
204     {
205         packageName = name;
206     }
207     
208     public String JavaDoc getPackage()
209     {
210         return packageName;
211     }
212     
213     public void setVerbose(String JavaDoc level)
214     {
215         verboseLevel = level;
216     }
217     
218     public String JavaDoc getVerbose()
219     {
220         return verboseLevel;
221     }
222     
223     public void setFailonerror(boolean fail)
224     {
225         failOnError = fail;
226     }
227     
228     public boolean getFailonerror()
229     {
230         return failOnError;
231     }
232     
233     public void setUribase(File JavaDoc base)
234     {
235         uriBase = base;
236     }
237     
238     public File JavaDoc getUribase()
239     {
240         if(uriBase!=null)
241             return uriBase;
242         return uriRoot;
243     }
244     
245     public void setUriroot(File JavaDoc root)
246     {
247         uriRoot = root;
248     }
249     
250     public File JavaDoc getUriroot()
251     {
252         return uriRoot;
253     }
254     
255     public void setClasspath(Path cp)
256     {
257         if(classPath == null)
258             classPath = cp;
259         else
260             classPath.append(cp);
261     }
262     
263     /** Nested ClassPath Element */
264     public Path createClasspath()
265     {
266         if(classPath==null)
267             classPath = new Path(project);
268         return classPath.createPath();
269     }
270     
271     /** Class Path Reference */
272     public void setClasspathref(Reference ref)
273     {
274         createClasspath().setRefid(ref);
275     }
276     
277     public void setWebapp(File JavaDoc baseDir)
278     {
279         webAppBaseDir = baseDir;
280     }
281     
282     public File JavaDoc getWebapp()
283     {
284         return webAppBaseDir;
285     }
286
287     
288     public void execute()throws BuildException
289     {
290         
291         CheckForMutuallyExclusiveAttribute();
292         
293         if(webAppBaseDir==null)
294         {
295             if(srcDir==null)
296                 throw new BuildException(lsm.getString("SourceDirectoryProviced"), location);
297             if(!srcDir.exists() || !srcDir.isDirectory())
298                 throw new BuildException(lsm.getString("SourceDirectoryDoesNotExist",
299                                                        new Object JavaDoc[] {srcDir.getAbsolutePath()}),
300                                          location);
301         }
302         else
303         {
304             if(!webAppBaseDir.exists() || !webAppBaseDir.isDirectory())
305                 throw new BuildException(lsm.getString("WebAppDirectoryDoesNotExist",
306                                                        new Object JavaDoc [] {webAppBaseDir.getAbsolutePath()}),
307                                          location);
308         }
309             
310         if(destDir!=null)
311         {
312             if(!destDir.exists())
313                 throw new BuildException(lsm.getString("DestinationDirectoryDoesNotExist",
314                                                        new Object JavaDoc[] {destDir}));
315             if(!destDir.isDirectory())
316                 throw new BuildException(lsm.getString("InvalidDestinationDirectory",
317                                                        new Object JavaDoc[] {destDir}));
318         }
319         else
320         {
321             throw new BuildException(lsm.getString("DestinationDirectoryNoProvided"));
322         }
323         
324         
325         String JavaDoc args[] = getCommandString();
326         if(srcDir!=null)
327             log(lsm.getString("PreCompilation", new Object JavaDoc[] {String.valueOf(compileListLength),
328                                                               destDir.getAbsolutePath()}));
329         if(!doCompilation(args))
330             throw new BuildException(lsm.getString("CompilationFailed"));
331     }
332
333
334         /**
335          * This private class checks for any mutually exclusive attributes.
336          * If mutually exclusive attributes that are specified, then a
337          * BuildException is thrown.
338          */

339     private void CheckForMutuallyExclusiveAttribute() throws BuildException
340     {
341         if(webAppBaseDir!=null && srcDir!=null) {
342             final String JavaDoc msg = lsm.getString("MutuallyExclusivelyAttribute",
343                                              new Object JavaDoc[] {"srcdir",
344                                                            "webapp"});
345             throw new BuildException(msg, getLocation());
346         }
347     }
348
349     
350     protected boolean doCompilation(String JavaDoc args[])
351     {
352         try
353         {
354             Java java = (Java)project.createTask("java");
355             java.setClasspath(constructPath());
356             java.setClassname("org.apache.jasper.JspC");
357             for(int i=0;i<args.length;i++)
358             {
359                 java.createArg().setValue(args[i]);
360             }
361             java.setFailonerror(failOnError);
362             java.setFork(true);
363             log("Executing Jasper Compiler");
364             int returnCode = java.executeJava();
365             if(returnCode == 1)
366             {
367                 log(lsm.getString("SetVerbose"));
368                 return false;
369             }
370             return true;
371         }
372         catch(Exception JavaDoc ex)
373         {
374             log(lsm.getString("ExceptionMessage", new Object JavaDoc[] {ex.toString()}));
375             return false;
376         }
377     }
378     
379     protected String JavaDoc[] getCommandString()
380     {
381         ArrayList JavaDoc commandList = new ArrayList JavaDoc();
382         
383         commandList.add("-d");
384         commandList.add(destDir.getAbsolutePath());
385         
386         if(packageName!=null && packageName.length()>0)
387         {
388             commandList.add("-p");
389             commandList.add(packageName);
390         }
391         
392         if(verboseLevel!=null)
393             commandList.add("-v".concat(verboseLevel));
394         
395         if(uriRoot!=null && uriRoot.exists())
396         {
397             commandList.add("-uriroot");
398             commandList.add(uriRoot.getAbsolutePath());
399         }
400         
401         if(uriBase!=null && uriBase.exists())
402         {
403             commandList.add("-uribase");
404             commandList.add(uriBase.getAbsolutePath());
405         }
406         else if(uriRoot!=null && uriRoot.exists())
407         {
408             commandList.add("-uribase");
409             commandList.add(uriRoot.getAbsolutePath());
410         }
411
412         // START PWC 6386258
413
commandList.add("-dtds");
414         commandList.add("/dtds/");
415
416         commandList.add("-schemas");
417         commandList.add("/schemas/");
418         // END PWC 6386258
419

420         commandList.add("-die1");
421         if(webAppBaseDir!=null)
422         {
423             commandList.add("-webapp");
424             commandList.add(webAppBaseDir.getAbsolutePath());
425         }
426         else
427         {
428             DirectoryScanner ds = super.getDirectoryScanner(srcDir);
429             String JavaDoc files[] = ds.getIncludedFiles();
430             compileListLength = files.length;
431             for(int i=0;i<files.length;i++)
432             {
433                 File JavaDoc tempFile = new File JavaDoc(srcDir,files[i]);
434                 commandList.add(tempFile.getAbsolutePath());
435             }
436         }
437
438         String JavaDoc args[] = (String JavaDoc[])commandList.toArray(new String JavaDoc[commandList.size()]);
439         return args;
440     }
441     
442     private Path constructPath() throws ClassNotFoundException JavaDoc
443     {
444         StringBuffer JavaDoc classPathBuffer = new StringBuffer JavaDoc();
445         if(getAsinstalldir()!=null)
446         {
447             for(int i=0;i<CLASSPATH_ELEMENTS.length;i++)
448             {
449                 classPathBuffer.append((new File JavaDoc(getAsinstalldir(),CLASSPATH_ELEMENTS[i])).getPath());
450                 classPathBuffer.append(":");
451             }
452         }
453         if(classPath!=null)
454         {
455             classPathBuffer.append(classPath);
456             classPathBuffer.append(":");
457         }
458         classPathBuffer.append(Path.systemClasspath);
459         return new Path(getProject(),classPathBuffer.toString());
460     }
461 }
462
Popular Tags