KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > module > api > support > ActionUtils


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.apache.tools.ant.module.api.support;
21
22 import java.io.IOException JavaDoc;
23 import java.util.ArrayList JavaDoc;
24 import java.util.Collection JavaDoc;
25 import java.util.LinkedHashSet JavaDoc;
26 import java.util.List JavaDoc;
27 import java.util.Properties JavaDoc;
28 import java.util.regex.Matcher JavaDoc;
29 import java.util.regex.Pattern JavaDoc;
30 import org.apache.tools.ant.module.api.AntProjectCookie;
31 import org.apache.tools.ant.module.api.AntTargetExecutor;
32 import org.openide.execution.ExecutorTask;
33 import org.openide.filesystems.FileObject;
34 import org.openide.filesystems.FileUtil;
35 import org.openide.loaders.DataObject;
36 import org.openide.util.Lookup;
37
38 /**
39  * Makes it easier to implement <code>org.netbeans.spi.project.ActionProvider</code> in a standard way
40  * by running targets in Ant scripts.
41  * @see <a HREF="@PROJECTS/PROJECTAPI@/org/netbeans/spi/project/ActionProvider.html"><code>ActionProvider</code></a>
42  * @author Jesse Glick
43  */

44 public final class ActionUtils {
45     
46     private ActionUtils() {}
47     
48     /**
49      * Runs an Ant target (or a sequence of them).
50      * @param buildXml an Ant build script
51      * @param targetNames one or more targets to run; or null for the default target
52      * @param properties any Ant properties to define, or null
53      * @return a task tracking the progress of Ant
54      * @throws IOException if there was a problem starting Ant
55      * @throws IllegalArgumentException if you did not provide any targets
56      */

57     public static ExecutorTask runTarget(FileObject buildXml, String JavaDoc[] targetNames, Properties JavaDoc properties) throws IOException JavaDoc, IllegalArgumentException JavaDoc {
58         if (buildXml == null) {
59             throw new NullPointerException JavaDoc("Must pass non-null build script"); // NOI18N
60
}
61         if (targetNames != null && targetNames.length == 0) {
62             throw new IllegalArgumentException JavaDoc("No targets supplied"); // NOI18N
63
}
64         AntProjectCookie apc = TargetLister.getAntProjectCookie(buildXml);
65         AntTargetExecutor.Env execenv = new AntTargetExecutor.Env();
66         if (properties != null) {
67             Properties JavaDoc p = execenv.getProperties();
68             p.putAll(properties);
69             execenv.setProperties(p);
70         }
71         return AntTargetExecutor.createTargetExecutor(execenv).execute(apc, targetNames);
72     }
73     
74     /**
75      * Convenience method to find a file selection in a selection (context).
76      * All files must exist on disk (according to {@link FileUtil#toFile}).
77      * If a constraining directory is supplied, they must also be contained in it.
78      * If a constraining file suffix is supplied, the base names of the files
79      * must end with that suffix.
80      * The return value is null if there are no matching files; or if the strict
81      * parameter is true and some of the files in the selection did not match
82      * the constraints (disk files, directory, and/or suffix).
83      * <p class="nonnormative">
84      * Typically {@link org.openide.loaders.DataNode}s will form a node selection
85      * which will be placed in the context. This method does <em>not</em> directly
86      * look for nodes in the selection; but generally the lookups of the nodes in
87      * a node selection are spliced into the context as well, so the {@link DataObject}s
88      * should be available. A corollary of not checking nodes directly is that any
89      * nodes in the context which do not correspond to files at all (i.e. do not have
90      * {@link DataObject} as a cookie) are ignored, even with the strict parameter on;
91      * and that multiple nodes in the context with the same associated file are treated
92      * as a single entry.
93      * </p>
94      * @param context a selection as provided to e.g. <code>ActionProvider.isActionEnabled(...)</code>
95      * @param dir a constraining parent directory, or null to not check for a parent directory
96      * @param suffix a file suffix (e.g. <samp>.java</samp>) to constrain files by,
97      * or null to not check suffixes
98      * @param strict if true, all files in the selection have to be accepted
99      * @return a nonempty selection of disk files, or null
100      * @see <a HREF="@PROJECTS/PROJECTAPI@/org/netbeans/spi/project/ActionProvider.html#isActionEnabled(java.lang.String,%20org.openide.util.Lookup)"><code>ActionProvider.isActionEnabled(...)</code></a>
101      */

102     public static FileObject[] findSelectedFiles(Lookup context, FileObject dir, String JavaDoc suffix, boolean strict) {
103         if (dir != null && !dir.isFolder()) {
104             throw new IllegalArgumentException JavaDoc("Not a folder: " + dir); // NOI18N
105
}
106         if (suffix != null && suffix.indexOf('/') != -1) {
107             throw new IllegalArgumentException JavaDoc("Cannot includes slashes in suffix: " + suffix); // NOI18N
108
}
109         Collection JavaDoc<FileObject> files = new LinkedHashSet JavaDoc<FileObject>(); // #50644: remove dupes
110
// XXX this should perhaps also check for FileObject's...
111
for (DataObject d : context.lookupAll(DataObject.class)) {
112             FileObject f = d.getPrimaryFile();
113             boolean matches = FileUtil.toFile(f) != null;
114             if (dir != null) {
115                 matches &= (FileUtil.isParentOf(dir, f) || dir == f);
116             }
117             if (suffix != null) {
118                 matches &= f.getNameExt().endsWith(suffix);
119             }
120             // Generally only files from one project will make sense.
121
// Currently the action UI infrastructure (PlaceHolderAction)
122
// checks for that itself. Should there be another check here?
123
if (matches) {
124                 files.add(f);
125             } else if (strict) {
126                 return null;
127             }
128         }
129         if (files.isEmpty()) {
130             return null;
131         }
132         return files.toArray(new FileObject[files.size()]);
133     }
134     
135     /**
136      * Map files of one kind in a source directory to files of another kind in a target directory.
137      * You may use regular expressions to remap file names in the process.
138      * Only files which actually exist in the target directory will be returned.
139      * <span class="nonnormative">(If you expect the target files to be created
140      * by Ant you do not need this method, since Ant's mappers suffice.)</span>
141      * The file paths considered by the regular expression (if supplied) always use
142      * <samp>/</samp> as the separator.
143      * <p class="nonnormative">
144      * Typical usage to map a set of Java source files to corresponding tests:
145      * <code>regexpMapFiles(files, srcDir, Pattern.compile("/([^/]+)\\.java"), testSrcDir, "/\\1Test.java", true)</code>
146      * </p>
147      * @param fromFiles a list of source files to start with (may be empty)
148      * @param fromDir a directory in which all the source files reside
149      * @param fromRx a regular expression to match against the source files
150      * (or null to keep the same relative file names); only one
151      * match (somewhere in the path) is checked for; failure to match
152      * prevents the file from being included
153      * @param toDir a target directory that results will reside in
154      * @param toSubst replacement text for <code>fromRx</code> (may include regexp references),
155      * or must be null if <code>fromRx</code> was null
156      * @param strict true to return null in case some starting files did not match any target file
157      * @return a list of corresponding target files (may be empty), or null if in strict mode
158      * and there was at least one source file which did not match a target file
159
160      * @throws IllegalArgumentException in case some source file is not in the source directory
161      */

162     public static FileObject[] regexpMapFiles(FileObject[] fromFiles, FileObject fromDir, Pattern JavaDoc fromRx, FileObject toDir, String JavaDoc toSubst, boolean strict) throws IllegalArgumentException JavaDoc {
163         List JavaDoc<FileObject> files = new ArrayList JavaDoc<FileObject>();
164         for (FileObject fromFile : fromFiles) {
165             String JavaDoc path = FileUtil.getRelativePath(fromDir, fromFile);
166             if (path == null) {
167                 throw new IllegalArgumentException JavaDoc("The file " + fromFile + " is not in " + fromDir); // NOI18N
168
}
169             String JavaDoc toPath;
170             if (fromRx != null) {
171                 Matcher JavaDoc m = fromRx.matcher(path);
172                 toPath = m.replaceFirst(toSubst);
173                 if (toPath.equals(path) && !m.find(0)) {
174                     // Did not match the pattern.
175
if (strict) {
176                         return null;
177                     } else {
178                         continue;
179                     }
180                 }
181             } else {
182                 toPath = path;
183             }
184             FileObject target = toDir.getFileObject(toPath);
185             if (target == null) {
186                 if (strict) {
187                     return null;
188                 } else {
189                     continue;
190                 }
191             }
192             files.add(target);
193         }
194         return files.toArray(new FileObject[files.size()]);
195     }
196     
197     /**
198      * Create an "includes" string such as is accepted by many Ant commands
199      * as well as filesets.
200      * <samp>/</samp> is always used as the separator in the relative paths.
201      * @param files a list of files or folders to include, in the case of folder
202      * the generated include contains recursively all files under the folder.
203      * @param dir a directory in which all the files reside
204      * @return a comma-separated list of relative file paths suitable for use by Ant
205      * (the empty string in case there are no files)
206      * @throws IllegalArgumentException in case some file is not in the directory
207      */

208     public static String JavaDoc antIncludesList(FileObject[] files, FileObject dir) throws IllegalArgumentException JavaDoc {
209         return antIncludesList (files, dir, true);
210     }
211
212     /**
213      * Create an "includes" string such as is accepted by many Ant commands
214      * as well as filesets.
215      * <samp>/</samp> is always used as the separator in the relative paths.
216      * @param files a list of files or folders to include, in the case of folder
217      * the generated include contains recursively all files under the folder.
218      * @param dir a directory in which all the files reside
219      * @param recursive if true the include list for directory is recursive
220      * @return a comma-separated list of relative file paths suitable for use by Ant
221      * (the empty string in case there are no files)
222      * @throws IllegalArgumentException in case some file is not in the directory
223      * @since org.apache.tools.ant.module/3 3.16
224      */

225     public static String JavaDoc antIncludesList(FileObject[] files, FileObject dir, boolean recursive) throws IllegalArgumentException JavaDoc {
226         if (!dir.isFolder()) {
227             throw new IllegalArgumentException JavaDoc("Not a folder: " + dir); // NOI18N
228
}
229         StringBuffer JavaDoc b = new StringBuffer JavaDoc();
230         for (int i = 0; i < files.length; i++) {
231             String JavaDoc path = FileUtil.getRelativePath(dir, files[i]);
232             if (path == null) {
233                 throw new IllegalArgumentException JavaDoc("The file " + files[i] + " is not in " + dir); // NOI18N
234
}
235             if (i > 0) {
236                 b.append(',');
237             }
238             b.append(path);
239             if (files[i].isFolder()) {
240                 // files[i] == dir, cannot use "/".
241
if (path.length() > 0) {
242                     b.append('/'); //NOI18N
243
}
244                 b.append('*'); //NOI18N
245
if (recursive) {
246                     b.append('*'); //NOI18N
247
}
248             }
249         }
250         return b.toString();
251     }
252     
253 }
254
Popular Tags