KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > info > jtrac > maven > AntPropsMojo


1 /*
2  * Copyright 2002-2005 the original author or authors.
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 info.jtrac.maven;
18
19 import java.io.File JavaDoc;
20 import java.io.FileInputStream JavaDoc;
21 import java.io.FileOutputStream JavaDoc;
22 import java.io.InputStream JavaDoc;
23 import java.io.OutputStream JavaDoc;
24 import java.io.PrintWriter JavaDoc;
25 import java.io.Writer JavaDoc;
26 import java.util.ArrayList JavaDoc;
27 import java.util.Collection JavaDoc;
28 import java.util.Date JavaDoc;
29 import java.util.HashSet JavaDoc;
30 import java.util.Iterator JavaDoc;
31 import java.util.LinkedHashMap JavaDoc;
32 import java.util.List JavaDoc;
33 import java.util.Map JavaDoc;
34 import java.util.Properties JavaDoc;
35 import java.util.Set JavaDoc;
36 import java.util.TreeSet JavaDoc;
37
38 import org.apache.maven.artifact.Artifact;
39 import org.apache.maven.artifact.factory.ArtifactFactory;
40 import org.apache.maven.artifact.repository.ArtifactRepository;
41 import org.apache.maven.artifact.resolver.ArtifactResolver;
42 import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter;
43 import org.apache.maven.plugin.AbstractMojo;
44 import org.apache.maven.plugin.MojoExecutionException;
45 import org.apache.maven.project.MavenProject;
46 import org.apache.maven.project.MavenProjectBuilder;
47
48 /**
49  * @goal generate
50  * @requiresDependencyResolution runtime
51  * @description ant build properties file generator
52  */

