You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by si...@apache.org on 2019/02/05 16:05:08 UTC

[sling-slingfeature-maven-plugin] branch apisjar_sources updated: SLING-8264 - Make the APIs JARs able to generate and package -javadoc artifacts

This is an automated email from the ASF dual-hosted git repository.

simonetripodi pushed a commit to branch apisjar_sources
in repository https://gitbox.apache.org/repos/asf/sling-slingfeature-maven-plugin.git


The following commit(s) were added to refs/heads/apisjar_sources by this push:
     new 7f2ae46  SLING-8264 - Make the APIs JARs able to generate and package -javadoc artifacts
7f2ae46 is described below

commit 7f2ae463a76bf126cdb073084152d6b6acc93d6c
Author: Simo Tripodi <st...@adobe.com>
AuthorDate: Tue Feb 5 17:04:57 2019 +0100

    SLING-8264 - Make the APIs JARs able to generate and package -javadoc
    artifacts
    
    initial checkin
---
 pom.xml                                            |   5 +
 .../sling/feature/maven/mojos/ApisJarMojo.java     | 119 +++++++++++---
 .../sling/feature/maven/mojos/JavadocExecutor.java | 178 +++++++++++++++++++++
 3 files changed, 284 insertions(+), 18 deletions(-)

diff --git a/pom.xml b/pom.xml
index 541bdca..f94ba40 100644
--- a/pom.xml
+++ b/pom.xml
@@ -284,6 +284,11 @@
             <artifactId>maven-model-builder</artifactId>
             <version>3.6.0</version>
         </dependency>
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-exec</artifactId>
+            <version>1.3</version>
+        </dependency>
         <!-- testing -->
         <dependency>
             <groupId>org.mockito</groupId>
diff --git a/src/main/java/org/apache/sling/feature/maven/mojos/ApisJarMojo.java b/src/main/java/org/apache/sling/feature/maven/mojos/ApisJarMojo.java
index f80229f..0d99902 100644
--- a/src/main/java/org/apache/sling/feature/maven/mojos/ApisJarMojo.java
+++ b/src/main/java/org/apache/sling/feature/maven/mojos/ApisJarMojo.java
@@ -20,7 +20,9 @@ import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.StringReader;
+import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
+import java.util.Calendar;
 import java.util.Collection;
 import java.util.Formatter;
 import java.util.Iterator;
@@ -33,6 +35,8 @@ import javax.json.Json;
 import javax.json.stream.JsonParser;
 import javax.json.stream.JsonParser.Event;
 
+import org.apache.commons.lang3.JavaVersion;
+import org.apache.commons.lang3.SystemUtils;
 import org.apache.felix.utils.manifest.Clause;
 import org.apache.felix.utils.manifest.Parser;
 import org.apache.maven.archiver.MavenArchiveConfiguration;
