View Javadoc

1   /**
2    * Pyx4me framework
3    * Copyright (C) 2006-2008 pyx4j.com.
4    * 
5    * Licensed under the Apache License, Version 2.0 (the "License");
6    * you may not use this file except in compliance with the License.
7    * 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,
12   * software distributed under the License is distributed on an
13   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14   * KIND, either express or implied.  See the License for the
15   * specific language governing permissions and limitations
16   * under the License.
17   * 
18   * @author vlads
19   * @version $Id: AbstractWtkMojo.java 2105 2008-07-08 15:25:35Z vlads $
20   */
21  package com.pyx4me.maven.j2me;
22  
23  import java.io.File;
24  import java.lang.reflect.InvocationTargetException;
25  import java.lang.reflect.Method;
26  import java.util.HashMap;
27  import java.util.Iterator;
28  import java.util.List;
29  import java.util.Map;
30  import java.util.Vector;
31  
32  import org.apache.maven.artifact.Artifact;
33  import org.apache.maven.plugin.AbstractMojo;
34  import org.apache.maven.plugin.MojoExecutionException;
35  import org.apache.maven.plugin.MojoFailureException;
36  import org.apache.maven.project.MavenProject;
37  import org.apache.tools.ant.DefaultLogger;
38  import org.apache.tools.ant.Project;
39  import org.apache.tools.ant.PropertyHelper;
40  import org.apache.tools.ant.Target;
41  import org.apache.tools.ant.Task;
42  
43  /**
44   * 
45   * @requiresDependencyResolution test
46   * 
47   */
48  public abstract class AbstractWtkMojo extends AbstractMojo {
49  
50      /**
51       * The path to the j2me sdk to use for preverifying. e.g. ${env.WTK_HOME}
52       * 
53       * @parameter
54       */
55      protected String wtkHome;
56  
57      /**
58       * Use WTK libraries or project dependency provided artifacts. See libs
59       * 
60       * @parameter default-value="true"
61       */
62      protected boolean useWtkLibs;
63  
64      /**
65       * Additional -libraryjars e.g. ${java.home}/lib/rt.jar Project compile
66       * dependency used by ProGuard instead of WTK libs. See useWtkLibs
67       * 
68       * @parameter
69       */
70      protected List libs;
71  
72      /**
73       * Apply ProGuard classpathentry Filters to dependencies. When project
74       * compile dependency is used by ProGuard instead of WTK libs. See
75       * useWtkLibs
76       * 
77       * @parameter
78       * 
79       */
80      protected List dependencies;
81  
82      /**
83       * Directory containing the generated JAR.
84       * 
85       * @parameter expression="${project.build.directory}"
86       * @required
87       */
88      protected File outputDirectory;
89  
90      /**
91       * The Maven project reference where the plugin is currently being executed.
92       * The default value is populated from maven.
93       * 
94       * @parameter expression="${project}"
95       * @required
96       */
97      protected MavenProject mavenProject;
98  
99      /**
100      * @parameter expression="${project.packaging}"
101      * @readonly
102      * @required
103      */
104     protected String packaging;
105 
106     /**
107      * The plugin dependencies.
108      * 
109      * @parameter expression="${plugin.artifacts}"
110      * @required
111      * @readonly
112      */
113     protected List pluginArtifacts;
114 
115     /**
116      * The midlets name
117      * 
118      * @parameter expression="${j2me.midlet.name}"
119      *            default-value="${project.name}"
120      * @required
121      */
122     protected String midletName;
123 
124     /**
125      * The midlets vendor
126      * 
127      * @parameter expression="${j2me.midlet.vendor}"
128      *            default-value="${project.organization.name}"
129      * @required
130      */
131     protected String midletVendor;
132 
133     /**
134      * The midlets version, -SNAPSHOT would be removed.
135      * 
136      * @parameter expression="${j2me.midlet.version}"
137      *            default-value="${project.version}"
138      * @required
139      */
140     protected String midletVersion;
141 
142     /**
143      * The midlets configuration
144      * 
145      * @parameter expression="${j2me.midlet.configuration}"
146      *            default-value="CLDC-1.1"
147      * @required
148      */
149     protected String j2meConfiguration;
150 
151     /**
152      * The midlets profile
153      * 
154      * @parameter expression="${j2me.midlet.profile}" default-value="MIDP-2.0"
155      * @required
156      */
157     protected String j2meProfile;
158 
159     private Project antProject;
160 
161     public void executeTask(Task task) throws MojoExecutionException, MojoFailureException {
162         List antTasks = new Vector();
163         antTasks.add(task);
164         executeTasks(antTasks);
165     }
166 
167     String getWtkVersion(String version) {
168         int i = version.indexOf('-');
169         if (i == -1) {
170             return version;
171         } else {
172             return version.substring(i + 1);
173         }
174     }
175 
176     Project getAntProject() throws MojoExecutionException {
177         if (antProject != null) {
178             return antProject;
179         }
180         antProject = new Project();
181         antProject.setName(mavenProject.getName());
182         antProject.init();
183 
184         if (useWtkLibs && (wtkHome == null)) {
185             throw new MojoExecutionException(
186                     "required plugin parameter is missing\n inside the definition for plugin: 'j2me-maven-plugin' specify the following:\n"
187                             + "<configuration>\n" + "  ...\n" + "  <wtkHome>${env.WTK_HOME}</wtkHome>\n"
188                             + "</configuration>.");
189         }
190         if (wtkHome != null) {
191             antProject.setProperty("wtk.home", wtkHome);
192         }
193         antProject.setProperty("wtk.cldc.version", getWtkVersion(j2meConfiguration));
194         antProject.setProperty("wtk.midp.version", getWtkVersion(j2meProfile));
195 
196         PropertyHelper propertyHelper = PropertyHelper.getPropertyHelper(antProject);
197 
198         propertyHelper.setNext(new AntPropertyHelper(this.mavenProject, getLog()));
199 
200         if (useWtkLibs) {
201             detectJSRLibrary(mavenProject, antProject);
202         }
203         DefaultLogger antLogger = new DefaultLogger();
204         antLogger.setOutputPrintStream(System.out);
205         antLogger.setErrorPrintStream(System.err);
206         antLogger.setMessageOutputLevel(getLog().isDebugEnabled() ? Project.MSG_DEBUG : Project.MSG_INFO);
207 
208         antProject.addBuildListener(antLogger);
209         antProject.setBaseDir(mavenProject.getBasedir());
210 
211         return antProject;
212 
213     }
214 
215     private void detectJSRLibrary(MavenProject mavenProject2, Project antProject2) {
216         // TODO Auto-generated method stub
217 
218     }
219 
220     public static String getSimpleName(Object obj) {
221         // Java 1.5
222         // obj.getClass().getSimpleName()
223         String simpleName = obj.getClass().getName();
224         // strip the package name
225         return simpleName.substring(simpleName.lastIndexOf(".") + 1);
226     }
227 
228     public void initTask(Task task) throws MojoExecutionException {
229         task.setTaskName(getSimpleName(task));
230         task.setProject(getAntProject());
231         task.init();
232     }
233 
234     public void executeTasks(List antTasks) throws MojoExecutionException, MojoFailureException {
235 
236         getAntProject();
237 
238         Target tasks = new Target();
239 
240         tasks.setName(getSimpleName(this));
241 
242         tasks.setProject(antProject);
243 
244         for (Iterator i = antTasks.iterator(); i.hasNext();) {
245             Task task = (Task) i.next();
246             tasks.addTask(task);
247         }
248 
249         tasks.execute();
250     }
251 
252     public static File getClasspathElement(Artifact artifact, MavenProject mavenProject) throws MojoExecutionException {
253         String refId = artifact.getGroupId() + ":" + artifact.getArtifactId();
254         MavenProject project = (MavenProject) mavenProject.getProjectReferences().get(refId);
255         if (project != null) {
256             return new File(project.getBuild().getOutputDirectory());
257         } else {
258             File file = artifact.getFile();
259             if ((file == null) || (!file.exists())) {
260                 throw new MojoExecutionException("Dependency Resolution Required " + artifact);
261             }
262             return file;
263         }
264     }
265 
266     private Map compileArtifactsByID = null;
267 
268     public Artifact getArtifactByID(String id) {
269         if (compileArtifactsByID == null) {
270             compileArtifactsByID = new HashMap();
271             List dependencies = mavenProject.getCompileArtifacts();
272             for (Iterator i = dependencies.iterator(); i.hasNext();) {
273                 Artifact artifact = (Artifact) i.next();
274                 compileArtifactsByID.put(artifact.getId(), artifact);
275             }
276         }
277         return (Artifact) compileArtifactsByID.get(id);
278     }
279 
280     public Dependency getDependencyConfig(Artifact artifact) {
281         if (dependencies == null) {
282             return null;
283         }
284         boolean hasTrailFlag = false;
285         for (Iterator iter = dependencies.iterator(); iter.hasNext();) {
286             Dependency d = (Dependency) iter.next();
287             if (d.match(artifact)) {
288                 return d;
289             }
290             if (d.withTrail) {
291                 hasTrailFlag = true;
292             }
293         }
294 
295         if (hasTrailFlag) {
296             for (Iterator trailIter = artifact.getDependencyTrail().iterator(); trailIter.hasNext();) {
297                 String artifactID = (String) trailIter.next();
298                 Artifact trailArtifact = getArtifactByID(artifactID);
299                 if (trailArtifact == null) {
300                     continue;
301                 }
302                 for (Iterator iter = dependencies.iterator(); iter.hasNext();) {
303                     Dependency d = (Dependency) iter.next();
304                     if ((d.withTrail) && (d.match(trailArtifact))) {
305                         return d;
306                     }
307                 }
308             }
309         }
310         return null;
311     }
312 
313     public boolean isUseDependency(Artifact artifact) {
314         Dependency dependencyConfig = getDependencyConfig(artifact);
315         boolean include = Artifact.SCOPE_PROVIDED.equals(artifact.getScope())
316                 || Artifact.SCOPE_SYSTEM.equals(artifact.getScope());
317         if (dependencyConfig != null) {
318             if (dependencyConfig.exclude) {
319                 return false;
320             }
321             if (dependencyConfig.include) {
322                 include = true;
323             }
324         }
325         return include;
326     }
327 
328     protected static void setFileValue(Object task, String methodName, File value) throws MojoFailureException {
329         Method mts[] = task.getClass().getMethods();
330         Method m = null;
331         for (int i = 0; i < mts.length; i++) {
332             if (!methodName.equals(mts[i].getName())) {
333                 continue;
334             }
335             if (mts[i].getReturnType() != void.class) {
336                 continue;
337             }
338             if (mts[i].getParameterTypes().length != 1) {
339                 continue;
340             }
341             m = mts[i];
342             break;
343         }
344         if (m == null) {
345             throw new MojoFailureException(methodName + " not found in " + task.getClass().getName());
346         }
347         Class paramType = m.getParameterTypes()[0];
348         try {
349             if (paramType.isAssignableFrom(File.class)) {
350                 m.invoke(task, new Object[] { value });
351             } else if (paramType.isAssignableFrom(String.class)) {
352                 m.invoke(task, new Object[] { value.getAbsolutePath() });
353             } else {
354                 throw new MojoFailureException(methodName + " in " + task.getClass().getName()
355                         + " accepts unknown type " + paramType.getName());
356             }
357         } catch (IllegalAccessException e) {
358             throw new MojoFailureException("Fail to execute " + methodName + " in " + task.getClass().getName() + e);
359         } catch (InvocationTargetException e) {
360             throw new MojoFailureException("Fail to execute " + methodName + " in " + task.getClass().getName() + e);
361         }
362     }
363 }