KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > nbbuild > TestDistFilter


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.nbbuild;
21
22 import java.io.File JavaDoc;
23 import java.io.FileInputStream JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.StringReader JavaDoc;
26 import java.util.ArrayList JavaDoc;
27 import java.util.Arrays JavaDoc;
28 import java.util.Collections JavaDoc;
29 import java.util.HashSet JavaDoc;
30 import java.util.Iterator JavaDoc;
31 import java.util.List JavaDoc;
32 import java.util.Properties JavaDoc;
33 import java.util.Set JavaDoc;
34 import java.util.StringTokenizer JavaDoc;
35 import javax.xml.parsers.DocumentBuilder JavaDoc;
36 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
37 import javax.xml.parsers.ParserConfigurationException JavaDoc;
38 import org.apache.tools.ant.*;
39 import org.w3c.dom.Element JavaDoc;
40 import org.w3c.dom.NodeList JavaDoc;
41 import org.xml.sax.EntityResolver JavaDoc;
42 import org.xml.sax.InputSource JavaDoc;
43 import org.xml.sax.SAXException JavaDoc;
44
45 /**
46  * It scans test distribution ant sets to property with name defined by param
47  * 'testListProperty'path with filtered test. The TestDistFilter is used for running tests
48  * in test distribution.
49  * <br>
50  *
51  * Parameters :
52  * <ul>
53  * <li>harness - type of harness (junit,xtest). For junit harness are
54  * scanned only tests with unit tes type and 'code' executor name inside
55  * cfg-unit.xml.
56  * <li>testtype - unit|qa-functional|all testtype
57  * <li>attribs - xtest.attribs filter (attribs are declared in cfg-<xxx>.xml file
58  * <li>testlistproperty - store to property path with test folders (separated by ':')
59  * <li>testdistdir - root folder with test distribution
60  * <li>requiredmodules - list of module names required on runtime classpath example:
61  * org-netbeans-modules-masterfs.jar,org-openide-loaders.jar. Only tests
62  * which contains masterfs and loaders will be stored to testlistproperty value.
63  * </ul>
64  */

