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.fields;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import org.basepom.mojo.propertyhelper.Field;
020import org.basepom.mojo.propertyhelper.FieldContext;
021import org.basepom.mojo.propertyhelper.ValueProvider;
022import org.basepom.mojo.propertyhelper.definitions.UuidDefinition;
023
024import java.util.Optional;
025import java.util.StringJoiner;
026import java.util.UUID;
027
028import com.google.common.annotations.VisibleForTesting;
029
030public final class UuidField extends Field<String, UuidDefinition> {
031
032    private final ValueProvider valueProvider;
033
034    @VisibleForTesting
035    public static UuidField forTesting(UuidDefinition uuidDefinition, ValueProvider valueProvider) {
036        return new UuidField(uuidDefinition, valueProvider, FieldContext.forTesting());
037    }
038
039    public UuidField(final UuidDefinition uuidDefinition, final ValueProvider valueProvider,
040        FieldContext fieldContext) {
041        super(uuidDefinition, fieldContext);
042
043        this.valueProvider = checkNotNull(valueProvider, "valueProvider is null");
044    }
045
046    @Override
047    public String getFieldName() {
048        return fieldDefinition.getId();
049    }
050
051    @Override
052    public String getValue() {
053        final Optional<String> propValue = valueProvider.getValue();
054
055        // Only add the value from the provider if it is not null.
056        UUID result = propValue.map(UUID::fromString)
057            .orElse(fieldDefinition.getValue()
058                .orElse(UUID.randomUUID()));
059
060        valueProvider.setValue(result.toString());
061        return formatResult(result.toString());
062    }
063
064    @Override
065    public String toString() {
066        return new StringJoiner(", ", UuidField.class.getSimpleName() + "[", "]")
067            .add("uuidDefinition=" + fieldDefinition)
068            .add("valueProvider=" + valueProvider)
069            .toString();
070    }
071}