Author: tchemit Date: 2008-10-12 21:44:25 +0000 (Sun, 12 Oct 2008) New Revision: 1176 Added: 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 Removed: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/AbstractLicenseMojo.java maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/AvailableLicensesMojo.java maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseMojo.java maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/SwitchLicenseMojo.java maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/ThirdPartyMojo.java Log: introduce plugin package to put mojo Deleted: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/AbstractLicenseMojo.java =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/AbstractLicenseMojo.java 2008-10-12 21:44:03 UTC (rev 1175) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/AbstractLicenseMojo.java 2008-10-12 21:44:25 UTC (rev 1176) @@ -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; - -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); - } - } -} Deleted: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/AvailableLicensesMojo.java =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/AvailableLicensesMojo.java 2008-10-12 21:44:03 UTC (rev 1175) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/AvailableLicensesMojo.java 2008-10-12 21:44:25 UTC (rev 1176) @@ -1,55 +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; - -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; - -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()); - } - -} Deleted: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseMojo.java =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseMojo.java 2008-10-12 21:44:03 UTC (rev 1175) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseMojo.java 2008-10-12 21:44:25 UTC (rev 1176) @@ -1,118 +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; - -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -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 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/SwitchLicenseMojo.java =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/SwitchLicenseMojo.java 2008-10-12 21:44:03 UTC (rev 1175) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/SwitchLicenseMojo.java 2008-10-12 21:44:25 UTC (rev 1176) @@ -1,282 +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; - -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 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 void init() throws IOException { - - 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 (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/ThirdPartyMojo.java =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/ThirdPartyMojo.java 2008-10-12 21:44:03 UTC (rev 1175) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/ThirdPartyMojo.java 2008-10-12 21:44:25 UTC (rev 1176) @@ -1,300 +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; - -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 (doGenerate) { - - // prepare thirdPartyFileContent - - DependencyNode dependencyTreeNode = resolveProject(); - - LicenseMap licenseMap = new LicenseMap(); - - for (Object o : dependencyTreeNode.getChildren()) { - - buildLicenseMap((DependencyNode) o, licenseMap); - } - - thirdPartyFileContent = buildGroupedLicenses(licenseMap); - } - } - - @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) { - - Artifact artifact = node.getArtifact(); - - 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 - getLog().warn("no license found for dependency " + artifactName); - - licenseMap.put(unknownLicenseMessage, artifactName); - - } else { - for (Object license : licenses) { - licenseMap.put(((License) license).getName(), 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/AbstractLicenseMojo.java (from rev 1165, maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/AbstractLicenseMojo.java) =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AbstractLicenseMojo.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AbstractLicenseMojo.java 2008-10-12 21:44:25 UTC (rev 1176) @@ -0,0 +1,108 @@ +/** + * *##% 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/AvailableLicensesMojo.java (from rev 1169, maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/AvailableLicensesMojo.java) =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AvailableLicensesMojo.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/AvailableLicensesMojo.java 2008-10-12 21:44:25 UTC (rev 1176) @@ -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 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/LicenseMojo.java (from rev 1171, maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/LicenseMojo.java) =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/LicenseMojo.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/LicenseMojo.java 2008-10-12 21:44:25 UTC (rev 1176) @@ -0,0 +1,120 @@ +/** + * *##% 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); + } + +} Copied: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/SwitchLicenseMojo.java (from rev 1171, maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/SwitchLicenseMojo.java) =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/SwitchLicenseMojo.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/SwitchLicenseMojo.java 2008-10-12 21:44:25 UTC (rev 1176) @@ -0,0 +1,284 @@ +/** + * *##% 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 void init() throws IOException { + + 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 (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); + } + +} Copied: maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/ThirdPartyMojo.java (from rev 1165, maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/ThirdPartyMojo.java) =================================================================== --- maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/ThirdPartyMojo.java (rev 0) +++ maven-license-switcher-plugin/trunk/src/main/java/org/codelutin/license/plugin/ThirdPartyMojo.java 2008-10-12 21:44:25 UTC (rev 1176) @@ -0,0 +1,300 @@ +/** + * *##% 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 (doGenerate) { + + // prepare thirdPartyFileContent + + DependencyNode dependencyTreeNode = resolveProject(); + + LicenseMap licenseMap = new LicenseMap(); + + for (Object o : dependencyTreeNode.getChildren()) { + + buildLicenseMap((DependencyNode) o, licenseMap); + } + + thirdPartyFileContent = buildGroupedLicenses(licenseMap); + } + } + + @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) { + + Artifact artifact = node.getArtifact(); + + 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 + getLog().warn("no license found for dependency " + artifactName); + + licenseMap.put(unknownLicenseMessage, artifactName); + + } else { + for (Object license : licenses) { + licenseMap.put(((License) license).getName(), 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); + } + } +}