65 public class TestDistFilter extends Task {
66     public static final String JavaDoc TYPE_ALL = "all";
67     public static final String JavaDoc TYPE_UNIT = "unit";
68     public static final String JavaDoc TYPE_QA_FUNCTIONAL = "qa-functional";
69   
70     public static final String JavaDoc HARNESS_JUNIT = "junit";
71     public static final String JavaDoc HARNESS_XTEST = "xtest";
72
73     private File JavaDoc testDistDir;
74     Set JavaDoc<TestConf> possibleTests = new HashSet JavaDoc<TestConf>();
75     // "unit|qa_functional|all
76
// default value is all
77
private String JavaDoc testtype = TYPE_ALL;
78     private String JavaDoc harness = HARNESS_XTEST;
79     // xtest attribs
80
private String JavaDoc attribs ;
81     private String JavaDoc testListProperty;
82     private String JavaDoc requiredModules;
83     // TODO customize method names to match custom task
84
// property and type (handled by inner class) names
85

86     /** represents a test directory
87      */

88     private static class TestConf {
89         File JavaDoc moduleDir;
90         boolean unit;
91         TestConf(File JavaDoc moduleDir,boolean unit) {
92             this.moduleDir = moduleDir;
93             this.unit = unit;
94         }
95
96         public int hashCode() {
97             return moduleDir.hashCode();
98         }
99         public boolean equals(Object JavaDoc obj) {
100             return (obj instanceof TestConf) && moduleDir.equals(((TestConf)obj).moduleDir);
101         }
102       
103         
104         /** check if cfg-<testtype>.xml contains xtest.attribs,
105          * ide executor is ignored for junit
106          */

107         boolean matchAttribs(String JavaDoc harness,String JavaDoc attribs) {
108             Element JavaDoc config;
109             try {
110                 config = getConfig();
111             } catch (SAXException JavaDoc ex) {
112                 throw new BuildException("Error in parsing " + getConfigFile(),ex);
113             } catch (ParserConfigurationException JavaDoc ex) {
114                 throw new BuildException("Error in parsing " + getConfigFile(),ex);
115             } catch (IOException JavaDoc ex) {
116                 throw new BuildException("Error in parsing " + getConfigFile(),ex);
117             }
118             if (config == null) {
119                 return false;
120             }
121             boolean junit = HARNESS_JUNIT.equals(harness);
122             NodeList JavaDoc elements = config.getElementsByTagName("testbag");
123             for (int n = 0 ; n < elements.getLength() ; n++) {
124                 Element JavaDoc testbag = (Element JavaDoc) elements.item(n);
125                 if (junit && "ide".equals(testbag.getAttribute("executor"))) {
126                     continue;
127                 }
128                 if (testAttr(testbag.getAttribute("testattribs"),attribs)) {
129                     return true;
130                 }
131             }
132             return false;
133         }
134         private static boolean testAttr(String JavaDoc xmlAttr,String JavaDoc userAttr) {
135             if (userAttr == null) {
136                 return true;
137             }
138             if (xmlAttr == null) {
139                 return false;
140             }
141             StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(xmlAttr,"&|, ");
142             while (tokenizer.hasMoreTokens()) {
143                 String JavaDoc token = tokenizer.nextToken().trim();
144                 if (token.equals(userAttr)) {
145                     return true;
146                 }
147             }
148             return false;
149         }
150         File JavaDoc getModuleDir() {
151             return moduleDir;
152         }
153         
154         private File JavaDoc getConfigFile () {
155             String JavaDoc name = (unit) ? "cfg-unit.xml" : "cfg-qa-functional.xml";
156             return new File JavaDoc(getModuleDir(),name);
157         }
158         private Element JavaDoc getConfig() throws ParserConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc {
159             File JavaDoc xml = getConfigFile();
160             if (!xml.exists()) {
161                 return null;
162             }
163             return getDocumentBuilder().parse(xml).getDocumentElement();
164         }
165         
166     }
167
168     
169     public void execute() throws BuildException {
170           possibleTests.clear();
171           if (getTestListProperty() == null) {
172               throw new BuildException("Param testlistproperty is not defined.");
173           }
174           if (getTestDistDir() == null || !getTestDistDir().exists()) {
175               throw new BuildException("Param testdistdir is not defined.");
176           }
177           if ("".equals(attribs)) {
178               attribs = null;
179           }
180           String JavaDoc tt = getTesttype();
181           if (getHarness().equals(HARNESS_JUNIT)) {
182               findCodeTests(HARNESS_JUNIT,TYPE_UNIT,getAttribs());
183           } else {
184               if (tt.equals(TYPE_QA_FUNCTIONAL) || tt.equals(TYPE_ALL)) {
185                   findCodeTests(HARNESS_XTEST,TYPE_QA_FUNCTIONAL,getAttribs());
186               }
187               if (tt.equals(TYPE_UNIT) || tt.equals(TYPE_ALL)) {
188                   findCodeTests(HARNESS_XTEST,TYPE_UNIT,getAttribs());
189               }
190           }
191           define(getTestListProperty(),getTestList());
192     }
193     /** get path with test dirs separated by :
194      */

195     private String JavaDoc getTestList() {
196         StringBuffer JavaDoc path = new StringBuffer JavaDoc();
197         for (Iterator JavaDoc it = possibleTests.iterator() ; it.hasNext() ; ) {
198             TestConf tc = (TestConf)it.next();
199             if (!matchRequiredModule(tc.getModuleDir())) {
200                 continue;
201             }
202             if (path.length() > 0) {
203                 path.append(':');
204             }
205             path.append(tc.getModuleDir().getAbsolutePath());
206         }
207         return path.toString();
208     }
209     private void define(String JavaDoc prop, String JavaDoc val) {
210         log("Setting " + prop + "=" + val, Project.MSG_VERBOSE);
211         String JavaDoc old = getProject().getProperty(prop);
212         if (old != null && !old.equals(val)) {
213             getProject().log("Warning: " + prop + " was already set to " + old, Project.MSG_WARN);
214         }
215         getProject().setNewProperty(prop, val);
216     }
217
218
219     public String JavaDoc getTesttype() {
220         return testtype;
221     }
222
223     public void setTesttype(String JavaDoc testtype) {
224         this.testtype = testtype;
225     }
226
227     public String JavaDoc getHarness() {
228         return harness;
229     }
230
231     public void setHarness(String JavaDoc harness) {
232         this.harness = harness;
233     }
234
235     public String JavaDoc getAttribs() {
236         return attribs;
237     }
238
239     public void setAttribs(String JavaDoc attribs) {
240         this.attribs = attribs;
241     }
242
243     public String JavaDoc getTestListProperty() {
244         return testListProperty;
245     }
246
247     public void setTestListProperty(String JavaDoc testListProperty) {
248         this.testListProperty = testListProperty;
249     }
250
251     private void findCodeTests(String JavaDoc harness, String JavaDoc type, String JavaDoc string) {
252           List JavaDoc tests = getTestList(type);
253           for (int i = 0 ; i < tests.size() ; i++) {
254               TestConf test = (TestConf)tests.get(i);
255               if (test.matchAttribs(harness,attribs)) {
256                   possibleTests.add(test);
257               }
258           }
259     }
260
261     private List JavaDoc getTestList(String JavaDoc testtype) {
262         File JavaDoc root = new File JavaDoc (getTestDistDir(),testtype);
263         List JavaDoc <TestConf> testList = new ArrayList JavaDoc<TestConf>();
264         if (!root.exists()) {
265             return Collections.EMPTY_LIST;
266         }
267         File JavaDoc clusters[] = root.listFiles();
268         for (int c = 0 ; c < clusters.length ; c++) {
269             File JavaDoc cluster = clusters[c];
270             if (cluster.isDirectory()) {
271                 File JavaDoc modules[] = cluster.listFiles();
272                 for (int m = 0 ; m < modules.length ; m++) {
273                     File JavaDoc module = modules[m];
274                     if (module.isDirectory()) {
275                         testList.add(new TestConf(module,testtype.equals(TYPE_UNIT)));
276                     }
277                 }
278             }
279         }
280         return testList;
281     }
282
283     
284     // create document builder with empty EntityResolver
285
//
286
private static DocumentBuilder JavaDoc db;
287     private static DocumentBuilder JavaDoc getDocumentBuilder() throws ParserConfigurationException JavaDoc {
288         if (db == null) {
289            db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
290            db.setEntityResolver(new EntityResolver JavaDoc() {
291                public InputSource JavaDoc resolveEntity(String JavaDoc publicId, String JavaDoc systemId) throws SAXException JavaDoc,IOException JavaDoc {
292                    return new InputSource JavaDoc(new StringReader JavaDoc(""));
293                }
294             
295            });
296         }
297         return db;
298     }
299
300     public File JavaDoc getTestDistDir() {
301         return testDistDir;
302     }
303
304     public void setTestDistDir(File JavaDoc testDistDir) {
305         this.testDistDir = testDistDir;
306     }
307
308     public String JavaDoc getRequiredModules() {
309         return requiredModules;
310     }
311
312     public void setRequiredModules(String JavaDoc requiredModules) {
313         this.requiredModules = requiredModules;
314     }
315
316     private boolean matchRequiredModule(File JavaDoc path) {
317        if (requiredModules == null || requiredModules.trim().length() == 0) {
318            return true;
319        }
320        File JavaDoc pfile = new File JavaDoc(path,"test.properties");
321        if (pfile.exists()) {
322            Properties JavaDoc props = new Properties JavaDoc();
323             try {
324                 FileInputStream JavaDoc fis = new FileInputStream JavaDoc(pfile);
325                 try {
326                   props.load(fis);
327                   
328                   String JavaDoc runCp = props.getProperty("test.unit.run.cp");
329                   if (runCp != null) {
330                       String JavaDoc paths[] = runCp.split(":");
331                       Set JavaDoc reqModules = getRequiredModulesSet();
332                       if (reqModules.size() == 0) {
333                           return true;
334                       }
335                       for (int i = 0 ; i < paths.length ; i++) {
336                           String JavaDoc p = paths[i];
337                           int lastSlash = p.lastIndexOf('/');
338                           if (lastSlash != -1) {
339                               p = p.substring(lastSlash + 1);
340                           }
341                           if (reqModules.contains(p)) {
342                               return true;
343                           }
344                       }
345                   }
346                 } finally {
347                   fis.close();
348                 }
349             } catch(IOException JavaDoc ioe){
350                 throw new BuildException(ioe);
351             }
352        }
353        return false;
354     }
355
356     private Set JavaDoc<String JavaDoc> getRequiredModulesSet() {
357         String JavaDoc names[] = getRequiredModules().split(",");
358         return new HashSet JavaDoc<String JavaDoc>(Arrays.asList(names));
359     }
360 }
361
Popular Tags