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

rec pushed a commit to branch 
feature/229-Add-skipDuringIncrementalBuild-option-to-enhance-goal
in repository https://gitbox.apache.org/repos/asf/uima-uimafit.git

commit 67d663f1d52a75de4b6131cf893b1abe489a73db
Author: Richard Eckart de Castilho <[email protected]>
AuthorDate: Wed Jul 5 13:48:47 2023 +0200

    #229 - Add skipDuringIncrementalBuild option to enhance goal
    #228 - Add skip parameter
    
    - Added skip and skipDuringIncrementalBuild options to both the enhance and 
generate goals
---
 .../org/apache/uima/fit/maven/EnhanceMojo.java     | 108 +++++++++++++--------
 .../uima/fit/maven/GenerateDescriptorsMojo.java    |  91 ++++++++++-------
 2 files changed, 128 insertions(+), 71 deletions(-)

diff --git 
a/uimafit-maven-plugin/src/main/java/org/apache/uima/fit/maven/EnhanceMojo.java 
b/uimafit-maven-plugin/src/main/java/org/apache/uima/fit/maven/EnhanceMojo.java
index 09b0dc9..1279170 100644
--- 
a/uimafit-maven-plugin/src/main/java/org/apache/uima/fit/maven/EnhanceMojo.java
+++ 
b/uimafit-maven-plugin/src/main/java/org/apache/uima/fit/maven/EnhanceMojo.java
@@ -173,6 +173,18 @@ public class EnhanceMojo extends AbstractMojo {
   @Parameter(defaultValue = "compile", required = true)
   private String includeScope;
 
+  /**
+   * Skip plugin execution.
+   */
+  @Parameter(property = "uima-enhance.skip", defaultValue = "false", required 
= true)
+  private boolean skip;
+
+  /**
+   * Skip plugin execution only during incremental builds (e.g. triggered from 
m2e).
+   */
+  @Parameter(defaultValue = "false", required = true)
+  private boolean skipDuringIncrementalBuilds;
+
   /**
    * Start of a line containing a class name in the missing meta data report 
file
    */
@@ -185,9 +197,13 @@ public class EnhanceMojo extends AbstractMojo {
 
   @Override
   public void execute() throws MojoExecutionException, MojoFailureException {
+    if (isSkipped()) {
+      return;
+    }
+
     // Get the compiled classes from this project
     String[] files = 
FileUtils.getFilesFromExtension(project.getBuild().getOutputDirectory(),
-        new String[] { "class" });
+            new String[] { "class" });
     componentLoader = Util.getClassloader(project, getLog(), includeScope);
 
     // Set up class pool with all the project dependencies and the project 
classes themselves
@@ -199,7 +215,7 @@ public class EnhanceMojo extends AbstractMojo {
 
     // Determine where to write the missing meta data report file
     File reportFile = new File(project.getBuild().getDirectory(),
-        "uimafit-missing-meta-data-report.txt");
+            "uimafit-missing-meta-data-report.txt");
 
     // Read existing report
     if (generateMissingMetaDataReport) {
@@ -251,7 +267,7 @@ public class EnhanceMojo extends AbstractMojo {
         ctClazz = classPool.get(clazzName);
       } catch (NotFoundException e) {
         throw new MojoExecutionException(
-            "Class [" + clazzName + "] not found in class pool: " + 
getRootCauseMessage(e), e);
+                "Class [" + clazzName + "] not found in class pool: " + 
getRootCauseMessage(e), e);
       }
 
       // Get the source file
@@ -289,15 +305,17 @@ public class EnhanceMojo extends AbstractMojo {
         }
       } catch (IOException e) {
         throw new MojoExecutionException(
-            "Enhanced class [" + clazzName + "] cannot be written: " + 
getRootCauseMessage(e), e);
+                "Enhanced class [" + clazzName + "] cannot be written: " + 
getRootCauseMessage(e),
+                e);
       } catch (CannotCompileException e) {
         throw new MojoExecutionException(
-            "Enhanced class [" + clazzName + "] cannot be compiled: " + 
getRootCauseMessage(e), e);
+                "Enhanced class [" + clazzName + "] cannot be compiled: " + 
getRootCauseMessage(e),
+                e);
       }
     }
 
     getLog().info("Enhanced " + countEnhanced + " class" + (countEnhanced != 1 
? "es" : "") + " ("
-        + countAlreadyEnhanced + " already enhanced).");
+            + countAlreadyEnhanced + " already enhanced).");
 
     if (generateMissingMetaDataReport) {
       // Remove any classes from the report that are no longer part of the 
build
@@ -310,11 +328,25 @@ public class EnhanceMojo extends AbstractMojo {
 
       if (failOnMissingMetaData && !reportData.isEmpty()) {
         throw new MojoFailureException("Component meta data missing. A report 
of the missing "
-            + "meta data can be found in " + reportFile);
+                + "meta data can be found in " + reportFile);
       }
     }
   }
 
