You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by gn...@apache.org on 2021/03/09 14:43:03 UTC

[camel] branch master updated: Add a cache to the ApiComponentGeneratorMojo

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

gnodet pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/master by this push:
     new 6a3882b  Add a cache to the ApiComponentGeneratorMojo
6a3882b is described below

commit 6a3882b1dcfcb062902599a668d449a24d042887
Author: Guillaume Nodet <gn...@gmail.com>
AuthorDate: Tue Mar 9 15:41:59 2021 +0100

    Add a cache to the ApiComponentGeneratorMojo
---
 .../maven/camel-api-component-maven-plugin/pom.xml |   7 ++
 .../camel/maven/ApiComponentGeneratorMojo.java     | 133 +++++++++++++++++++++
 .../java/org/apache/camel/maven/HashHelper.java    | 108 +++++++++++++++++
 3 files changed, 248 insertions(+)

diff --git a/tooling/maven/camel-api-component-maven-plugin/pom.xml b/tooling/maven/camel-api-component-maven-plugin/pom.xml
index 8a51194..fa928d3 100644
--- a/tooling/maven/camel-api-component-maven-plugin/pom.xml
+++ b/tooling/maven/camel-api-component-maven-plugin/pom.xml
@@ -136,6 +136,13 @@
             <version>${roaster-version}</version>
         </dependency>
 
+        <!-- for hashing -->
+        <dependency>
+            <groupId>com.google.guava</groupId>
+            <artifactId>guava</artifactId>
+            <version>30.1-jre</version>
+        </dependency>
+
         <!-- logging -->
         <dependency>
             <groupId>org.apache.logging.log4j</groupId>
diff --git a/tooling/maven/camel-api-component-maven-plugin/src/main/java/org/apache/camel/maven/ApiComponentGeneratorMojo.java b/tooling/maven/camel-api-component-maven-plugin/src/main/java/org/apache/camel/maven/ApiComponentGeneratorMojo.java
index cd1cf41..38d0ffc 100644
--- a/tooling/maven/camel-api-component-maven-plugin/src/main/java/org/apache/camel/maven/ApiComponentGeneratorMojo.java
+++ b/tooling/maven/camel-api-component-maven-plugin/src/main/java/org/apache/camel/maven/ApiComponentGeneratorMojo.java
@@ -17,13 +17,24 @@
 package org.apache.camel.maven;
 
 import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.util.Arrays;
 import java.util.Collections;
+import java.util.Comparator;
 import java.util.List;
 import java.util.Locale;
+import java.util.Objects;
 import java.util.regex.Matcher;
+import java.util.stream.Stream;
 
 import org.apache.camel.util.StringHelper;
 import org.apache.maven.plugin.MojoExecutionException;
+import org.apache.maven.plugin.logging.Log;
 import org.apache.maven.plugins.annotations.LifecyclePhase;
 import org.apache.maven.plugins.annotations.Mojo;
 import org.apache.maven.plugins.annotations.Parameter;
