summaryrefslogtreecommitdiffstats
path: root/common/onap-common-configuration-management/onap-configuration-management-core/src/main/java/org/onap/config/impl/ConfigurationRepository.java
blob: 90346d1ec313e3ca3c2c63cf49ac24bee4fabc30 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97

@media only all and (prefers-color-scheme: dark) {
.highlight .hll { background-color: #49483e }
.highlight .c { color: #75715e } /* Comment */
.highlight .err { color: #960050; background-color: #1e0010 } /* Error */
.highlight .k { color: #66d9ef } /* Keyword */
.highlight .l { color: #ae81ff } /* Literal */
.highlight .n { color: #f8f8f2 } /* Name */
.highlight .o { color: #f92672 } /* Operator */
.highlight .p { color: #f8f8f2 } /* Punctuation */
.highlight .ch { color: #75715e } /* Comment.Hashbang */
.highlight .cm { color: #75715e } /* Comment.Multiline */
.highlight .cp { color: #75715e } /* Comment.Preproc */
.highlight .cpf { color: #75715e } /* Comment.PreprocFile */
.highlight .c1 { color: #75715e } /* Comment.Single */
.highlight .cs { color: #75715e } /* Comment.Special */
.highlight .gd { color: #f92672 } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gi { color: #a6e22e } /* Generic.Inserted */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #75715e } /* Generic.Subheading */
.highlight .kc { color: #66d9ef } /* Keyword.Constant */
.highlight .kd { color: #66d9ef } /* Keyword.Declaration */
.highlight .kn { color: #f92672 } /* Keyword.Namespace */
.highlight .kp { color: #66d9ef } /* Keyword.Pseudo */
.highlight .kr { color: #66d9ef } /* Keyword.Reserved */
.highlight .kt { color: #66d9ef } /* Keyword.Type */
.highlight .ld { color: #e6db74 } /* Literal.Date */
.highlight .m { color: #ae81ff } /* Literal.Number */
.highlight .s { color: #e6db74 } /* Literal.String */
.highlight .na { color: #a6e22e } /* Name.Attribute */
.highlight .nb { color: #f8f8f2 } /* Name.Builtin */
.highlight .nc { color: #a6e22e } /* Name.Class */
.highlight .no { color: #66d9ef } /* Name.Constant */
.highlight .nd { color: #a6e22e } /* Name.Decorator */
.highlight .ni { color: #f8f8f2 } /* Name.Entity */
.highlight .ne { color: #a6e22e } /* Name.Exception */
.highlight .nf { color: #a6e22e } /* Name.Function */
.highlight .nl { color: #f8f8f2 } /* Name.Label */
.highlight .nn { color: #f8f8f2 } /* Name.Namespace */
.highlight .nx { color: #a6e22e } /* Name.Other */
.highlight .py { color: #f8f8f2 } /* Name.Property */
.highlight .nt { color: #f92672 } /* Name.Tag */
.highlight .nv { color: #f8f8f2 } /* Name.Variable */
.highlight .ow { color: #f92672 } /* Operator.Word */
.highlight .w { color: #f8f8f2 } /* Text.Whitespace */
.highlight .mb { color: #ae81ff } /* Literal.Number.Bin */
.highlight .mf { color: #ae81ff } /* Literal.Number.Float */
.highlight .mh { color: #ae81ff } /* Literal.Number.Hex */
.highlight .mi { color: #ae81ff } /* Literal.Number.Integer */
.highlight .mo { color: #ae81ff } /* Literal.Number.Oct */
.highlight .sa { color: #e6db74 } /* Literal.String.Affix */
.highlight .sb { color: #e6db74 } /* Literal.String.Backtick */
.highlight .sc { color: #e6db74 } /* Literal.String.Char */
.highlight .dl { color: #e6db74 } /* Literal.String.Delimiter */
.highlight .sd { color: #e6db74 } /* Literal.String.Doc */
.highlight .s2 { color: #e6db74 } /* Literal.String.Double */
.highlight .se { color: #ae81ff } /* Literal.String.Escape */
.highlight .sh { color: #e6db74 } /* Literal.String.Heredoc */
.highlight .si { color: #e6db74 } /* Literal.String.Interpol */
.highlight .sx { color: #e6db74 } /* Literal.String.Other */
.highlight .sr { color: #e6db74 } /* Literal.String.Regex */
.highlight .s1 { color: #e6db74 } /* Literal.String.Single */
.highlight .ss { color: #e6db74 } /* Literal.String.Symbol */
.highlight .bp { color: #f8f8f2 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #a6e22e } /* Name.Function.Magic */
.highlight .vc { color: #f8f8f2 } /* Name.Variable.Class */
.highlight .vg { color: #f8f8f2 } /* Name.Variable.Global */
.highlight .vi { color: #f8f8f2 } /* Name.Variable.Instance */
.highlight .vm { color: #f8f8f2 } /* Name.Variable.Magic */
.highlight .il { color: #ae81ff } /* Literal.Number.Integer.Long */
}
@media (prefers-color-scheme: light) {
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
}
package org.onap.config.api;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.util.Collection;
import java.util.Map;
import java.util.ServiceLoader;

/**
 * The interface Configuration manager.
 */
public interface ConfigurationManager extends Configuration {

  /**
   * The constant config.
   */
  public static fi
/*
 * Copyright © 2016-2018 European Support Limited
 *
 * 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.onap.config.impl;

import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.configuration2.CombinedConfiguration;
import org.apache.commons.configuration2.CompositeConfiguration;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.FileBasedConfiguration;
import org.apache.commons.configuration2.builder.BasicConfigurationBuilder;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.onap.config.ConfigurationUtils;
import org.onap.config.Constants;

/**
 * The type Configuration repository.
 */
public final class ConfigurationRepository {

  /**
   * The Repo.
   */
  static ConfigurationRepository repo;
  private static Set<String> validCallers = Collections.unmodifiableSet(new HashSet<>(Arrays
      .asList(ConfigurationChangeNotifier.NotificationData.class.getName(),
          ConfigurationUtils.class.getName(), CliConfigurationImpl.class.getName(),
          ConfigurationChangeNotifier.class.getName(),
          ConfigurationImpl.class.getName())));

  static {
    repo = new ConfigurationRepository();
  }

  private boolean dbAccessible = true;
  private Set<String> tenants = new HashSet<>();
  private Set<String> namespaces = new HashSet<>();
  private LinkedHashMap<String, ConfigurationHolder> store =
      new LinkedHashMap<String, ConfigurationHolder>(16, 0.75f, true) {
        @Override
        protected boolean removeEldestEntry(Map.Entry eldest) {
          try {
            return size() > getConfigurationFor(Constants.DEFAULT_TENANT, Constants.DB_NAMESPACE)
                .getInt("config.size.max");
          } catch (Exception exception) {
            return false;
          }
        }
      };

  private ConfigurationRepository() {
    if (repo != null) {
      throw new RuntimeException("Illegal access to configuration.");
    }
    tenants.add(Constants.DEFAULT_TENANT);
    namespaces.add(Constants.DEFAULT_NAMESPACE);
  }

  /**
   * Lookup configuration repository.
   *
   * @return the configuration repository
   */
  public static ConfigurationRepository lookup() {
    if (validCallers.contains(Thread.currentThread().getStackTrace()[2].getClassName())) {
      return repo;
    }
    return null;
  }

  /**
   * Gets tenants.
   *
   * @return the tenants
   */
  public Set<String> getTenants() {
    return tenants;
  }

  /**
   * Gets namespaces.
   *
   * @return the namespaces
   */
  public Set<String> getNamespaces() {
    return namespaces;
  }

  private void populateTenantsNamespace(String key, boolean sourcedFromDb) {
    String[] array = key.split(Constants.KEY_ELEMENTS_DELEMETER);
    if (!array[1].equalsIgnoreCase(Constants.DB_NAMESPACE)) {
      if (!sourcedFromDb) {
        dbAccessible = false;
      }
      tenants.add(array[0]);
      namespaces.add(array[1]);
    }
  }

  /**
   * Init tenants and namespaces.
   */
  public void initTenantsAndNamespaces() {
    // nothing to do here, left for backward compatibility
  }

  /**
   * Is valid tenant boolean.
   *
   * @param tenant the tenant
   * @return the boolean
   */
  public boolean isValidTenant(String tenant) {
    return tenant != null && tenants.contains(tenant.toUpperCase());
  }

  /**
   * Is valid namespace boolean.
   *
   * @param namespace the namespace
   * @return the boolean
   */
  public boolean isValidNamespace(String namespace) {
    return namespace != null && namespaces.contains(namespace.toUpperCase());
  }

  /**
   * Gets configuration for.
   *
   * @param tenant    the tenant
   * @param namespace the namespace
   * @return the configuration for
   * @throws Exception the exception
   */
  public Configuration getConfigurationFor(String tenant, String namespace) throws Exception {
    ConfigurationHolder config;
    String module = tenant + Constants.KEY_ELEMENTS_DELEMETER + namespace;
    config = store.get(module);
    if (config == null) {
      config = new ConfigurationHolder(new BasicConfigurationBuilder<>(AgglomerateConfiguration.class));
      store.put(module, config);
    }
    return config.getConfiguration(tenant + Constants.KEY_ELEMENTS_DELEMETER + namespace);
  }

  /**
   * Populate configurtaion.
   *
   * @param key     the key
   * @param builder the builder
   */
  public void populateConfigurtaion(String key, Configuration builder) {
    store.put(key, new ConfigurationHolder(builder));
    populateTenantsNamespace(key, false);
  }

  /**
   * Populate override configurtaion.
   *
   * @param key  the key
   * @param file the file
   * @throws Exception the exception
   */
  public void populateOverrideConfigurtaion(String key, File file) {
    ConfigurationHolder holder = store.get(key);
    if (holder == null) {
        holder = new ConfigurationHolder(new CombinedConfiguration());
      store.put(key, holder);
    }
    holder.addOverrideConfiguration(file.getAbsolutePath(),
        ConfigurationUtils.getConfigurationBuilder(file, true));
    populateTenantsNamespace(key, true);
  }

  /**
   * Refresh override configurtaion for.
   *
   * @param key   the key
   * @param index the index
   * @throws Exception the exception
   */
  public void refreshOverrideConfigurtaionFor(String key, int index) {
    ConfigurationHolder holder = store.get(key);
    if (holder != null) {
      holder.refreshOverrideConfiguration(index);
    }
  }

  /**
   * Remove override configurtaion.
   *
   * @param file the file
   * @throws Exception the exception
   */
  public void removeOverrideConfigurtaion(File file) throws Exception {
    Iterator<String> iterator = new ArrayList(store.keySet()).iterator();
    while (iterator.hasNext()) {
      ConfigurationHolder holder = store.get(iterator.next());
      if (holder.containsOverrideConfiguration(file.getAbsolutePath())) {
        holder.removeOverrideConfiguration(file.getAbsolutePath());
      }
    }

  }

  private class ConfigurationHolder {

    /**
     * The Builder.
     */
    BasicConfigurationBuilder<Configuration> builder;
    /**
     * The Last configuration build time.
     */
    Timestamp lastConfigurationBuildTime;
    /**
     * The Config.
     */
    Configuration config;
    /**
     * The Composite.
     */
    Configuration composite;
    /**
     * The Last config change timestamp.
     */
    Timestamp lastConfigChangeTimestamp;
    private Map<String, FileBasedConfigurationBuilder<FileBasedConfiguration>>
        overrideConfiguration = new LinkedHashMap<>();


    /**
     * Instantiates a new Configuration holder.
     *
     * @param builder the builder
     */
    public ConfigurationHolder(BasicConfigurationBuilder builder) {
      this.builder = builder;
    }

    /**
     * Instantiates a new Configuration holder.
     *
     * @param builder the builder
     */
    public ConfigurationHolder(Configuration builder) {
      this.config = builder;
    }

    /**
     * Refresh override configuration.
     *
     * @param index the index
     */
    public void refreshOverrideConfiguration(int index) {
      int count = -1;
      for (FileBasedConfigurationBuilder overrides : overrideConfiguration.values()) {
        try {
          if (++count == index) {
            overrides.save();
            overrides.resetResult();
          }
        } catch (ConfigurationException exception) {
          //do nothing
        }
      }
    }

    /**
     * Add override configuration.
     *
     * @param path    the path
     * @param builder the builder
     */
    public void addOverrideConfiguration(String path,
                                     BasicConfigurationBuilder<FileBasedConfiguration> builder) {
      overrideConfiguration.put(path.toUpperCase(), (FileBasedConfigurationBuilder) builder);
      getEffectiveConfiguration(config, overrideConfiguration.values());
    }

    /**
     * Remove override configuration.
     *
     * @param path the path
     */
    public void removeOverrideConfiguration(String path) {
      overrideConfiguration.remove(path.toUpperCase());
      getEffectiveConfiguration(config, overrideConfiguration.values());
    }

    /**
     * Contains override configuration boolean.
     *
     * @param path the path
     * @return the boolean
     */
    public boolean containsOverrideConfiguration(String path) {
      return overrideConfiguration.containsKey(path.toUpperCase());
    }

    /**
     * Gets configuration.
     *
     * @param namespace the namespace
     * @return the configuration
     * @throws Exception the exception
     */
    public Configuration getConfiguration(String namespace) throws Exception {
      if (config == null) {
        config = builder.getConfiguration();
        lastConfigurationBuildTime = new Timestamp(System.currentTimeMillis());
      } else if (lastConfigurationBuildTime != null
          && System.currentTimeMillis() - lastConfigurationBuildTime.getTime()
          > getConfigurationFor(Constants.DEFAULT_TENANT, Constants.DB_NAMESPACE)
                  .getInt("config.refresh.interval")) {
        Timestamp temp = getLastUpdateTimestampFor(namespace);
        if ((temp != null)
            && (lastConfigChangeTimestamp == null
            || temp.getTime() > lastConfigChangeTimestamp.getTime())) {
          builder.resetResult();
          config = builder.getConfiguration();
          lastConfigChangeTimestamp = temp;
          getEffectiveConfiguration(config, overrideConfiguration.values());
        }
        lastConfigurationBuildTime = new Timestamp(System.currentTimeMillis());
      }
      if (composite == null && overrideConfiguration.size() != 0) {
        composite = getEffectiveConfiguration(config, overrideConfiguration.values());
      }
      return overrideConfiguration.size() == 0 ? config : composite;
    }

    private Configuration getEffectiveConfiguration(Configuration configuration,
                    Collection<FileBasedConfigurationBuilder<FileBasedConfiguration>> list) {
      try {
        CompositeConfiguration cc = new CompositeConfiguration();
        for (FileBasedConfigurationBuilder<FileBasedConfiguration> b : list) {
          cc.addConfiguration(b.getConfiguration());
        }
        cc.addConfiguration(configuration);
        composite = cc;
        return composite;
      } catch (Exception exception) {
        return null;
      }
    }

    /**
     * Gets last update timestamp for.
     *
     * @param namespace the namespace
     * @return the last update timestamp for
     */
    public Timestamp getLastUpdateTimestampFor(String namespace) {
      return null;
    }


  }

  public boolean isDBAccessible(){
    return dbAccessible;
  }


}