53 public class AntPropsMojo extends AbstractMojo {
54
55     //======================== MOJO ===============================
56
/**
57      * @parameter expression="${project}"
58      */

59     private MavenProject project;
60
61     /**
62      * @parameter expression="${localRepository}"
63      */

64     private ArtifactRepository localRepository;
65
66     /**
67      * @component role="org.apache.maven.artifact.resolver.ArtifactResolver"
68      */

69     private ArtifactResolver artifactResolver;
70
71     /**
72      * @parameter expression="${project.remoteArtifactRepositories}"
73      */

74     private List JavaDoc remoteArtifactRepositories;
75
76     /**
77      * @component role="org.apache.maven.artifact.factory.ArtifactFactory"
78      */

79     private ArtifactFactory artifactFactory;
80
81     /**
82      * @component role="org.apache.maven.project.MavenProjectBuilder"
83      */

84     private MavenProjectBuilder mavenProjectBuilder;
85     
86     //======================== CONFIG ================================
87

88     /**
89      * Things that will be added to the "test.jars" master classpath
90      * @parameter
91      */

92     private List JavaDoc testPaths;
93     
94     /**
95      * Things that are not related to build / test and run but other
96      * stuff like checkstyle, code coverage etc.
97      * @parameter
98      */

99     private List JavaDoc extraPaths;
100     
101     //======================== PRIVATE ===============================
102
/**
103      * properties initialized at the top e.g. "m2.repo"
104      */

105     private Map JavaDoc buildProperties = new LinkedHashMap JavaDoc();
106     
107     /**
108      * this collects paths resolved from the input "testPaths" parameter
109      */

110     private Map JavaDoc testClassPaths = new LinkedHashMap JavaDoc();
111     
112     /**
113      * this collects paths resolved from the input "extraPaths" parameter
114      */

115     private Map JavaDoc extraClassPaths = new LinkedHashMap JavaDoc();
116     
117     /**
118      * this collects the list of files that go into WEB-INF/lib
119      */

120     private Set JavaDoc runtimeFiles;
121     
122     /**
123      * hack to hold paths flagged as filesets and that should be output as
124      * (relativePath1,relativePath2) not classpaths like (absolutePath1:absolutePath2)
125      * ideally we should have extended the Value Objects instead of using Maps above
126      */

127     private Set JavaDoc filesets = new HashSet JavaDoc();
128                                              
129     //========================== MAIN ================================
130

131     public void execute() throws MojoExecutionException {
132         if (testPaths == null) {
133             testPaths = new ArrayList JavaDoc();
134         }
135         if (extraPaths == null) {
136             extraPaths = new ArrayList JavaDoc();
137         }
138         String JavaDoc repoBaseDir = localRepository.getBasedir().replace('\\','/');
139         try {
140             buildProperties.put("m2.repo", repoBaseDir);
141             //========================================================
142
Collection JavaDoc runtimeArtifacts = project.getArtifacts();
143             runtimeFiles = getRelativePaths(getFiles(runtimeArtifacts), repoBaseDir);
144             //========================================================
145
Set JavaDoc testArtifacts = project.getDependencyArtifacts();
146             testArtifacts.addAll(project.getTestArtifacts());
147             Collection JavaDoc testFiles = getFiles(testArtifacts);
148             testClassPaths.put("m2.repo", getRelativePaths(testFiles, repoBaseDir));
149             //========================================================
150
Properties JavaDoc props = loadProperties();
151             for (Iterator JavaDoc i = testPaths.iterator(); i.hasNext(); ) {
152                 TestPath testPath = (TestPath) i.next();
153                 String JavaDoc baseDirProperty = testPath.getBaseDirProperty();
154                 String JavaDoc baseDirPath = props.getProperty(baseDirProperty);
155                 if (baseDirPath == null) {
156                     getLog().warn("baseDirProperty + '" + baseDirProperty + "' does not exist in build.properties");
157                     break;
158                 }
159                 File JavaDoc baseDir = new File JavaDoc(baseDirPath);
160                 if (!baseDir.exists() || !baseDir.isDirectory()) {
161                     getLog().warn("path + '" + baseDirPath + "' is not valid directory");
162                     break;
163                 }
164                 buildProperties.put(baseDirProperty, baseDirPath);
165                 Set JavaDoc filePaths = new TreeSet JavaDoc();
166                 for (Iterator JavaDoc j = testPath.getPaths().iterator(); j.hasNext(); ) {
167                     String JavaDoc path = (String JavaDoc) j.next();
168                     File JavaDoc file = new File JavaDoc(baseDirPath + "/" + path);
169                     if (!file.exists()) {
170                         getLog().warn("additional test path: '" + file.getPath() + "' does not exist");
171                         continue;
172                     }
173                     if (file.isDirectory()) {
174                         File JavaDoc[] files = file.listFiles();
175                         for (int x = 0; x < files.length; x++) {
176                             filePaths.add(getRelativePath(files[x], baseDir.getPath()));
177                         }
178                     } else {
179                         filePaths.add(getRelativePath(file, baseDir.getPath()));
180                     }
181                 }
182                 testClassPaths.put(baseDirProperty, filePaths);
183             }
184             //========================================================
185
for (Iterator JavaDoc i = extraPaths.iterator(); i.hasNext(); ) {
186                 ExtraPath ep = (ExtraPath) i.next();
187                 Set JavaDoc paths = new TreeSet JavaDoc();
188                 Collection JavaDoc files = new ArrayList JavaDoc();
189                 for (Iterator JavaDoc j = ep.getDependencies().iterator(); j.hasNext(); ) {
190                     Dependency d = (Dependency) j.next();
191                     if (d.isResolve()) {
192                         files.addAll(getFiles(d.getGroupId(), d.getArtifactId(), d.getVersion()));
193                     } else {
194                         Artifact a = getArtifact(d.getGroupId(), d.getArtifactId(), d.getVersion());
195                         files.add(resolveArtifact(a));
196                     }
197                 }
198                 paths.addAll(getRelativePaths(files, repoBaseDir));
199                 extraClassPaths.put(ep.getName(), paths);
200                 if (ep.isFileset()) {
201                     filesets.add(ep.getName());
202                 }
203             }
204             //========================================================
205
writeAntPropsFile();
206         } catch (Exception JavaDoc e) {
207             e.printStackTrace();
208             throw new MojoExecutionException(e.getLocalizedMessage());
209         }
210     }
211     
212     //========================== HELPER METHODS ======================
213

214     /**
215      * instantiate a single artifact using Maven, on the fly
216      */

217     private Artifact getArtifact(String JavaDoc groupId, String JavaDoc artifactId, String JavaDoc version) {
218         return artifactFactory.createArtifact(groupId, artifactId, version, "", "jar");
219     }
220
221     /**
222      * resolve dependencies for the given artifact details using Maven, on the fly
223      */

224     private Collection JavaDoc resolveDependencies(String JavaDoc groupId, String JavaDoc artifactId, String JavaDoc version) throws Exception JavaDoc {
225         Artifact pomArtifact = getArtifact(groupId, artifactId, version);
226         MavenProject pomProject = mavenProjectBuilder.buildFromRepository(pomArtifact, remoteArtifactRepositories, localRepository);
227         Collection JavaDoc artifacts = pomProject.createArtifacts(artifactFactory, Artifact.SCOPE_TEST, new ScopeArtifactFilter(Artifact.SCOPE_TEST));
228         Iterator JavaDoc i = artifacts.iterator();
229         while(i.hasNext()) {
230             Artifact a = (Artifact) i.next();
231             resolveArtifact(a);
232         }
233         artifacts.add(pomArtifact);
234         return artifacts;
235     }
236
237     /**
238      * resolve single artifact to file, and resolve fully from repository if required
239      */

240     private File JavaDoc resolveArtifact(Artifact artifact) throws Exception JavaDoc {
241         File JavaDoc f = artifact.getFile();
242         if (f != null) {
243             return f;
244         }
245         getLog().info("resolving artifact: " + artifact);
246         artifactResolver.resolve(artifact, remoteArtifactRepositories, localRepository);
247         return artifact.getFile();
248     }
249     
250     /**
251      * convert a collection of maven artifacts into a collection of files
252      */

253     private Collection JavaDoc getFiles(Collection JavaDoc artifacts) throws Exception JavaDoc {
254         Collection JavaDoc files = new ArrayList JavaDoc();
255         Iterator JavaDoc i = artifacts.iterator();
256         while(i.hasNext()) {
257             Artifact a = (Artifact) i.next();
258             files.add(resolveArtifact(a));
259         }
260         return files;
261     }
262     
263     /**
264      * convenience combination of resolving and getting a bunch of files
265      */

266     private Collection JavaDoc getFiles(String JavaDoc groupId, String JavaDoc artifactId, String JavaDoc version) throws Exception JavaDoc {
267         return getFiles(resolveDependencies(groupId, artifactId, version));
268     }
269     
270     /**
271      * function to return relative path given base path and the target file
272      */

273     private String JavaDoc getRelativePath(File JavaDoc file, String JavaDoc basePath) {
274         String JavaDoc p = basePath.replace('\\','/');
275         int len = p.length() + 1;
276         if (p.endsWith("/")) {
277             len--;
278         }
279         return file.getPath().substring(len).replace('\\','/');
280     }
281     
282     /**
283      * add path entries for the given bunch of files
284      */

285     private Set JavaDoc getRelativePaths(Collection JavaDoc files, String JavaDoc basePath) {
286         Set JavaDoc paths = new TreeSet JavaDoc();
287         Iterator JavaDoc i = files.iterator();
288         while (i.hasNext()) {
289             File JavaDoc f = (File JavaDoc) i.next();
290             String JavaDoc path = getRelativePath(f, basePath);
291             paths.add(path);
292         }
293         return paths;
294     }
295     
296     /**
297      * load properties from file
298      */

299     private Properties JavaDoc loadProperties() throws Exception JavaDoc {
300         File JavaDoc file = new File JavaDoc("build.properties");
301         Properties JavaDoc props = new Properties JavaDoc();
302         if (!file.exists()) {
303             getLog().warn("build.properties does not exist");
304             return props;
305         }
306         InputStream JavaDoc is = null;
307         try {
308             is = new FileInputStream JavaDoc("build.properties");
309             props.load(is);
310         } finally {
311             is.close();
312         }
313         return props;
314     }
315     
316     /**
317      * generate properties file with dependency information, ready to use by ant
318      */

319     private void writeAntPropsFile() throws Exception JavaDoc {
320         OutputStream JavaDoc os = new FileOutputStream JavaDoc("build-deps.properties");
321         Writer JavaDoc out = new PrintWriter JavaDoc(os);
322         Date JavaDoc date = new Date JavaDoc();
323         out.write("# *** generated by the AntProps Maven2 plugin: " + date + " ***\n\n");
324         Set JavaDoc allPaths = new TreeSet JavaDoc(); // collect all paths here
325
//==========================================================
326
for (Iterator JavaDoc i = buildProperties.entrySet().iterator(); i.hasNext(); ) {
327             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) i.next();
328             out.write(entry.getKey() + "=" + entry.getValue() + "\n\n");
329         }
330         //===========================================================
331
out.write("runtime.jars=");
332         for (Iterator JavaDoc i = runtimeFiles.iterator(); i.hasNext(); ) {
333             String JavaDoc path = (String JavaDoc) i.next();
334             out.write("\\\n " + path + ",");
335         }
336         out.write("\n\n");
337         //===========================================================
338
out.write("test.jars=");
339         for (Iterator JavaDoc i = testClassPaths.entrySet().iterator(); i.hasNext(); ) {
340             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) i.next();
341             String JavaDoc key = (String JavaDoc) entry.getKey();
342             Set JavaDoc paths = (Set JavaDoc) entry.getValue();
343             for (Iterator JavaDoc j = paths.iterator(); j.hasNext(); ) {
344                 String JavaDoc path = (String JavaDoc) j.next();
345                 String JavaDoc fullPath = "${" + key + "}/" + path;
346                 out.write("\\\n " + fullPath + ":");
347                 if(key.equals("m2.repo")) {
348                     allPaths.add(path);
349                 }
350             }
351         }
352         out.write("\n\n");
353         //===============================================================
354
for (Iterator JavaDoc i = extraClassPaths.entrySet().iterator(); i.hasNext(); ) {
355             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) i.next();
356             String JavaDoc name = (String JavaDoc) entry.getKey();
357             boolean isFileset = filesets.contains(name);
358             out.write(name + "=");
359             Set JavaDoc paths = (Set JavaDoc) entry.getValue();
360             for (Iterator JavaDoc j = paths.iterator(); j.hasNext(); ) {
361                 String JavaDoc path = (String JavaDoc) j.next();
362                 String JavaDoc fullPath = "${m2.repo}/" + path;
363                 if (isFileset) {
364                     out.write("\\\n " + path + ",");
365                 } else {
366                     out.write("\\\n " + fullPath + ":");
367                 }
368                 allPaths.add(path);
369             }
370             out.write("\n\n");
371         }
372         //===============================================================
373
out.write("all.jars=");
374         for (Iterator JavaDoc i = allPaths.iterator(); i.hasNext(); ) {
375             String JavaDoc path = (String JavaDoc) i.next();
376             out.write("\\\n " + path + ",");
377         }
378         out.write("\n\n");
379         //===============================================================
380
out.close();
381         os.close();
382     }
383     
384 }
385
Popular Tags