KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > servicemix > maven > plugin > jbi > GenerateServiceUnitDescriptorMojo


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 package org.apache.servicemix.maven.plugin.jbi;
18
19 import java.io.File JavaDoc;
20 import java.net.MalformedURLException JavaDoc;
21 import java.net.URL JavaDoc;
22 import java.net.URLClassLoader JavaDoc;
23 import java.util.ArrayList JavaDoc;
24 import java.util.HashSet JavaDoc;
25 import java.util.Iterator JavaDoc;
26 import java.util.List JavaDoc;
27 import java.util.Set JavaDoc;
28
29 import org.apache.maven.artifact.Artifact;
30 import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter;
31 import org.apache.maven.model.Plugin;
32 import org.apache.maven.plugin.MojoExecutionException;
33 import org.apache.maven.plugin.MojoFailureException;
34 import org.apache.maven.project.MavenProject;
35 import org.apache.maven.project.ProjectBuildingException;
36 import org.apache.servicemix.common.packaging.ServiceUnitAnalyzer;
37 import org.codehaus.plexus.util.xml.Xpp3Dom;
38
39 /**
40  * A Mojo used to build the jbi.xml file for a service unit.
41  *
42  * @author <a HREF="pdodds@apache.org">Philip Dodds</a>
43  * @version $Id: GenerateComponentDescriptorMojo 314956 2005-10-12 16:27:15Z
44  * brett $
45  * @goal generate-jbi-service-unit-descriptor
46  * @phase generate-resources
47  * @requiresDependencyResolution runtime
48  * @description generates the jbi.xml deployment descriptor for a service unit
49  */

