001/* 002 * Licensed under the Apache License, Version 2.0 (the "License"); 003 * you may not use this file except in compliance with the License. 004 * You may obtain a copy of the License at 005 * 006 * http://www.apache.org/licenses/LICENSE-2.0 007 * 008 * Unless required by applicable law or agreed to in writing, software 009 * distributed under the License is distributed on an "AS IS" BASIS, 010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 011 * See the License for the specific language governing permissions and 012 * limitations under the License. 013 */ 014 015package org.basepom.mojo.propertyhelper; 016 017 018import org.basepom.mojo.propertyhelper.definitions.FieldDefinition; 019 020import java.util.Optional; 021 022import com.google.common.collect.ImmutableMap; 023import org.apache.maven.plugin.MojoExecutionException; 024 025/** 026 * Describe all the fields. 027 */ 028public abstract class Field<T, U extends FieldDefinition<T>> { 029 030 protected final U fieldDefinition; 031 private final InterpolatorFactory interpolatorFactory; 032 private final TransformerRegistry transformerRegistry; 033 034 035 protected Field(U fieldDefinition, FieldContext context) { 036 this.fieldDefinition = fieldDefinition; 037 this.interpolatorFactory = context.getInterpolatorFactory(); 038 this.transformerRegistry = context.getTransformerRegistry(); 039 } 040 041 /** 042 * The name of the field. 043 */ 044 public abstract String getFieldName(); 045 046 /** 047 * The value of the field. {@link Optional#empty()} can be returned if the value is not defined. 048 */ 049 public abstract String getValue() throws MojoExecutionException; 050 051 protected String formatResult(T value) { 052 053 return Optional.ofNullable(value) 054 .map(fieldDefinition.getPreFormat()) 055 .map(interpolatorFactory.interpolate(getFieldName(), fieldDefinition.getOnMissingProperty(), ImmutableMap.of())) 056 .map(fieldDefinition.getPostFormat()) 057 .map(fieldDefinition.getRegexp()) 058 .map(transformerRegistry.applyTransformers(fieldDefinition.getTransformers())) 059 .orElse(""); 060 } 061 062 /** 063 * True if the value of this element should be exposed as a maven property. 064 */ 065 public boolean isExposeAsProperty() { 066 return fieldDefinition.isExport(); 067 } 068}