001/*
002 * Licensed to DuraSpace under one or more contributor license agreements.
003 * See the NOTICE file distributed with this work for additional information
004 * regarding copyright ownership.
005 *
006 * DuraSpace licenses this file to you under the Apache License,
007 * Version 2.0 (the "License"); you may not use this file except in
008 * compliance 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, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.fcrepo.config;
020
021import java.util.Objects;
022
023import org.slf4j.Logger;
024import org.slf4j.LoggerFactory;
025import org.springframework.context.annotation.ConditionContext;
026import org.springframework.context.annotation.ConfigurationCondition;
027import org.springframework.core.type.AnnotatedTypeMetadata;
028
029/**
030 * This condition enables a bean/configuration when the specified property matches the expected value
031 *
032 * Implementations must provide a no-arg constructor.
033 *
034 * @author pwinckles
035 */
036public abstract class ConditionOnProperty<T> implements ConfigurationCondition {
037
038    private static final Logger LOGGER = LoggerFactory.getLogger(ConditionOnProperty.class);
039
040    private final String name;
041    private final T expected;
042    private final T defaultValue;
043    private final Class<T> clazz;
044
045    public ConditionOnProperty(final String name, final T expected, final T defaultValue, final Class<T> clazz) {
046        this.name = name;
047        this.expected = expected;
048        this.defaultValue = defaultValue;
049        this.clazz = clazz;
050    }
051
052    @Override
053    public boolean matches(final ConditionContext context, final AnnotatedTypeMetadata metadata) {
054        LOGGER.debug("Prop {}: {}", name, context.getEnvironment().getProperty(name));
055        return Objects.equals(expected, context.getEnvironment().getProperty(name, clazz, defaultValue));
056    }
057
058    @Override
059    public ConfigurationPhase getConfigurationPhase() {
060        // This forces spring to not evaluate these conditions until after it has loaded other @Configuration classes,
061        // ensuring that the properties have been loaded.
062        return ConfigurationPhase.REGISTER_BEAN;
063    }
064}