Field.java

  1. /*
  2.  * Licensed under the Apache License, Version 2.0 (the "License");
  3.  * you may not use this file except in compliance with the License.
  4.  * You may obtain a copy of the License at
  5.  *
  6.  * http://www.apache.org/licenses/LICENSE-2.0
  7.  *
  8.  * Unless required by applicable law or agreed to in writing, software
  9.  * distributed under the License is distributed on an "AS IS" BASIS,
  10.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11.  * See the License for the specific language governing permissions and
  12.  * limitations under the License.
  13.  */

  14. package org.basepom.mojo.propertyhelper;


  15. import org.basepom.mojo.propertyhelper.definitions.FieldDefinition;

  16. import java.util.Optional;

  17. import com.google.common.collect.ImmutableMap;
  18. import org.apache.maven.plugin.MojoExecutionException;

  19. /**
  20.  * Describe all the fields.
  21.  */
  22. public abstract class Field<T, U extends FieldDefinition<T>> {

  23.     protected final U fieldDefinition;
  24.     private final InterpolatorFactory interpolatorFactory;
  25.     private final TransformerRegistry transformerRegistry;


  26.     protected Field(U fieldDefinition, FieldContext context) {
  27.         this.fieldDefinition = fieldDefinition;
  28.         this.interpolatorFactory = context.getInterpolatorFactory();
  29.         this.transformerRegistry = context.getTransformerRegistry();
  30.     }

  31.     /**
  32.      * The name of the field.
  33.      */
  34.     public abstract String getFieldName();

  35.     /**
  36.      * The value of the field. {@link Optional#empty()} can be returned if the value is not defined.
  37.      */
  38.     public abstract String getValue() throws MojoExecutionException;

  39.     protected String formatResult(T value) {

  40.         return Optional.ofNullable(value)
  41.             .map(fieldDefinition.getPreFormat())
  42.             .map(interpolatorFactory.interpolate(getFieldName(), fieldDefinition.getOnMissingProperty(), ImmutableMap.of()))
  43.             .map(fieldDefinition.getPostFormat())
  44.             .map(fieldDefinition.getRegexp())
  45.             .map(transformerRegistry.applyTransformers(fieldDefinition.getTransformers()))
  46.             .orElse("");
  47.     }

  48.     /**
  49.      * True if the value of this element should be exposed as a maven property.
  50.      */
  51.     public boolean isExposeAsProperty() {
  52.         return fieldDefinition.isExport();
  53.     }
  54. }