/*
 * Copyright 2002-2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.config.java.annotation.valuesource;

import static java.lang.String.format;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.config.java.annotation.Bean;
import org.springframework.config.java.annotation.Configuration;
import org.springframework.config.java.annotation.ExternalValue;
import org.springframework.config.java.context.JavaConfigApplicationContext;
import org.springframework.config.java.valuesource.EnvironmentValueResolver;
import org.springframework.config.java.valuesource.ValueResolutionException;


/**
 * System tests for {@link EnvironmentValueSource}.
 */
public class EnvironmentValueSourceTests {

    private static final Log log = LogFactory.getLog(EnvironmentValueSourceTests.class);
    private static final String NONEXISTENT_ENV_VAR_NAME = "does.not.exist";
    private static final String WELL_KNOWN_ENV_VAR_NAME = "TMPDIR";

    private JavaConfigApplicationContext ctx;

    static class ValueHolder {
        public String value;
    }

    @Before
    public void initContext() {
        ctx = null;
    }

    // -------------------------------------------------------------------------

    @Test
    public void testNonExistentEnvironmentVariableName() {
        try {
            ctx = new JavaConfigApplicationContext(ConfigWithNonExistentEnvVariable.class);
            fail("should have thrown " + ValueResolutionException.class.getName());
        } catch (BeanCreationException ex) {
            Throwable rootCause = ExceptionUtils.getRootCause(ex);
            assertThat(rootCause, instanceOf(ValueResolutionException.class));
            assertThat(rootCause.getMessage(),
                    equalTo(format("Cannot resolve property for name '%s' against resolvers [%s]",
                            NONEXISTENT_ENV_VAR_NAME, EnvironmentValueResolver.class.getSimpleName())));
        }

    }

    @Configuration
    @EnvironmentValueSource
    static abstract class ConfigWithNonExistentEnvVariable {
        abstract @ExternalValue(NONEXISTENT_ENV_VAR_NAME) String value();

        public @Bean ValueHolder valueHolder() {
            ValueHolder valueHolder = new ValueHolder();
            valueHolder.value = value();
            return valueHolder;
        }
    }

    // -------------------------------------------------------------------------

    @Test
    public void testWellKnownEnvironmentVariable() {
        if(System.getenv(WELL_KNOWN_ENV_VAR_NAME) == null) {
            log.error(format("Environment variable %s not present on" +
                    "this system. Skipping testWellKnownEnvironmentVariable()",
                    WELL_KNOWN_ENV_VAR_NAME));
            return;
        }

        ctx = new JavaConfigApplicationContext(ConfigWithSetEnvVariable.class);
        assertThat(ctx.getBean(ValueHolder.class).value, not(nullValue()));
    }

    @Configuration
    @EnvironmentValueSource
    static abstract class ConfigWithSetEnvVariable {
        abstract @ExternalValue(WELL_KNOWN_ENV_VAR_NAME) String value();

        public @Bean ValueHolder valueHolder() {
            ValueHolder valueHolder = new ValueHolder();
            valueHolder.value = value();
            return valueHolder;
        }
    }

}
