KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > taskdefs > optional > jsp > WLJspc


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */

18 package org.apache.tools.ant.taskdefs.optional.jsp;
19
20 //apache/ant imports
21
import java.io.File JavaDoc;
22 import java.util.Date JavaDoc;
23 import java.util.StringTokenizer JavaDoc;
24 import java.util.Vector JavaDoc;
25 import org.apache.tools.ant.BuildException;
26 import org.apache.tools.ant.DirectoryScanner;
27 import org.apache.tools.ant.Project;
28 import org.apache.tools.ant.taskdefs.Java;
29 import org.apache.tools.ant.taskdefs.MatchingTask;
30 import org.apache.tools.ant.types.Path;
31
32 /**
33  * Precompiles JSP's using WebLogic's JSP compiler (weblogic.jspc).
34  *
35  * Tested only on Weblogic 4.5.1 - NT4.0 and Solaris 5.7
36  *
37  * required attributes
38  * src : root of source tree for JSP, ie, the document root for your weblogic server
39  * dest : root of destination directory, what you have set as
40  * WorkingDir in the weblogic properties
41  * package : start package name under which your JSP's would be compiled
42  *
43  * other attributes
44  * classpath
45  *
46  * A classpath should be set which contains the weblogic classes as well as all
47  * application classes referenced by the JSP. The system classpath is also
48  * appended when the jspc is called, so you may choose to put everything in
49  * the classpath while calling Ant. However, since presumably the JSP's will
50  * reference classes being build by Ant, it would be better to explicitly add
51  * the classpath in the task
52  *
53  * The task checks timestamps on the JSP's and the generated classes, and compiles
54  * only those files that have changed.
55  *
56  * It follows the weblogic naming convention of putting classes in
57  * <b> _dirName/_fileName.class for dirname/fileName.jsp </b>
58  *
59  * Limitation: It compiles the files thru the Classic compiler only.
60  * Limitation: Since it is my experience that weblogic jspc throws out of
61  * memory error on being given too many files at one go, it is
62  * called multiple times with one jsp file each.
63  *
64  * <pre>
65  * example
66  * &lt;target name="jspcompile" depends="compile"&gt;
67  * &lt;wljspc SRC="c:\\weblogic\\myserver\\public_html"
68  * dest="c:\\weblogic\\myserver\\serverclasses" package="myapp.jsp"&gt;
69  * &lt;classpath&gt;
70  * &lt;pathelement location="${weblogic.classpath}" /&gt;
71  * &lt;pathelement path="${compile.dest}" /&gt;
72  * &lt;/classpath&gt;
73  *
74  * &lt;/wljspc&gt;
75  * &lt;/target&gt;
76  * </pre>
77  *
78  */

