KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > types > PatternSet


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
19 package org.apache.tools.ant.types;
20
21 import java.io.BufferedReader JavaDoc;
22 import java.io.File JavaDoc;
23 import java.io.FileReader JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.util.Enumeration JavaDoc;
26 import java.util.StringTokenizer JavaDoc;
27 import java.util.Vector JavaDoc;
28 import org.apache.tools.ant.BuildException;
29 import org.apache.tools.ant.Project;
30
31 /**
32  * Named collection of include/exclude tags.
33  *
34  * <p>Moved out of MatchingTask to make it a standalone object that
35  * could be referenced (by scripts for example).
36  *
37  */

38 public class PatternSet extends DataType implements Cloneable JavaDoc {
39     private Vector JavaDoc includeList = new Vector JavaDoc();
40     private Vector JavaDoc excludeList = new Vector JavaDoc();
41     private Vector JavaDoc includesFileList = new Vector JavaDoc();
42     private Vector JavaDoc excludesFileList = new Vector JavaDoc();
43
44     /**
45      * inner class to hold a name on list. "If" and "Unless" attributes
46      * may be used to invalidate the entry based on the existence of a
47      * property (typically set thru the use of the Available task).
48      */

49     public class NameEntry {
50         private String JavaDoc name;
51         private String JavaDoc ifCond;
52         private String JavaDoc unlessCond;
53
54         /**
55          * Sets the name pattern.
56          *
57          * @param name The pattern string.
58          */

59         public void setName(String JavaDoc name) {
60             this.name = name;
61         }
62
63         /**
64          * Sets the if attribute. This attribute and the "unless"
65          * attribute are used to validate the name, based in the
66          * existence of the property.
67          *
68          * @param cond A property name. If this property is not
69          * present, the name is invalid.
70          */

71         public void setIf(String JavaDoc cond) {
72             ifCond = cond;
73         }
74
75         /**
76          * Sets the unless attribute. This attribute and the "if"
77          * attribute are used to validate the name, based in the
78          * existence of the property.
79          *
80          * @param cond A property name. If this property is
81          * present, the name is invalid.
82          */

83         public void setUnless(String JavaDoc cond) {
84             unlessCond = cond;
85         }
86
87         /**
88          * @return the name attribute.
89          */

90         public String JavaDoc getName() {
91             return name;
92         }
93
94         /**
95          * This validates the name - checks the if and unless
96          * properties.
97          *
98          * @param p the current project, used to check the presence or
99          * absence of a property.
100          * @return the name attribute or null if the "if" or "unless"
101          * properties are not/are set.
102          */

103         public String JavaDoc evalName(Project p) {
104             return valid(p) ? name : null;
105         }
106
107         private boolean valid(Project p) {
108             if (ifCond != null && p.getProperty(ifCond) == null) {
109                 return false;
110             } else if (unlessCond != null && p.getProperty(unlessCond) != null) {
111                 return false;
112             }
113             return true;
114         }
115
116         /**
117          * @return a printable form of this object.
118          */

119         public String JavaDoc toString() {
120             StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
121             if (name == null) {
122                 buf.append("noname");
123             } else {
124                 buf.append(name);
125             }
126             if ((ifCond != null) || (unlessCond != null)) {
127                 buf.append(":");
128                 String JavaDoc connector = "";
129
130                 if (ifCond != null) {
131                     buf.append("if->");
132                     buf.append(ifCond);
133                     connector = ";";
134                 }
135                 if (unlessCond != null) {
136                     buf.append(connector);
137                     buf.append("unless->");
138                     buf.append(unlessCond);
139                 }
140             }
141
142             return buf.toString();
143         }
144     }
145
146     /**
147      * Creates a new <code>PatternSet</code> instance.
148      */

149     public PatternSet() {
150         super();
151     }
152
153     /**
154      * Makes this instance in effect a reference to another PatternSet
155      * instance.
156      *
157      * <p>You must not set another attribute or nest elements inside
158      * this element if you make it a reference.</p>
159      * @param r the reference to another patternset.
160      * @throws BuildException on error.
161      */

162     public void setRefid(Reference r) throws BuildException {
163         if (!includeList.isEmpty() || !excludeList.isEmpty()) {
164             throw tooManyAttributes();
165         }
166         super.setRefid(r);
167     }
168
169     /**
170      * This is a patternset nested element.
171      *
172      * @param p a configured patternset nested element.
173      */

174     public void addConfiguredPatternset(PatternSet p) {
175         if (isReference()) {
176             throw noChildrenAllowed();
177         }
178
179         String JavaDoc[] nestedIncludes = p.getIncludePatterns(getProject());
180         String JavaDoc[] nestedExcludes = p.getExcludePatterns(getProject());
181
182         if (nestedIncludes != null) {
183             for (int i = 0; i < nestedIncludes.length; i++) {
184                 createInclude().setName(nestedIncludes[i]);
185             }
186         }
187
188         if (nestedExcludes != null) {
189             for (int i = 0; i < nestedExcludes.length; i++) {
190                 createExclude().setName(nestedExcludes[i]);
191             }
192         }
193     }
194
195     /**
196      * add a name entry on the include list
197      * @return a nested include element to be configured.
198      */

199     public NameEntry createInclude() {
200         if (isReference()) {
201             throw noChildrenAllowed();
202         }
203         return addPatternToList(includeList);
204     }
205
206     /**
207      * add a name entry on the include files list
208      * @return a nested includesfile element to be configured.
209      */

210     public NameEntry createIncludesFile() {
211         if (isReference()) {
212             throw noChildrenAllowed();
213         }
214         return addPatternToList(includesFileList);
215     }
216
217     /**
218      * add a name entry on the exclude list
219      * @return a nested exclude element to be configured.
220      */

221     public NameEntry createExclude() {
222         if (isReference()) {
223             throw noChildrenAllowed();
224         }
225         return addPatternToList(excludeList);
226     }
227
228     /**
229      * add a name entry on the exclude files list
230      * @return a nested excludesfile element to be configured.
231      */

232     public NameEntry createExcludesFile() {
233         if (isReference()) {
234             throw noChildrenAllowed();
235         }
236         return addPatternToList(excludesFileList);
237     }
238
239     /**
240      * Appends <code>includes</code> to the current list of include patterns.
241      * Patterns may be separated by a comma or a space.
242      *
243      * @param includes the string containing the include patterns
244      */

245     public void setIncludes(String JavaDoc includes) {
246         if (isReference()) {
247             throw tooManyAttributes();
248         }
249         if (includes != null && includes.length() > 0) {
250             StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(includes, ", ", false);
251             while (tok.hasMoreTokens()) {
252                 createInclude().setName(tok.nextToken());
253             }
254         }
255     }
256
257     /**
258      * Appends <code>excludes</code> to the current list of exclude patterns.
259      * Patterns may be separated by a comma or a space.
260      *
261      * @param excludes the string containing the exclude patterns
262      */

263     public void setExcludes(String JavaDoc excludes) {
264         if (isReference()) {
265             throw tooManyAttributes();
266         }
267         if (excludes != null && excludes.length() > 0) {
268             StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(excludes, ", ", false);
269             while (tok.hasMoreTokens()) {
270                 createExclude().setName(tok.nextToken());
271             }
272         }
273     }
274
275     /**
276      * add a name entry to the given list
277      */

278     private NameEntry addPatternToList(Vector JavaDoc list) {
279         NameEntry result = new NameEntry();
280         list.addElement(result);
281         return result;
282     }
283
284     /**
285      * Sets the name of the file containing the includes patterns.
286      *
287      * @param includesFile The file to fetch the include patterns from.
288      * @throws BuildException on error.
289      */

290      public void setIncludesfile(File JavaDoc includesFile) throws BuildException {
291          if (isReference()) {
292              throw tooManyAttributes();
293          }
294          createIncludesFile().setName(includesFile.getAbsolutePath());
295      }
296
297     /**
298      * Sets the name of the file containing the excludes patterns.
299      *
300      * @param excludesFile The file to fetch the exclude patterns from.
301      * @throws BuildException on error.
302      */

303      public void setExcludesfile(File JavaDoc excludesFile) throws BuildException {
304          if (isReference()) {
305              throw tooManyAttributes();
306          }
307          createExcludesFile().setName(excludesFile.getAbsolutePath());
308      }
309
310     /**
311      * Reads path matching patterns from a file and adds them to the
312      * includes or excludes list (as appropriate).
313      */

314     private void readPatterns(File JavaDoc patternfile, Vector JavaDoc patternlist, Project p)
315         throws BuildException {
316
317         BufferedReader JavaDoc patternReader = null;
318         try {
319             // Get a FileReader
320
patternReader =
321                 new BufferedReader JavaDoc(new FileReader JavaDoc(patternfile));
322
323             // Create one NameEntry in the appropriate pattern list for each
324
// line in the file.
325
String JavaDoc line = patternReader.readLine();
326             while (line != null) {
327                 if (line.length() > 0) {
328                     line = p.replaceProperties(line);
329                     addPatternToList(patternlist).setName(line);
330                 }
331                 line = patternReader.readLine();
332             }
333         } catch (IOException JavaDoc ioe) {
334             String JavaDoc msg = "An error occurred while reading from pattern file: "
335                 + patternfile;
336             throw new BuildException(msg, ioe);
337         } finally {
338             if (null != patternReader) {
339                 try {
340                     patternReader.close();
341                 } catch (IOException JavaDoc ioe) {
342                     //Ignore exception
343
}
344             }
345         }
346     }
347
348     /**
349      * Adds the patterns of the other instance to this set.
350      * @param other the other PatternSet instance.
351      * @param p the current project.
352      */

353     public void append(PatternSet other, Project p) {
354         if (isReference()) {
355             throw new BuildException("Cannot append to a reference");
356         }
357
358         String JavaDoc[] incl = other.getIncludePatterns(p);
359         if (incl != null) {
360             for (int i = 0; i < incl.length; i++) {
361                 createInclude().setName(incl[i]);
362             }
363         }
364
365         String JavaDoc[] excl = other.getExcludePatterns(p);
366         if (excl != null) {
367             for (int i = 0; i < excl.length; i++) {
368                 createExclude().setName(excl[i]);
369             }
370         }
371     }
372
373     /**
374      * Returns the filtered include patterns.
375      * @param p the current project.
376      * @return the filtered included patterns.
377      */

378     public String JavaDoc[] getIncludePatterns(Project p) {
379         if (isReference()) {
380             return getRef(p).getIncludePatterns(p);
381         } else {
382             readFiles(p);
383             return makeArray(includeList, p);
384         }
385     }
386
387     /**
388      * Returns the filtered include patterns.
389      * @param p the current project.
390      * @return the filtered excluded patterns.
391      */

392     public String JavaDoc[] getExcludePatterns(Project p) {
393         if (isReference()) {
394             return getRef(p).getExcludePatterns(p);
395         } else {
396             readFiles(p);
397             return makeArray(excludeList, p);
398         }
399     }
400
401     /**
402      * Helper for FileSet classes.
403      * Check if there are patterns defined.
404      * @param p the current project.
405      * @return true if there are patterns.
406      */

407     public boolean hasPatterns(Project p) {
408         if (isReference()) {
409             return getRef(p).hasPatterns(p);
410         } else {
411             return includesFileList.size() > 0 || excludesFileList.size() > 0
412                 || includeList.size() > 0 || excludeList.size() > 0;
413         }
414     }
415
416     /**
417      * Performs the check for circular references and returns the
418      * referenced PatternSet.
419      */

420     private PatternSet getRef(Project p) {
421         return (PatternSet) getCheckedRef(p);
422     }
423
424     /**
425      * Convert a vector of NameEntry elements into an array of Strings.
426      */

427     private String JavaDoc[] makeArray(Vector JavaDoc list, Project p) {
428         if (list.size() == 0) {
429             return null;
430         }
431
432         Vector JavaDoc tmpNames = new Vector JavaDoc();
433         for (Enumeration JavaDoc e = list.elements(); e.hasMoreElements();) {
434             NameEntry ne = (NameEntry) e.nextElement();
435             String JavaDoc pattern = ne.evalName(p);
436             if (pattern != null && pattern.length() > 0) {
437                 tmpNames.addElement(pattern);
438             }
439         }
440
441         String JavaDoc[] result = new String JavaDoc[tmpNames.size()];
442         tmpNames.copyInto(result);
443         return result;
444     }
445
446     /**
447      * Read includesfile ot excludesfile if not already done so.
448      */

449     private void readFiles(Project p) {
450         if (includesFileList.size() > 0) {
451             Enumeration JavaDoc e = includesFileList.elements();
452             while (e.hasMoreElements()) {
453                 NameEntry ne = (NameEntry) e.nextElement();
454                 String JavaDoc fileName = ne.evalName(p);
455                 if (fileName != null) {
456                     File JavaDoc inclFile = p.resolveFile(fileName);
457                     if (!inclFile.exists()) {
458                         throw new BuildException("Includesfile "
459                                                  + inclFile.getAbsolutePath()
460                                                  + " not found.");
461                     }
462                     readPatterns(inclFile, includeList, p);
463                 }
464             }
465             includesFileList.removeAllElements();
466         }
467
468         if (excludesFileList.size() > 0) {
469             Enumeration JavaDoc e = excludesFileList.elements();
470             while (e.hasMoreElements()) {
471                 NameEntry ne = (NameEntry) e.nextElement();
472                 String JavaDoc fileName = ne.evalName(p);
473                 if (fileName != null) {
474                     File JavaDoc exclFile = p.resolveFile(fileName);
475                     if (!exclFile.exists()) {
476                         throw new BuildException("Excludesfile "
477                                                  + exclFile.getAbsolutePath()
478                                                  + " not found.");
479                     }
480                     readPatterns(exclFile, excludeList, p);
481                 }
482             }
483             excludesFileList.removeAllElements();
484         }
485     }
486
487     /**
488      * @return a printable form of this object.
489      */

490     public String JavaDoc toString() {
491         return "patternSet{ includes: " + includeList
492                 + " excludes: " + excludeList + " }";
493     }
494
495     /**
496      * @since Ant 1.6
497      * @return a clone of this patternset.
498      */

499     public Object JavaDoc clone() {
500         try {
501             PatternSet ps = (PatternSet) super.clone();
502             ps.includeList = (Vector JavaDoc) includeList.clone();
503             ps.excludeList = (Vector JavaDoc) excludeList.clone();
504             ps.includesFileList = (Vector JavaDoc) includesFileList.clone();
505             ps.excludesFileList = (Vector JavaDoc) excludesFileList.clone();
506             return ps;
507         } catch (CloneNotSupportedException JavaDoc e) {
508             throw new BuildException(e);
509         }
510     }
511
512 }
513
Popular Tags