Debian Codegraph @

src/main/java/net/sf/antcontrib/design/VerifyDesignDelegate.java

raw symbols SCIP
1 /*
2 * Copyright (c) 2004-2005 Ant-Contrib project. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package net.sf.antcontrib.design;
18
19 import java.io.File;
20 import java.io.FileInputStream;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.util.Enumeration;
24 import java.util.HashSet;
25 import java.util.Vector;
26 import java.util.jar.JarFile;
27 import java.util.zip.ZipEntry;
28
29 import org.apache.bcel.Constants;
30 import org.apache.bcel.classfile.ClassFormatException;
31 import org.apache.bcel.classfile.ClassParser;
32 import org.apache.bcel.classfile.Constant;
33 import org.apache.bcel.classfile.ConstantClass;
34 import org.apache.bcel.classfile.ConstantPool;
35 import org.apache.bcel.classfile.ConstantUtf8;
36 import org.apache.bcel.classfile.DescendingVisitor;
37 import org.apache.bcel.classfile.JavaClass;
38 import org.apache.bcel.classfile.Utility;
39 import org.apache.tools.ant.BuildException;
40 import org.apache.tools.ant.DirectoryScanner;
41 import org.apache.tools.ant.Project;
42 import org.apache.tools.ant.Task;
43 import org.apache.tools.ant.types.FileSet;
44 import org.apache.tools.ant.types.Path;
45 import org.apache.tools.ant.types.PatternSet;
46 import org.apache.tools.ant.util.JAXPUtils;
47 import org.xml.sax.InputSource;
48 import org.xml.sax.SAXException;
49 import org.xml.sax.SAXParseException;
50 import org.xml.sax.XMLReader;
51
52 /**
53 *
54 *
55 *
56 * @author dhiller
57 *
58 */
59
60 public class VerifyDesignDelegate implements Log {
61
62 private File designFile;
63 private Vector paths = new Vector();
64 private boolean isCircularDesign = false;
65 private boolean deleteFiles = false;
66 private boolean fillInBuildException = false;
67 private boolean needDeclarationsDefault = true;
68 private boolean needDependsDefault = true;
69
70 private Task task;
71 private Design design;
72 private HashSet primitives = new HashSet();
73 private Vector designErrors = new Vector();
74 private boolean verifiedAtLeastOne = false;
75
76 public VerifyDesignDelegate(Task task) {
77 this.task = task;
78 primitives.add("B");
79 primitives.add("C");
80 primitives.add("D");
81 primitives.add("F");
82 primitives.add("I");
83 primitives.add("J");
84 primitives.add("S");
85 primitives.add("Z");
86 }
87
88 public void addConfiguredPath(Path path) {
89 // Path newPath = new Path(task.getProject());
90 // path.
91
92
93 paths.add(path);
94 }
95
96 public void setJar(File f) {
97 Path p = (Path)task.getProject().createDataType("path");
98 p.createPathElement().setLocation(f.getAbsoluteFile());
99 addConfiguredPath(p);
100 }
101
102 public void setDesign(File f) {
103 this.designFile = f;
104 }
105
106 public void setCircularDesign(boolean isCircularDesign) {
107 this.isCircularDesign = isCircularDesign;
108 }
109
110 public void setDeleteFiles(boolean deleteFiles) {
111 this.deleteFiles = deleteFiles;
112 }
113
114 public void setFillInBuildException(boolean b) {
115 fillInBuildException = b;
116 }
117
118 public void setNeedDeclarationsDefault(boolean b) {
119 needDeclarationsDefault = b;
120 }
121
122 public void setNeedDependsDefault(boolean b) {
123 needDependsDefault = b;
124 }
125
126 public void execute() {
127 if(!designFile.exists() || designFile.isDirectory())
128 throw new BuildException("design attribute in verifydesign element specified an invalid file="+designFile);
129
130 verifyJarFilesExist();
131
132 try {
133 XMLReader reader = JAXPUtils.getXMLReader();
134 DesignFileHandler ch = new DesignFileHandler(this, designFile, isCircularDesign, task.getLocation());
135 ch.setNeedDeclarationsDefault(needDeclarationsDefault);
136 ch.setNeedDependsDefault(needDependsDefault);
137 reader.setContentHandler(ch);
138 //reader.setEntityResolver(ch);
139 //reader.setErrorHandler(ch);
140 //reader.setDTDHandler(ch);
141
142 log("about to start parsing file='"+designFile+"'", Project.MSG_INFO);
143 FileInputStream fileInput = new FileInputStream(designFile);
144 InputSource src = new InputSource(fileInput);
145 reader.parse(src);
146 design = ch.getDesign();
147
148 Enumeration pathsEnum = paths.elements();
149 Path p = null;
150 while (pathsEnum.hasMoreElements()) {
151 p = (Path)pathsEnum.nextElement();
152 verifyPathAdheresToDesign(design, p);
153 }
154
155 //only put unused errors if there are no other errors
156 //this is because you end up with false unused errors if you don't do this.
157 if(designErrors.isEmpty())
158 design.fillInUnusedPackages(designErrors);
159
160 if (! designErrors.isEmpty()) {
161 log(designErrors.size()+"Errors.", Project.MSG_WARN);
162 if(!fillInBuildException)
163 throw new BuildException("Design check failed due to previous errors");
164 throwAllErrors();
165 }
166
167 } catch (SAXException e) {
168 maybeDeleteFiles();
169 if (e.getException() != null
170 && e.getException() instanceof RuntimeException)
171 throw (RuntimeException) e.getException();
172 else if (e instanceof SAXParseException) {
173 SAXParseException pe = (SAXParseException) e;
174 throw new BuildException("\nProblem parsing design file='"
175 + designFile + "'. \nline=" + pe.getLineNumber()
176 + " column=" + pe.getColumnNumber() + " Reason:\n"
177 + e.getMessage() + "\n", e);
178 }
179 throw new BuildException("\nProblem parsing design file='"
180 + designFile + "'. Reason:\n" + e, e);
181 } catch (IOException e) {
182 maybeDeleteFiles();
183 throw new RuntimeException("See attached exception", e);
184 // throw new BuildException("IOException on design file='"
185 // + designFile + "'. attached:", e);
186 } catch(RuntimeException e) {
187 maybeDeleteFiles();
188 throw e;
189 } finally {
190
191 }
192
193 if(!verifiedAtLeastOne)
194 throw new BuildException("Did not find any class or jar files to verify");
195 }
196 //some auto builds like cruisecontrol can only report all the
197 //standard ant task errors and the build exceptions so here
198 //we need to fill in the buildexception so the errors are reported
199 //correctly through those tools....though, you think ant has a hook
200 //in that cruisecontrol is not using like LogListeners or something
201 private void throwAllErrors() {
202 String result = "Design check failed due to following errors";
203 Enumeration exceptions = designErrors.elements();
204 while(exceptions.hasMoreElements()) {
205 BuildException be = (BuildException)exceptions.nextElement();
206 String message = be.getMessage();
207 result += "\n" + message;
208 }
209 throw new BuildException(result);
210 }
211
212 private void verifyJarFilesExist() {
213 Enumeration pathsEnum = paths.elements();
214 Path p = null;
215 while (pathsEnum.hasMoreElements()) {
216 p = (Path)pathsEnum.nextElement();
217 String files[] = p.list();
218 for (int i=0;i<files.length;i++) {
219 File file = new File(files[i]);
220
221 if (!file.exists())
222 throw new BuildException(VisitorImpl.getNoFileMsg(file));
223 }
224 }
225 }
226
227 private void maybeDeleteFiles() {
228 if (deleteFiles) {
229 log("Deleting all class and jar files so you do not get tempted to\n" +
230 "use a jar that doesn't abide by the design(This option can\n" +
231 "be turned off if you really want)", Project.MSG_INFO);
232
233 Enumeration pathsEnum = paths.elements();
234 Path p = null;
235 while (pathsEnum.hasMoreElements()) {
236 p = (Path)pathsEnum.nextElement();
237 deleteFilesInPath(p);
238 }
239 }
240 }
241
242 private void deleteFilesInPath(Path p) {
243 String files[] = p.list();
244 for (int i=0;i<files.length;i++) {
245 File file = new File(files[i]);
246
247 boolean deleted = file.delete();
248 if (! deleted) {
249 file.deleteOnExit();
250 }
251 }
252 }
253
254 private void verifyPathAdheresToDesign(Design d, Path p) throws ClassFormatException, IOException {
255 String files[] = p.list();
256 for (int i=0;i<files.length;i++) {
257 File file = new File(files[i]);
258 if(file.isDirectory()) {
259 FileSet set = new FileSet();
260 set.setDir(file);
261 set.setProject(task.getProject());
262 PatternSet.NameEntry entry1 = set.createInclude();
263 PatternSet.NameEntry entry2 = set.createInclude();
264 PatternSet.NameEntry entry3 = set.createInclude();
265 entry1.setName("**/*.class");
266 entry2.setName("**/*.jar");
267 entry3.setName("**/*.war");
268 DirectoryScanner scanner = set.getDirectoryScanner(task.getProject());
269 scanner.setBasedir(file);
270 String[] scannerFiles = scanner.getIncludedFiles();
271 for(int j = 0; j < scannerFiles.length; j++) {
272 verifyPartOfPath(scannerFiles[j], new File(file, scannerFiles[j]), d);
273 }
274 } else
275 verifyPartOfPath(files[i], file, d);
276 }
277 }
278
279 private void verifyPartOfPath(String fileName, File file, Design d) throws IOException {
280 if (fileName.endsWith(".jar") || fileName.endsWith(".war")) {
281 JarFile jarFile = new JarFile(file);
282 verifyJarAdheresToDesign(d, jarFile, file);
283 } else if (fileName.endsWith(".class")) {
284 verifyClassAdheresToDesign(d, file);
285 } else
286 throw new BuildException("Only directories, jars, wars, and class files can be supplied to verify design, not file="+file.getAbsolutePath());
287 }
288
289 private void verifyClassAdheresToDesign(Design d, File classFile)
290 throws ClassFormatException, IOException {
291 FileInputStream fis = null;
292 try {
293 fis = new FileInputStream(classFile);
294 verifyClassAdheresToDesign(d, fis, classFile.getAbsolutePath(), classFile);
295 }
296 finally {
297 try {
298 if (fis != null) {
299 fis.close();
300 }
301 }
302 catch (IOException e) {
303 ; //doh!!
304 }
305 }
306
307 }
308
309 private void verifyJarAdheresToDesign(Design d, JarFile jarFile, File original)
310 throws ClassFormatException, IOException {
311
312 try {
313 Enumeration en = jarFile.entries();
314 while(en.hasMoreElements()) {
315 ZipEntry entry = (ZipEntry)en.nextElement();
316 InputStream in = null;
317 if(entry.getName().endsWith(".class")) {
318 in = jarFile.getInputStream(entry);
319 try {
320 in = jarFile.getInputStream(entry);
321 verifyClassAdheresToDesign(d, in, entry.getName(), original);
322 }
323 finally {
324 try {
325 if (in != null) {
326 in.close();
327 }
328 }
329 catch (IOException e) {
330 ; // doh!!!
331 }
332 }
333 }
334 }
335 }
336 finally {
337 try {
338 jarFile.close();
339 }
340 catch (IOException e) {
341 ; //doh!!!
342 }
343 }
344 }
345
346 private String className = "";
347
348 private void verifyClassAdheresToDesign(Design d, InputStream in, String name, File originalClassOrJarFile) throws ClassFormatException, IOException {
349 try {
350 verifiedAtLeastOne = true;
351 ClassParser parser = new ClassParser(in, name);
352 JavaClass javaClass = parser.parse();
353 className = javaClass.getClassName();
354
355 if(!d.needEvalCurrentClass(className))
356 return;
357
358 ConstantPool pool = javaClass.getConstantPool();
359 processConstantPool(pool);
360 VisitorImpl visitor = new VisitorImpl(pool, this, d, task.getLocation());
361 DescendingVisitor desc = new DescendingVisitor(javaClass, visitor);
362 desc.visit();
363 } catch(BuildException e) {
364 log(Design.getWrapperMsg(originalClassOrJarFile, e.getMessage()), Project.MSG_ERR);
365 designErrors.addElement(e);
366 }
367 }
368
369 private void processConstantPool(ConstantPool pool) {
370 Constant[] constants = pool.getConstantPool();
371 if(constants == null) {
372 log(" constants=null", Project.MSG_VERBOSE);
373 return;
374 }
375
376 log(" constants len="+constants.length, Project.MSG_VERBOSE);
377 for(int i = 0; i < constants.length; i++) {
378 processConstant(pool, constants[i], i);
379 }
380 }
381
382 private void processConstant(ConstantPool pool, Constant c, int i) {
383 if(c == null) //don't know why, but constant[0] seems to be always null.
384 return;
385
386 log(" const["+i+"]="+pool.constantToString(c)+" inst="+c.getClass().getName(), Project.MSG_DEBUG);
387 byte tag = c.getTag();
388 switch(tag) {
389 //reverse engineered from ConstantPool.constantToString..
390 case Constants.CONSTANT_Class:
391 int ind = ((ConstantClass)c).getNameIndex();
392 c = pool.getConstant(ind, Constants.CONSTANT_Utf8);
393 String className = Utility.compactClassName(((ConstantUtf8)c).getBytes(), false);
394 log(" classNamePre="+className, Project.MSG_DEBUG);
395 className = getRidOfArray(className);
396 String firstLetter = className.charAt(0)+"";
397 if(primitives.contains(firstLetter))
398 return;
399 log(" className="+className, Project.MSG_VERBOSE);
400 design.checkClass(className);
401 break;
402 default:
403
404 }
405 }
406
407 private static String getRidOfArray(String className) {
408 while(className.startsWith("["))
409 className = className.substring(1, className.length());
410 return className;
411 }
412
413 public static String getPackageName(String className) {
414 String packageName = Package.DEFAULT;
415 int index = className.lastIndexOf(".");
416 if(index > 0)
417 packageName = className.substring(0, index);
418 //DEANDO: test the else scenario here(it is a corner case)...
419
420 return packageName;
421 }
422
423 public void log(String msg, int level) {
424 //if(level == Project.MSG_WARN || level == Project.MSG_INFO
425 // || level == Project.MSG_ERR || level == Project.MSG_VERBOSE)
426 //VerifyDesignTest.log(msg);
427 task.log(msg, level);
428 }
429 }