79
80 public class WLJspc extends MatchingTask {
81     //TODO Test on other versions of weblogic
82
//TODO add more attributes to the task, to take care of all jspc options
83
//TODO Test on Unix
84

85     /** root of compiled files tree */
86     private File JavaDoc destinationDirectory;
87
88     /** root of source files tree */
89     private File JavaDoc sourceDirectory;
90
91     /** package under which resultant classes will reside */
92     private String JavaDoc destinationPackage;
93
94     /** classpath used to compile the jsp files. */
95     private Path compileClasspath;
96
97     //private String compilerPath; //fully qualified name for the compiler executable
98

99     private String JavaDoc pathToPackage = "";
100     private Vector JavaDoc filesToDo = new Vector JavaDoc();
101
102     /**
103      * Run the task.
104      * @throws BuildException if there is an error.
105      */

106     public void execute() throws BuildException {
107         if (!destinationDirectory.isDirectory()) {
108             throw new BuildException("destination directory "
109                 + destinationDirectory.getPath() + " is not valid");
110         }
111
112         if (!sourceDirectory.isDirectory()) {
113             throw new BuildException("src directory "
114                 + sourceDirectory.getPath() + " is not valid");
115         }
116
117         if (destinationPackage == null) {
118             throw new BuildException("package attribute must be present.",
119                                      getLocation());
120         }
121
122
123         pathToPackage
124             = this.destinationPackage.replace('.', File.separatorChar);
125         // get all the files in the sourceDirectory
126
DirectoryScanner ds = super.getDirectoryScanner(sourceDirectory);
127
128         //use the systemclasspath as well, to include the ant jar
129
if (compileClasspath == null) {
130             compileClasspath = new Path(getProject());
131         }
132
133         compileClasspath = compileClasspath.concatSystemClasspath();
134         String JavaDoc[] files = ds.getIncludedFiles();
135
136         //Weblogic.jspc calls System.exit() ... have to fork
137
// Therefore, takes loads of time
138
// Can pass directories at a time (*.jsp) but easily runs out of
139
// memory on hefty dirs (even on a Sun)
140
Java helperTask = new Java(this);
141         helperTask.setFork(true);
142         helperTask.setClassname("weblogic.jspc");
143         helperTask.setTaskName(getTaskName());
144         String JavaDoc[] args = new String JavaDoc[12];
145
146         File JavaDoc jspFile = null;
147         String JavaDoc parents = "";
148         int j = 0;
149         //XXX this array stuff is a remnant of prev trials.. gotta remove.
150
args[j++] = "-d";
151         args[j++] = destinationDirectory.getAbsolutePath().trim();
152         args[j++] = "-docroot";
153         args[j++] = sourceDirectory.getAbsolutePath().trim();
154         args[j++] = "-keepgenerated"; //TODO: Parameterise ??
155
//Call compiler as class... dont want to fork again
156
//Use classic compiler -- can be parameterised?
157
args[j++] = "-compilerclass";
158         args[j++] = "sun.tools.javac.Main";
159         //Weblogic jspc does not seem to work unless u explicitly set this...
160
// Does not take the classpath from the env....
161
// Am i missing something about the Java task??
162
args[j++] = "-classpath";
163         args[j++] = compileClasspath.toString();
164
165         this.scanDir(files);
166         log("Compiling " + filesToDo.size() + " JSP files");
167
168         for (int i = 0; i < filesToDo.size(); i++) {
169             //XXX
170
// All this to get package according to weblogic standards
171
// Can be written better... this is too hacky!
172
// Careful.. similar code in scanDir , but slightly different!!
173
String JavaDoc filename = (String JavaDoc) filesToDo.elementAt(i);
174             jspFile = new File JavaDoc(filename);
175             args[j] = "-package";
176             parents = jspFile.getParent();
177             if ((parents != null) && (!("").equals(parents))) {
178                 parents = this.replaceString(parents, File.separator, "_.");
179                 args[j + 1] = destinationPackage + "." + "_" + parents;
180             } else {
181                 args[j + 1] = destinationPackage;
182             }
183
184
185             args[j + 2] = sourceDirectory + File.separator + filename;
186             helperTask.clearArgs();
187
188             for (int x = 0; x < j + 3; x++) {
189                 helperTask.createArg().setValue(args[x]);
190             }
191
192             helperTask.setClasspath(compileClasspath);
193             if (helperTask.executeJava() != 0) {
194                 log(filename + " failed to compile", Project.MSG_WARN);
195             }
196         }
197     }
198
199
200
201     /**
202      * Set the classpath to be used for this compilation.
203      * @param classpath the classpath to use.
204      */

205     public void setClasspath(Path classpath) {
206         if (compileClasspath == null) {
207             compileClasspath = classpath;
208         } else {
209             compileClasspath.append(classpath);
210         }
211     }
212
213     /**
214      * Maybe creates a nested classpath element.
215      * @return a path to be configured.
216      */

217     public Path createClasspath() {
218         if (compileClasspath == null) {
219             compileClasspath = new Path(getProject());
220         }
221         return compileClasspath;
222     }
223
224     /**
225      * Set the directory containing the source jsp's
226      *
227      *
228      * @param dirName the directory containg the source jsp's
229      */

230     public void setSrc(File JavaDoc dirName) {
231
232         sourceDirectory = dirName;
233     }
234
235      /**
236      * Set the directory containing the source jsp's
237      *
238      *
239      * @param dirName the directory containg the source jsp's
240      */

241     public void setDest(File JavaDoc dirName) {
242
243         destinationDirectory = dirName;
244     }
245
246     /**
247      * Set the package under which the compiled classes go
248      *
249      * @param packageName the package name for the clases
250      */

251     public void setPackage(String JavaDoc packageName) {
252
253         destinationPackage = packageName;
254     }
255
256     /**
257      * Scan the array of files and add the jsp
258      * files that need to be compiled to the filesToDo field.
259      * @param files the files to scan.
260      */

261     protected void scanDir(String JavaDoc[] files) {
262
263         long now = (new Date JavaDoc()).getTime();
264         File JavaDoc jspFile = null;
265         String JavaDoc parents = null;
266         String JavaDoc pack = "";
267         for (int i = 0; i < files.length; i++) {
268             File JavaDoc srcFile = new File JavaDoc(this.sourceDirectory, files[i]);
269             //XXX
270
// All this to convert source to destination directory according
271
// to weblogic standards Can be written better... this is too hacky!
272
jspFile = new File JavaDoc(files[i]);
273             parents = jspFile.getParent();
274
275             if ((parents != null) && (!("").equals(parents))) {
276                 parents = this.replaceString(parents, File.separator, "_/");
277                 pack = pathToPackage + File.separator + "_" + parents;
278             } else {
279                 pack = pathToPackage;
280             }
281
282             String JavaDoc filePath = pack + File.separator + "_";
283             int startingIndex = files[i].lastIndexOf(File.separator) != -1
284                     ? files[i].lastIndexOf(File.separator) + 1 : 0;
285             int endingIndex = files[i].indexOf(".jsp");
286             if (endingIndex == -1) {
287                 log("Skipping " + files[i] + ". Not a JSP",
288                     Project.MSG_VERBOSE);
289                 continue;
290             }
291
292             filePath += files[i].substring(startingIndex, endingIndex);
293             filePath += ".class";
294             File JavaDoc classFile = new File JavaDoc(this.destinationDirectory, filePath);
295
296             if (srcFile.lastModified() > now) {
297                 log("Warning: file modified in the future: "
298                     + files[i], Project.MSG_WARN);
299             }
300             if (srcFile.lastModified() > classFile.lastModified()) {
301                 filesToDo.addElement(files[i]);
302                 log("Recompiling File " + files[i], Project.MSG_VERBOSE);
303             }
304         }
305     }
306
307
308     /**
309      * Replace occurances of a string with a replacement string.
310      * @param inpString the string to convert.
311      * @param escapeChars the string to replace.
312      * @param replaceChars the string to place.
313      * @return the converted string.
314      */

315     protected String JavaDoc replaceString(String JavaDoc inpString, String JavaDoc escapeChars,
316                                    String JavaDoc replaceChars) {
317         String JavaDoc localString = "";
318         int numTokens = 0;
319         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(inpString, escapeChars, true);
320         numTokens = st.countTokens();
321         for (int i = 0; i < numTokens; i++) {
322             String JavaDoc test = st.nextToken();
323             test = (test.equals(escapeChars) ? replaceChars : test);
324             localString += test;
325         }
326         return localString;
327     }
328 }
329
Popular Tags