@@ -102,7 +106,7 @@ public class ApisJarMojo extends AbstractIncludingFeatureMojo {
 
     private static final String JAVADOC = "javadoc";
 
-    private static final String[] OUT_DIRS = { SOURCES, JAVADOC };
+    private static final String CLASS_EXTENSION = ".class";
 
     @Parameter
     private FeatureSelectionConfig selection;
@@ -116,6 +120,9 @@ public class ApisJarMojo extends AbstractIncludingFeatureMojo {
     @Parameter
     private Set<String> excludeRegions;
 
+    @Parameter
+    private String[] javadocLinks;
+
     @Component(hint = "default")
     private ModelBuilder modelBuilder;
 
@@ -186,16 +193,6 @@ public class ApisJarMojo extends AbstractIncludingFeatureMojo {
         // calculate all api-regions first, taking the inheritance in account
         List<ApiRegion> apiRegions = fromJson(feature, jsonRepresentation);
 
-        // setup all output directories
-        for (ApiRegion apiRegion : apiRegions) {
-            File regionDir = new File(featureDir, apiRegion.getName());
-            regionDir.mkdirs();
-
-            for (String dirName : OUT_DIRS) {
-                new File(regionDir, dirName).mkdir();
-            }
-        }
-
         // for each artifact included in the feature file:
         for (Artifact artifact : feature.getBundles()) {
             ArtifactId artifactId = artifact.getId();
@@ -222,9 +219,19 @@ public class ApisJarMojo extends AbstractIncludingFeatureMojo {
                 continue;
             }
 
-            recollect(feature.getId(), apiRegion, deflatedBinDir, featureDir, APIS);
-            recollect(feature.getId(), apiRegion, deflatedSourcesDir, featureDir, SOURCES);
-            // TODO create -javadoc artifacts
+            File regionDir = new File(featureDir, apiRegion.getName());
+
+            File apisDir = new File(regionDir, APIS);
+            recollect(featureDir, deflatedBinDir, apiRegion, apisDir);
+            inflate(feature.getId(), apisDir, apiRegion, APIS);
+
+            File sourcesDir = new File(regionDir, SOURCES);
+            recollect(featureDir, deflatedSourcesDir, apiRegion, sourcesDir);
+            inflate(feature.getId(), sourcesDir, apiRegion, SOURCES);
+
+            File javadocsDir = new File(regionDir, JAVADOC);
+            generateJavadoc(apiRegion, sourcesDir, javadocsDir);
+            inflate(feature.getId(), javadocsDir, apiRegion, JAVADOC);
         }
 
         getLog().debug(MessageUtils.buffer().a("APIs JARs for Feature ").debug(feature.getId().toMvnId())
@@ -467,13 +474,15 @@ public class ApisJarMojo extends AbstractIncludingFeatureMojo {
         }
     }
 
-    private void recollect(ArtifactId featureId, ApiRegion apiRegion, File deflatedDir, File featureDir, String classifier) throws MojoExecutionException {
+    private void recollect(File featureDir, File deflatedDir, ApiRegion apiRegion, File destination) throws MojoExecutionException {
+        destination.mkdirs();
+
         DirectoryScanner directoryScanner = new DirectoryScanner();
         directoryScanner.setBasedir(deflatedDir);
 
         // for each region, include both APIs and resources
         String[] includes;
-        if (APIS.equals(classifier)) {
+        if (APIS.equals(destination.getName())) {
             includes = concatenate(apiRegion.getFilteringApis(), includeResources);
         } else {
             includes = apiRegion.getFilteringApis();
@@ -481,10 +490,34 @@ public class ApisJarMojo extends AbstractIncludingFeatureMojo {
         directoryScanner.setIncludes(includes);
         directoryScanner.scan();
 
+        for (String includedFile : directoryScanner.getIncludedFiles()) {
+            File target = new File(destination, includedFile.substring(includedFile.indexOf(File.separator) + 1));
+            target.getParentFile().mkdirs();
+
+            try {
+                if (includedFile.endsWith(CLASS_EXTENSION)) {
+                    FileUtils.copyFile(new File(deflatedDir, includedFile), target);
+                } else {
+                    FileUtils.copyFile(new File(deflatedDir, includedFile), target, StandardCharsets.UTF_8.name());
+                }
+            } catch (IOException e) {
+                throw new MojoExecutionException("An error occurred while copying file "
+                                                 + includedFile
+                                                 + " to "
+                                                 + destination, e);
+            }
+        }
+    }
+
+    private void inflate(ArtifactId featureId, File collectedDir, ApiRegion apiRegion, String classifier) throws MojoExecutionException {
+        DirectoryScanner directoryScanner = new DirectoryScanner();
+        directoryScanner.setBasedir(collectedDir);
+        directoryScanner.setIncludes("**/*.*");
+        directoryScanner.scan();
+
         JarArchiver jarArchiver = new JarArchiver();
         for (String includedFile : directoryScanner.getIncludedFiles()) {
-            // first level is always the filename...
-            jarArchiver.addFile(new File(deflatedDir, includedFile), includedFile.substring(includedFile.indexOf(File.separator) + 1));
+            jarArchiver.addFile(new File(collectedDir, includedFile), includedFile);
         }
 
         String bundleName;
@@ -534,6 +567,52 @@ public class ApisJarMojo extends AbstractIncludingFeatureMojo {
         }
     }
 
+    private void generateJavadoc(ApiRegion apiRegion, File sourcesDir, File javadocDir) throws MojoExecutionException {
+        javadocDir.mkdirs();
+
+        JavadocExecutor javadocExecutor = new JavadocExecutor()
+                                          .addArgument("-public")
+                                          .addArgument("-d")
+                                          .addArgument(javadocDir.getAbsolutePath())
+                                          .addArgument("-sourcepath")
+                                          .addArgument(sourcesDir.getAbsolutePath());
+
+        if (isNotEmpty(project.getName())) {
+            javadocExecutor.addArgument("-doctitle")
+                           .addQuotedArgument(project.getName());
+        }
+
+        if (isNotEmpty(project.getDescription())) {
+            javadocExecutor.addArgument("-windowtitle")
+                           .addQuotedArgument(project.getDescription());
+        }
+
+        if (isNotEmpty(project.getInceptionYear())
+                && project.getOrganization() != null
+                && isNotEmpty(project.getOrganization().getName())) {
+            javadocExecutor.addArgument("-bottom")
+                           .addQuotedArgument(String.format("Copyright &copy; %s - %s %s. All Rights Reserved",
+                                              project.getInceptionYear(),
+                                              Calendar.getInstance().get(Calendar.YEAR),
+                                              project.getOrganization().getName()));
+        }
+
+        if (javadocLinks != null && javadocLinks.length > 0) {
+            javadocExecutor.addArguments("-link", javadocLinks);
+        }
+
+        //javadocExecutor.addArgument("-classpath")
+        //               .addArgument(javadocClasspath, File.pathSeparator);
+
+        // turn off doclint when running Java8
+        // http://blog.joda.org/2014/02/turning-off-doclint-in-jdk-8-javadoc.html
+        if (SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8)) {
+            javadocExecutor.addArgument("-Xdoclint:none").addArgument("-quiet");
+        }
+
+        javadocExecutor.addArguments(apiRegion.apis).execute(javadocDir, getLog());
+    }
+
     private static ArtifactId newArtifacId(ArtifactId original, String classifier, String type) {
         return new ArtifactId(original.getGroupId(),
                               original.getArtifactId(),
@@ -696,4 +775,8 @@ public class ApisJarMojo extends AbstractIncludingFeatureMojo {
         return what;
     }
 
+    private static boolean isNotEmpty(String s) {
+        return s != null && !s.isEmpty();
+    }
+
 }
diff --git a/src/main/java/org/apache/sling/feature/maven/mojos/JavadocExecutor.java b/src/main/java/org/apache/sling/feature/maven/mojos/JavadocExecutor.java
new file mode 100644
index 0000000..2d2c7b6
--- /dev/null
+++ b/src/main/java/org/apache/sling/feature/maven/mojos/JavadocExecutor.java
@@ -0,0 +1,178 @@
+/*
+ * 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.
+ */
+package org.apache.sling.feature.maven.mojos;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Arrays;
+import java.util.Collection;
+
+import org.apache.commons.exec.CommandLine;
+import org.apache.commons.exec.DefaultExecutor;
+import org.apache.commons.lang3.SystemUtils;
+import org.apache.maven.plugin.MojoExecutionException;
+import org.apache.maven.plugin.logging.Log;
+import org.codehaus.plexus.util.StringUtils;
+
+final class JavadocExecutor {
+
+    private static final char QUOTE_CHAR = '"';
+
+    private final CommandLine javadocCommand;
+
+    public JavadocExecutor() throws MojoExecutionException {
+        javadocCommand = new CommandLine(getJavadocExecutable());
+        addArgument("-J-Xmx2048m");
+    }
+
+    public <T> JavadocExecutor addArgument(T value) {
+        javadocCommand.addArgument(String.valueOf(value));
+        return this;
+    }
+
+    public <T> JavadocExecutor addQuotedArgument(T value) {
+        return addArgument(StringUtils.quoteAndEscape(String.valueOf(value), QUOTE_CHAR));
+    }
+
+    public <T> JavadocExecutor addArgument(Collection<T> value, String valueSeparator) {
+        return addArgument(StringUtils.join(value.iterator(), valueSeparator));
+    }
+
+    public <T> JavadocExecutor addArguments(Collection<T> value) {
+        for (T current : value) {
+            addArgument(current);
+        }
+        return this;
+    }
+
+    public <T> JavadocExecutor addArguments(String key, T[] values) {
+        return addArguments(key, Arrays.asList(values));
+    }
+
+    public <T> JavadocExecutor addArguments(String key, Collection<T> value) {
+        for (T current : value) {
+            addArgument(key);
+            addArgument(current);
+        }
+        return this;
+    }
+
+    public void execute(File workingDir, Log logger) throws MojoExecutionException {
+        logger.info("Executing javadoc tool: " + javadocCommand);
+
+        DefaultExecutor executor = new DefaultExecutor();
+        executor.setWorkingDirectory(workingDir);
+        executor.setExitValues(new int[] { 1, 0, -1 });
+        try {
+            executor.getStreamHandler().setProcessInputStream(new LoggerOutputStream(logger));
+            executor.execute(javadocCommand);
+        } catch (IOException ioe) {
+            throw new MojoExecutionException("Javadoc tool cannot be invoked on that machine", ioe);
+        }
+    }
+
+    /**
+     * Try to find javadocExe from System.getProperty( "java.home" ) By default,
+     * System.getProperty( "java.home" ) = JRE_HOME and JRE_HOME should be in the
+     * JDK_HOME.
+     *
+     * @return
+     */
+    private static File getJavadocExecutable() throws MojoExecutionException {
+        String javadocCommand = "javadoc" + (SystemUtils.IS_OS_WINDOWS ? ".exe" : "");
+
+        File javadocExe;
+
+        // For IBM's JDK 1.2
+        if (SystemUtils.IS_OS_AIX) {
+            javadocExe = getFile(SystemUtils.getJavaHome(), "..", "sh", javadocCommand);
+        }
+        // For Apple's JDK 1.6.x (and older?) on Mac OSX
+        else if (SystemUtils.IS_OS_MAC_OSX && org.apache.commons.lang.SystemUtils.JAVA_VERSION_FLOAT < 1.7f) {
+            javadocExe = getFile(SystemUtils.getJavaHome(), "bin", javadocCommand);
+        } else {
+            javadocExe = getFile(SystemUtils.getJavaHome(), "..", "bin", javadocCommand);
+        }
+
+        // ----------------------------------------------------------------------
+        // Try to find javadocExe from JAVA_HOME environment variable
+        // ----------------------------------------------------------------------
+        if (!javadocExe.exists() || !javadocExe.isFile()) {
+            String javaHome = System.getenv().get("JAVA_HOME");
+            if (StringUtils.isEmpty(javaHome)) {
+                throw new MojoExecutionException("The environment variable JAVA_HOME is not correctly set.");
+            }
+
+            File javaHomeDir = new File(javaHome);
+            if ((!javaHomeDir.exists()) || javaHomeDir.isFile()) {
+                throw new MojoExecutionException("The environment variable JAVA_HOME=" + javaHome
+                        + " doesn't exist or is not a valid directory.");
+            }
+
+            javadocExe = getFile(javaHomeDir, "bin", javadocCommand);
+        }
+
+        if (!javadocExe.exists() || !javadocExe.isFile()) {
+            throw new MojoExecutionException("The javadoc executable '" + javadocExe
+                    + "' doesn't exist or is not a file. Verify the JAVA_HOME environment variable.");
+        }
+
+        return javadocExe;
+    }
+
+    private static File getFile(File parent, String... path) {
+        File tmp = parent;
+        for (String current : path) {
+            tmp = new File(tmp, current);
+        }
+        return tmp;
+    }
+
+    private static final class LoggerOutputStream extends OutputStream {
+
+        private final StringBuilder output = new StringBuilder();
+
+        private final Log log;
+
+        public LoggerOutputStream(Log log) {
+            this.log = log;
+        }
+
+        @Override
+        public void write(int data) throws IOException {
+            output.append((char) data);
+            if ('\n' == data) {
+                flush();
+            }
+        }
+
+        @Override
+        public void flush() throws IOException {
+            log.info(output);
+            output.setLength(0);
+        }
+
+        @Override
+        public void close() throws IOException {
+            flush();
+            super.close();
+        }
+
+    }
+
+}