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.fields;
16  
17  import static com.google.common.base.Preconditions.checkNotNull;
18  
19  import org.basepom.mojo.propertyhelper.Field;
20  import org.basepom.mojo.propertyhelper.FieldContext;
21  import org.basepom.mojo.propertyhelper.ValueProvider;
22  import org.basepom.mojo.propertyhelper.definitions.UuidDefinition;
23  
24  import java.util.Optional;
25  import java.util.StringJoiner;
26  import java.util.UUID;
27  
28  import com.google.common.annotations.VisibleForTesting;
29  
30  public final class UuidField extends Field<String, UuidDefinition> {
31  
32      private final ValueProvider valueProvider;
33  
34      @VisibleForTesting
35      public static UuidField forTesting(UuidDefinition uuidDefinition, ValueProvider valueProvider) {
36          return new UuidField(uuidDefinition, valueProvider, FieldContext.forTesting());
37      }
38  
39      public UuidField(final UuidDefinition uuidDefinition, final ValueProvider valueProvider,
40          FieldContext fieldContext) {
41          super(uuidDefinition, fieldContext);
42  
43          this.valueProvider = checkNotNull(valueProvider, "valueProvider is null");
44      }
45  
46      @Override
47      public String getFieldName() {
48          return fieldDefinition.getId();
49      }
50  
51      @Override
52      public String getValue() {
53          final Optional<String> propValue = valueProvider.getValue();
54  
55          // Only add the value from the provider if it is not null.
56          UUID result = propValue.map(UUID::fromString)
57              .orElse(fieldDefinition.getValue()
58                  .orElse(UUID.randomUUID()));
59  
60          valueProvider.setValue(result.toString());
61          return formatResult(result.toString());
62      }
63  
64      @Override
65      public String toString() {
66          return new StringJoiner(", ", UuidField.class.getSimpleName() + "[", "]")
67              .add("uuidDefinition=" + fieldDefinition)
68              .add("valueProvider=" + valueProvider)
69              .toString();
70      }
71  }