+  private boolean isSkipped() {
+    if (skipDuringIncrementalBuilds && buildContext.isIncremental()) {
+      getLog().info("Enhancement of UIMA component classes skipped in 
incremental build.");
+      return true;
+    }
+
+    if (skip) {
+      getLog().info("Enhancement of UIMA component classes skipped.");
+      return true;
+    }
+
+    return false;
+  }
+
   /**
    * Add the EnhancedClassFile annotation.
    */
@@ -323,7 +355,7 @@ public class EnhanceMojo extends AbstractMojo {
     ConstPool constPool = classFile.getConstPool();
 
     AnnotationsAttribute annoAttr = (AnnotationsAttribute) classFile
-        .getAttribute(AnnotationsAttribute.visibleTag);
+            .getAttribute(AnnotationsAttribute.visibleTag);
 
     // Create annotation attribute if it does not exist
     if (annoAttr == null) {
@@ -344,12 +376,12 @@ public class EnhanceMojo extends AbstractMojo {
    * Enhance resource meta data
    */
   private void enhanceResourceMetaData(JavaSource aAST, Class<?> aClazz, 
CtClass aCtClazz,
-      Multimap<String, String> aReportData) {
+          Multimap<String, String> aReportData) {
     ClassFile classFile = aCtClazz.getClassFile();
     ConstPool constPool = classFile.getConstPool();
 
     AnnotationsAttribute annoAttr = (AnnotationsAttribute) classFile
-        .getAttribute(AnnotationsAttribute.visibleTag);
+            .getAttribute(AnnotationsAttribute.visibleTag);
 
     // Create annotation attribute if it does not exist
     if (annoAttr == null) {
@@ -362,25 +394,25 @@ public class EnhanceMojo extends AbstractMojo {
       a = new Annotation(ResourceMetaData.class.getName(), constPool);
       // Add a name, otherwise there will be none in the generated descriptor.
       a.addMemberValue("name",
-          new 
StringMemberValue(ResourceMetaDataFactory.getDefaultName(aClazz), constPool));
+              new 
StringMemberValue(ResourceMetaDataFactory.getDefaultName(aClazz), constPool));
     }
 
     // Update description from JavaDoc
     String doc = Util.getComponentDocumentation(aAST, aClazz.getName());
     enhanceMemberValue(a, "description", doc, overrideComponentDescription,
-        ResourceMetaDataFactory.getDefaultDescription(aClazz), constPool, 
aReportData, aClazz);
+            ResourceMetaDataFactory.getDefaultDescription(aClazz), constPool, 
aReportData, aClazz);
 
     // Update version
     enhanceMemberValue(a, "version", componentVersion, 
overrideComponentVersion,
-        ResourceMetaDataFactory.getDefaultVersion(aClazz), constPool, 
aReportData, aClazz);
+            ResourceMetaDataFactory.getDefaultVersion(aClazz), constPool, 
aReportData, aClazz);
 
     // Update vendor
     enhanceMemberValue(a, "vendor", componentVendor, overrideComponentVendor,
-        ResourceMetaDataFactory.getDefaultVendor(aClazz), constPool, 
aReportData, aClazz);
+            ResourceMetaDataFactory.getDefaultVendor(aClazz), constPool, 
aReportData, aClazz);
 
     // Update copyright
     enhanceMemberValue(a, "copyright", componentCopyright, 
overrideComponentCopyright,
-        ResourceMetaDataFactory.getDefaultCopyright(aClazz), constPool, 
aReportData, aClazz);
+            ResourceMetaDataFactory.getDefaultCopyright(aClazz), constPool, 
aReportData, aClazz);
 
     // Replace annotation
     annoAttr.addAnnotation(a);
@@ -402,12 +434,11 @@ public class EnhanceMojo extends AbstractMojo {
    * @param aOverride
    *          set value even if it is already set
    * @param aDefault
-   *          default value set by uimaFIT - if the member has this value, it 
is considered
-   *          unset
+   *          default value set by uimaFIT - if the member has this value, it 
is considered unset
    */
   private void enhanceMemberValue(Annotation aAnnotation, String aName, String 
aNewValue,
-      boolean aOverride, String aDefault, ConstPool aConstPool,
-      Multimap<String, String> aReportData, Class<?> aClazz) {
+          boolean aOverride, String aDefault, ConstPool aConstPool,
+          Multimap<String, String> aReportData, Class<?> aClazz) {
     String value = getStringMemberValue(aAnnotation, aName);
     boolean isEmpty = value.length() == 0;
     boolean isDefault = value.equals(aDefault);
@@ -438,12 +469,12 @@ public class EnhanceMojo extends AbstractMojo {
    * Enhance descriptions in configuration parameters.
    */
   private void enhanceConfigurationParameter(JavaSource aAST, Class<?> aClazz, 
CtClass aCtClazz,
-      Multimap<String, String> aReportData) throws MojoExecutionException {
+          Multimap<String, String> aReportData) throws MojoExecutionException {
     // Get the parameter name constants
     Map<String, String> parameterNameFields = getParameterConstants(aClazz,
-        parameterNameConstantPrefixes);
+            parameterNameConstantPrefixes);
     Map<String, String> resourceNameFields = getParameterConstants(aClazz,
-        externalResourceNameConstantPrefixes);
+            externalResourceNameConstantPrefixes);
 
     // Fetch configuration parameters from the @ConfigurationParameter 
annotations in the
     // compiled class. We only need the fields in the class itself. 
Superclasses should be
@@ -460,7 +491,7 @@ public class EnhanceMojo extends AbstractMojo {
         pname = 
ConfigurationParameterFactory.createPrimitiveParameter(field).getName();
         // Extract JavaDoc for this resource from the source file
         pdesc = Util.getParameterDocumentation(aAST, field.getName(),
-            parameterNameFields.get(pname));
+                parameterNameFields.get(pname));
       }
 
       // Is this an external resource?
@@ -470,7 +501,7 @@ public class EnhanceMojo extends AbstractMojo {
         pname = 
ExternalResourceFactory.createResourceDependency(field).getKey();
         // Extract JavaDoc for this resource from the source file
         pdesc = Util.getParameterDocumentation(aAST, field.getName(),
-            resourceNameFields.get(pname));
+                resourceNameFields.get(pname));
       } else {
         continue;
       }
@@ -486,7 +517,7 @@ public class EnhanceMojo extends AbstractMojo {
       try {
         CtField ctField = aCtClazz.getField(field.getName());
         AnnotationsAttribute annoAttr = (AnnotationsAttribute) 
ctField.getFieldInfo()
-            .getAttribute(AnnotationsAttribute.visibleTag);
+                .getAttribute(AnnotationsAttribute.visibleTag);
 
         // Locate and update annotation
         if (annoAttr != null) {
@@ -495,14 +526,14 @@ public class EnhanceMojo extends AbstractMojo {
           // Update existing annotation
           for (Annotation a : annotations) {
             if (a.getTypeName()
-                
.equals(org.apache.uima.fit.descriptor.ConfigurationParameter.class.getName())
-                || a.getTypeName()
-                    
.equals(org.apache.uima.fit.descriptor.ExternalResource.class.getName())
-                || 
a.getTypeName().equals("org.uimafit.descriptor.ConfigurationParameter")
-                || 
a.getTypeName().equals("org.uimafit.descriptor.ExternalResource")) {
+                    
.equals(org.apache.uima.fit.descriptor.ConfigurationParameter.class.getName())
+                    || a.getTypeName()
+                            
.equals(org.apache.uima.fit.descriptor.ExternalResource.class.getName())
+                    || 
a.getTypeName().equals("org.uimafit.descriptor.ConfigurationParameter")
+                    || 
a.getTypeName().equals("org.uimafit.descriptor.ExternalResource")) {
               if (a.getMemberValue("description") == null) {
                 a.addMemberValue("description",
-                    new StringMemberValue(pdesc, 
aCtClazz.getClassFile().getConstPool()));
+                        new StringMemberValue(pdesc, 
aCtClazz.getClassFile().getConstPool()));
                 getLog().debug("Enhanced description of " + type + " [" + 
pname + "]");
                 // Replace updated annotation
                 annoAttr.addAnnotation(a);
@@ -520,7 +551,7 @@ public class EnhanceMojo extends AbstractMojo {
         ctField.getFieldInfo().addAttribute(annoAttr);
       } catch (NotFoundException e) {
         throw new MojoExecutionException("Field [" + field.getName() + "] not 
found in byte code: "
-            + ExceptionUtils.getRootCauseMessage(e), e);
+                + ExceptionUtils.getRootCauseMessage(e), e);
       }
     }
   }
@@ -552,7 +583,7 @@ public class EnhanceMojo extends AbstractMojo {
         result.put(parameterName, f.getName());
       } catch (IllegalAccessException e) {
         getLog().warn("Unable to access name constant field [" + f.getName() + 
"]: "
-            + ExceptionUtils.getRootCauseMessage(e), e);
+                + ExceptionUtils.getRootCauseMessage(e), e);
       }
     }
     return result;
@@ -563,7 +594,7 @@ public class EnhanceMojo extends AbstractMojo {
       return Util.parseSource(aSourceFile, encoding);
     } catch (IOException e) {
       throw new MojoExecutionException("Unable to parse source file [" + 
aSourceFile + "]: "
-          + ExceptionUtils.getRootCauseMessage(e), e);
+              + ExceptionUtils.getRootCauseMessage(e), e);
     }
   }
 
