View Javadoc
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  
15  package org.basepom.mojo.propertyhelper;
16  
17  
18  import org.basepom.mojo.propertyhelper.definitions.FieldDefinition;
19  
20  import java.util.Optional;
21  
22  import com.google.common.collect.ImmutableMap;
23  import org.apache.maven.plugin.MojoExecutionException;
24  
25  /**
26   * Describe all the fields.
27   */
28  public abstract class Field<T, U extends FieldDefinition<T>> {
29  
30      protected final U fieldDefinition;
31      private final InterpolatorFactory interpolatorFactory;
32      private final TransformerRegistry transformerRegistry;
33  
34  
35      protected Field(U fieldDefinition, FieldContext context) {
36          this.fieldDefinition = fieldDefinition;
37          this.interpolatorFactory = context.getInterpolatorFactory();
38          this.transformerRegistry = context.getTransformerRegistry();
39      }
40  
41      /**
42       * The name of the field.
43       */
44      public abstract String getFieldName();
45  
46      /**
47       * The value of the field. {@link Optional#empty()} can be returned if the value is not defined.
48       */
49      public abstract String getValue() throws MojoExecutionException;
50  
51      protected String formatResult(T value) {
52  
53          return Optional.ofNullable(value)
54              .map(fieldDefinition.getPreFormat())
55              .map(interpolatorFactory.interpolate(getFieldName(), fieldDefinition.getOnMissingProperty(), ImmutableMap.of()))
56              .map(fieldDefinition.getPostFormat())
57              .map(fieldDefinition.getRegexp())
58              .map(transformerRegistry.applyTransformers(fieldDefinition.getTransformers()))
59              .orElse("");
60      }
61  
62      /**
63       * True if the value of this element should be exposed as a maven property.
64       */
65      public boolean isExposeAsProperty() {
66          return fieldDefinition.isExport();
67      }
68  }