[Lutinutil-commits] r1314 - in maven-license-switcher-plugin/trunk: . src/main/java/org/codelutin/license src/main/java/org/codelutin/license/plugin src/main/java/org/codelutin/license/plugin/impl src/main/resources src/test/java/org/codelutin/license src/test/java/org/codelutin/license/plugin src/test/java/org/codelutin/license/plugin/impl src/test/resources src/test/resources/org src/test/resources/org/codelutin src/test/resources/org/codelutin/license src/test/resources/org/codelutin/license/plugin src/t
Author: tchemit Date: 2009-01-28 20:18:25 +0000 (Wed, 28 Jan 2009) New Revision: 1314 Added: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/JavaLicenseGenerator.java maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseGenerator.java maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseGeneratorFactory.java maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/XmlLicenseGenerator.java maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AbstractLicensePlugin.java maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AvailableLicensesPlugin.java maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/impl/ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/impl/LicensePlugin.java maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/impl/SwitchLicensePlugin.java maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/impl/ThirdPartyPlugin.java maven-license-switcher-plugin/trunk/src/main/resources/log4j.properties maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/JavaLicenseGeneratorTest.java maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/LicenseGeneratorFactoryTest.java maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/XmlLicenseGeneratorTest.java maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/plugin/ maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/plugin/BasePluginTestCase.java maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/plugin/PluginConfig.java maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/plugin/impl/ maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/plugin/impl/LicensePluginTest.java maven-license-switcher-plugin/trunk/src/test/resources/org/ maven-license-switcher-plugin/trunk/src/test/resources/org/codelutin/ maven-license-switcher-plugin/trunk/src/test/resources/org/codelutin/license/ maven-license-switcher-plugin/trunk/src/test/resources/org/codelutin/license/plugin/ maven-license-switcher-plugin/trunk/src/test/resources/org/codelutin/license/plugin/impl/ maven-license-switcher-plugin/trunk/src/test/resources/org/codelutin/license/plugin/impl/LicensePluginTest/ maven-license-switcher-plugin/trunk/src/test/resources/org/codelutin/license/plugin/impl/LicensePluginTest/licenseOne.txt maven-license-switcher-plugin/trunk/src/test/resources/org/codelutin/license/plugin/impl/LicensePluginTest/testOne.xml Removed: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AbstractLicenseMojo.java maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AvailableLicensesMojo.java maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/LicenseMojo.java maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/SwitchLicenseMojo.java maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/ThirdPartyMojo.java Modified: maven-license-switcher-plugin/trunk/pom.xml maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseFactory.java maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseResolver.java maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/BaseLicenseTestCase.java maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/JarLicenseResolverTest.java maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/LicenseFactoryTest.java maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/LicenseResolverTest.java Log: refactor tests in JUnit 4 use lutinpluginproject 3.4.0 refactor Mojo in Plugins Modified: maven-license-switcher-plugin/trunk/pom.xml =================================================================== --- maven-license-switcher-plugin/trunk/pom.xml 2009-01-26 12:40:09 UTC (rev 1313) +++ maven-license-switcher-plugin/trunk/pom.xml 2009-01-28 20:18:25 UTC (rev 1314) @@ -1,5 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> @@ -9,13 +10,13 @@ <parent> <groupId>org.codelutin</groupId> <artifactId>lutinpluginproject</artifactId> - <version>3.2</version> + <version>3.4.0</version> </parent> <artifactId>maven-license-switcher-plugin</artifactId> - + <version>0.6-SNAPSHOT</version> - + <dependencies> <dependency> @@ -38,6 +39,22 @@ <scope>compile</scope> </dependency> + <!-- tests dependencies --> + + <dependency> + <groupId>org.apache.maven.shared</groupId> + <artifactId>maven-plugin-testing-harness</artifactId> + <version>1.1</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.apache.maven.shared</groupId> + <artifactId>maven-verifier</artifactId> + <version>1.0</version> + <scope>test</scope> + </dependency> + </dependencies> <!-- ************************************************************* --> @@ -54,7 +71,16 @@ <packaging>maven-plugin</packaging> + <properties> + <labs.id>12</labs.id> + <labs.project>lutinutil</labs.project> + <license-switcher.version>${project.version}</license-switcher.version> + </properties> + <build> + + <defaultGoal>install</defaultGoal> + <plugins> <plugin> <artifactId>maven-antrun-plugin</artifactId> @@ -65,10 +91,11 @@ <phase>pre-site</phase> <configuration> <tasks> - <mkdir dir="${maven.site.gen.dir}/resources" /> - <copy todir="${maven.site.gen.dir}/resources" verbose="${maven.verbose}" overwrite="false"> + <mkdir dir="${maven.site.gen.dir}/resources"/> + <copy todir="${maven.site.gen.dir}/resources" verbose="${maven.verbose}" + overwrite="false"> <fileset dir="${maven.src.dir}/main/resources/META-INF"> - <include name="licenses/**" /> + <include name="licenses/**"/> </fileset> </copy> </tasks> @@ -82,16 +109,6 @@ </plugins> </build> - <properties> - - <!-- id du projet du labs --> - <labs.id>12</labs.id> - - <!-- nom du projet sur le labs --> - <labs.project>lutinutil</labs.project> - - </properties> - <!-- ************************************************************* --> <!-- *** Build Environment ************************************** --> <!-- ************************************************************* --> Added: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/JavaLicenseGenerator.java =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/JavaLicenseGenerator.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/JavaLicenseGenerator.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -0,0 +1,13 @@ +package org.codelutin.license; + +import org.codelutin.processor.filters.LicenseFilter; + +/** @author chemit */ +public class JavaLicenseGenerator implements LicenseGenerator { + + @Override + public String getHeader(String licenseHeaderContent) { + return "/**\n * " + LicenseFilter.HEADER + " " + licenseHeaderContent + " " + LicenseFilter.FOOTER + "\n */\n"; + } + +} Modified: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseFactory.java =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseFactory.java 2009-01-26 12:40:09 UTC (rev 1313) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseFactory.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -24,10 +24,12 @@ // always put jar resolver first result.addResolver(new JarLicenseResolver()); - for (String extraResolver : extraResolvers) { - if (extraResolver != null && !extraResolver.trim().isEmpty()) { - // add a extra resolver - result.addResolver(new LicenseResolver(extraResolver)); + if (extraResolvers != null) { + for (String extraResolver : extraResolvers) { + if (extraResolver != null && !extraResolver.trim().isEmpty()) { + // add a extra resolver + result.addResolver(new LicenseResolver(extraResolver)); + } } } return result; Added: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseGenerator.java =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseGenerator.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseGenerator.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -0,0 +1,14 @@ +package org.codelutin.license; + +import java.io.File; + +/** + * A simple Contract to generate a new header for a given type of file + * + * @author chemit + */ +public interface LicenseGenerator { + + String getHeader(String licenseHeaderContent); + +} Added: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseGeneratorFactory.java =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseGeneratorFactory.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseGeneratorFactory.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -0,0 +1,73 @@ +package org.codelutin.license; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * A factory of {@link LicenseFactory} + * + * @author chemit + */ +public class LicenseGeneratorFactory { + + public static class LicenceGeneratorContext { + + File src; + String[] files; + + public LicenceGeneratorContext(File src, String[] files) { + this.src = src; + this.files = files; + } + + public File getSrc() { + return src; + } + + public String[] getFiles() { + return files; + } + + public void setSrc(File src) { + this.src = src; + } + + public void setFiles(String[] files) { + this.files = files; + } + + } + + protected static Map<LicenseGenerator, List<String>> availableGenerator; + + public static Map<LicenseGenerator, List<String>> getAvailableGenerator() { + if (availableGenerator == null) { + availableGenerator = new HashMap<LicenseGenerator, List<String>>(); + } + return availableGenerator; + } + + public static List<String> getGeneratorMatchers(LicenseGenerator generator) { + List<String> result = null; + if (availableGenerator != null) { + result = availableGenerator.get(generator); + if (result == null) { + // add a new empty list in cache + result = new ArrayList<String>(); + availableGenerator.put(generator, result); + } + } + return result; + } + + public static void addGenerator(LicenseGenerator generator, String matcher) { + List<String> matchers = getGeneratorMatchers(generator); + if (matcher.isEmpty() || !matcher.contains(matcher)) { + matchers.add(matcher); + } + } + +} Modified: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseResolver.java =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseResolver.java 2009-01-26 12:40:09 UTC (rev 1313) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseResolver.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -122,7 +122,6 @@ } catch (IOException e) { return null; } - } @Override Added: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/XmlLicenseGenerator.java =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/XmlLicenseGenerator.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/XmlLicenseGenerator.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -0,0 +1,13 @@ +package org.codelutin.license; + +import org.codelutin.processor.filters.LicenseFilter; + +/** @author chemit */ +public class XmlLicenseGenerator implements LicenseGenerator { + + @Override + public String getHeader(String licenseHeaderContent) { + return "<!--\n\n/**\n * " + LicenseFilter.HEADER + " " + licenseHeaderContent + " " + LicenseFilter.FOOTER + "\n */\n\n-->\n"; + } + +} \ No newline at end of file Deleted: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AbstractLicenseMojo.java =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AbstractLicenseMojo.java 2009-01-26 12:40:09 UTC (rev 1313) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AbstractLicenseMojo.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -1,108 +0,0 @@ -/** - * *##% Plugin maven pour switcher les licenses - * Copyright (C) 2008 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.codelutin.license.plugin; - -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 org.codelutin.util.FileUtil; - -import java.io.File; -import java.io.IOException; - -/** - * Un MOJO de base pour les autres MOJO concrets avec les options communes. - * - * @author chemit - */ -public abstract class AbstractLicenseMojo extends AbstractMojo { - - /** - * la methode qui est lancee au debut de la methode {@link #execute()} pour preparer l'init du goal. - * - * @throws Exception if any - */ - protected abstract void init() throws Exception; - - /** - * Dependance du projet. - * - * @parameter default-value="${project}" - * @required - * @readonly - */ - protected MavenProject project; - - /** - * Repertoire de sortie des classes (classpath). - * - * @parameter expression="${licence-switcher.outputDirectory}" default-value="${project.build.outputDirectory}" - * @required - */ - protected File projectOutputDirectory; - - /** - * Encoding a utiliser pour lire et ecrire les fichiers. - * - * @parameter expression="${licence-switcher.encoding}" default-value="${maven.compile.encoding}" - * @required - */ - protected String encoding; - - /** - * Un flag pour conserver un backup des fichiers modifies. - * - * @parameter expression="${license-switcher.keepBackup}" default-value="false" - */ - protected boolean keepBackup; - /** - * Un flag pour activer le mode verbeux. - * - * @parameter expression="${license-switcher.verbose}" default-value="${maven.verbose}" - */ - protected boolean verbose; - - public void execute() throws MojoExecutionException, MojoFailureException { - try { - init(); - } catch (Exception e) { - throw new MojoExecutionException("could not init goal " + getClass().getSimpleName() + " for reason : " + e.getMessage(), e); - } - } - - protected void copyFileToOutputDirectory(File file) throws MojoExecutionException { - - final String type = project.getArtifact().getType(); - if ("pom".equals(type) || "site".equals(type)) { - // project is not classpath cabable - return; - } - //TODO should be able to use path - File target = new File(projectOutputDirectory, file.getName()); - - try { - - FileUtil.copy(file, target); - - } catch (IOException e) { - throw new MojoExecutionException("could not write file " + target + " for reason : " + e.getMessage(), e); - } - } -} Copied: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AbstractLicensePlugin.java (from rev 1312, maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AbstractLicenseMojo.java) =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AbstractLicensePlugin.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AbstractLicensePlugin.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -0,0 +1,197 @@ +/** + * *##% Plugin maven pour switcher les licenses + * Copyright (C) 2008 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.codelutin.license.plugin; + +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; + +/** + * Un MOJO de base pour les autres MOJO concrets avec les options communes. + * + * @author chemit + */ +public abstract class AbstractLicensePlugin extends AbstractMojo { + + protected abstract boolean shouldSkip(); + + /** + * 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 #shouldSkip()} returns <code>false</code> (filtrer project type, for example).</li> + * <li>{@link #force} is activate or method {@link #init()} returns <code>true</code>.</li> + * </ul> + * + * @throws Exception if any + */ + protected abstract void doAction() throws Exception; + + /** + * Dependance du projet. + * + * @parameter default-value="${project}" + * @required + */ + protected MavenProject project; + + /** + * Repertoire de sortie des classes (classpath). + * + * @parameter expression="${licence-switcher.outputDirectory}" default-value="${project.build.outputDirectory}" + * @required + */ + protected File outputDirectory; + + /** + * Encoding a utiliser pour lire et ecrire les fichiers. + * + * @parameter expression="${licence-switcher.encoding}" default-value="${maven.compile.encoding}" + * @required + */ + protected String encoding; + + /** + * Un flag pour conserver un backup des fichiers modifies. + * + * @parameter expression="${license-switcher.keepBackup}" default-value="false" + */ + protected boolean keepBackup; + /** + * Un flag pour activer le mode verbeux. + * + * @parameter expression="${license-switcher.verbose}" default-value="${maven.verbose}" + */ + protected boolean verbose; + /** + * Un flag pour forcer la generation. + * + * @parameter expression="${license-switcher.force}" default-value="false" + */ + protected boolean force; + + /** + * Fichier ou ecrire les licences des dependances. + * + * @parameter expression="${license-switcher.pomFile}" default-value="pom.xml" + * @required + */ + protected File pomFile; + + public void execute() throws MojoExecutionException, MojoFailureException { + try { + + if (shouldSkip()) { + getLog().info("skip switch goal for packaging " + project.getPackaging()); + return; + } + + boolean shouldGenerate = init(); + + if (!(force || shouldGenerate)) { + getLog().info("all files are up-to-date."); + return; + } + + doAction(); + + } catch (Exception e) { + throw new MojoExecutionException("could not init goal " + getClass().getSimpleName() + " for reason : " + e.getMessage(), e); + } + } + + /** + * Test if a file exists and is newer than the {@link #pomFile} 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) { + return f.exists() && f.lastModified() > pomFile.lastModified(); + } + + public MavenProject getProject() { + return project; + } + + public File getOutputDirectory() { + return outputDirectory; + } + + public String getEncoding() { + return encoding; + } + + public boolean isKeepBackup() { + return keepBackup; + } + + public boolean isVerbose() { + return verbose; + } + + public boolean isForce() { + return force; + } + + public File getPomFile() { + return pomFile; + } + + public void setProject(MavenProject project) { + this.project = project; + } + + public void setOutputDirectory(File outputDirectory) { + this.outputDirectory = outputDirectory; + } + + public void setEncoding(String encoding) { + this.encoding = encoding; + } + + public void setKeepBackup(boolean keepBackup) { + this.keepBackup = keepBackup; + } + + public void setVerbose(boolean verbose) { + this.verbose = verbose; + } + + public void setForce(boolean force) { + this.force = force; + } + + public void setPomFile(File pomFile) { + this.pomFile = pomFile; + } +} Deleted: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AvailableLicensesMojo.java =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AvailableLicensesMojo.java 2009-01-26 12:40:09 UTC (rev 1313) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AvailableLicensesMojo.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -1,56 +0,0 @@ -/** - * *##% Plugin maven pour switcher les licenses - * Copyright (C) 2008 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.codelutin.license.plugin; - -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.codelutin.license.LicenseFactory; - -import java.util.Map.Entry; - -/** - * Le goal pour afficher dans la console les differentes licenses connues. - * - * @author chemit - * @goal available-licenses - * @requiresProject false - */ -public class AvailableLicensesMojo extends AbstractMojo { - - /** - * La baseURL d'un resolver de license supplementaire - * - * @parameter expression="${license-switcher.extraResolver}" - */ - protected String extraResolver; - - public void execute() throws MojoExecutionException, MojoFailureException { - StringBuilder sb = new StringBuilder(); - sb.append("Available licenses :\n"); - - LicenseFactory factory = LicenseFactory.newInstance(extraResolver); - - for (Entry<String, String> license : factory.getLicenseNames().entrySet()) { - sb.append(" * ").append(license.getKey()).append(" : ").append(license.getValue()).append('\n'); - } - System.out.println(sb.toString()); - } - -} Copied: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AvailableLicensesPlugin.java (from rev 1312, maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AvailableLicensesMojo.java) =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AvailableLicensesPlugin.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AvailableLicensesPlugin.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -0,0 +1,56 @@ +/** + * *##% Plugin maven pour switcher les licenses + * Copyright (C) 2008 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.codelutin.license.plugin; + +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.codelutin.license.LicenseFactory; + +import java.util.Map.Entry; + +/** + * Le goal pour afficher dans la console les differentes licenses connues. + * + * @author chemit + * @goal available-licenses + * @requiresProject false + */ +public class AvailableLicensesPlugin extends AbstractMojo { + + /** + * La baseURL d'un resolver de license supplementaire + * + * @parameter expression="${license-switcher.extraResolver}" + */ + protected String extraResolver; + + public void execute() throws MojoExecutionException, MojoFailureException { + StringBuilder sb = new StringBuilder(); + sb.append("Available licenses :\n"); + + LicenseFactory factory = LicenseFactory.newInstance(extraResolver); + + for (Entry<String, String> license : factory.getLicenseNames().entrySet()) { + sb.append(" * ").append(license.getKey()).append(" : ").append(license.getValue()).append('\n'); + } + getLog().info(sb.toString()); + } + +} Deleted: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/LicenseMojo.java =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/LicenseMojo.java 2009-01-26 12:40:09 UTC (rev 1313) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/LicenseMojo.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -1,120 +0,0 @@ -/** - * *##% Plugin maven pour switcher les licenses - * Copyright (C) 2008 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.codelutin.license.plugin; - -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.codelutin.util.FileUtil; -import org.codelutin.license.License; -import org.codelutin.license.LicenseFactory; - -import java.io.File; -import java.io.IOException; - -/** - * Le goal pour ajouter le fichier LICENSE.txt dans le classpath (et le generer s'il n'existe pas). - * - * @author chemit - * @goal license - * @phase process-classes - * @requiresProject true - */ -public class LicenseMojo extends AbstractLicenseMojo { - /** - * Un flag pour indiquer la regeneration des fichiers. - * - * @parameter expression="${license-switcher.doGenerate}" default-value="false" - */ - protected boolean doGenerate; - /** - * Fichier de la licence du module. - * - * @parameter expression="${license-switcher.licenceFile}" default-value="${basedir}/LICENSE.txt" - * @required - * @readonly - */ - protected File licenseFile; - - /** - * Le type de license a appliquer. - * - * @parameter expression="${license-switcher.licenseName}" - * @required - */ - protected String licenseName; - - /** - * La baseURL d'un resolver de license supplementaire - * - * @parameter expression="${license-switcher.extraResolver}" - */ - protected String[] extraResolver; - - protected License license; - - protected void init() throws Exception { - - // must generate if file does not exist - doGenerate = doGenerate || !licenseFile.exists(); - - if (doGenerate) { - - // acquire license - - LicenseFactory factory = LicenseFactory.newInstance(extraResolver); - - license = factory.revolv(licenseName); - - } - } - - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - - super.execute(); - - if (doGenerate) { - - getLog().info("using licence ["+licenseName+"]"); - - if (verbose) { - getLog().info("licence : "+license); - } - - if (licenseFile.exists() && keepBackup) { - if (verbose) { - getLog().info("backup " + licenseFile); - } - // copy it to backup file - File backup = new File(licenseFile.getAbsolutePath() + "~"); - licenseFile.renameTo(backup); - } - try { - FileUtil.writeString(licenseFile, license.getLicenseContent(encoding), encoding); - - } catch (IOException e) { - throw new MojoExecutionException("could not write license file " + licenseFile + " for reason : " + e.getMessage(), e); - } - } - - // copy LICENSE.txt to classpath - copyFileToOutputDirectory(licenseFile); - } - -} Deleted: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/SwitchLicenseMojo.java =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/SwitchLicenseMojo.java 2009-01-26 12:40:09 UTC (rev 1313) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/SwitchLicenseMojo.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -1,297 +0,0 @@ -/** - * *##% Plugin maven pour switcher les licenses - * Copyright (C) 2008 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.codelutin.license.plugin; - -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.codehaus.plexus.util.DirectoryScanner; -import org.codelutin.processor.LicenseProcessor; -import org.codelutin.processor.filters.LicenseFilter; -import org.codelutin.util.FileUtil; -import org.codelutin.license.LicenseFactory; -import org.codelutin.license.License; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -/** - * Le goal pour switcher les licenses de tous les sources java d'un module - * maven. - * - * @author chemit - * @goal switch - * @phase process-resources - * @requiresProject true - */ -public class SwitchLicenseMojo extends AbstractLicenseMojo { - - /** - * l'annee de creation du module (sera place dans le header) - * - * @parameter default-value="${project.inceptionYear}" - * @required - */ - protected String inceptionYear; - - /** - * le nom de l'organisation (sera place dans le header) - * - * @parameter default-value="${project.organization.name}" - * @required - * @readonly - */ - protected String organizationName; - - /** - * le nom du projet (sera place dans le header) - * - * @parameter default-value="${project.name}" - * @required - * @readonly - */ - protected String projectName; - - /** - * Le type de license a appliquer. - * - * @parameter expression="${license-switcher.licenseName}" - * @required - */ - protected String licenseName; - - /** - * Repertoires des fichiers sources a traiter. - * - * @parameter expression="${license-switcher.compileSourceRoots}" default-value="${project.compileSourceRoots}" - * @required - */ - protected List<String> compileSourceRoots; - - /** - * Repertoires des fichiers sources de test a traiter. - * - * @parameter expression="${license-switcher.testCompileSourceRoots}" default-value="${project.testCompileSourceRoots}" - * @required - */ - protected List<String> testCompileSourceRoots; - - /** - * Un resolver externe - * - * @parameter expression="${license-switcher.extraResolver}" - */ - protected String[] extraResolver; - - /** le header a ajouter dans chaque fichier source java */ - protected String licenseHeaderContent; - - /** la liste des chemin relatifs des sources java a traiter pour chaque repertoire contenant des sources */ - protected Map<File, String[]> javaFilesToTreate; - - protected long timestamp; - - protected boolean skip; - - protected void init() throws IOException { - - if ("pom".equals(project.getPackaging()) || "site".equals(project.getPackaging())) { - // nothing to be done for this type of packaging - skip=true; - return; - } - - timestamp = System.nanoTime(); - - // obtain all java source files to be treated - javaFilesToTreate = getFilesToTreate(); - - if (javaFilesToTreate.isEmpty()) { - // nothing to do, since no file to treate was found - return; - } - - LicenseFactory factory = LicenseFactory.newInstance(extraResolver); - - License license = factory.revolv(licenseName); - - // obtain content of license header - licenseHeaderContent = computeHeader(license); - - if (verbose) { - getLog().info("header to write on java source files \n" + licenseHeaderContent); - } - - } - - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - - super.execute(); - - if (skip) { - getLog().info("skip switch goal for packaging " + project.getPackaging()); - return; - } - - if (javaFilesToTreate.isEmpty()) { - getLog().warn("no java source files found to be treated."); - return; - } - - // create a licence processor with given header - LicenseProcessor p = new LicenseProcessor(licenseHeaderContent); - - for (Entry<File, String[]> entry : javaFilesToTreate.entrySet()) { - File src = entry.getKey(); - for (String javaRelativePath : entry.getValue()) { - File sourceFile = new File(src, javaRelativePath); - try { - processJavaSource(p, sourceFile); - } catch (Exception e) { - throw new MojoExecutionException("could not treate java source file " + sourceFile + " for reason : " + e.getMessage(), e); - } - } - } - } - - protected Map<File, String[]> getFilesToTreate() { - - // init directory scanner - DirectoryScanner ds = new DirectoryScanner(); - ds.setIncludes(new String[]{"**\\/*.java"}); - - Map<File, String[]> files = new java.util.HashMap<File, String[]>(); - - List<String> roots = new ArrayList<String>(); - - roots.addAll(compileSourceRoots); - roots.addAll(testCompileSourceRoots); - - for (String src : roots) { - File f = new File(src); - if (!f.exists()) { - // do nothing - continue; - } - if (verbose) { - getLog().info("discovering java source files in root " + src); - } - ds.setBasedir(f); - // scan - ds.scan(); - - // get files - String[] tmp = ds.getIncludedFiles(); - if (tmp.length > 0) { - files.put(f, tmp); - } - } - - return files; - } - - protected String computeHeader(License license) throws IOException { - - - String tmpHeader = license.getHeaderContent(encoding); - - // defined inceptionYear (if year is older than now suffix with a - thisYear) - Calendar cal = Calendar.getInstance(); - cal.setTime(new Date()); - String thisYear = cal.get(Calendar.YEAR) + ""; - if (!thisYear.equals(inceptionYear)) { - inceptionYear = inceptionYear + " - " + thisYear; - } - - // format header with projet informations - tmpHeader = String.format(tmpHeader, projectName, inceptionYear, organizationName); - - // add " * " before each line - BufferedReader reader = new BufferedReader(new java.io.StringReader(tmpHeader)); - StringBuilder sb = new StringBuilder(); - - String line = reader.readLine(); - sb.append(line).append('\n'); - while ((line = reader.readLine()) != null) { - line = line.trim(); - if (line.isEmpty()) { - sb.append(" *\n"); - } else { - sb.append(" * ").append(line).append("\n"); - } - } - tmpHeader = sb.toString(); - return tmpHeader.substring(0, tmpHeader.length() - 1); - } - - /** - * @param p license processor - * @param sourceFile the java source file where to switch (or add the licence) - * @throws java.io.IOException if IO pb - */ - protected void processJavaSource(LicenseProcessor p, File sourceFile) throws Exception { - - if (verbose) { - getLog().info("process file " + sourceFile); - } - - // file where to write result - File processFile = new File(sourceFile.getAbsolutePath() + "_" + timestamp); - - try { - p.process(sourceFile, processFile); - - if (!p.getLicenceFilter().wasTouched()) { - // no license header found in file, add it - addLicenseToJavaSourceFile(sourceFile, processFile); - } - - if (keepBackup) { - File backupFile = new File(sourceFile.getAbsolutePath() + "~"); - if (verbose) { - getLog().debug("backup original file " + sourceFile); - } - sourceFile.renameTo(backupFile); - } - processFile.renameTo(sourceFile); - - } catch (Exception e) { - getLog().error("could not process file " + sourceFile + " for reason " + e.getMessage(), e); - processFile.delete(); - throw e; - } finally { - p.getLicenceFilter().reset(); - } - } - - protected void addLicenseToJavaSourceFile(File sourceFile, File processFile) throws IOException { - getLog().warn("no license was found on file " + sourceFile + ", adding one"); - String content = FileUtil.readAsString(sourceFile, encoding); - content = "/**\n * " + LicenseFilter.HEADER + " " + licenseHeaderContent + " " + LicenseFilter.FOOTER + "\n */\n" + content; - FileUtil.writeString(processFile, content, encoding); - } - -} Deleted: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/ThirdPartyMojo.java =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/ThirdPartyMojo.java 2009-01-26 12:40:09 UTC (rev 1313) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/ThirdPartyMojo.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -1,333 +0,0 @@ -/** - * *##% Plugin maven pour switcher les licenses - * Copyright (C) 2008 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.codelutin.license.plugin; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.factory.ArtifactFactory; -import org.apache.maven.artifact.metadata.ArtifactMetadataSource; -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.artifact.resolver.ArtifactCollector; -import org.apache.maven.artifact.resolver.filter.ArtifactFilter; -import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; -import org.apache.maven.model.License; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.MavenProjectBuilder; -import org.apache.maven.project.ProjectBuildingException; -import org.apache.maven.shared.dependency.tree.DependencyNode; -import org.apache.maven.shared.dependency.tree.DependencyTreeBuilder; -import org.apache.maven.shared.dependency.tree.DependencyTreeBuilderException; -import org.codelutin.util.FileUtil; - -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.SortedSet; -import java.util.TreeSet; - -/** - * Le goal pour copier le fichier THIRD-PARTY.txt (contenant les licenses de toutes les dependances du projet) - * dans le classpath (et le generer s'il n'existe pas). - * - * @author chemit - * @goal third-party - * @phase process-classes - * @requiresDependencyResolution test - * @requiresProject true - */ -public class ThirdPartyMojo extends AbstractLicenseMojo { - - private static final String unknownLicenseMessage = "Unknown license"; - - /** - * Local Repository. - * - * @parameter expression="${localRepository}" - * @required - * @readonly - */ - protected ArtifactRepository localRepository; - - - /** - * Remote repositories used for the project. - * - * @parameter expression="${project.remoteArtifactRepositories}" - * @required - * @readonly - */ - protected List remoteRepositories; - - /** - * Fichier ou ecrire les licences des dependances. - * - * @parameter expression="${license-switcher.thirdPartyFile}" default-value="${project.build.outputDirectory}/THIRD-PARTY.txt" - * @required - */ - protected File thirdPartyFile; - - /** - * Dependency tree builder component. - * - * @component - */ - protected DependencyTreeBuilder dependencyTreeBuilder; - - /** - * Artifact Factory component. - * - * @component - */ - protected ArtifactFactory factory; - - /** - * Artifact metadata source component. - * - * @component - */ - protected ArtifactMetadataSource artifactMetadataSource; - - /** - * Artifact collector component. - * - * @component - */ - protected ArtifactCollector collector; - - /** - * Maven Project Builder component. - * - * @component - */ - protected MavenProjectBuilder mavenProjectBuilder; - - /** - * Un flag pour indiquer la regeneration des fichiers. - * - * @parameter expression="${license-switcher.doGenerate}" default-value="true" - */ - protected boolean doGenerate; - /** - * content of third party file (only computed if {@link #doGenerate} is active or the - * {@link #thirdPartyFile} does not exist. - */ - protected String thirdPartyFileContent; - - protected void init() throws Exception { - - // must generate if file does not exist - doGenerate = doGenerate || !thirdPartyFile.exists(); - - if ("pom".equals(project.getPackaging()) || "site".equals(project.getPackaging())) { - // nothing to be done for this type of packaging - doGenerate = false; - getLog().info("skip third-party goal for packaging " + project.getPackaging()); - return; - } - - if (doGenerate) { - - // prepare thirdPartyFileContent - - DependencyNode dependencyTreeNode = resolveProject(); - - LicenseMap licenseMap = new LicenseMap(); - - for (Object o : dependencyTreeNode.getChildren()) { - - buildLicenseMap((DependencyNode) o, licenseMap); - } - - thirdPartyFileContent = buildGroupedLicenses(licenseMap); - - // log dependencies with no license - SortedSet<String> dependenciesWithNoLicense = licenseMap.get(unknownLicenseMessage); - if (dependenciesWithNoLicense != null) { - for (String dep : dependenciesWithNoLicense) { - // no license found for the dependency - getLog().warn("no license found for dependency " + dep); - } - } - } - } - - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - - super.execute(); - - if (doGenerate) { - if (verbose) { - getLog().info("writing third-party file : " + thirdPartyFile); - } - if (keepBackup && thirdPartyFile.exists()) { - if (verbose) { - getLog().info("backup " + thirdPartyFile); - } - thirdPartyFile.renameTo(new File(thirdPartyFile.getAbsolutePath() + '~')); - } - try { - FileUtil.writeString(thirdPartyFile, thirdPartyFileContent, encoding); - } catch (IOException e) { - throw new MojoExecutionException("could not write file " + thirdPartyFile + " for reason : " + e.getMessage(), e); - } - } - - } - - - /** @return resolve the dependency tree */ - protected DependencyNode resolveProject() { - try { - ArtifactFilter artifactFilter = new ScopeArtifactFilter(Artifact.SCOPE_TEST); - return dependencyTreeBuilder.buildDependencyTree(project, localRepository, factory, - artifactMetadataSource, artifactFilter, collector); - } - catch (DependencyTreeBuilderException e) { - getLog().error("Unable to build dependency tree.", e); - return null; - } - } - - protected void buildLicenseMap(DependencyNode node, LicenseMap licenseMap) { - if (node.getState() != DependencyNode.INCLUDED) { - // this dependency is not included, so do not treate it - if (verbose) { - getLog().info("do not include this dependency " + node.toNodeString()); - } - return; - } - Artifact artifact = node.getArtifact(); - - if (verbose && getLog().isDebugEnabled()) { - getLog().debug("treate node " + node.toNodeString()); - } - - if (!Artifact.SCOPE_SYSTEM.equals(artifact.getScope())) { - try { - MavenProject artifactProject = getMavenProjectFromRepository(artifact); - String artifactName = getArtifactName(artifactProject); - - List licenses = artifactProject.getLicenses(); - - if (licenses.isEmpty()) { - // no license found for the dependency - licenseMap.put(unknownLicenseMessage, artifactName); - - } else { - for (Object o : licenses) { - if (o == null) { - getLog().warn("could not acquire the license for " + artifactName); - continue; - } - License license = (License) o; - String licenseKey = license.getName(); - if (license.getName() == null) { - licenseKey = license.getUrl(); - } - licenseMap.put(licenseKey, artifactName); - } - } - } - catch (ProjectBuildingException e) { - getLog().error("ProjectBuildingException error : ", e); - } - } - if (!node.getChildren().isEmpty()) { - for (Object o : node.getChildren()) { - buildLicenseMap((DependencyNode) o, licenseMap); - } - } - } - - protected String buildGroupedLicenses(LicenseMap licenseMap) { - StringBuilder sb = new StringBuilder(); - sb.append("List of third-party dependencies grouped by their license type."); - for (String licenseName : licenseMap.keySet()) { - sb.append("\n\n").append(licenseName).append(" : "); - - SortedSet<String> projects = licenseMap.get(licenseName); - - for (String projectName : projects) { - sb.append("\n * ").append(projectName); - } - } - return sb.toString(); - } - - protected String getArtifactName(MavenProject artifactProject) { - StringBuilder sb = new StringBuilder(); - - sb.append(artifactProject.getName()); - sb.append(" ("); - sb.append(artifactProject.getGroupId()); - sb.append(":"); - sb.append(artifactProject.getArtifactId()); - sb.append(":"); - sb.append(artifactProject.getVersion()); - sb.append(" - "); - String url = artifactProject.getUrl(); - sb.append(url == null ? "no url defined" : url); - sb.append(")"); - - return sb.toString(); - } - - /** - * Get the <code>Maven project</code> from the repository depending the <code>Artifact</code> given. - * - * @param artifact an artifact - * @return the Maven project for the given artifact - * @throws ProjectBuildingException if any - */ - protected MavenProject getMavenProjectFromRepository(Artifact artifact) - throws ProjectBuildingException { - - boolean allowStubModel = false; - - if (!"pom".equals(artifact.getType())) { - artifact = factory.createProjectArtifact(artifact.getGroupId(), artifact.getArtifactId(), - artifact.getVersion(), artifact.getScope()); - allowStubModel = true; - } - - // TODO: we should use the MavenMetadataSource instead - return mavenProjectBuilder.buildFromRepository(artifact, remoteRepositories, localRepository, - allowStubModel); - } - - protected class LicenseMap extends java.util.TreeMap<String, SortedSet<String>> { - private static final long serialVersionUID = 864199843545688069L; - - /** {@inheritDoc} */ - public SortedSet<String> put(String key, String value) { - // handle multiple values as a set to avoid duplicates - SortedSet<String> valueList = get(key); - if (valueList == null) { - valueList = new TreeSet<String>(); - } - if (getLog().isDebugEnabled()) { - getLog().debug("key:" + key + ",value: " + value); - } - valueList.add(value); - return put(key, valueList); - } - } -} Copied: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/impl/LicensePlugin.java (from rev 1312, maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/LicenseMojo.java) =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/impl/LicensePlugin.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/impl/LicensePlugin.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -0,0 +1,192 @@ +/** + * *##% Plugin maven pour switcher les licenses + * Copyright (C) 2008 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.codelutin.license.plugin.impl; + +import org.apache.maven.plugin.MojoExecutionException; +import org.codelutin.license.License; +import org.codelutin.license.LicenseFactory; +import org.codelutin.license.plugin.AbstractLicensePlugin; +import org.codelutin.util.FileUtil; + +import java.io.File; +import java.io.IOException; + +/** + * Le goal pour ajouter le fichier LICENSE.txt dans le classpath (et le generer s'il n'existe pas). + * + * @author chemit + * @goal license + * @phase generate-resources + * @requiresProject true + * @requiresDependencyResolution compile + */ +public class LicensePlugin extends AbstractLicensePlugin { + /** + * Fichier de la licence du module. + * + * @parameter expression="${license-switcher.licenceFile}" default-value="${basedir}/LICENSE.txt" + * @required + * @readonly + */ + protected File licenseFile; + + /** + * Le type de license a appliquer. + * + * @parameter expression="${license-switcher.licenseName}" + * @required + */ + protected String licenseName; + + /** + * La baseURL d'un resolver de license supplementaire + * + * @parameter expression="${license-switcher.extraResolver}" + */ + protected String[] extraResolver; + + protected License license; + + @Override + protected boolean shouldSkip() { + return project != null && ("pom".equals(project.getPackaging()) || "site".equals(project.getPackaging())); + } + + protected boolean init() throws Exception { + + // must generate if file does not exist + boolean doGenerate = false; + + if (!force) { + // regenerate only if file exists and is newer than pom file + doGenerate = !isFileNewerThanPomFile(licenseFile); + } + + if (doGenerate) { + + // acquire license + + LicenseFactory factory = LicenseFactory.newInstance(extraResolver); + + license = factory.revolv(licenseName); + + } + return doGenerate; + } + + protected void doAction() throws Exception { + getLog().info("using licence [" + licenseName + "]"); + + if (verbose) { + getLog().info("detail : " + license); + } + + if (licenseFile.exists() && keepBackup) { + if (verbose) { + getLog().info("backup " + licenseFile); + } + // copy it to backup file + File backup = new File(licenseFile.getAbsolutePath() + "~"); + licenseFile.renameTo(backup); + } + try { + FileUtil.writeString(licenseFile, license.getLicenseContent(encoding), encoding); + + // copy LICENSE.txt to classpath + File target = new File(outputDirectory, licenseFile.getName()); + + try { + + FileUtil.copy(licenseFile, target); + + } catch (IOException e) { + throw new MojoExecutionException("could not write file " + target + " for reason : " + e.getMessage(), e); + } + + } catch (IOException e) { + throw new MojoExecutionException("could not write license file " + licenseFile + " for reason : " + e.getMessage(), e); + } + } + + /*@Override + public void execute() throws MojoExecutionException, MojoFailureException { + + super.execute(); + + if (doGenerate) { + + getLog().info("using licence [" + licenseName + "]"); + + if (verbose) { + getLog().info("licence : " + license); + } + + if (licenseFile.exists() && keepBackup) { + if (verbose) { + getLog().info("backup " + licenseFile); + } + // copy it to backup file + File backup = new File(licenseFile.getAbsolutePath() + "~"); + licenseFile.renameTo(backup); + } + try { + FileUtil.writeString(licenseFile, license.getLicenseContent(encoding), encoding); + + } catch (IOException e) { + throw new MojoExecutionException("could not write license file " + licenseFile + " for reason : " + e.getMessage(), e); + } + } + + // copy LICENSE.txt to classpath + copyFileToOutputDirectory(licenseFile); + }*/ + + + public File getLicenseFile() { + return licenseFile; + } + + public String getLicenseName() { + return licenseName; + } + + public License getLicense() { + return license; + } + + public String[] getExtraResolver() { + return extraResolver; + } + + public void setLicenseFile(File licenseFile) { + this.licenseFile = licenseFile; + } + + public void setLicenseName(String licenseName) { + this.licenseName = licenseName; + } + + public void setExtraResolver(String[] extraResolver) { + this.extraResolver = extraResolver; + } + + public void setLicense(License license) { + this.license = license; + } +} Copied: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/impl/SwitchLicensePlugin.java (from rev 1312, maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/SwitchLicenseMojo.java) =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/impl/SwitchLicensePlugin.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/impl/SwitchLicensePlugin.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -0,0 +1,366 @@ +/** + * *##% Plugin maven pour switcher les licenses + * Copyright (C) 2008 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.codelutin.license.plugin.impl; + +import org.apache.maven.plugin.MojoExecutionException; +import org.codehaus.plexus.util.DirectoryScanner; +import org.codelutin.license.License; +import org.codelutin.license.LicenseFactory; +import org.codelutin.license.LicenseGenerator; +import org.codelutin.license.plugin.AbstractLicensePlugin; +import org.codelutin.processor.LicenseProcessor; +import org.codelutin.processor.filters.LicenseFilter; +import org.codelutin.util.FileUpdater; +import org.codelutin.util.FileUpdaterHelper; +import org.codelutin.util.FileUtil; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +/** + * Le goal pour switcher les licenses de tous les sources java d'un module + * maven. + * + * @author chemit + * @goal switch + * @phase process-resources + * @requiresProject true + */ +public class SwitchLicensePlugin extends AbstractLicensePlugin { + + /** + * l'annee de creation du module (sera place dans le header) + * + * @parameter default-value="${project.inceptionYear}" + * @required + */ + protected String inceptionYear; + + /** + * le nom de l'organisation (sera place dans le header) + * + * @parameter default-value="${project.organization.name}" + * @required + * @readonly + */ + protected String organizationName; + + /** + * le nom du projet (sera place dans le header) + * + * @parameter default-value="${project.name}" + * @required + * @readonly + */ + protected String projectName; + + /** + * Le type de license a appliquer. + * + * @parameter expression="${license-switcher.licenseName}" + * @required + */ + protected String licenseName; + + /** + * Repertoires des fichiers sources a traiter. + * + * @parameter expression="${license-switcher.compileSourceRoots}" default-value="${project.compileSourceRoots}" + * @required + */ + protected List<String> compileSourceRoots; + + /** + * Repertoires des fichiers sources de test a traiter. + * + * @parameter expression="${license-switcher.testCompileSourceRoots}" default-value="${project.testCompileSourceRoots}" + * @required + */ + protected List<String> testCompileSourceRoots; + + /** + * Repertoires du build des sources + * + * @parameter expression="${license-switcher.outputDirectory}" default-value="${project.build.outputDirectory}" + * @required + */ + protected File outputDirectory; + /** + * Repertoire du build des tests + * + * @parameter expression="${license-switcher.testOutputDirectory}" default-value="${project.build.testOutputDirectory}" + * @required + */ + protected File testOutputDirectory; + + /** + * Un resolver externe + * + * @parameter expression="${license-switcher.extraResolver}" + */ + protected String[] extraResolver; + + /** le header a ajouter dans chaque fichier source java */ + protected String licenseHeaderContent; + + /** la liste des chemin relatifs des sources java a traiter pour chaque repertoire contenant des sources */ + protected Map<File, String[]> javaFilesToTreate; + + protected Map<LicenseGenerator, List<String>> generators; + + protected long timestamp; + + @Override + protected boolean shouldSkip() { + return "pom".equals(project.getPackaging()) || "site".equals(project.getPackaging()); + } + + protected boolean init() throws IOException { + + boolean doGenerate = force; + + timestamp = System.nanoTime(); + + // obtain all java source files to be treated + javaFilesToTreate = getFilesToTreate(); + + doGenerate &= !javaFilesToTreate.isEmpty(); + + if (doGenerate) { + + LicenseFactory factory = LicenseFactory.newInstance(extraResolver); + License license = factory.revolv(licenseName); + + // obtain content of license header + licenseHeaderContent = computeHeader(license); + + if (verbose) { + getLog().info("header to write on java source files \n" + licenseHeaderContent); + } + + } + + return doGenerate; + } + + @Override + protected void doAction() throws Exception { + // create a licence processor with given header + LicenseProcessor p = new LicenseProcessor(licenseHeaderContent); + + for (Entry<File, String[]> entry : javaFilesToTreate.entrySet()) { + File src = entry.getKey(); + for (String javaRelativePath : entry.getValue()) { + File sourceFile = new File(src, javaRelativePath); + try { + processJavaSource(p, sourceFile); + } catch (Exception e) { + throw new MojoExecutionException("could not treate java source file " + sourceFile + " for reason : " + e.getMessage(), e); + } + } + } + } + + /*@Override + public void execute() throws MojoExecutionException, MojoFailureException { + + super.execute(); + + + + if (javaFilesToTreate.isEmpty()) { + getLog().warn("no java source files found to be treated."); + return; + } + + // create a licence processor with given header + LicenseProcessor p = new LicenseProcessor(licenseHeaderContent); + + for (Entry<File, String[]> entry : javaFilesToTreate.entrySet()) { + File src = entry.getKey(); + for (String javaRelativePath : entry.getValue()) { + File sourceFile = new File(src, javaRelativePath); + try { + processJavaSource(p, sourceFile); + } catch (Exception e) { + throw new MojoExecutionException("could not treate java source file " + sourceFile + " for reason : " + e.getMessage(), e); + } + } + } + }*/ + + protected Map<File, String[]> getFilesToTreate() { + + // init directory scanner + DirectoryScanner ds = new DirectoryScanner(); + ds.setIncludes(new String[]{"**\\/*.java"}); + + Map<File, String[]> files = new java.util.HashMap<File, String[]>(); + + getFilesToTreateForJavaRoots(ds, compileSourceRoots, outputDirectory, files); + + getFilesToTreateForJavaRoots(ds, testCompileSourceRoots, testOutputDirectory, files); + + return files; + } + + protected void getFilesToTreateForJavaRoots(DirectoryScanner ds, List<String> roots, File dstRoot, Map<File, String[]> files) { + + for (String src : roots) { + + File f = new File(src); + if (!f.exists()) { + // do nothing on a non-existent + continue; + } + + if (verbose) { + 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; + } + + FileUpdater updater = FileUpdaterHelper.newJavaFileUpdater(f, dstRoot); + List<String> toTreate = new ArrayList<String>(); + + for (String filePath : tmp) { + File srcFile = new File(f, filePath); + // check file is up-to-date + if (!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 String computeHeader(License license) throws IOException { + + + String tmpHeader = license.getHeaderContent(encoding); + + // defined inceptionYear (if year is older than now suffix with a - thisYear) + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date()); + String thisYear = cal.get(Calendar.YEAR) + ""; + if (!thisYear.equals(inceptionYear)) { + inceptionYear = inceptionYear + " - " + thisYear; + } + + // format header with projet informations + tmpHeader = String.format(tmpHeader, projectName, inceptionYear, organizationName); + + // add " * " before each line + BufferedReader reader = new BufferedReader(new java.io.StringReader(tmpHeader)); + StringBuilder sb = new StringBuilder(); + + String line = reader.readLine(); + sb.append(line).append('\n'); + while ((line = reader.readLine()) != null) { + line = line.trim(); + if (line.isEmpty()) { + sb.append(" *\n"); + } else { + sb.append(" * ").append(line).append("\n"); + } + } + tmpHeader = sb.toString(); + return tmpHeader.substring(0, tmpHeader.length() - 1); + } + + /** + * @param p license processor + * @param sourceFile the java source file where to switch (or add the licence) + * @throws java.io.IOException if IO pb + */ + protected void processJavaSource(LicenseProcessor p, File sourceFile) throws Exception { + + if (verbose) { + getLog().info("process file " + sourceFile); + } + + // file where to write result + File processFile = new File(sourceFile.getAbsolutePath() + "_" + timestamp); + + try { + p.process(sourceFile, processFile); + + if (!p.getLicenceFilter().wasTouched()) { + // no license header found in file, add it + addLicenseToJavaSourceFile(sourceFile, processFile); + } + + if (keepBackup) { + File backupFile = new File(sourceFile.getAbsolutePath() + "~"); + if (verbose) { + getLog().debug("backup original file " + sourceFile); + } + sourceFile.renameTo(backupFile); + } + processFile.renameTo(sourceFile); + + } catch (Exception e) { + getLog().error("could not process file " + sourceFile + " for reason " + e.getMessage(), e); + processFile.delete(); + throw e; + } finally { + p.getLicenceFilter().reset(); + } + } + + protected void addLicenseToJavaSourceFile(File sourceFile, File processFile) throws IOException { + getLog().warn("no license was found on file " + sourceFile + ", adding one"); + String content = FileUtil.readAsString(sourceFile, encoding); + content = "/**\n * " + LicenseFilter.HEADER + " " + licenseHeaderContent + " " + LicenseFilter.FOOTER + "\n */\n" + content; + FileUtil.writeString(processFile, content, encoding); + } + + protected void addLicenseToXmlSourceFile(File sourceFile, File processFile) throws IOException { + getLog().warn("no license was found on file " + sourceFile + ", adding one"); + String content = FileUtil.readAsString(sourceFile, encoding); + content = "<!--\n\n/**\n * " + LicenseFilter.HEADER + " " + licenseHeaderContent + " " + LicenseFilter.FOOTER + "\n */\n" + content + " \n\n-->"; + FileUtil.writeString(processFile, content, encoding); + } + +} Copied: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/impl/ThirdPartyPlugin.java (from rev 1312, maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/ThirdPartyMojo.java) =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/impl/ThirdPartyPlugin.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/impl/ThirdPartyPlugin.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -0,0 +1,349 @@ +/** + * *##% Plugin maven pour switcher les licenses + * Copyright (C) 2008 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.codelutin.license.plugin.impl; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.factory.ArtifactFactory; +import org.apache.maven.artifact.metadata.ArtifactMetadataSource; +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.artifact.resolver.ArtifactCollector; +import org.apache.maven.artifact.resolver.filter.ArtifactFilter; +import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; +import org.apache.maven.model.License; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.project.MavenProject; +import org.apache.maven.project.MavenProjectBuilder; +import org.apache.maven.project.ProjectBuildingException; +import org.apache.maven.shared.dependency.tree.DependencyNode; +import org.apache.maven.shared.dependency.tree.DependencyTreeBuilder; +import org.apache.maven.shared.dependency.tree.DependencyTreeBuilderException; +import org.codelutin.license.plugin.AbstractLicensePlugin; +import org.codelutin.util.FileUtil; + +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.SortedSet; +import java.util.TreeSet; + +/** + * Le goal pour copier le fichier THIRD-PARTY.txt (contenant les licenses de toutes les dependances du projet) + * dans le classpath (et le generer s'il n'existe pas). + * + * @author chemit + * @goal third-party + * @phase process-classes + * @requiresDependencyResolution test + * @requiresProject true + */ +public class ThirdPartyPlugin extends AbstractLicensePlugin { + + private static final String unknownLicenseMessage = "Unknown license"; + + /** + * Local Repository. + * + * @parameter expression="${localRepository}" + * @required + * @readonly + */ + protected ArtifactRepository localRepository; + + + /** + * Remote repositories used for the project. + * + * @parameter expression="${project.remoteArtifactRepositories}" + * @required + * @readonly + */ + protected List remoteRepositories; + + /** + * Fichier ou ecrire les licences des dependances. + * + * @parameter expression="${license-switcher.thirdPartyFile}" default-value="${project.build.outputDirectory}/THIRD-PARTY.txt" + * @required + */ + protected File thirdPartyFile; + + /** + * Dependency tree builder component. + * + * @component + */ + protected DependencyTreeBuilder dependencyTreeBuilder; + + /** + * Artifact Factory component. + * + * @component + */ + protected ArtifactFactory factory; + + /** + * Artifact metadata source component. + * + * @component + */ + protected ArtifactMetadataSource artifactMetadataSource; + + /** + * Artifact collector component. + * + * @component + */ + protected ArtifactCollector collector; + + /** + * Maven Project Builder component. + * + * @component + */ + protected MavenProjectBuilder mavenProjectBuilder; + + /** + * content of third party file (only computed if {@link #force} is active or the + * {@link #thirdPartyFile} does not exist, or is not up-to-date. + */ + protected String thirdPartyFileContent; + + @Override + protected boolean shouldSkip() { + return "pom".equals(project.getPackaging()) || "site".equals(project.getPackaging()); + } + + protected boolean init() throws Exception { + + boolean doGenerate = false; + + if (!force) { + // regenerate only if file exists and is newer than pom file + doGenerate = !isFileNewerThanPomFile(thirdPartyFile); + } + + if (doGenerate) { + + // prepare thirdPartyFileContent + + DependencyNode dependencyTreeNode = resolveProject(); + + LicenseMap licenseMap = new LicenseMap(); + + for (Object o : dependencyTreeNode.getChildren()) { + + buildLicenseMap((DependencyNode) o, licenseMap); + } + + thirdPartyFileContent = buildGroupedLicenses(licenseMap); + + // log dependencies with no license + SortedSet<String> dependenciesWithNoLicense = licenseMap.get(unknownLicenseMessage); + if (dependenciesWithNoLicense != null) { + for (String dep : dependenciesWithNoLicense) { + // no license found for the dependency + getLog().warn("no license found for dependency " + dep); + } + } + } + + return doGenerate; + } + + @Override + protected void doAction() throws Exception { + if (verbose) { + getLog().info("writing third-party file : " + thirdPartyFile); + } + if (keepBackup && thirdPartyFile.exists()) { + if (verbose) { + getLog().info("backup " + thirdPartyFile); + } + thirdPartyFile.renameTo(new File(thirdPartyFile.getAbsolutePath() + '~')); + } + try { + FileUtil.writeString(thirdPartyFile, thirdPartyFileContent, encoding); + } catch (IOException e) { + throw new MojoExecutionException("could not write file " + thirdPartyFile + " for reason : " + e.getMessage(), e); + } + } + + /*@Override + public void execute() throws MojoExecutionException, MojoFailureException { + + super.execute(); + + if (doGenerate) { + if (verbose) { + getLog().info("writing third-party file : " + thirdPartyFile); + } + if (keepBackup && thirdPartyFile.exists()) { + if (verbose) { + getLog().info("backup " + thirdPartyFile); + } + thirdPartyFile.renameTo(new File(thirdPartyFile.getAbsolutePath() + '~')); + } + try { + FileUtil.writeString(thirdPartyFile, thirdPartyFileContent, encoding); + } catch (IOException e) { + throw new MojoExecutionException("could not write file " + thirdPartyFile + " for reason : " + e.getMessage(), e); + } + } + + }*/ + + + /** @return resolve the dependency tree */ + protected DependencyNode resolveProject() { + try { + ArtifactFilter artifactFilter = new ScopeArtifactFilter(Artifact.SCOPE_TEST); + return dependencyTreeBuilder.buildDependencyTree(project, localRepository, factory, + artifactMetadataSource, artifactFilter, collector); + } + catch (DependencyTreeBuilderException e) { + getLog().error("Unable to build dependency tree.", e); + return null; + } + } + + protected void buildLicenseMap(DependencyNode node, LicenseMap licenseMap) { + if (node.getState() != DependencyNode.INCLUDED) { + // this dependency is not included, so do not treate it + if (verbose) { + getLog().info("do not include this dependency " + node.toNodeString()); + } + return; + } + Artifact artifact = node.getArtifact(); + + if (verbose && getLog().isDebugEnabled()) { + getLog().debug("treate node " + node.toNodeString()); + } + + if (!Artifact.SCOPE_SYSTEM.equals(artifact.getScope())) { + try { + MavenProject artifactProject = getMavenProjectFromRepository(artifact); + String artifactName = getArtifactName(artifactProject); + + List licenses = artifactProject.getLicenses(); + + if (licenses.isEmpty()) { + // no license found for the dependency + licenseMap.put(unknownLicenseMessage, artifactName); + + } else { + for (Object o : licenses) { + if (o == null) { + getLog().warn("could not acquire the license for " + artifactName); + continue; + } + License license = (License) o; + String licenseKey = license.getName(); + if (license.getName() == null) { + licenseKey = license.getUrl(); + } + licenseMap.put(licenseKey, artifactName); + } + } + } + catch (ProjectBuildingException e) { + getLog().error("ProjectBuildingException error : ", e); + } + } + if (!node.getChildren().isEmpty()) { + for (Object o : node.getChildren()) { + buildLicenseMap((DependencyNode) o, licenseMap); + } + } + } + + protected String buildGroupedLicenses(LicenseMap licenseMap) { + StringBuilder sb = new StringBuilder(); + sb.append("List of third-party dependencies grouped by their license type."); + for (String licenseName : licenseMap.keySet()) { + sb.append("\n\n").append(licenseName).append(" : "); + + SortedSet<String> projects = licenseMap.get(licenseName); + + for (String projectName : projects) { + sb.append("\n * ").append(projectName); + } + } + return sb.toString(); + } + + protected String getArtifactName(MavenProject artifactProject) { + StringBuilder sb = new StringBuilder(); + + sb.append(artifactProject.getName()); + sb.append(" ("); + sb.append(artifactProject.getGroupId()); + sb.append(":"); + sb.append(artifactProject.getArtifactId()); + sb.append(":"); + sb.append(artifactProject.getVersion()); + sb.append(" - "); + String url = artifactProject.getUrl(); + sb.append(url == null ? "no url defined" : url); + sb.append(")"); + + return sb.toString(); + } + + /** + * Get the <code>Maven project</code> from the repository depending the <code>Artifact</code> given. + * + * @param artifact an artifact + * @return the Maven project for the given artifact + * @throws ProjectBuildingException if any + */ + protected MavenProject getMavenProjectFromRepository(Artifact artifact) + throws ProjectBuildingException { + + boolean allowStubModel = false; + + if (!"pom".equals(artifact.getType())) { + artifact = factory.createProjectArtifact(artifact.getGroupId(), artifact.getArtifactId(), + artifact.getVersion(), artifact.getScope()); + allowStubModel = true; + } + + // TODO: we should use the MavenMetadataSource instead + return mavenProjectBuilder.buildFromRepository(artifact, remoteRepositories, localRepository, + allowStubModel); + } + + protected class LicenseMap extends java.util.TreeMap<String, SortedSet<String>> { + private static final long serialVersionUID = 864199843545688069L; + + /** {@inheritDoc} */ + public SortedSet<String> put(String key, String value) { + // handle multiple values as a set to avoid duplicates + SortedSet<String> valueList = get(key); + if (valueList == null) { + valueList = new TreeSet<String>(); + } + if (getLog().isDebugEnabled()) { + getLog().debug("key:" + key + ",value: " + value); + } + valueList.add(value); + return put(key, valueList); + } + } +} Added: maven-license-switcher-plugin/trunk/src/main/resources/log4j.properties =================================================================== --- maven-license-switcher-plugin/trunk/src/main/resources/log4j.properties (rev 0) +++ maven-license-switcher-plugin/trunk/src/main/resources/log4j.properties 2009-01-28 20:18:25 UTC (rev 1314) @@ -0,0 +1,10 @@ +# Global logging configuration +log4j.rootLogger=ERROR, stdout +# Console output... +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) %M - %m%n + +# package level +log4j.logger.org.codelutin=INFO + Modified: maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/BaseLicenseTestCase.java =================================================================== --- maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/BaseLicenseTestCase.java 2009-01-26 12:40:09 UTC (rev 1313) +++ maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/BaseLicenseTestCase.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -1,13 +1,13 @@ package org.codelutin.license; -import junit.framework.TestCase; import org.codelutin.util.FileUtil; +import org.junit.Assert; import java.io.File; import java.io.IOException; /** @author chemit */ -public abstract class BaseLicenseTestCase extends TestCase { +public abstract class BaseLicenseTestCase extends Assert { protected static final String encoding = "utf-8"; Modified: maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/JarLicenseResolverTest.java =================================================================== --- maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/JarLicenseResolverTest.java 2009-01-26 12:40:09 UTC (rev 1313) +++ maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/JarLicenseResolverTest.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -1,5 +1,7 @@ package org.codelutin.license; +import org.junit.Test; + import java.util.ArrayList; import java.util.Arrays; import java.util.Map; @@ -7,29 +9,24 @@ /** @author chemit */ public class JarLicenseResolverTest extends BaseLicenseTestCase { - public void testResolv() throws Exception { - JarLicenseResolver resolver = new JarLicenseResolver(); + @Test(expected = IllegalArgumentException.class) + public void testResolvFailed1() throws Exception { + new JarLicenseResolver().resolv(null); + } - try { - resolver.resolv(null); - fail(); - } catch (IllegalArgumentException e) { - assertTrue(true); - } + @Test(expected = IllegalArgumentException.class) + public void testResolvFailed2() throws Exception { + new JarLicenseResolver().resolv(""); + } - try { - resolver.resolv(""); - fail(); - } catch (IllegalArgumentException e) { - assertTrue(true); - } + @Test(expected = IllegalArgumentException.class) + public void testResolvFailed3() throws Exception { + new JarLicenseResolver().resolv(" "); + } - try { - resolver.resolv(" "); - fail(); - } catch (IllegalArgumentException e) { - assertTrue(true); - } + @Test + public void testResolv() throws Exception { + JarLicenseResolver resolver = new JarLicenseResolver(); { String name = "dummy_" + System.currentTimeMillis(); @@ -49,6 +46,7 @@ } + @Test public void testGetLicenseNames() throws Exception { JarLicenseResolver resolver = new JarLicenseResolver(); Map<String, String> licenseNames = resolver.getLicenseNames(); Added: maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/JavaLicenseGeneratorTest.java =================================================================== --- maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/JavaLicenseGeneratorTest.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/JavaLicenseGeneratorTest.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -0,0 +1,24 @@ +package org.codelutin.license; + +import org.junit.Before; +import org.junit.After; +import org.junit.Test; + +/** @author chemit */ +public class JavaLicenseGeneratorTest { + + @Before + public void setUp() { + // Add your code here + } + + @After + public void tearDown() { + // Add your code here + } + + @Test + public void testGetHeader() { + // Add your code here + } +} Modified: maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/LicenseFactoryTest.java =================================================================== --- maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/LicenseFactoryTest.java 2009-01-26 12:40:09 UTC (rev 1313) +++ maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/LicenseFactoryTest.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -1,11 +1,14 @@ package org.codelutin.license; +import org.junit.Test; + import java.io.File; import java.util.Map; /** @author chemit */ public class LicenseFactoryTest extends BaseLicenseTestCase { + @Test public void testNewInstance() throws Exception { LicenseFactory factory = LicenseFactory.newInstance(); @@ -42,6 +45,7 @@ } + @Test public void testGetLicenseNames() throws Exception { LicenseFactory factory = LicenseFactory.newInstance(); @@ -64,7 +68,7 @@ // add a new license to repo long timestamp = System.currentTimeMillis(); String licenseName = "dummy2_" + timestamp; - addLicenseToRepository(repo,licenseName); + addLicenseToRepository(repo, licenseName); factory = LicenseFactory.newInstance(repo.toURI().toURL().toString()); @@ -73,5 +77,4 @@ } - } Added: maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/LicenseGeneratorFactoryTest.java =================================================================== --- maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/LicenseGeneratorFactoryTest.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/LicenseGeneratorFactoryTest.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -0,0 +1,34 @@ +package org.codelutin.license; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** @author chemit */ +public class LicenseGeneratorFactoryTest { + + @Before + public void setUp() { + // Add your code here + } + + @After + public void tearDown() { + // Add your code here + } + + @Test + public void testGetAvailableGenerator() { + // Add your code here + } + + @Test + public void testGetGeneratorMatchers() { + // Add your code here + } + + @Test + public void testAddGenerator() { + // Add your code here + } +} Modified: maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/LicenseResolverTest.java =================================================================== --- maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/LicenseResolverTest.java 2009-01-26 12:40:09 UTC (rev 1313) +++ maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/LicenseResolverTest.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -1,66 +1,67 @@ package org.codelutin.license; +import org.junit.Test; + import java.io.File; import java.util.Map; /** @author chemit */ public class LicenseResolverTest extends BaseLicenseTestCase { - public void testResolvIllegalArgumentException() throws Exception { + @Test(expected = IllegalArgumentException.class) + public void testResolvIllegalArgumentException1() throws Exception { LicenseResolver resolver = new LicenseResolver(); + // no baseURL + // no licenseName + // no licenses.txt + resolver.resolv(null); + } - try { - // no baseURL - // no licenseName - // no licenses.txt - resolver.resolv(null); - fail(); - } catch (IllegalArgumentException e) { - assertTrue(true); - } + @Test(expected = IllegalArgumentException.class) + public void testResolvIllegalArgumentException2() throws Exception { - try { - // no baseURL - // no licenseName - // no licenses.txt - resolver.resolv(""); - fail(); - } catch (IllegalArgumentException e) { - assertTrue(true); - } + LicenseResolver resolver = new LicenseResolver(); - try { - // no baseURL - // no licenseName - // no licenses.txt - resolver.resolv(" "); - fail(); - } catch (IllegalArgumentException e) { - assertTrue(true); - } + // no baseURL + // no licenseName + // no licenses.txt + resolver.resolv(""); + } - try { - // no baseURL - // no licenses.txt - resolver.resolv("dummy"); - fail(); - } catch (IllegalArgumentException e) { - assertTrue(true); - } + @Test(expected = IllegalArgumentException.class) + public void testResolvIllegalArgumentException3() throws Exception { - resolver.setBaseURL("dummy"); - try { - // no licenses.txt - resolver.resolv("dummy"); - fail(); - } catch (IllegalArgumentException e) { - assertTrue(true); - } + LicenseResolver resolver = new LicenseResolver(); + // no baseURL + // no licenseName + // no licenses.txt + resolver.resolv(" "); } + @Test(expected = IllegalArgumentException.class) + public void testResolvIllegalArgumentException4() throws Exception { + LicenseResolver resolver = new LicenseResolver(); + + // no baseURL + // no licenses.txt + resolver.resolv("dummy"); + } + + @Test(expected = IllegalArgumentException.class) + public void testResolvIllegalArgumentException5() throws Exception { + + LicenseResolver resolver = new LicenseResolver(); + + + resolver.setBaseURL("dummy"); + // no licenses.txt + resolver.resolv("dummy"); + } + + @Test public void testResolv() throws Exception { LicenseResolver resolver = new LicenseResolver(); @@ -104,8 +105,8 @@ assertEquals(licenseName, license.getName()); assertNotNull(license.getLicenseContent(encoding)); assertNotNull(license.getHeaderContent(encoding)); - assertEquals("license:"+licenseName, license.getLicenseContent(encoding)); - assertEquals("header:"+licenseName, license.getHeaderContent(encoding)); + assertEquals("license:" + licenseName, license.getLicenseContent(encoding)); + assertEquals("header:" + licenseName, license.getHeaderContent(encoding)); } Added: maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/XmlLicenseGeneratorTest.java =================================================================== --- maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/XmlLicenseGeneratorTest.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/XmlLicenseGeneratorTest.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -0,0 +1,23 @@ +package org.codelutin.license; + +import org.junit.Before; +import org.junit.After; +import org.junit.Test; + +/** @author chemit */ +public class XmlLicenseGeneratorTest { + @Before + public void setUp() { + // Add your code here + } + + @After + public void tearDown() { + // Add your code here + } + + @Test + public void testGetHeader() { + // Add your code here + } +} Added: maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/plugin/BasePluginTestCase.java =================================================================== --- maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/plugin/BasePluginTestCase.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/plugin/BasePluginTestCase.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -0,0 +1,99 @@ +package org.codelutin.license.plugin; + +import org.apache.commons.logging.Log; +import org.apache.maven.plugin.Mojo; +import org.apache.maven.plugin.testing.AbstractMojoTestCase; +import org.junit.Before; + +import java.io.File; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** @author chemit */ +public abstract class BasePluginTestCase { + + protected static File basedir; + protected static File testDir; + protected static Iterator<PluginConfig> configItr; + protected static MyAbstractMojoTestCase delegate; + + protected String goalName; + protected File pomFile; + protected Mojo mojo; + + protected static File getBaseDir() { + if (basedir == null) { + String path = System.getenv("basedir"); + if (path == null) { + path = new File("").getAbsolutePath(); + } + basedir = new File(path); + } + return basedir; + } + + protected static File getTestDir() { + return testDir; + } + + protected static void initConfigs(Class<? extends BasePluginTestCase> klass, String... testNames) throws Exception { + List<PluginConfig> configs = new ArrayList<PluginConfig>(); + String rep = klass.getName(); + rep = rep.replaceAll("\\.", File.separator); + + File f = new File(getBaseDir(), "src" + File.separator + "test" + File.separator + "resources"); + testDir = new File(f, rep); + System.out.println("test dir : " + testDir); + + for (String testName : testNames) { + Method m = klass.getMethod(testName); + if (m == null) { + throw new IllegalAccessException("could not find method " + testName + " on class " + klass.getName()); + } + + PluginConfig annotation = m.getAnnotation(PluginConfig.class); + if (annotation == null) { + throw new IllegalAccessException("could not find annotation " + PluginConfig.class.getName() + " on method " + testName); + } + configs.add(annotation); + } + + delegate = new MyAbstractMojoTestCase(); + delegate.setUp(); + configItr = configs.iterator(); + } + + @Before + public void setUp() throws Exception { + initPomFile(configItr.next()); + } + + protected void initPomFile(PluginConfig pluginConfig) throws Exception { + this.goalName = pluginConfig.goalName(); + this.pomFile = new File(getTestDir(), pluginConfig.pomName()); + this.mojo = delegate.lookupMojo(goalName, pomFile); + + } + + private static class MyAbstractMojoTestCase 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(); + } + + + } +} \ No newline at end of file Added: maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/plugin/PluginConfig.java =================================================================== --- maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/plugin/PluginConfig.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/plugin/PluginConfig.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -0,0 +1,20 @@ +package org.codelutin.license.plugin; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; + +/** @author chemit */ +@Retention(RetentionPolicy.RUNTIME) + +@Target(ElementType.METHOD) +@Inherited +public @interface PluginConfig { + + String goalName(); + + String pomName(); + +} \ No newline at end of file Added: maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/plugin/impl/LicensePluginTest.java =================================================================== --- maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/plugin/impl/LicensePluginTest.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/test/java/org/codelutin/license/plugin/impl/LicensePluginTest.java 2009-01-28 20:18:25 UTC (rev 1314) @@ -0,0 +1,54 @@ +package org.codelutin.license.plugin.impl; + +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.codelutin.license.plugin.BasePluginTestCase; +import org.codelutin.license.plugin.PluginConfig; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; + +/** @author chemit */ +public class LicensePluginTest extends BasePluginTestCase { + + @BeforeClass + public static void initClass() throws Exception { + initConfigs(LicensePluginTest.class, "testOne"); + } + + @AfterClass + public static void afterClass() throws Exception { + configItr = null; + testDir = null; + } + + @Before + public void setUp() throws Exception { + super.setUp(); + LicensePlugin plugin = (LicensePlugin) mojo; + plugin.setPomFile(pomFile); + plugin.setOutputDirectory(new File(getBaseDir(), plugin.getOutputDirectory().toString())); + if (!plugin.getOutputDirectory().exists()) { + if (!plugin.getOutputDirectory().mkdirs()) { + throw new IOException("could not create directory : " + plugin.getOutputDirectory()); + } + } + plugin.setLicenseFile(new File(pomFile.getParentFile(), plugin.getLicenseFile().toString())); + } + + @Test + @PluginConfig(pomName = "testOne.xml", goalName = "license") + public void testOne() throws MojoExecutionException, MojoFailureException { + // Add your code here + Assert.assertNotNull(this.mojo); + + this.mojo.execute(); + + } + +} Added: maven-license-switcher-plugin/trunk/src/test/resources/org/codelutin/license/plugin/impl/LicensePluginTest/licenseOne.txt =================================================================== --- maven-license-switcher-plugin/trunk/src/test/resources/org/codelutin/license/plugin/impl/LicensePluginTest/licenseOne.txt (rev 0) +++ maven-license-switcher-plugin/trunk/src/test/resources/org/codelutin/license/plugin/impl/LicensePluginTest/licenseOne.txt 2009-01-28 20:18:25 UTC (rev 1314) @@ -0,0 +1 @@ +dummy license \ No newline at end of file Added: maven-license-switcher-plugin/trunk/src/test/resources/org/codelutin/license/plugin/impl/LicensePluginTest/testOne.xml =================================================================== --- maven-license-switcher-plugin/trunk/src/test/resources/org/codelutin/license/plugin/impl/LicensePluginTest/testOne.xml (rev 0) +++ maven-license-switcher-plugin/trunk/src/test/resources/org/codelutin/license/plugin/impl/LicensePluginTest/testOne.xml 2009-01-28 20:18:25 UTC (rev 1314) @@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + <parent> + <groupId>org.codelutin</groupId> + <artifactId>lutinproject</artifactId> + <version>3.3</version> + </parent> + <build> + + <plugins> + <plugin> + <groupId>org.codelutin</groupId> + <artifactId>maven-license-switcher-plugin</artifactId> + <configuration> + <encoding>UTF-8</encoding> + <licenseName>lgpl_v3</licenseName> + <licenseFile>licenseOne.txt</licenseFile> + <pomFile>testOne.xml</pomFile> + <outputDirectory>target/tests/LicenPluginTest/test-java</outputDirectory> + </configuration> + <executions> + <execution> + <goals> + <goal>license</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> \ No newline at end of file
participants (1)
-
tchemit@users.labs.libre-entreprise.org