@@ -589,7 +620,7 @@ public class EnhanceMojo extends AbstractMojo {
    * Write a report on any meta data missing from components.
    */
   private void writeMissingMetaDataReport(File aReportFile, Multimap<String, 
String> aReportData)
-      throws MojoExecutionException {
+          throws MojoExecutionException {
     String[] classes = aReportData.keySet().toArray(new 
String[aReportData.keySet().size()]);
     Arrays.sort(classes);
 
@@ -616,7 +647,7 @@ public class EnhanceMojo extends AbstractMojo {
       }
     } catch (IOException e) {
       throw new MojoExecutionException("Unable to write missing meta data 
report to [" + aReportFile
-          + "]" + ExceptionUtils.getRootCauseMessage(e), e);
+              + "]" + ExceptionUtils.getRootCauseMessage(e), e);
     } finally {
       IOUtils.closeQuietly(out);
     }
@@ -626,7 +657,7 @@ public class EnhanceMojo extends AbstractMojo {
    * Read the missing meta data report from a previous run.
    */
   private void readMissingMetaDataReport(File aReportFile, Multimap<String, 
String> aReportData)
-      throws MojoExecutionException {
+          throws MojoExecutionException {
     if (!aReportFile.exists()) {
       // Ignore if the file is missing
       return;
@@ -657,7 +688,8 @@ public class EnhanceMojo extends AbstractMojo {
       }
     } catch (IOException e) {
       throw new MojoExecutionException(
-          "Unable to read missing meta data report: " + 
ExceptionUtils.getRootCauseMessage(e), e);
+              "Unable to read missing meta data report: " + 
ExceptionUtils.getRootCauseMessage(e),
+              e);
     } finally {
       LineIterator.closeQuietly(i);
     }
diff --git 
a/uimafit-maven-plugin/src/main/java/org/apache/uima/fit/maven/GenerateDescriptorsMojo.java
 
b/uimafit-maven-plugin/src/main/java/org/apache/uima/fit/maven/GenerateDescriptorsMojo.java
index 48460a6..702581f 100644
--- 
a/uimafit-maven-plugin/src/main/java/org/apache/uima/fit/maven/GenerateDescriptorsMojo.java
+++ 
b/uimafit-maven-plugin/src/main/java/org/apache/uima/fit/maven/GenerateDescriptorsMojo.java
@@ -31,7 +31,6 @@ import java.lang.reflect.Modifier;
 import java.nio.file.Path;
 import java.nio.file.Paths;
 
-import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang3.exception.ExceptionUtils;
 import org.apache.maven.model.Resource;
 import org.apache.maven.plugin.AbstractMojo;
@@ -96,6 +95,18 @@ public class GenerateDescriptorsMojo extends AbstractMojo {
   @Parameter(defaultValue = "true", required = true)
   private boolean failOnError;
 
+  /**
+   * Skip plugin execution.
+   */
+  @Parameter(property = "uima-generate.skip", defaultValue = "false", required 
= true)
+  private boolean skip;
+
+  /**
+   * Skip plugin execution only during incremental builds (e.g. triggered from 
m2e).
+   */
+  @Parameter(defaultValue = "false", required = true)
+  private boolean skipDuringIncrementalBuilds;
+
   enum TypeSystemSerialization {
     NONE, EMBEDDED
   }
@@ -116,6 +127,10 @@ public class GenerateDescriptorsMojo extends AbstractMojo {
 
   @Override
   public void execute() throws MojoExecutionException {
+    if (isSkipped()) {
+      return;
+    }
+
     // add the generated sources to the build
     if (!outputDirectory.exists()) {
       outputDirectory.mkdirs();
@@ -124,7 +139,7 @@ public class GenerateDescriptorsMojo extends AbstractMojo {
 
     // Get the compiled classes from this project
     String[] files = 
FileUtils.getFilesFromExtension(project.getBuild().getOutputDirectory(),
-        new String[] { "class" });
+            new String[] { "class" });
 
     componentLoader = Util.getClassloader(project, getLog(), includeScope);
 
@@ -152,27 +167,27 @@ public class GenerateDescriptorsMojo extends AbstractMojo 
{
         ResourceCreationSpecifier desc = null;
         ProcessingResourceMetaData metadata = null;
         switch (Util.getType(componentLoader, clazz)) {
-        case ANALYSIS_ENGINE:
-          AnalysisEngineDescription aeDesc = createEngineDescription(clazz);
-          metadata = aeDesc.getAnalysisEngineMetaData();
-          desc = aeDesc;
-          break;
-        case COLLECTION_READER:
-          CollectionReaderDescription crDesc = createReaderDescription(clazz);
-          metadata = crDesc.getCollectionReaderMetaData();
-          desc = crDesc;
-        default:
-          // Do nothing
+          case ANALYSIS_ENGINE:
+            AnalysisEngineDescription aeDesc = createEngineDescription(clazz);
+            metadata = aeDesc.getAnalysisEngineMetaData();
+            desc = aeDesc;
+            break;
+          case COLLECTION_READER:
+            CollectionReaderDescription crDesc = 
createReaderDescription(clazz);
+            metadata = crDesc.getCollectionReaderMetaData();
+            desc = crDesc;
+          default:
+            // Do nothing
         }
 
         if (desc != null) {
           switch (addTypeSystemDescriptions) {
-          case EMBEDDED:
-            embedTypeSystems(metadata);
-            break;
-          case NONE: // fall-through
-          default:
-            // Do nothing
+            case EMBEDDED:
+              embedTypeSystems(metadata);
+              break;
+            case NONE: // fall-through
+            default:
+              // Do nothing
           }
 
           File out = new File(outputDirectory, clazzPath + ".xml");
@@ -196,8 +211,8 @@ public class GenerateDescriptorsMojo extends AbstractMojo {
       }
     }
 
-    getLog()
-        .info("Generated " + countGenerated + " descriptor" + (countGenerated 
!= 1 ? "s." : "."));
+    getLog().info(
+            "Generated " + countGenerated + " descriptor" + (countGenerated != 
1 ? "s." : "."));
 
     // Write META-INF/org.apache.uima.fit/components.txt unless skipped and 
unless there are no
     // components
@@ -208,16 +223,16 @@ public class GenerateDescriptorsMojo extends AbstractMojo 
{
         FileUtils.fileWrite(path.getPath(), encoding, 
componentsManifest.toString());
       } catch (IOException e) {
         handleError("Cannot write components manifest to [" + path + "]"
-            + ExceptionUtils.getRootCauseMessage(e), e);
+                + ExceptionUtils.getRootCauseMessage(e), e);
       }
     }
 
     if (addOutputDirectoryAsResourceDirectory && countGenerated > 0) {
       Path absoluteDescriptorOutputPath = 
outputDirectory.toPath().toAbsolutePath();
       Path absoluteBuildOutputDirectory = 
Paths.get(project.getBuild().getOutputDirectory())
-          .toAbsolutePath();
+              .toAbsolutePath();
       Path absoluteBuildTestOutputDirectory = 
Paths.get(project.getBuild().getTestOutputDirectory())
-          .toAbsolutePath();
+              .toAbsolutePath();
 
       // Add the output folder as a new resource folder if any descriptors 
were generated and
       // only
@@ -226,7 +241,7 @@ public class GenerateDescriptorsMojo extends AbstractMojo {
       // be the case if the mojo is executed in a late build phase where the 
resources plugin
       // doesn't run anymore.
       if (!absoluteBuildOutputDirectory.equals(absoluteDescriptorOutputPath)
-          && 
!absoluteBuildTestOutputDirectory.equals(absoluteDescriptorOutputPath)) {
+              && 
!absoluteBuildTestOutputDirectory.equals(absoluteDescriptorOutputPath)) {
         Resource resource = new Resource();
         resource.setDirectory(outputDirectory.getPath());
         resource.setFiltering(false);
@@ -236,6 +251,20 @@ public class GenerateDescriptorsMojo extends AbstractMojo {
     }
   }
 
+  private boolean isSkipped() {
+    if (skipDuringIncrementalBuilds && buildContext.isIncremental()) {
+      getLog().info("Generation of UIMA component descriptors skipped in 
incremental build.");
+      return true;
+    }
+
+    if (skip) {
+      getLog().info("Generation of UIMA component descriptors skipped.");
+      return true;
+    }
+
+    return false;
+  }
+
   private void handleError(String message, Exception e) throws 
MojoExecutionException {
     if (failOnError) {
       throw new MojoExecutionException(message, e);
@@ -245,7 +274,7 @@ public class GenerateDescriptorsMojo extends AbstractMojo {
   }
 
   private void embedTypeSystems(ProcessingResourceMetaData metadata)
-      throws ResourceInitializationException {
+          throws ResourceInitializationException {
     TypeSystemDescriptionFactory.forceTypeDescriptorsScan();
     TypeSystemDescription tsDesc = 
TypeSystemDescriptionFactory.createTypeSystemDescription();
     metadata.setTypeSystem(tsDesc);
@@ -255,14 +284,10 @@ public class GenerateDescriptorsMojo extends AbstractMojo 
{
    * Save descriptor XML to file system.
    */
   private void toXML(ResourceSpecifier aDesc, String aFilename) throws 
SAXException, IOException {
-    OutputStream os = null;
-    try {
-      File out = new File(aFilename);
-      getLog().debug("Writing descriptor to: " + out);
-      os = new FileOutputStream(out);
+    File out = new File(aFilename);
+    getLog().debug("Writing descriptor to: " + out);
+    try (OutputStream os = new FileOutputStream(out);) {
       aDesc.toXML(os);
-    } finally {
-      IOUtils.closeQuietly(os);
     }
   }
 }

Reply via email to