All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.zhengframework.configuration.source.FallbackConfigurationSource Maven / Gradle / Ivy

There is a newer version: 1.8.0
Show newest version
package com.github.zhengframework.configuration.source;

import com.github.zhengframework.configuration.environment.Environment;
import com.github.zhengframework.configuration.ex.ConfigurationSourceException;
import com.github.zhengframework.configuration.ex.MissingEnvironmentException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class FallbackConfigurationSource implements ConfigurationSource {

  private final List sources = new ArrayList<>();

  public FallbackConfigurationSource(ConfigurationSource... sources) {
    Objects.requireNonNull(sources);
    for (ConfigurationSource source : sources) {
      this.sources.add(Objects.requireNonNull(source));
    }
  }

  public FallbackConfigurationSource(Iterator sources) {
    Objects.requireNonNull(sources).forEachRemaining(configurationSource -> {
      FallbackConfigurationSource.this.sources.add(Objects.requireNonNull(configurationSource));
    });
  }

  public FallbackConfigurationSource(Iterable sources) {
    Objects.requireNonNull(sources).forEach(configurationSource -> {
      FallbackConfigurationSource.this.sources.add(Objects.requireNonNull(configurationSource));
    });
  }

  @Override
  public void init() {
    boolean atLeastOneSuccess = false;
    for (ConfigurationSource source : sources) {
      try {
        source.init();
        atLeastOneSuccess = true;
      } catch (IllegalStateException | ConfigurationSourceException e) {
        // NOP
      }
    }
    if (!atLeastOneSuccess) {
      throw new IllegalStateException("Unable to initialize any of the underlying sources");
    }
  }

  @Override
  public void addListener(ConfigurationSourceListener listener) {
    for (ConfigurationSource source : sources) {
      source.addListener(listener);
    }
  }

  @Override
  public void removeListener(ConfigurationSourceListener listener) {
    for (ConfigurationSource source : sources) {
      source.removeListener(listener);
    }
  }

  @Override
  public Map getConfiguration(Environment environment) {
    boolean allMissEnvironment = true;
    for (ConfigurationSource source : sources) {
      try {
        return source.getConfiguration(environment);
      } catch (MissingEnvironmentException e) {
        // NOP
      } catch (IllegalStateException e) {
        allMissEnvironment = false;
      }
    }
    if (allMissEnvironment) {
      throw new MissingEnvironmentException(environment.getName());
    }
    throw new IllegalStateException();
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy