org.createnet.raptor.auth.service.YamlFileApplicationContextInitializer.java Source code

Java tutorial

Introduction

Here is the source code for org.createnet.raptor.auth.service.YamlFileApplicationContextInitializer.java

Source

/*
 * Copyright 2017 FBK/CREATE-NET
 *
 * 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.createnet.raptor.auth.service;

import java.io.File;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

/**
 *
 * @author Luca Capra <luca.capra@fbk.eu>
 */
public class YamlFileApplicationContextInitializer
        implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    private static final Logger logger = LoggerFactory.getLogger(YamlFileApplicationContextInitializer.class);

    static String configPath = "/etc/raptor/auth-service.yml";

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {

        File configFile = new File(configPath);
        if (!configFile.exists()) {
            logger.warn("Configurations file does not exists: {}", configPath);
            return;
        }

        try {

            String context = System.getenv("SPRING_PROFILES_ACTIVE");
            if (context == null || context.isEmpty()) {
                context = "default";
            }

            Resource resource = new FileSystemResource(configFile);
            YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
            PropertySource<?> yamlTestProperties = sourceLoader.load("etcProperties", resource, context);
            applicationContext.getEnvironment().getPropertySources().addFirst(yamlTestProperties);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}