50 public class GenerateServiceUnitDescriptorMojo extends AbstractJbiMojo {
51
52     public static final String JavaDoc UTF_8 = "UTF-8";
53
54     /**
55      * Whether the jbi.xml should be generated or not.
56      *
57      * @parameter
58      */

59     private Boolean JavaDoc generateJbiDescriptor = Boolean.TRUE;
60
61     /**
62      * Determines whether to use the service unit analyzer
63      *
64      * @parameter
65      */

66     private Boolean JavaDoc useServiceUnitAnalyzer = Boolean.TRUE;
67
68     /**
69      * The component name.
70      *
71      * @parameter expression="${project.artifactId}"
72      */

73     private String JavaDoc name;
74
75     /**
76      * The component description.
77      *
78      * @parameter expression="${project.name}"
79      */

80     private String JavaDoc description;
81
82     /**
83      * Character encoding for the auto-generated application.xml file.
84      *
85      * @parameter
86      */

87     private String JavaDoc encoding = UTF_8;
88
89     /**
90      * Directory where the application.xml file will be auto-generated.
91      *
92      * @parameter expression="${project.build.directory}/classes/META-INF"
93      */

94     private String JavaDoc generatedDescriptorLocation;
95
96     /**
97      * Directory where artifacts for the service unit are held
98      *
99      * @parameter expression="${basedir}/src/main/resources"
100      */

101     private File JavaDoc serviceUnitArtifactsDir;
102
103     public void execute() throws MojoExecutionException, MojoFailureException {
104
105         getLog().debug(
106                 " ======= GenerateServiceUnitDescriptorMojo settings =======");
107         getLog().debug("workDirectory[" + workDirectory + "]");
108         getLog().debug("generateDescriptor[" + generateJbiDescriptor + "]");
109         getLog().debug("name[" + name + "]");
110         getLog().debug("description[" + description + "]");
111         getLog().debug("encoding[" + encoding + "]");
112         getLog().debug(
113                 "generatedDescriptorLocation[" + generatedDescriptorLocation
114                         + "]");
115
116         if (!generateJbiDescriptor.booleanValue()) {
117             getLog().debug("Generation of jbi.xml is disabled");
118             return;
119         }
120
121         // Generate jbi descriptor and copy it to the build directory
122
getLog().info("Generating jbi.xml");
123         try {
124             generateJbiDescriptor();
125         } catch (JbiPluginException e) {
126             throw new MojoExecutionException("Failed to generate jbi.xml", e);
127         }
128
129     }
130
131     /**
132      * Set up a classloader for the execution of the main class.
133      *
134      * @return
135      * @throws MojoExecutionException
136      */

137     private URLClassLoader JavaDoc getClassLoader() throws MojoExecutionException {
138         try {
139             Set JavaDoc urls = new HashSet JavaDoc();
140
141             URL JavaDoc mainClasses = new File JavaDoc(project.getBuild().getOutputDirectory())
142                     .toURL();
143             getLog().debug("Adding to classpath : " + mainClasses);
144             urls.add(mainClasses);
145
146             URL JavaDoc testClasses = new File JavaDoc(project.getBuild()
147                     .getTestOutputDirectory()).toURL();
148             getLog().debug("Adding to classpath : " + testClasses);
149             urls.add(testClasses);
150
151             Set JavaDoc dependencies = project.getArtifacts();
152             Iterator JavaDoc iter = dependencies.iterator();
153             while (iter.hasNext()) {
154                 Artifact classPathElement = (Artifact) iter.next();
155                 getLog().debug(
156                         "Adding artifact: " + classPathElement.getFile()
157                                 + " to classpath");
158                 urls.add(classPathElement.getFile().toURL());
159             }
160             URLClassLoader JavaDoc appClassloader = new URLClassLoader JavaDoc((URL JavaDoc[]) urls
161                     .toArray(new URL JavaDoc[urls.size()]), this.getClass()
162                     .getClassLoader());
163             return appClassloader;
164         } catch (MalformedURLException JavaDoc e) {
165             throw new MojoExecutionException(
166                     "Error during setting up classpath", e);
167         }
168     }
169
170     /**
171      * Generates the deployment descriptor if necessary.
172      */

173     protected void generateJbiDescriptor() throws JbiPluginException {
174         File JavaDoc outputDir = new File JavaDoc(generatedDescriptorLocation);
175         if (!outputDir.exists()) {
176             outputDir.mkdirs();
177         }
178
179         ClassLoader JavaDoc old = Thread.currentThread().getContextClassLoader();
180         
181         try {
182             URLClassLoader JavaDoc newClassLoader = getClassLoader();
183             Thread.currentThread().setContextClassLoader(newClassLoader);
184             File JavaDoc descriptor = new File JavaDoc(outputDir, JBI_DESCRIPTOR);
185             List JavaDoc uris = new ArrayList JavaDoc();
186             JbiServiceUnitDescriptorWriter writer = new JbiServiceUnitDescriptorWriter(
187                     encoding);
188
189             List JavaDoc consumes = new ArrayList JavaDoc();
190             List JavaDoc provides = new ArrayList JavaDoc();
191
192             if (useServiceUnitAnalyzer.booleanValue()) {
193                 String JavaDoc serviceUnitAnalyzerClazzName = getServiceUnitAnalyzer();
194
195                 // The ServiceUnitAnalyzer should give us the consumes and
196
// provides
197
if (serviceUnitAnalyzerClazzName != null) {
198                     ServiceUnitAnalyzer serviceUnitAnalyzer = (ServiceUnitAnalyzer) newClassLoader
199                             .loadClass(serviceUnitAnalyzerClazzName)
200                             .newInstance();
201                     getLog().info(
202                             "Created Service Unit Analyzer "
203                                     + serviceUnitAnalyzer);
204                     serviceUnitAnalyzer.init(serviceUnitArtifactsDir);
205                     consumes.addAll(serviceUnitAnalyzer.getConsumes());
206                     provides.addAll(serviceUnitAnalyzer.getProvides());
207                 }
208
209                 getLog().info(
210                         "generated : consumes " + consumes + " provides "
211                                 + provides);
212
213             }
214             writer.write(descriptor, name, description, uris, consumes,
215                     provides);
216         } catch (Exception JavaDoc e) {
217             throw new JbiPluginException(
218                     "Unable to generate service unit descriptor!", e);
219         } finally {
220             Thread.currentThread().setContextClassLoader(old);
221         }
222     }
223
224     private String JavaDoc getServiceUnitAnalyzer() {
225         MavenProject project = getComponentProject();
226         if (project != null) {
227             List JavaDoc plugins = project.getBuild().getPlugins();
228             for (Iterator JavaDoc iterator = plugins.iterator(); iterator.hasNext();) {
229                 Plugin plugin = (Plugin) iterator.next();
230                 if ("org.apache.servicemix.tooling".equals(plugin.getGroupId())
231                         && "jbi-maven-plugin".equals(plugin.getArtifactId())) {
232                     Xpp3Dom o = (Xpp3Dom) plugin.getConfiguration();
233                     if (o != null && o.getChild("serviceUnitAnalyzer") != null) {
234                         String JavaDoc clazzName = o.getChild("serviceUnitAnalyzer")
235                                 .getValue();
236                         return clazzName;
237                     }
238                 }
239             }
240         }
241         return null;
242     }
243
244     private MavenProject getComponentProject() {
245         Set JavaDoc artifacts = project.getArtifacts();
246         for (Iterator JavaDoc iter = artifacts.iterator(); iter.hasNext();) {
247             Artifact artifact = (Artifact) iter.next();
248
249             // TODO: utilise appropriate methods from project builder
250
ScopeArtifactFilter filter = new ScopeArtifactFilter(
251                     Artifact.SCOPE_RUNTIME);
252             if (!artifact.isOptional() && filter.include(artifact)
253                     && (artifact.getDependencyTrail().size() == 2)) {
254                 MavenProject project = null;
255                 try {
256                     project = projectBuilder.buildFromRepository(artifact, remoteRepos,
257                             localRepo);
258                 } catch (ProjectBuildingException e) {
259                     getLog().warn(
260                             "Unable to determine packaging for dependency : "
261                                     + artifact.getArtifactId()
262                                     + " assuming jar");
263                 }
264                 if ((project != null)
265                         && (project.getPackaging().equals("jbi-component"))) {
266                     return project;
267                 }
268
269             }
270         }
271         return null;
272     }
273
274 }
275
Popular Tags