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
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import java.util.Locale;
020import java.util.function.Supplier;
021
022import com.google.common.flogger.FluentLogger;
023
024public enum IgnoreWarnFail {
025    IGNORE, WARN, FAIL;
026
027    private static final FluentLogger LOG = FluentLogger.forEnclosingClass();
028
029    public static IgnoreWarnFail forString(final String value) {
030        checkNotNull(value, "the value can not be null");
031        return Enum.valueOf(IgnoreWarnFail.class, value.toUpperCase(Locale.getDefault()));
032    }
033
034    /**
035     * Ensure that a given element exists. If it does not exist, react based on the {@link IgnoreWarnFail} attribute:
036     * <ul>
037     *     <li>IGNORE - do nothing</li>
038     *     <li>WARN - warn that an element does not exist</li>
039     *     <li>FAIL - throw an exception</li>
040     * </ul>
041     *
042     * @param check Should be true
043     * @param iwf    What to do
044     * @return True if the thing exists, false otherwise
045     */
046    public static boolean checkIgnoreWarnFailState(final boolean check, final IgnoreWarnFail iwf,
047        final Supplier<String> checkMessage, final Supplier<String> errorMessage) {
048
049        if (check) {
050            LOG.atFine().log(checkMessage.get());
051            return true;
052        }
053
054        switch (iwf) {
055            case IGNORE:
056                LOG.atFine().log(errorMessage.get());
057                break;
058            case WARN:
059                LOG.atWarning().log(errorMessage.get());
060                break;
061            case FAIL:
062                throw new IllegalStateException(errorMessage.get());
063            default:
064                throw new IllegalStateException("Unknown state: " + iwf);
065        }
066
067        return false;
068    }
069}