@@ -37,9 +48,29 @@ import org.apache.velocity.VelocityContext;
       defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true)
 public class ApiComponentGeneratorMojo extends AbstractApiMethodBaseMojo {
 
+    /** The Constant CACHE_PROPERTIES_FILENAME. */
+    private static final String CACHE_PROPERTIES_FILENAME = "camel-api-component-maven-plugin-cache.properties";
+
     protected static final String DEFAULT_EXCLUDE_PACKAGES = "javax?\\.lang.*";
 
     /**
+     * Projects cache directory.
+     *
+     * <p>
+     * This file is a hash cache of the files in the project source. It can be preserved in source code such that it
+     * ensures builds are always fast by not unnecessarily writing files constantly. It can also be added to gitignore
+     * in case startup is not necessary. It further can be redirected to another location.
+     *
+     * <p>
+     * When stored in the repository, the cache if run on cross platforms will display the files multiple times due to
+     * line ending differences on the platform.
+     *
+     * @since 2.9.0
+     */
+    @Parameter(defaultValue = "${project.build.directory}")
+    private File cachedir;
+
+    /**
      * List of API names, proxies and code generation settings.
      */
     @Parameter(required = true)
@@ -74,6 +105,39 @@ public class ApiComponentGeneratorMojo extends AbstractApiMethodBaseMojo {
             apis[0].setApiName("");
         }
 
+        String newHash = new HashHelper()
+                .hash("ApiComponentGeneratorMojo")
+                .hash("apis", apis)
+                .hash("fromJavasource", fromJavasource)
+                .hash("nullableOptions", nullableOptions)
+                .hash("aliases", aliases)
+                .hash("substitutions", substitutions)
+                .hash("excludeConfigNames", excludeConfigNames)
+                .hash("excludeConfigTypes", excludeConfigTypes)
+                .hash("extraOptions", extraOptions)
+                .toString();
+        Instant newDate = Stream.of(generatedSrcDir, generatedTestDir)
+                .map(File::toPath)
+                .flatMap(this::walk)
+                .filter(Files::isRegularFile)
+                .map(this::lastModified)
+                .max(Comparator.naturalOrder())
+                .orElse(Instant.now());
+
+        List<String> cache = readCacheFile();
+        String prevHash = cache.stream().filter(s -> s.startsWith("hash=")).findFirst()
+                .map(s -> s.substring("hash=".length())).orElse(null);
+        Instant prevDate = cache.stream().filter(s -> s.startsWith("date=")).findFirst()
+                .map(s -> s.substring("date=".length()))
+                .map(Instant::parse)
+                .orElse(Instant.ofEpochSecond(0));
+
+        if (Objects.equals(prevHash, newHash) && !newDate.isAfter(prevDate)) {
+            getLog().info("Skipping api generation, everything is up to date.");
+            setCompileSourceRoots();
+            return;
+        }
+
         // generate API methods for each API proxy
         for (ApiProxy api : apis) {
             // validate API configuration
@@ -126,6 +190,34 @@ public class ApiComponentGeneratorMojo extends AbstractApiMethodBaseMojo {
 
         // generate ApiName
         mergeTemplate(getApiContext(), getApiNameFile(), "/api-name-enum.vm");
+
+        newDate = Stream.of(generatedSrcDir, generatedTestDir)
+                .map(File::toPath)
+                .flatMap(this::walk)
+                .filter(Files::isRegularFile)
+                .map(this::lastModified)
+                .max(Comparator.naturalOrder())
+                .orElse(Instant.now());
+        writeCacheFile(Arrays.asList(
+                "# ApiComponentGenerator cache file",
+                "hash=" + newHash,
+                "date=" + newDate.toString()));
+    }
+
+    private Instant lastModified(Path path) {
+        try {
+            return Files.getLastModifiedTime(path).toInstant();
+        } catch (IOException e) {
+            return Instant.now();
+        }
+    }
+
+    private Stream<Path> walk(Path p) {
+        try {
+            return Files.walk(p, Integer.MAX_VALUE);
+        } catch (IOException e) {
+            return Stream.empty();
+        }
     }
 
     private void configureMethodGenerator(AbstractApiMethodGeneratorMojo mojo, ApiProxy apiProxy) {
@@ -266,4 +358,45 @@ public class ApiComponentGeneratorMojo extends AbstractApiMethodBaseMojo {
         }
         return builder.toString();
     }
+
+    /**
+     * Store file hash cache.
+     */
+    private void writeCacheFile(List<String> cache) {
+        File cacheFile = new File(this.cachedir, CACHE_PROPERTIES_FILENAME);
+        try (OutputStream out = new FileOutputStream(cacheFile)) {
+            Files.write(cacheFile.toPath(), cache);
+        } catch (IOException e) {
+            getLog().warn("Cannot store file hash cache properties file", e);
+        }
+    }
+
+    /**
+     * Read file hash cache file.
+     */
+    private List<String> readCacheFile() {
+        Log log = getLog();
+        if (!this.cachedir.exists()) {
+            if (!this.cachedir.mkdirs()) {
+                log.warn("Unable to create cache directory '" + this.cachedir + "'.");
+            }
+        } else if (!this.cachedir.isDirectory()) {
+            log.warn("Something strange here as the '" + this.cachedir
+                     + "' supposedly cache directory is not a directory.");
+            return Collections.emptyList();
+        }
+
+        File cacheFile = new File(this.cachedir, CACHE_PROPERTIES_FILENAME);
+        if (!cacheFile.exists()) {
+            return Collections.emptyList();
+        }
+
+        try {
+            return Files.readAllLines(cacheFile.toPath());
+        } catch (IOException e) {
+            log.warn("Cannot load cache file", e);
+            return Collections.emptyList();
+        }
+    }
+
 }
diff --git a/tooling/maven/camel-api-component-maven-plugin/src/main/java/org/apache/camel/maven/HashHelper.java b/tooling/maven/camel-api-component-maven-plugin/src/main/java/org/apache/camel/maven/HashHelper.java
new file mode 100644
index 0000000..2dcdda7
--- /dev/null
+++ b/tooling/maven/camel-api-component-maven-plugin/src/main/java/org/apache/camel/maven/HashHelper.java
@@ -0,0 +1,108 @@
+/*
+ * 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.camel.maven;
+
+import java.util.Arrays;
+
+import com.google.common.hash.Hasher;
+import com.google.common.hash.Hashing;
+
+public class HashHelper {
+
+    private final Hasher hasher = Hashing.murmur3_128().newHasher();
+
+    public HashHelper hash(String field, Object f) {
+        hasher.putUnencodedChars(field);
+        return hash(f);
+    }
+
+    public HashHelper hash(Object f) {
+        if (f != null) {
+            if (f.getClass().isArray()) {
+                f = Arrays.asList((Object[]) f);
+            }
+            if (f instanceof String) {
+                hasher.putUnencodedChars((String) f);
+            } else if (f instanceof Boolean) {
+                hasher.putBoolean((Boolean) f);
+            } else if (f instanceof Iterable) {
+                for (Object a : (Iterable<? extends Object>) f) {
+                    hash(a);
+                }
+            } else if (f instanceof ApiMethodAlias) {
+                ApiMethodAlias apiMethodAlias = (ApiMethodAlias) f;
+                hash("ApiMethodAlias");
+                hash("methodPattern", apiMethodAlias.getMethodPattern());
+                hash("methodAlias", apiMethodAlias.getMethodAlias());
+            } else if (f instanceof ApiProxy) {
+                ApiProxy apiProxy = (ApiProxy) f;
+                hash("ApiProxy");
+                hash("apiName", apiProxy.getApiName());
+                hash("apiDescription", apiProxy.getApiDescription());
+                hash("consumerOnly", apiProxy.isConsumerOnly());
+                hash("producerOnly", apiProxy.isProducerOnly());
+                hash("fromJavasource", apiProxy.getFromJavasource());
+                hash("substitutions", apiProxy.getSubstitutions());
+                hash("excludeConfigNames", apiProxy.getExcludeConfigNames());
+                hash("excludeConfigTypes", apiProxy.getExcludeConfigTypes());
+                hash("extraOptions", apiProxy.getExtraOptions());
+                hash("nullableOptions", apiProxy.getNullableOptions());
+                hash("classPrefix", apiProxy.getClassPrefix());
+                hash("aliases", apiProxy.getAliases());
+            } else if (f instanceof ExtraOption) {
+                ExtraOption extraOption = (ExtraOption) f;
+                hash("ExtraOption");
+                hash("type", extraOption.getType());
+                hash("name", extraOption.getName());
+                hash("description", extraOption.getDescription());
+            } else if (f instanceof FromJavasource) {
+                FromJavasource fromJavasource = (FromJavasource) f;
+                hash("FromJavasource");
+                hash("excludePackages", fromJavasource.getExcludePackages());
+                hash("excludeClasses", fromJavasource.getExcludeClasses());
+                hash("includeMethods", fromJavasource.getIncludeMethods());
+                hash("excludeMethods", fromJavasource.getExcludeMethods());
+                hash("includeStaticMethods", fromJavasource.getIncludeStaticMethods());
+            } else if (f instanceof SignatureModel) {
+                SignatureModel signatureModel = (SignatureModel) f;
+                hash("SignatureModel");
+                hash("apiName", signatureModel.getApiName());
+                hash("apiDescription", signatureModel.getApiDescription());
+                hash("methodDescription", signatureModel.getMethodDescription());
+                hash("signature", signatureModel.getSignature());
+                hash("parameterDescriptions", signatureModel.getMethodDescription());
+                hash("parameterTypes", signatureModel.getParameterTypes());
+            } else if (f instanceof Substitution) {
+                Substitution substitution = (Substitution) f;
+                hash("Substitution");
+                hash("method", substitution.getMethod());
+                hash("argName", substitution.getArgName());
+                hash("argType", substitution.getArgType());
+                hash("replacement", substitution.getReplacement());
+                hash("replaceWithType", substitution.isReplaceWithType());
+            } else {
+                throw new UnsupportedOperationException();
+            }
+        }
+        return this;
+    }
+
+    public String toString() {
+        return hasher.hash().toString();
+    }
+
+}