Author: tchemit Date: 2009-09-15 17:44:19 +0200 (Tue, 15 Sep 2009) New Revision: 573 Added: trunk/src/main/java/org/nuiton/plugin/ trunk/src/main/java/org/nuiton/plugin/AbstractPlugin.java trunk/src/main/java/org/nuiton/plugin/Plugin.java trunk/src/test/java/org/nuiton/plugin/ trunk/src/test/java/org/nuiton/plugin/AbstractMojoTest.java trunk/src/test/java/org/nuiton/plugin/TestHelper.java Removed: trunk/src/main/java/org/nuiton/Plugin.java trunk/src/main/java/org/nuiton/RunJavaPlugin.java Modified: trunk/pom.xml trunk/src/main/java/org/nuiton/AbstractPlugin.java trunk/src/main/java/org/nuiton/license/plugin/LicensePlugin.java trunk/src/main/java/org/nuiton/license/plugin/ThirdPartyPlugin.java trunk/src/test/java/org/nuiton/license/BaseLicenseTestCase.java trunk/src/test/java/org/nuiton/license/plugin/LicensePluginTest.java trunk/src/test/java/org/nuiton/util/BasePluginTestCase.java trunk/src/test/java/org/nuiton/util/JavaFileUpdaterTest.java trunk/src/test/java/org/nuiton/util/JaxxFileUpdaterTest.java trunk/src/test/java/org/nuiton/util/PluginConfig.java Log: [FEATURE #50 & #51] update to junit 4.7, rethink AbstractPlugin api Modified: trunk/pom.xml =================================================================== --- trunk/pom.xml 2009-09-11 22:06:27 UTC (rev 572) +++ trunk/pom.xml 2009-09-15 15:44:19 UTC (rev 573) @@ -22,12 +22,6 @@ <version>1.1.1</version> </dependency> - <!--dependency> - <groupId>org.apache.maven.enforcer</groupId> - <artifactId>enforcer-api</artifactId> - <version>1.0-beta-1</version> - </dependency--> - <dependency> <groupId>org.apache.maven.shared</groupId> <artifactId>maven-dependency-tree</artifactId> @@ -83,17 +77,10 @@ <scope>test</scope> </dependency> - <!--dependency> - <groupId>org.apache.maven.shared</groupId> - <artifactId>maven-verifier</artifactId> - <version>1.0</version> - <scope>test</scope> - </dependency--> - <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> - <version>4.6</version> + <version>4.7</version> <scope>test</scope> </dependency> @@ -115,7 +102,6 @@ <licenses> <license> <name>Lesser General Public License (LGPL)</name> - <!--<url>http://www.gnu.org/licenses/lgpl.txt</url>--> <url>${project.basedir}/LICENSE.txt</url> <distribution>local</distribution> </license> Modified: trunk/src/main/java/org/nuiton/AbstractPlugin.java =================================================================== --- trunk/src/main/java/org/nuiton/AbstractPlugin.java 2009-09-11 22:06:27 UTC (rev 572) +++ trunk/src/main/java/org/nuiton/AbstractPlugin.java 2009-09-15 15:44:19 UTC (rev 573) @@ -41,6 +41,7 @@ import org.codehaus.plexus.util.DirectoryScanner; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.io.RawInputStreamFacade; +import org.nuiton.plugin.Plugin; import org.nuiton.util.MirroredFileUpdater; import org.nuiton.util.PluginHelper; @@ -48,7 +49,9 @@ * Un MOJO de base pour les autres MOJO concrets avec les options communes. * * @author chemit + * @deprecated since 1.0.3, prefer use {@link org.nuiton.plugin.AbstractPlugin} */ +@Deprecated public abstract class AbstractPlugin extends AbstractMojo implements Plugin { protected abstract boolean ensurePackaging(); Deleted: trunk/src/main/java/org/nuiton/Plugin.java =================================================================== --- trunk/src/main/java/org/nuiton/Plugin.java 2009-09-11 22:06:27 UTC (rev 572) +++ trunk/src/main/java/org/nuiton/Plugin.java 2009-09-15 15:44:19 UTC (rev 573) @@ -1,23 +0,0 @@ -package org.nuiton; - -import org.apache.maven.plugin.Mojo; -import org.apache.maven.project.MavenProject; - -/** - * A common contract to be implements by our mojo and reports. - * - * Just expose a {@link #isVerbose()} flag and the maven project {@link #getProject()}. - * - * @author chemit - * @since 1.0.3 - */ -public interface Plugin extends Mojo { - - MavenProject getProject(); - - void setProject(MavenProject project); - - boolean isVerbose(); - - void setVerbose(boolean verbose); -} Deleted: trunk/src/main/java/org/nuiton/RunJavaPlugin.java =================================================================== --- trunk/src/main/java/org/nuiton/RunJavaPlugin.java 2009-09-11 22:06:27 UTC (rev 572) +++ trunk/src/main/java/org/nuiton/RunJavaPlugin.java 2009-09-15 15:44:19 UTC (rev 573) @@ -1,190 +0,0 @@ -/* - * *##% - * Maven helper plugin - * Copyright (C) 2009 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * ##%* - */ -package org.nuiton; - -import java.io.File; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import org.apache.maven.project.MavenProject; - -/** - * @goal runJava - * @requiresDependencyResolution test - * @requiresProject true - * @execute phase="process-classes" - * @since 1.0 - * @author chemit - */ -public class RunJavaPlugin extends AbstractPlugin { - - /** - * Dependance du projet. - * - * @parameter default-value="${project}" - * @required - * @since 1.0.0 - */ - protected MavenProject project; - /** - * The main class to execute. - * - * @parameter expression="${mainClass}" default-value="${maven.jar.main.class}" - * @required - * @since 1.0 - */ - protected String mainClass; - /** - * The class arguments. - * - * @parameter expression="${args}" - * @since 1.0 - */ - protected String args; - /** - * Un flag pour activer le mode verbeux. - * - * @parameter expression="${helper.verbose}" default-value="${maven.verbose}" - * @since 1.0.0 - */ - protected boolean verbose; - protected Class<?> clazz; - protected ClassLoader cl; - - public RunJavaPlugin() { - super(""); - } - - @Override - protected boolean ensurePackaging() { - return project != null && ("pom".equals(project.getPackaging()) || "site".equals(project.getPackaging())); - } - - @Override - protected boolean init() throws Exception { - - cl = initClassLoader(project, new File(project.getBuild().getOutputDirectory()), false, false, false, true, true); - - Thread.currentThread().setContextClassLoader(cl); - - clazz = Class.forName(mainClass, true, cl); - - if (args == null) { - args = ""; - } - return true; - } - - @Override - protected void doAction() throws Exception { - ThreadGroup threadGroup = Thread.currentThread().getThreadGroup(); - Thread bootstrapThread = new Thread(threadGroup, new Runnable() { - - @Override - public void run() { - try { - Method main = Class.forName(mainClass, true, cl).getMethod("main", String[].class); - if (!main.isAccessible()) { - getLog().debug("Setting accessibility to true in order to invoke main()."); - main.setAccessible(true); - } - main.invoke(main, new Object[]{args.split(" ")}); - } catch (NoSuchMethodException e) { - // just pass it on - Thread.currentThread().getThreadGroup().uncaughtException(Thread.currentThread(), new Exception("The specified mainClass doesn't contain a main method with appropriate signature.", e)); - } catch (Exception e) { - // just pass it on - Thread.currentThread().getThreadGroup().uncaughtException(Thread.currentThread(), e); - } finally { - - } - } - }, mainClass + ".main()"); - - bootstrapThread.setContextClassLoader(cl); - - bootstrapThread.start(); - - joinNonDaemonThreads(threadGroup); - } - - @Override - public MavenProject getProject() { - return project; - } - - @Override - public void setProject(MavenProject project) { - this.project = project; - } - - @Override - public boolean isVerbose() { - return verbose; - } - - @Override - public void setVerbose(boolean verbose) { - this.verbose = verbose; - } - - private void joinNonDaemonThreads(ThreadGroup threadGroup) { - boolean foundNonDaemon; - do { - foundNonDaemon = false; - Collection<Thread> threads = getActiveThreads(threadGroup); - for (Iterator<Thread> iter = threads.iterator(); iter.hasNext();) { - Thread thread = iter.next(); - if (thread.isDaemon()) { - continue; - } - foundNonDaemon = true; //try again; maybe more threads were created while we were busy - joinThread(thread, 0); - } - } while (foundNonDaemon); - } - - private void joinThread(Thread thread, long timeoutMsecs) { - try { - getLog().debug("joining on thread " + thread); - thread.join(timeoutMsecs); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); // good practice if don't throw - getLog().warn("interrupted while joining against thread " + thread, e); // not expected! - } - if (thread.isAlive()) //generally abnormal - { - getLog().warn("thread " + thread + " was interrupted but is still alive after waiting at least " + timeoutMsecs + "msecs"); - } - } - - private Collection<Thread> getActiveThreads(ThreadGroup threadGroup) { - Thread[] threads = new Thread[threadGroup.activeCount()]; - int numThreads = threadGroup.enumerate(threads); - Collection<Thread> result = new ArrayList<Thread>(numThreads); - for (int i = 0; i < threads.length && threads[i] != null; i++) { - result.add(threads[i]); - } - return result; //note: result should be modifiable - } - -} Modified: trunk/src/main/java/org/nuiton/license/plugin/LicensePlugin.java =================================================================== --- trunk/src/main/java/org/nuiton/license/plugin/LicensePlugin.java 2009-09-11 22:06:27 UTC (rev 572) +++ trunk/src/main/java/org/nuiton/license/plugin/LicensePlugin.java 2009-09-15 15:44:19 UTC (rev 573) @@ -35,7 +35,7 @@ * @requiresProject true * @requiresDependencyResolution compile */ -public class LicensePlugin extends org.nuiton.AbstractPlugin { +public class LicensePlugin extends org.nuiton.plugin.AbstractPlugin { /** * Dependance du projet. Modified: trunk/src/main/java/org/nuiton/license/plugin/ThirdPartyPlugin.java =================================================================== --- trunk/src/main/java/org/nuiton/license/plugin/ThirdPartyPlugin.java 2009-09-11 22:06:27 UTC (rev 572) +++ trunk/src/main/java/org/nuiton/license/plugin/ThirdPartyPlugin.java 2009-09-15 15:44:19 UTC (rev 573) @@ -41,7 +41,7 @@ import java.util.SortedSet; import java.util.TreeSet; import org.codehaus.plexus.util.IOUtil; -import org.nuiton.AbstractPlugin; +import org.nuiton.plugin.AbstractPlugin; /** * Le goal pour copier le fichier THIRD-PARTY.txt (contenant les licenses de toutes les dependances du projet) Copied: trunk/src/main/java/org/nuiton/plugin/AbstractPlugin.java (from rev 571, trunk/src/main/java/org/nuiton/AbstractPlugin.java) =================================================================== --- trunk/src/main/java/org/nuiton/plugin/AbstractPlugin.java (rev 0) +++ trunk/src/main/java/org/nuiton/plugin/AbstractPlugin.java 2009-09-15 15:44:19 UTC (rev 573) @@ -0,0 +1,438 @@ +/* + * *##% + * Maven helper plugin + * Copyright (C) 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * ##%* + */ +package org.nuiton.plugin; + +import java.io.ByteArrayInputStream; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.project.MavenProject; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.model.Resource; +import org.codehaus.plexus.util.DirectoryScanner; +import org.codehaus.plexus.util.FileUtils; +import org.codehaus.plexus.util.io.RawInputStreamFacade; +import org.nuiton.util.MirroredFileUpdater; +import org.nuiton.util.PluginHelper; + +/** + * Un MOJO de base pour les autres MOJO concrets avec les options communes. + * + * @author chemit + */ +public abstract class AbstractPlugin extends AbstractMojo implements Plugin { + + protected abstract boolean ensurePackaging(); + + /** + * la methode qui est lancee au debut de la methode {@link #execute()} pour preparer l'init du goal. + * + * @return <code>true</code> if there is something to generate, <code>false</code> otherwise. + * @throws Exception if any + */ + protected abstract boolean init() throws Exception; + + /** + * Do plugin action. + * <p/> + * The method {@link #execute()} invoke this method only and only if : + * <ul> + * <li>{@link #ensurePackaging()} returns <code>false</code> (filtrer project type, for example).</li> + * <li>method {@link #init()} returns <code>true</code>.</li> + * </ul> + * + * @throws Exception if any + */ + protected abstract void doAction() throws Exception; + protected final String skipAfterInitMessage; + + protected AbstractPlugin(String skipAfterInitMessage) { + this.skipAfterInitMessage = skipAfterInitMessage; + } + + @Override + public void execute() throws MojoExecutionException, MojoFailureException { + try { + + if (ensurePackaging()) { + getLog().info("skip goal for packaging " + getProject().getPackaging()); + return; + } + + boolean canContinue = init(); + + if (!canContinue) { + getLog().info(skipAfterInitMessage); + return; + } + + doAction(); + + } catch (Exception e) { + throw new MojoExecutionException("could not init goal " + getClass().getSimpleName() + " for reason : " + e.getMessage(), e); + } + } + + /** + * Does the actual copy of the file and logging. + * + * @param srcFile represents the file to copy. + * @param destFile file name of destination file. + * + * @throws MojoExecutionException with a message if an + * error occurs. + */ + protected void copyFile(File srcFile, File destFile) + throws MojoExecutionException { + try { + getLog().info("Copying " + srcFile.getName() + " to " + destFile); + + FileUtils.copyFile(srcFile, destFile); + + } catch (Exception e) { + throw new MojoExecutionException("Error copying from " + srcFile + " to " + destFile, e); + } + } + + /** + * Does the actual copy of the content to a fileand logging. + * + * @param content represents the content to writeFile into file. + * @param destFile file name of destination file. + * @param encoding encoding to use to writeFile file + * @throws MojoExecutionException with a message if an + * error occurs. + */ + protected void copyFile(String content, File destFile, String encoding) + throws MojoExecutionException { + try { + getLog().info("Copying content to " + destFile); + + InputStream in = new ByteArrayInputStream(content.getBytes(encoding)); + RawInputStreamFacade facade = new RawInputStreamFacade(in); + + FileUtils.copyStreamToFile(facade, destFile); + + } catch (Exception e) { + throw new MojoExecutionException("Error copying content to " + destFile, e); + } + } + + public void writeFile(File destFile, String content, String encoding) throws IOException { + PluginHelper.write(destFile, content, encoding); + } + + /** + * Test if a file exists and is newer than the pom file. + * + * @param f the file to test + * @return <code>true</code> if file exists and is newer than the pom file, + * <code>false</code> otherwise. + */ + protected boolean isFileNewerThanPomFile(File f) { + File pomFile = getProject().getFile(); + return f.exists() && f.lastModified() > pomFile.lastModified(); + } + + protected void getFilesToTreateForRoots(String[] includes, String[] excludes, List<String> roots, Map<File, String[]> files, MirroredFileUpdater updater) { + + DirectoryScanner ds = new DirectoryScanner(); + ds.setIncludes(includes); + if (excludes != null) { + ds.setExcludes(excludes); + + } + for (String src : roots) { + + File f = new File(src); + if (!f.exists()) { + // do nothing on a non-existent + continue; + } + + if (isVerbose()) { + getLog().info("discovering java source files in root " + src); + } + + ds.setBasedir(f); + // scan + ds.scan(); + + // get files + String[] tmp = ds.getIncludedFiles(); + + if (tmp.length < 1) { + // no files found + continue; + } + + List<String> toTreate = new ArrayList<String>(); + + if (updater != null) { + updater.setSourceDirectory(f); + } + + + for (String filePath : tmp) { + File srcFile = new File(f, filePath); + // check file is up-to-date + if (updater == null || !updater.isFileUpToDate(srcFile)) { + toTreate.add(filePath); + } + } + + + if (toTreate.isEmpty()) { + // no file or all are up-to-date + continue; + } + + // register files + files.put(f, toTreate.toArray(new String[toTreate.size()])); + + } + } + + protected Map<String, String> getFilesToTreate(String[] includes, String[] excludes, File srcDir, MirroredFileUpdater updater) { + + Map<String, String> result = new java.util.TreeMap<String, String>(); + + DirectoryScanner ds = new DirectoryScanner(); + ds.setIncludes(includes); + if (excludes != null) { + ds.setExcludes(excludes); + + } + + if (!srcDir.exists()) { + // do nothing on a non-existent + return result; + } + + if (isVerbose()) { + getLog().info("discovering files for " + srcDir); + } + + ds.setBasedir(srcDir); + // scan + ds.scan(); + + // get files + String[] tmp = ds.getIncludedFiles(); + + if (tmp.length < 1) { + // no files found + return result; + } + + List<String> toTreate = new ArrayList<String>(); + + if (updater != null) { + updater.setSourceDirectory(srcDir); + } + + for (String filePath : tmp) { + File srcFile = new File(srcDir, filePath); + File mirrorFile = updater.getMirrorFile(srcFile); + // check file is up-to-date + if (updater == null || !updater.isFileUpToDate(srcFile)) { + result.put(filePath, mirrorFile.getAbsolutePath()); + toTreate.add(filePath); + } + } + + + if (toTreate.isEmpty()) { + // no file or all are up-to-date + return result; + } + + // register files + return result; + } + + protected void addCompileSourceRoots(File srcDir) { + if (!getProject().getCompileSourceRoots().contains(srcDir.getPath())) { + if (isVerbose()) { + getLog().info("adding source roots : " + srcDir.getPath()); + } + getProject().addCompileSourceRoot(srcDir.getPath()); + } + } + + protected void removeCompileSourceRoots(File srcDir) { + if (getProject().getCompileSourceRoots().contains(srcDir.getPath())) { + if (isVerbose()) { + getLog().info("removing source roots : " + srcDir.getPath()); + } + getProject().getCompileSourceRoots().remove(srcDir.getPath()); + } + } + + protected void addTestCompileSourceRoots(File srcDir) { + if (!getProject().getTestCompileSourceRoots().contains(srcDir.getPath())) { + if (isVerbose()) { + getLog().info("adding test source roots : " + srcDir.getPath()); + } + getProject().addTestCompileSourceRoot(srcDir.getPath()); + } + } + + protected void removeTestCompileSourceRoots(File srcDir) { + if (getProject().getTestCompileSourceRoots().contains(srcDir.getPath())) { + if (isVerbose()) { + getLog().info("removing test source roots : " + srcDir.getPath()); + } + getProject().getTestCompileSourceRoots().remove(srcDir.getPath()); + } + } + + protected void addResourceDir(String dir) { + boolean added = PluginHelper.addResourceDir(dir, getProject()); + if (added) { + getLog().info("add resource " + dir); + } + } + + protected void addTestResourceDir(String dir) { + boolean added = PluginHelper.addTestResourceDir(dir, getProject()); + if (added) { + getLog().info("add test resource " + dir); + } + } + + @SuppressWarnings({"unchecked"}) + protected URLClassLoader initClassLoader(MavenProject project, File src, boolean addSourcesToClassPath, boolean testPhase, boolean addResourcesToClassPath, boolean addCompileClassPath, boolean addProjectClassPath) throws MalformedURLException { + URLClassLoader loader = null; + if (project != null) { + + URLClassLoader result; + try { + + List<URL> lUrls = new ArrayList<URL>(); + List<String> sources = project.getCompileSourceRoots(); + + if (addSourcesToClassPath) { + for (String source : sources) { + lUrls.add(new File(source).toURI().toURL()); + } + if (testPhase) { + for (Object source : project.getTestCompileSourceRoots()) { + lUrls.add(new File(source.toString()).toURI().toURL()); + } + } + } + if (addResourcesToClassPath) { + for (Object source : project.getResources()) { + Resource r = (Resource) source; + lUrls.add(new File(r.getDirectory()).toURI().toURL()); + } + } + if (testPhase && addCompileClassPath) { + if (project != null) { + lUrls.add(new File(project.getBuild().getOutputDirectory()).toURI().toURL()); + } + } + if (src != null) { + lUrls.add(src.toURI().toURL()); + } + if (addProjectClassPath) { + getLog().info("use project compile scope class-path"); + // add also all dependencies of the project in compile scope + Set<?> artifacts = project.getArtifacts(); + for (Object o : artifacts) { + Artifact a = (Artifact) o; + lUrls.add(a.getFile().toURI().toURL()); + } + } + + result = new URLClassLoader(lUrls.toArray(new URL[lUrls.size()]), getClass().getClassLoader()); + + } catch (IOException e) { + throw new RuntimeException("Can't create ClassLoader for reason " + e.getMessage(), e); + } + loader = result; + } else { + List<URL> lUrls = new ArrayList<URL>(); + if (addSourcesToClassPath) { + lUrls.add(src.toURI().toURL()); + } + loader = new URLClassLoader(lUrls.toArray(new URL[lUrls.size()]), getClass().getClassLoader()); + } + if (isVerbose()) { + for (URL entry : loader.getURLs()) { + getLog().info("classpath : " + entry); + } + } + return loader; + } + + /** + * + * @param f le fichier de template + * @return l'url du fichier demande + * @throws IOException pour toute erreur de recherche + */ + protected URL getTemplate(File f) throws IOException { + URL r = null; + if (f.exists()) { + r = f.toURI().toURL(); + } else { + r = getClass().getResource(f.toString()); + } + return r; + } + + /** + * Vérifie que le fichier donné existe bien (sur le filesystem ou + * dans le class-path). + * + * @param f le fichier que l'on veut vérifié + * @throws IOException pour tout erreur de recherche + */ + protected void checkResource(File f) throws IOException { + if (!f.exists()) { + // test in classPath + InputStream r = null; + try { + r = getClass().getResourceAsStream(f.toString()); + if (r == null) { + throw new IOException("could not find ressource " + f); + } + } finally { + if (r != null) { + r.close(); + } + } + } + } +} Property changes on: trunk/src/main/java/org/nuiton/plugin/AbstractPlugin.java ___________________________________________________________________ Added: svn:mergeinfo + Copied: trunk/src/main/java/org/nuiton/plugin/Plugin.java (from rev 571, trunk/src/main/java/org/nuiton/Plugin.java) =================================================================== --- trunk/src/main/java/org/nuiton/plugin/Plugin.java (rev 0) +++ trunk/src/main/java/org/nuiton/plugin/Plugin.java 2009-09-15 15:44:19 UTC (rev 573) @@ -0,0 +1,23 @@ +package org.nuiton.plugin; + +import org.apache.maven.plugin.Mojo; +import org.apache.maven.project.MavenProject; + +/** + * A common contract to be implements by our mojo and reports. + * + * Just expose a {@link #isVerbose()} flag and the maven project {@link #getProject()}. + * + * @author chemit + * @since 1.0.3 + */ +public interface Plugin extends Mojo { + + MavenProject getProject(); + + void setProject(MavenProject project); + + boolean isVerbose(); + + void setVerbose(boolean verbose); +} Property changes on: trunk/src/main/java/org/nuiton/plugin/Plugin.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL Added: svn:mergeinfo + Modified: trunk/src/test/java/org/nuiton/license/BaseLicenseTestCase.java =================================================================== --- trunk/src/test/java/org/nuiton/license/BaseLicenseTestCase.java 2009-09-11 22:06:27 UTC (rev 572) +++ trunk/src/test/java/org/nuiton/license/BaseLicenseTestCase.java 2009-09-15 15:44:19 UTC (rev 573) @@ -23,22 +23,21 @@ import org.junit.Assert; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; -import org.codehaus.plexus.util.IOUtil; +import org.nuiton.plugin.TestHelper; import org.nuiton.util.PluginHelper; /** @author chemit */ public abstract class BaseLicenseTestCase extends Assert { protected static final String encoding = "utf-8"; + protected File baseDir; protected File getBaseDir() { - String path = System.getenv("basedir"); - if (path == null) { - path = new File("").getAbsolutePath(); + if (baseDir == null) { + baseDir = TestHelper.getBasedir(); } - return new File(path); + return baseDir; } protected void assertLicenseFound(String name, License license) throws IOException { @@ -51,7 +50,7 @@ protected File createLicenseRepository(boolean createLicene) throws IOException { long timestamp = System.currentTimeMillis(); - File repo = new File(getBaseDir(), "target" + File.separator + "licenses_" + timestamp); + File repo = TestHelper.getFile(getBaseDir(), "target", "licenses_" + timestamp); if (createLicene) { @@ -68,20 +67,16 @@ String content = ""; if (defFile.exists()) { - content = IOUtil.toString(new FileInputStream(defFile), encoding) + "\n"; -// content = FileUtil.readAsString(defFile, encoding) + "\n"; + content = PluginHelper.readAsString(defFile, encoding) + "\n"; } - PluginHelper.write(defFile, content + licenseName + "=My dummy license\n", encoding); -// FileUtil.writeString(defFile, content + licenseName + "=My dummy license\n", encoding); + // create dummy licenses File file = new File(repo, licenseName); file.mkdirs(); PluginHelper.write(new File(file, "license.txt"), "license:" + licenseName, encoding); PluginHelper.write(new File(file, "header.txt"), "header:" + licenseName, encoding); -// FileUtil.writeString(new File(file, "license.txt"), "license:" + licenseName, encoding); -// FileUtil.writeString(new File(file, "header.txt"), "header:" + licenseName, encoding); } } Modified: trunk/src/test/java/org/nuiton/license/plugin/LicensePluginTest.java =================================================================== --- trunk/src/test/java/org/nuiton/license/plugin/LicensePluginTest.java 2009-09-11 22:06:27 UTC (rev 572) +++ trunk/src/test/java/org/nuiton/license/plugin/LicensePluginTest.java 2009-09-15 15:44:19 UTC (rev 573) @@ -20,51 +20,38 @@ */ package org.nuiton.license.plugin; -import org.nuiton.util.PluginConfig; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; import static org.junit.Assert.*; -import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; -import org.junit.AfterClass; -import org.nuiton.util.BasePluginTestCase; +import org.nuiton.plugin.AbstractMojoTest; -/** @author chemit */ -public class LicensePluginTest extends BasePluginTestCase<LicensePlugin> { +public class LicensePluginTest extends AbstractMojoTest<LicensePlugin> { - @BeforeClass - public static void initClass() throws Exception { - initConfigs(LicensePluginTest.class, "testOne"); + @Override + protected String getGoalName(String methodName) { + return "add-license"; } - @AfterClass - public static void afterClass() throws Exception { - configItr = null; - testDir = null; - } - - @Before @Override - public void setUp() throws Exception { - super.setUp(); - mojo.setOutputDirectory(new File(getBaseDir(), mojo.getOutputDirectory().toString())); - if (!mojo.getOutputDirectory().exists()) { - if (!mojo.getOutputDirectory().mkdirs()) { - throw new IOException("could not create directory : " + mojo.getOutputDirectory()); + protected void setUpMojo(LicensePlugin mojo, File pomFile) throws Exception { + super.setUpMojo(mojo, pomFile); + File outputDirectory = new File(getBasedir(), mojo.getOutputDirectory().toString()); + mojo.setOutputDirectory(outputDirectory); + if (!outputDirectory.exists()) { + if (!outputDirectory.mkdirs()) { + throw new IOException("could not create directory : " + outputDirectory); } } mojo.setLicenseFile(new File(pomFile.getParentFile(), mojo.getLicenseFile().toString())); } @Test - @PluginConfig(pomName = "testOne.xml", goalName = "add-license") - public void testOne() throws MojoExecutionException, MojoFailureException { - assertNotNull(mojo); + public void testOne() throws Exception { + LicensePlugin mojo = getMojo(); + long t0 = mojo.getLicenseFile().lastModified(); // always assume pom is older than any file @@ -84,4 +71,29 @@ assertTrue(t1 > t0); } + + @Test + public void testTwo() throws Exception { + + LicensePlugin mojo = getMojo(); + + long t0 = mojo.getLicenseFile().lastModified(); + + // always assume pom is older than any file + // since we can not ensure order of copy test resources + mojo.getProject().getFile().setLastModified(0); + + mojo.execute(); + + long t1 = mojo.getLicenseFile().lastModified(); + + assertEquals(t0, t1); + + mojo.setForce(true); + + mojo.execute(); + t1 = mojo.getLicenseFile().lastModified(); + + assertTrue(t1 > t0); + } } Added: trunk/src/test/java/org/nuiton/plugin/AbstractMojoTest.java =================================================================== --- trunk/src/test/java/org/nuiton/plugin/AbstractMojoTest.java (rev 0) +++ trunk/src/test/java/org/nuiton/plugin/AbstractMojoTest.java 2009-09-15 15:44:19 UTC (rev 573) @@ -0,0 +1,163 @@ +package org.nuiton.plugin; + +import java.io.File; +import org.apache.maven.plugin.Mojo; +import org.apache.maven.plugin.logging.Log; +import org.apache.maven.plugin.logging.SystemStreamLog; +import org.apache.maven.project.MavenProject; +import org.junit.rules.TestName; +import org.junit.Rule; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.runners.model.FrameworkMethod; + +/** + * + * @param <P> type of goal to test + * @author chemit + * @since 1.0.3 + */ +public abstract class AbstractMojoTest<P extends Plugin> { + + protected static Log log; + protected static File testDir; + @Rule + public MojoTestName name = new MojoTestName(); + + @BeforeClass + public static void beforeClass() throws Exception { + log = new SystemStreamLog(); + TestHelper.getBasedir(); + } + + @AfterClass + public static void afterClass() throws Exception { + testDir = null; + log = null; + } + + protected abstract String getGoalName(String methodName); + + protected File getPomFile(File testDir, String methodName, String goalName) { + File pom = new File(testDir, methodName + ".xml"); + + if (isVerbose()) { + log.info("getPomFile = " + TestHelper.getRelativePath(getBasedir(), pom)); + } + + return pom; + } + + @SuppressWarnings("unchecked") + protected P createMojo(File pomFile, String goalName) throws Exception { + Mojo lookupMojo = TestHelper.lookupMojo(goalName, pomFile); + P mojo = (P) lookupMojo; + return mojo; + } + + protected void setUpMojo(P mojo, File pomFile) throws Exception { + + MavenProject project = mojo.getProject(); + if (project == null) { + +// MavenProjectBuilder projectBuilder = (MavenProjectBuilder) delegate.getContainer().lookup(MavenProjectBuilder.ROLE); +// ProjectBuilderConfiguration projectBuilderConfiguration = null; +// project = projectBuilder.build(pomFile, projectBuilderConfiguration); + + project = new MavenProject(); + + mojo.setProject(project); + } + + mojo.getProject().setFile(pomFile); + } + + protected P getMojo() { + return name.getMojo(); + } + + protected String getMethodName() { + return name.getMethodName(); + } + + protected File getPomFile() { + return name.getPomFile(); + } + + protected File getBasedir() { + return TestHelper.getBasedir(); + } + + protected File getTestDir() { + if (testDir == null) { + + String rep = getClass().getName(); + rep = rep.replaceAll("\\.", File.separator); + + File f = TestHelper.getFile(getBasedir(), "target", "test-classes"); + + testDir = new File(f, rep); + if (isVerbose()) { + log.info("test dir = " + TestHelper.getRelativePath(getBasedir(), testDir)); + } + } + return testDir; + } + + protected boolean isVerbose() { + return TestHelper.isVerbose(); + } + + public class MojoTestName extends TestName { + + private File pomFile; + private P mojo; + + public MojoTestName() { + if (log.isDebugEnabled()) { + log.debug("NEW MojotestName instance for " + AbstractMojoTest.this); + } + getTestDir(); + } + + @Override + public void starting(FrameworkMethod method) { + super.starting(method); + + if (isVerbose()) { + log.info("=============================================================================================="); + } + log.info("NEW Mojo test starting : " + AbstractMojoTest.this.getClass().getName() + "#" + getMethodName()); + String goalName = getGoalName(name.getMethodName()); + + pomFile = AbstractMojoTest.this.getPomFile(getTestDir(), getMethodName(), goalName); + + try { + Assert.assertTrue("could not find pom " + pomFile.getAbsoluteFile(), pomFile.exists()); + + mojo = createMojo(pomFile, goalName); + + AbstractMojoTest.this.setUpMojo(mojo, pomFile); + + } catch (Exception ex) { + throw new IllegalStateException("could not init test " + getClass() + " - " + getMethodName() + " for reason " + ex.getMessage(), ex); + } + } + + @Override + public void finished(FrameworkMethod method) { + super.finished(method); + pomFile = null; + mojo = null; + } + + public P getMojo() { + return mojo; + } + + public File getPomFile() { + return pomFile; + } + } +} Property changes on: trunk/src/test/java/org/nuiton/plugin/AbstractMojoTest.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL Added: trunk/src/test/java/org/nuiton/plugin/TestHelper.java =================================================================== --- trunk/src/test/java/org/nuiton/plugin/TestHelper.java (rev 0) +++ trunk/src/test/java/org/nuiton/plugin/TestHelper.java 2009-09-15 15:44:19 UTC (rev 573) @@ -0,0 +1,113 @@ +package org.nuiton.plugin; + +import org.apache.maven.plugin.Mojo; +import org.apache.maven.plugin.testing.AbstractMojoTestCase; +import org.codehaus.plexus.PlexusContainer; +import org.codehaus.plexus.PlexusTestCase; +import java.io.File; +import org.junit.Assert; + +/** + * + * @author chemit + * @since 1.0.3 + */ +public abstract class TestHelper { + + protected static boolean verbose; + protected static File basedir; + protected static DelegateMojoTestCase delegateMojoTest; + + /** + * + * @return the basedir for all tests + * @see PlexusTestCase#getBasedir() + */ + public static File getBasedir() { + if (basedir == null) { + String path = PlexusTestCase.getBasedir(); + basedir = new File(path); + if (verbose) { + System.out.println("basedir = " + basedir.getAbsolutePath()); + } + } + return basedir; + } + + public static void setBasedir(File basedir) { + TestHelper.basedir = basedir; + } + + public static boolean isVerbose() { + return verbose; + } + + public static void setVerbose(boolean verbose) { + TestHelper.verbose = verbose; + } + + public static File getTestDir(Class<?> type, String prefix) { + String rep = type.getName(); + rep = rep.replaceAll("\\.", File.separator); + + File f = new File(getBasedir(), prefix); + File testDir = new File(f, rep); + return testDir; + } + + public static Mojo lookupMojo(String goalName, File pomFile) throws Exception { + Mojo lookupMojo = getDelegateMojoTest().lookupMojo(goalName, pomFile); + Assert.assertNotNull(lookupMojo); + return lookupMojo; + + } + + public static DelegateMojoTestCase getDelegateMojoTest() throws Exception { + if (TestHelper.delegateMojoTest == null) { + TestHelper.delegateMojoTest = new DelegateMojoTestCase(); + TestHelper.delegateMojoTest.setUp(); + } + return TestHelper.delegateMojoTest; + } + + public static void setDelegateMojoTest(DelegateMojoTestCase delegateMojoTest) { + TestHelper.delegateMojoTest = delegateMojoTest; + } + + public static File getFile(File base, String... paths) { + StringBuilder buffer = new StringBuilder(); + for (String path : paths) { + buffer.append(File.separator).append(path); + } + File f = new File(base, buffer.substring(1)); + return f; + } + + public static String getRelativePath(File base, File file) { + String result = file.getAbsolutePath().substring(base.getAbsolutePath().length() + 1); + return result; + } + + public static class DelegateMojoTestCase extends AbstractMojoTestCase { + + @Override + public Mojo lookupMojo(String goal, File pom) throws Exception { + return super.lookupMojo(goal, pom); + } + + @Override + public void setUp() throws Exception { + super.setUp(); + } + + @Override + public void tearDown() throws Exception { + super.tearDown(); + } + + @Override + public PlexusContainer getContainer() { + return super.getContainer(); + } + } +} Property changes on: trunk/src/test/java/org/nuiton/plugin/TestHelper.java ___________________________________________________________________ Added: svn:keywords + "Author Date Id Revision HeadURL Modified: trunk/src/test/java/org/nuiton/util/BasePluginTestCase.java =================================================================== --- trunk/src/test/java/org/nuiton/util/BasePluginTestCase.java 2009-09-11 22:06:27 UTC (rev 572) +++ trunk/src/test/java/org/nuiton/util/BasePluginTestCase.java 2009-09-15 15:44:19 UTC (rev 573) @@ -35,11 +35,16 @@ import org.codehaus.plexus.PlexusTestCase; import org.junit.Ignore; import org.junit.Test; -import org.nuiton.Plugin; +import org.nuiton.plugin.Plugin; /** * @param <P> le mojo a test - * @author chemit */ + * @author chemit + * + * @deprecated since 1.0.3, prefer use the {@link AbstractMojoTest} which + * need no more annotation on each test method. + */ +@Deprecated public abstract class BasePluginTestCase<P extends Plugin> { protected static SystemStreamLog log; Modified: trunk/src/test/java/org/nuiton/util/JavaFileUpdaterTest.java =================================================================== --- trunk/src/test/java/org/nuiton/util/JavaFileUpdaterTest.java 2009-09-11 22:06:27 UTC (rev 572) +++ trunk/src/test/java/org/nuiton/util/JavaFileUpdaterTest.java 2009-09-15 15:44:19 UTC (rev 573) @@ -20,13 +20,11 @@ */ package org.nuiton.util; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - import org.nuiton.util.FileUpdaterHelper.JavaFileUpdater; import java.io.File; import org.junit.BeforeClass; import org.junit.Test; +import org.nuiton.plugin.TestHelper; import static org.junit.Assert.*; /** @@ -36,32 +34,20 @@ */ public class JavaFileUpdaterTest { - /** to use log facility, just put in your code: log.info(\"...\"); */ - static private final Log log = LogFactory.getLog(FileUpdaterHelper.class); - - - static final char SEP = File.separatorChar; - static MirroredFileUpdater fileUpdater; - static File sourceFile; static File mirrorFile; @BeforeClass public static void initClass() throws Exception { - String basedir = System.getProperty("basedir"); - if (basedir == null) { - log.warn("basedir not found, test is not executed from maven..."); - basedir = new File(new File("").getAbsolutePath()).getAbsolutePath(); - } - log.info("basedir = " + basedir); + File basedir = TestHelper.getBasedir(); - File src = new File(basedir, "src" + SEP + "test" + SEP + "java"); - File dir = new File(basedir, "target" + SEP + "test-classes"); - fileUpdater = (MirroredFileUpdater) FileUpdaterHelper.newJavaFileUpdater(src, dir); - log.info(fileUpdater); + File src = TestHelper.getFile(basedir, "src", "test", "java"); + File dir = TestHelper.getFile(basedir, "target", "test-classes"); + fileUpdater = FileUpdaterHelper.newJavaFileUpdater(src, dir); + // test source dir exists File sourceDirectory = fileUpdater.getSourceDirectory(); assertTrue("sourcedir is null", sourceDirectory != null); @@ -72,11 +58,11 @@ assertTrue("destinationDirectory is null", destinationDirectory != null); assertTrue("destinationDirectory does not exists " + destinationDirectory, destinationDirectory.exists()); - sourceFile = new File(fileUpdater.getSourceDirectory(), "org" + SEP + "nuiton" + SEP + "util" + SEP + JavaDummy.class.getSimpleName() + ".java"); + sourceFile = TestHelper.getFile(fileUpdater.getSourceDirectory(), "org", "nuiton", "util", JavaDummy.class.getSimpleName() + ".java"); } -@Test + @Test public void testSourceFileIsUptoDate() throws Exception { assertTrue("fileUpdater was not init", fileUpdater != null); @@ -89,7 +75,7 @@ mirrorFile = fileUpdater.getMirrorFile(sourceFile); } -@Test + @Test public void testSourceFileDoesNotHaveMirrorFile() throws Exception { assertTrue("fileUpdater was not init", fileUpdater != null); @@ -112,7 +98,7 @@ assertTrue(sourceFile + " should be uptodate", fileUpdater.isFileUpToDate(sourceFile)); } -@Test + @Test public void testSourceFileIsNewerThanMirrorFile() throws Exception { assertTrue("fileUpdater was not init", fileUpdater != null); @@ -136,5 +122,4 @@ // java file is now up to date (rename method does not affect lasmodified property on a file) assertTrue(sourceFile + " should be uptodate", fileUpdater.isFileUpToDate(sourceFile)); } - } Modified: trunk/src/test/java/org/nuiton/util/JaxxFileUpdaterTest.java =================================================================== --- trunk/src/test/java/org/nuiton/util/JaxxFileUpdaterTest.java 2009-09-11 22:06:27 UTC (rev 572) +++ trunk/src/test/java/org/nuiton/util/JaxxFileUpdaterTest.java 2009-09-15 15:44:19 UTC (rev 573) @@ -20,12 +20,10 @@ */ package org.nuiton.util; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - import java.io.File; import org.junit.BeforeClass; import org.junit.Test; +import org.nuiton.plugin.TestHelper; import static org.junit.Assert.*; /** @@ -35,9 +33,6 @@ */ public class JaxxFileUpdaterTest { - /** to use log facility, just put in your code: log.info(\"...\"); */ - static private final Log log = LogFactory.getLog(FileUpdaterHelper.class); - static final char SEP = File.separatorChar; static MirroredFileUpdater fileUpdater; static File sourceFile; static File mirrorFile; @@ -45,18 +40,11 @@ @BeforeClass public static void initClass() throws Exception { - String basedir = System.getProperty("basedir"); - if (basedir == null) { - log.warn("basedir not found, test is not executed from maven..."); - basedir = new File(new File("").getAbsolutePath()).getAbsolutePath(); - } + File basedir = TestHelper.getBasedir(); - log.info("basedir = " + basedir); - - File src = new File(basedir, "src" + SEP + "test" + SEP + "resources"); - File dir = new File(basedir, "src" + SEP + "test" + SEP + "java"); + File src = TestHelper.getFile(basedir, "src", "test", "resources"); + File dir = TestHelper.getFile(basedir, "src", "test", "java"); fileUpdater = FileUpdaterHelper.newJaxxFileUpdater(src, dir); - log.info(fileUpdater); // test source dir exists File sourceDirectory = fileUpdater.getSourceDirectory(); @@ -68,7 +56,7 @@ assertTrue("destinationDirectory is null", destinationDirectory != null); assertTrue("destinationDirectory does not exists " + destinationDirectory, destinationDirectory.exists()); - sourceFile = new File(fileUpdater.getSourceDirectory(), "org" + SEP + "nuiton" + SEP + "util" + SEP + JaxxDummy.class.getSimpleName() + ".jaxx"); + sourceFile = TestHelper.getFile(fileUpdater.getSourceDirectory(), "org", "nuiton", "util", JaxxDummy.class.getSimpleName() + ".jaxx"); } Modified: trunk/src/test/java/org/nuiton/util/PluginConfig.java =================================================================== --- trunk/src/test/java/org/nuiton/util/PluginConfig.java 2009-09-11 22:06:27 UTC (rev 572) +++ trunk/src/test/java/org/nuiton/util/PluginConfig.java 2009-09-15 15:44:19 UTC (rev 573) @@ -25,16 +25,19 @@ import java.lang.annotation.Target; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; +import org.nuiton.plugin.AbstractMojoTest; -/** @author chemit */ +/** @author chemit + * @deprecated since 1.0.3, prefer use the {@link AbstractMojoTest} which + * need no more annotation on each test method. + */ @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.METHOD) @Inherited +@Deprecated public @interface PluginConfig { String goalName(); String pomName(); - }