Commit b495b8f2 by Alex Rhodes

Initial commit

parents
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>copyright-plugin</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
encoding/<project>=UTF-8
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.7
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.7
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.alexscottrhodes</groupId>
<artifactId>copyright-maven-plugin</artifactId>
<version>1.0</version>
<packaging>maven-plugin</packaging>
<name>copyright-plugin</name>
<url>http://www.alexscottrhodes.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugin-tools</groupId>
<artifactId>maven-plugin-annotations</artifactId>
<version>3.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-utils</artifactId>
<version>3.0.8</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-plugin-plugin</artifactId>
<version>3.2</version>
<configuration>
<goalPrefix>copyright</goalPrefix>
<skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
</configuration>
<executions>
<execution>
<id>mojo-descriptor</id>
<goals>
<goal>descriptor</goal>
</goals>
</execution>
<execution>
<id>help-goal</id>
<goals>
<goal>helpmojo</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>run-its</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-invoker-plugin</artifactId>
<version>1.7</version>
<configuration>
<debug>true</debug>
<cloneProjectsTo>${project.build.directory}/it</cloneProjectsTo>
<pomIncludes>
<pomInclude>*/pom.xml</pomInclude>
</pomIncludes>
<postBuildHookScript>verify</postBuildHookScript>
<localRepositoryPath>${project.build.directory}/local-repo</localRepositoryPath>
<settingsFile>src/it/settings.xml</settingsFile>
<goals>
<goal>clean</goal>
<goal>test-compile</goal>
</goals>
</configuration>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>install</goal>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor
license agreements. See the NOTICE file distributed with this work for additional
information regarding copyright ownership. The ASF licenses this file to
you under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of
the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License. -->
<settings>
<plugingroups>
<plugingroup>com.alexscottrhodes</plugingroup>
</plugingroups>
<profiles>
<profile>
<id>it-repo</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<repositories>
<repository>
<id>local.central</id>
<url>@localRepositoryUrl@</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>local.central</id>
<url>@localRepositoryUrl@</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
</settings>
<?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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.alexscottrhodes.it</groupId>
<artifactId>simple-it</artifactId>
<version>1.0-SNAPSHOT</version>
<description>A simple IT verifying the basic use case.</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>@project.groupId@</groupId>
<artifactId>@project.artifactId@</artifactId>
<version>@project.version@</version>
<executions>
<execution>
<id>touch</id>
<phase>validate</phase>
<goals>
<goal>touch</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
File touchFile = new File( basedir, "target/touch.txt" );
assert touchFile.isFile()
package com.alexscottrhodes.copyright_plugin;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
/**
* Goal that adds a custom copyright to the top of each file, only applicable to
* Java source, XML, XHTML, and HTML files.
*
* @Goal cr
*
* @phase test
*/
@Mojo(name="cr")
public class CopyrightGenerator extends AbstractMojo {
@Parameter(defaultValue="${remove}")
private boolean remove = false;
@Parameter(defaultValue="${basedir}",required=true)
private File sourceDir = new File("");
private ArrayList<String> fileNames = new ArrayList<String>();
private HashMap<String,String> copyrightText = new HashMap<String,String>();
public void execute() throws MojoExecutionException {
getLog().debug("remove = " + remove);
if (!sourceDir.exists()) {
getLog().error("Could not find source directory specified in POM");
}
populateFileList(sourceDir);
Iterator<String> it = fileNames.iterator();
while (it.hasNext()) {
String name = it.next();
if(name.contains("copyright-config.xml")){
populateCopyrights(name);
if(copyrightText.size()<1){
getLog().error("Copyright confiruation invalid.");
return;
}
}
if (name.lastIndexOf(".") == -1) {
it.remove();
}
String ext = name.substring(name.lastIndexOf("."));
if (!(ext.contains("xhtml") || ext.contains("html") || ext.contains("xml") || ext.contains("java"))) {
it.remove();
}
}
for (String fname : fileNames) {
if(remove){
stripHeader(fname);
}else{
writeHeader(fname);
}
}
}
public void populateFileList(File root) {
if (root.isFile()) {
fileNames.add(root.getPath());
return;
}
for (final File file : root.listFiles()) {
if (file.isDirectory()) {
populateFileList(file);
} else {
fileNames.add(file.getPath());
}
}
}
public void writeHeader(String fileName) {
String header = getBody(fileName);
if(header == null){
return;
}
try {
if(fileName.contains("copyright-plugin-backup") || fileName.contains("copyright-config.xml")){
return;
}
File edit = new File(fileName);
File backupDest = new File(sourceDir.getAbsolutePath()+"/copyright-plugin-backup/");
backupDest.mkdirs();
FileUtils.copyFileToDirectory(edit, backupDest);
FileInputStream fis = new FileInputStream(edit);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
String testSequence = "";
while((line = br.readLine())!=null){
testSequence+= line;
}
testSequence = sanitize(testSequence);
String testHeader = sanitize(new String(header));
if(testSequence.contains(testHeader)){
br.close();
fis.close();
return;
}
br.close();
fis.close();
fis = new FileInputStream(edit);
br = new BufferedReader(new InputStreamReader(fis));
PrintWriter writer = new PrintWriter("tmp");
writer.println(header);
while ((line = br.readLine()) != null) {
writer.println(line);
}
writer.close();
br.close();
fis.close();
edit.delete();
File temp = new File("tmp");
Path source = Paths.get(temp.getAbsolutePath());
Files.move(source, source.resolveSibling(fileName));
} catch (Exception e) {
e.printStackTrace();
}
}
public void stripHeader(String fileName) {
String header = getBody(fileName);
if(header == null){
return;
}
try {
if(fileName.contains("copyright-plugin-backup") || fileName.contains("copyright-config.xml")){
return;
}
File edit = new File(fileName);
File backupDest = new File(sourceDir.getAbsolutePath()+"/copyright-plugin-backup/");
backupDest.mkdirs();
FileUtils.copyFileToDirectory(edit, backupDest);
FileInputStream fis = new FileInputStream(edit);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
PrintWriter writer = new PrintWriter("tmp");
String line;
while ((line = br.readLine()) != null) {
if(!header.contains(line)){
writer.println(line);
}
}
writer.close();
br.close();
fis.close();
edit.delete();
File temp = new File("tmp");
Path source = Paths.get(temp.getAbsolutePath());
Files.move(source, source.resolveSibling(fileName));
} catch (Exception e) {
e.printStackTrace();
}
}
public String getBody(String fileName){
if (fileName.lastIndexOf(".") == -1) {
return null;
}
String ext = fileName.substring(fileName.lastIndexOf("."));
ext = ext.replace(".", "");
String body = copyrightText.get(ext);
if(body == null){
return body;
}
if(ext.equalsIgnoreCase("java")){
body = "/*" + body + "*/";
}else if(ext.equalsIgnoreCase("xml") || ext.equalsIgnoreCase("xhtml") || ext.equalsIgnoreCase("html")){
body = "<!-- \n" + body + "\n -->";
}
return body;
}
public void populateCopyrights(String configFileName){
try{
SAXBuilder builder = new SAXBuilder();
File config = new File(configFileName);
Document document = (Document) builder.build(config);
Element root = document.getRootElement();
@SuppressWarnings("rawtypes")
List copyrightElements = root.getChildren("copyright");
for(int i = 0; i < copyrightElements.size(); i++){
Element cp = (Element) copyrightElements.get(i);
String ext = cp.getChildText("file-type");
if(ext == null){
throw new Exception("Invalid copyright configuration file.");
}
if(!(ext.equals("xhtml") || ext.equals("html") || ext.equals("xml") || ext.equals("java"))){
throw new Exception("Unsupproted file type in copyright configuration file.");
}
String body = cp.getChildText("body");
if(body == null || body==""){
continue;
}else{
copyrightText.put(ext, body);
}
}
}catch(Exception e){
getLog().error(e.getMessage());
}
}
public String sanitize(String in){
in = in.replace("\n", "").replace("\r", "").replace(" ","").replaceAll(" ","");
return in;
}
}
Manifest-Version: 1.0
Built-By: Alex
Build-Jdk: 1.8.0_51
Created-By: Maven Integration for Eclipse
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated by maven-plugin-tools 3.2 on 2016-07-27 -->
<plugin>
<name>copyright-plugin</name>
<description></description>
<groupId>com.alexscottrhodes</groupId>
<artifactId>copyright-maven-plugin</artifactId>
<version>1.0</version>
<goalPrefix>copyright</goalPrefix>
<mojos>
<mojo>
<goal>cr</goal>
<description>Goal that adds a custom copyright to the top of each file, only applicable to Java source, XML, XHTML, and HTML files.</description>
<requiresDirectInvocation>false</requiresDirectInvocation>
<requiresProject>true</requiresProject>
<requiresReports>false</requiresReports>
<aggregator>false</aggregator>
<requiresOnline>false</requiresOnline>
<inheritedByDefault>true</inheritedByDefault>
<implementation>com.alexscottrhodes.copyright_plugin.CopyrightGenerator</implementation>
<language>java</language>
<instantiationStrategy>per-lookup</instantiationStrategy>
<executionStrategy>once-per-session</executionStrategy>
<threadSafe>false</threadSafe>
<parameters>
<parameter>
<name>remove</name>
<type>boolean</type>
<required>false</required>
<editable>true</editable>
<description></description>
</parameter>
<parameter>
<name>sourceDir</name>
<type>java.io.File</type>
<required>true</required>
<editable>true</editable>
<description></description>
</parameter>
</parameters>
<configuration>
<remove implementation="boolean" default-value="${remove}"/>
<sourceDir implementation="java.io.File" default-value="${basedir}"/>
</configuration>
</mojo>
<mojo>
<goal>help</goal>
<description>Display help information on copyright-maven-plugin.
Call mvn copyright:help -Ddetail=true -Dgoal=&lt;goal-name&gt; to display parameter details.</description>
<requiresDirectInvocation>false</requiresDirectInvocation>
<requiresProject>false</requiresProject>
<requiresReports>false</requiresReports>
<aggregator>false</aggregator>
<requiresOnline>false</requiresOnline>
<inheritedByDefault>true</inheritedByDefault>
<implementation>com.alexscottrhodes.copyright_plugin.HelpMojo</implementation>
<language>java</language>
<instantiationStrategy>per-lookup</instantiationStrategy>
<executionStrategy>once-per-session</executionStrategy>
<threadSafe>true</threadSafe>
<parameters>
<parameter>
<name>detail</name>
<type>boolean</type>
<required>false</required>
<editable>true</editable>
<description>If true, display all settable properties for each goal.</description>
</parameter>
<parameter>
<name>goal</name>
<type>java.lang.String</type>
<required>false</required>
<editable>true</editable>
<description>The name of the goal for which to show help. If unspecified, all goals will be displayed.</description>
</parameter>
<parameter>
<name>indentSize</name>
<type>int</type>
<required>false</required>
<editable>true</editable>
<description>The number of spaces per indentation level, should be positive.</description>
</parameter>
<parameter>
<name>lineLength</name>
<type>int</type>
<required>false</required>
<editable>true</editable>
<description>The maximum length of a display line, should be positive.</description>
</parameter>
</parameters>
<configuration>
<detail implementation="boolean" default-value="false">${detail}</detail>
<goal implementation="java.lang.String">${goal}</goal>
<indentSize implementation="int" default-value="2">${indentSize}</indentSize>
<lineLength implementation="int" default-value="80">${lineLength}</lineLength>
</configuration>
</mojo>
</mojos>
</plugin>
\ No newline at end of file
#Generated by Maven Integration for Eclipse
#Wed Jul 27 22:41:24 MST 2016
version=1.0
groupId=com.alexscottrhodes
m2e.projectName=copyright-plugin
m2e.projectLocation=E\:\\Portfolio Workspace\\copyright-plugin
artifactId=copyright-maven-plugin
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.alexscottrhodes</groupId>
<artifactId>copyright-maven-plugin</artifactId>
<version>1.0</version>
<packaging>maven-plugin</packaging>
<name>copyright-plugin</name>
<url>http://www.alexscottrhodes.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugin-tools</groupId>
<artifactId>maven-plugin-annotations</artifactId>
<version>3.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-utils</artifactId>
<version>3.0.8</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-plugin-plugin</artifactId>
<version>3.2</version>
<configuration>
<goalPrefix>copyright</goalPrefix>
<skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
</configuration>
<executions>
<execution>
<id>mojo-descriptor</id>
<goals>
<goal>descriptor</goal>
</goals>
</execution>
<execution>
<id>help-goal</id>
<goals>
<goal>helpmojo</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>run-its</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-invoker-plugin</artifactId>
<version>1.7</version>
<configuration>
<debug>true</debug>
<cloneProjectsTo>${project.build.directory}/it</cloneProjectsTo>
<pomIncludes>
<pomInclude>*/pom.xml</pomInclude>
</pomIncludes>
<postBuildHookScript>verify</postBuildHookScript>
<localRepositoryPath>${project.build.directory}/local-repo</localRepositoryPath>
<settingsFile>src/it/settings.xml</settingsFile>
<goals>
<goal>clean</goal>
<goal>test-compile</goal>
</goals>
</configuration>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>install</goal>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated by maven-plugin-tools 3.2 on 2016-07-27 -->
<plugin>
<name>copyright-plugin</name>
<description></description>
<groupId>com.alexscottrhodes</groupId>
<artifactId>copyright-maven-plugin</artifactId>
<version>1.0</version>
<goalPrefix>copyright</goalPrefix>
<isolatedRealm>false</isolatedRealm>
<inheritedByDefault>true</inheritedByDefault>
<mojos>
<mojo>
<goal>cr</goal>
<description>Goal that adds a custom copyright to the top of each file, only applicable to
Java source, XML, XHTML, and HTML files.</description>
<requiresDirectInvocation>false</requiresDirectInvocation>
<requiresProject>true</requiresProject>
<requiresReports>false</requiresReports>
<aggregator>false</aggregator>
<requiresOnline>false</requiresOnline>
<inheritedByDefault>true</inheritedByDefault>
<implementation>com.alexscottrhodes.copyright_plugin.CopyrightGenerator</implementation>
<language>java</language>
<instantiationStrategy>per-lookup</instantiationStrategy>
<executionStrategy>once-per-session</executionStrategy>
<threadSafe>false</threadSafe>
<parameters>
<parameter>
<name>remove</name>
<type>boolean</type>
<required>false</required>
<editable>true</editable>
<description></description>
</parameter>
<parameter>
<name>sourceDir</name>
<type>java.io.File</type>
<required>true</required>
<editable>true</editable>
<description></description>
</parameter>
</parameters>
<configuration>
<remove implementation="boolean" default-value="${remove}"/>
<sourceDir implementation="java.io.File" default-value="${basedir}"/>
</configuration>
</mojo>
<mojo>
<goal>help</goal>
<description>Display help information on copyright-maven-plugin.&lt;br/&gt;
Call &lt;code&gt;mvn copyright:help -Ddetail=true -Dgoal=&amp;lt;goal-name&amp;gt;&lt;/code&gt; to display parameter details.</description>
<requiresDirectInvocation>false</requiresDirectInvocation>
<requiresProject>false</requiresProject>
<requiresReports>false</requiresReports>
<aggregator>false</aggregator>
<requiresOnline>false</requiresOnline>
<inheritedByDefault>true</inheritedByDefault>
<implementation>com.alexscottrhodes.copyright_plugin.HelpMojo</implementation>
<language>java</language>
<instantiationStrategy>per-lookup</instantiationStrategy>
<executionStrategy>once-per-session</executionStrategy>
<threadSafe>true</threadSafe>
<parameters>
<parameter>
<name>detail</name>
<type>boolean</type>
<required>false</required>
<editable>true</editable>
<description>If &lt;code&gt;true&lt;/code&gt;, display all settable properties for each goal.</description>
</parameter>
<parameter>
<name>goal</name>
<type>java.lang.String</type>
<required>false</required>
<editable>true</editable>
<description>The name of the goal for which to show help. If unspecified, all goals will be displayed.</description>
</parameter>
<parameter>
<name>indentSize</name>
<type>int</type>
<required>false</required>
<editable>true</editable>
<description>The number of spaces per indentation level, should be positive.</description>
</parameter>
<parameter>
<name>lineLength</name>
<type>int</type>
<required>false</required>
<editable>true</editable>
<description>The maximum length of a display line, should be positive.</description>
</parameter>
</parameters>
<configuration>
<detail implementation="boolean" default-value="false">${detail}</detail>
<goal implementation="java.lang.String">${goal}</goal>
<indentSize implementation="int" default-value="2">${indentSize}</indentSize>
<lineLength implementation="int" default-value="80">${lineLength}</lineLength>
</configuration>
</mojo>
</mojos>
<dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<type>jar</type>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom</artifactId>
<type>jar</type>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<type>jar</type>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-utils</artifactId>
<type>jar</type>
<version>3.0.8</version>
</dependency>
</dependencies>
</plugin>
\ No newline at end of file
package com.alexscottrhodes.copyright_plugin;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Display help information on copyright-maven-plugin.<br/>
* Call <code>mvn copyright:help -Ddetail=true -Dgoal=&lt;goal-name&gt;</code> to display parameter details.
* @author
* @version
*/
@Mojo( name = "help", requiresProject = false, threadSafe = true )
public class HelpMojo
extends AbstractMojo
{
/**
* If <code>true</code>, display all settable properties for each goal.
*
*/
@Parameter( property = "detail", defaultValue = "false" )
private boolean detail;
/**
* The name of the goal for which to show help. If unspecified, all goals will be displayed.
*
*/
@Parameter( property = "goal" )
private java.lang.String goal;
/**
* The maximum length of a display line, should be positive.
*
*/
@Parameter( property = "lineLength", defaultValue = "80" )
private int lineLength;
/**
* The number of spaces per indentation level, should be positive.
*
*/
@Parameter( property = "indentSize", defaultValue = "2" )
private int indentSize;
// groupId/artifactId/plugin-help.xml
private static final String PLUGIN_HELP_PATH = "/META-INF/maven/com.alexscottrhodes/copyright-maven-plugin/plugin-help.xml";
private Document build()
throws MojoExecutionException
{
getLog().debug( "load plugin-help.xml: " + PLUGIN_HELP_PATH );
InputStream is = getClass().getResourceAsStream( PLUGIN_HELP_PATH );
try
{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
return dBuilder.parse( is );
}
catch ( IOException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
catch ( ParserConfigurationException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
catch ( SAXException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
}
/**
* {@inheritDoc}
*/
public void execute()
throws MojoExecutionException
{
if ( lineLength <= 0 )
{
getLog().warn( "The parameter 'lineLength' should be positive, using '80' as default." );
lineLength = 80;
}
if ( indentSize <= 0 )
{
getLog().warn( "The parameter 'indentSize' should be positive, using '2' as default." );
indentSize = 2;
}
Document doc = build();
StringBuilder sb = new StringBuilder();
Node plugin = getSingleChild( doc, "plugin" );
String name = getValue( plugin, "name" );
String version = getValue( plugin, "version" );
String id = getValue( plugin, "groupId" ) + ":" + getValue( plugin, "artifactId" ) + ":" + version;
if ( isNotEmpty( name ) && !name.contains( id ) )
{
append( sb, name + " " + version, 0 );
}
else
{
if ( isNotEmpty( name ) )
{
append( sb, name, 0 );
}
else
{
append( sb, id, 0 );
}
}
append( sb, getValue( plugin, "description" ), 1 );
append( sb, "", 0 );
//<goalPrefix>plugin</goalPrefix>
String goalPrefix = getValue( plugin, "goalPrefix" );
Node mojos1 = getSingleChild( plugin, "mojos" );
List<Node> mojos = findNamedChild( mojos1, "mojo" );
if ( goal == null || goal.length() <= 0 )
{
append( sb, "This plugin has " + mojos.size() + ( mojos.size() > 1 ? " goals:" : " goal:" ), 0 );
append( sb, "", 0 );
}
for ( Node mojo : mojos )
{
writeGoal( sb, goalPrefix, (Element) mojo );
}
if ( getLog().isInfoEnabled() )
{
getLog().info( sb.toString() );
}
}
private static boolean isNotEmpty( String string )
{
return string != null && string.length() > 0;
}
private String getValue( Node node, String elementName )
throws MojoExecutionException
{
return getSingleChild( node, elementName ).getTextContent();
}
private Node getSingleChild( Node node, String elementName )
throws MojoExecutionException
{
List<Node> namedChild = findNamedChild( node, elementName );
if ( namedChild.isEmpty() )
{
throw new MojoExecutionException( "Could not find " + elementName + " in plugin-help.xml" );
}
if ( namedChild.size() > 1 )
{
throw new MojoExecutionException( "Multiple " + elementName + " in plugin-help.xml" );
}
return namedChild.get( 0 );
}
private List<Node> findNamedChild( Node node, String elementName )
{
List<Node> result = new ArrayList<Node>();
NodeList childNodes = node.getChildNodes();
for ( int i = 0; i < childNodes.getLength(); i++ )
{
Node item = childNodes.item( i );
if ( elementName.equals( item.getNodeName() ) )
{
result.add( item );
}
}
return result;
}
private Node findSingleChild( Node node, String elementName )
throws MojoExecutionException
{
List<Node> elementsByTagName = findNamedChild( node, elementName );
if ( elementsByTagName.isEmpty() )
{
return null;
}
if ( elementsByTagName.size() > 1 )
{
throw new MojoExecutionException( "Multiple " + elementName + "in plugin-help.xml" );
}
return elementsByTagName.get( 0 );
}
private void writeGoal( StringBuilder sb, String goalPrefix, Element mojo )
throws MojoExecutionException
{
String mojoGoal = getValue( mojo, "goal" );
Node configurationElement = findSingleChild( mojo, "configuration" );
Node description = findSingleChild( mojo, "description" );
if ( goal == null || goal.length() <= 0 || mojoGoal.equals( goal ) )
{
append( sb, goalPrefix + ":" + mojoGoal, 0 );
Node deprecated = findSingleChild( mojo, "deprecated" );
if ( ( deprecated != null ) && isNotEmpty( deprecated.getNodeValue() ) )
{
append( sb, "Deprecated. " + deprecated, 1 );
if ( detail && description != null )
{
append( sb, "", 0 );
append( sb, description.getTextContent(), 1 );
}
}
else if (description != null )
{
append( sb, description.getTextContent(), 1 );
}
append( sb, "", 0 );
if ( detail )
{
Node parametersNode = getSingleChild( mojo, "parameters" );
List<Node> parameters = findNamedChild( parametersNode, "parameter" );
append( sb, "Available parameters:", 1 );
append( sb, "", 0 );
for ( Node parameter : parameters )
{
writeParameter( sb, parameter, configurationElement );
}
}
}
}
private void writeParameter( StringBuilder sb, Node parameter, Node configurationElement )
throws MojoExecutionException
{
String parameterName = getValue( parameter, "name" );
String parameterDescription = getValue( parameter, "description" );
Node fieldConfigurationElement = findSingleChild( configurationElement, parameterName );
String parameterDefaultValue = "";
if ( fieldConfigurationElement != null && fieldConfigurationElement.getNodeValue() != null )
{
parameterDefaultValue = " (Default: " + ((Element)fieldConfigurationElement).getAttribute( "default-value" ) + ")";
}
append( sb, parameterName + parameterDefaultValue, 2 );
Node deprecated = findSingleChild( parameter, "deprecated" );
if ( ( deprecated != null ) && isNotEmpty( deprecated.getNodeValue() ) )
{
append( sb, "Deprecated. " + deprecated.getNodeValue(), 3 );
append( sb, "", 0 );
}
append( sb, parameterDescription, 3 );
if ( "true".equals( getValue( parameter, "required" ) ) )
{
append( sb, "Required: Yes", 3 );
}
Node expression = findSingleChild( parameter, "expression" );
if ( ( expression != null ) && isNotEmpty( expression.getNodeValue() ) )
{
String property = getPropertyFromExpression( expression.getNodeValue() );
append( sb, "User property: " + property, 3 );
}
append( sb, "", 0 );
}
/**
* <p>Repeat a String <code>n</code> times to form a new string.</p>
*
* @param str String to repeat
* @param repeat number of times to repeat str
* @return String with repeated String
* @throws NegativeArraySizeException if <code>repeat < 0</code>
* @throws NullPointerException if str is <code>null</code>
*/
private static String repeat( String str, int repeat )
{
StringBuilder buffer = new StringBuilder( repeat * str.length() );
for ( int i = 0; i < repeat; i++ )
{
buffer.append( str );
}
return buffer.toString();
}
/**
* Append a description to the buffer by respecting the indentSize and lineLength parameters.
* <b>Note</b>: The last character is always a new line.
*
* @param sb The buffer to append the description, not <code>null</code>.
* @param description The description, not <code>null</code>.
* @param indent The base indentation level of each line, must not be negative.
*/
private void append( StringBuilder sb, String description, int indent )
{
for ( String line : toLines( description, indent, indentSize, lineLength ) )
{
sb.append( line ).append( '\n' );
}
}
/**
* Splits the specified text into lines of convenient display length.
*
* @param text The text to split into lines, must not be <code>null</code>.
* @param indent The base indentation level of each line, must not be negative.
* @param indentSize The size of each indentation, must not be negative.
* @param lineLength The length of the line, must not be negative.
* @return The sequence of display lines, never <code>null</code>.
* @throws NegativeArraySizeException if <code>indent < 0</code>
*/
private static List<String> toLines( String text, int indent, int indentSize, int lineLength )
{
List<String> lines = new ArrayList<String>();
String ind = repeat( "\t", indent );
String[] plainLines = text.split( "(\r\n)|(\r)|(\n)" );
for ( String plainLine : plainLines )
{
toLines( lines, ind + plainLine, indentSize, lineLength );
}
return lines;
}
/**
* Adds the specified line to the output sequence, performing line wrapping if necessary.
*
* @param lines The sequence of display lines, must not be <code>null</code>.
* @param line The line to add, must not be <code>null</code>.
* @param indentSize The size of each indentation, must not be negative.
* @param lineLength The length of the line, must not be negative.
*/
private static void toLines( List<String> lines, String line, int indentSize, int lineLength )
{
int lineIndent = getIndentLevel( line );
StringBuilder buf = new StringBuilder( 256 );
String[] tokens = line.split( " +" );
for ( String token : tokens )
{
if ( buf.length() > 0 )
{
if ( buf.length() + token.length() >= lineLength )
{
lines.add( buf.toString() );
buf.setLength( 0 );
buf.append( repeat( " ", lineIndent * indentSize ) );
}
else
{
buf.append( ' ' );
}
}
for ( int j = 0; j < token.length(); j++ )
{
char c = token.charAt( j );
if ( c == '\t' )
{
buf.append( repeat( " ", indentSize - buf.length() % indentSize ) );
}
else if ( c == '\u00A0' )
{
buf.append( ' ' );
}
else
{
buf.append( c );
}
}
}
lines.add( buf.toString() );
}
/**
* Gets the indentation level of the specified line.
*
* @param line The line whose indentation level should be retrieved, must not be <code>null</code>.
* @return The indentation level of the line.
*/
private static int getIndentLevel( String line )
{
int level = 0;
for ( int i = 0; i < line.length() && line.charAt( i ) == '\t'; i++ )
{
level++;
}
for ( int i = level + 1; i <= level + 4 && i < line.length(); i++ )
{
if ( line.charAt( i ) == '\t' )
{
level++;
break;
}
}
return level;
}
private String getPropertyFromExpression( String expression )
{
if ( expression != null && expression.startsWith( "${" ) && expression.endsWith( "}" )
&& !expression.substring( 2 ).contains( "${" ) )
{
// expression="${xxx}" -> property="xxx"
return expression.substring( 2, expression.length() - 1 );
}
// no property can be extracted
return null;
}
}
#Generated by Maven
#Wed Jul 27 17:39:52 MST 2016
version=1.0
groupId=com.alexscottrhodes
artifactId=copyright-maven-plugin
#maven plugin help mojo generation informations
#Wed Jul 27 22:36:27 MST 2016
helpPackageName=com.alexscottrhodes.copyright_plugin
destinationDirectory=e\:\\Portfolio Workspace\\copyright-plugin\\target\\generated-sources\\plugin
e:\Portfolio Workspace\copyright-plugin\src\main\java\com\alexscottrhodes\copyright_plugin\CopyrightGenerator.java
e:\Portfolio Workspace\copyright-plugin\target\generated-sources\plugin\HelpMojo.java
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment