001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.maven.enforcer.rules.property;
020
021import javax.inject.Inject;
022import javax.inject.Named;
023
024import java.util.Objects;
025
026import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
027import org.apache.maven.enforcer.rules.utils.ExpressionEvaluator;
028import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException;
029
030/**
031 * This rule checks that certain properties are set.
032 *
033 * @author Paul Gier
034 */
035@Named("requireProperty")
036public final class RequireProperty extends AbstractPropertyEnforcerRule {
037
038    /**
039     * Specify the required property.
040     */
041    private String property = null;
042
043    private final ExpressionEvaluator evaluator;
044
045    @Inject
046    public RequireProperty(ExpressionEvaluator evaluator) {
047        this.evaluator = Objects.requireNonNull(evaluator);
048    }
049
050    public void setProperty(String property) {
051        this.property = property;
052    }
053
054    @Override
055    public Object resolveValue() throws EnforcerRuleException {
056        try {
057            return evaluator.evaluate("${" + property + "}");
058        } catch (ExpressionEvaluationException e) {
059            throw new EnforcerRuleException(e);
060        }
061    }
062
063    @Override
064    public String getPropertyName() {
065        return property;
066    }
067
068    @Override
069    public String getName() {
070        return "Property";
071    }
072
073    @Override
074    public String toString() {
075        return String.format(
076                "RequireProperty[message=%s, property=%s, regex=%s, regexMessage=%s]",
077                getMessage(), property, getRegex(), getRegexMessage());
078    }
079}