index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius/persisted2/ScopePredicate.java
package com.netflix.archaius.persisted2; import java.util.Map; import java.util.Set; /** * Predicate for excluding properties that are no in scope * * @author elandau * */ public interface ScopePredicate { public boolean evaluate(Map<String, Set<String>> attrs); }
9,200
0
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius/persisted2/ScopedValueResolver.java
package com.netflix.archaius.persisted2; import java.util.List; /** * Contract for resolving a list of ScopesValues into a single value. * * @author elandau * */ public interface ScopedValueResolver { String resolve(String propName, List<ScopedValue> variations); }
9,201
0
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius/persisted2/Persisted2ConfigProvider.java
package com.netflix.archaius.persisted2; import java.net.URL; import java.net.URLEncoder; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Provider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.archaius.api.Config; import com.netflix.archaius.config.EmptyConfig; import com.netflix.archaius.config.PollingDynamicConfig; import com.netflix.archaius.config.polling.FixedPollingStrategy; import com.netflix.archaius.instrumentation.AccessMonitorUtil; import com.netflix.archaius.persisted2.loader.HTTPStreamLoader; /** * Provider that sets up a Config that is a client to a Persisted2 service. * Once injected the Config will poll the service for updated on a configurable * interval. Note that injection of this Config will block until the first * set of properties has been fetched from teh remote service. * * The provider must be bound to a specific config layer within the override * hierarchy. * * For example, Persisted2Config may boudn to the OverrideLayer like this, * <pre> * final Persisted2ClientConfig config = new DefaultPersisted2ClientConfig() * .withServiceUrl("http://persiste2serviceurl") * .withQueryScope("env", "test") * .withQueryScope("region", "us-east-1") * .withScope("env", "test") * .withScope("region", "us-east-1") * .withScope("asg", "app-v0001") * .withPrioritizedScopes("env", "region", "stack", "serverId"); * * Guice.createInjector( * Modules * .override(new ArchaiusModule()) * .with(new AbstractModule() { * @Override * protected void configure() { * bind(Persisted2ClientConfig.class).toInstance(config); * bind(Config.class).annotatedWith(OverrideLayer.class).toProvider(Persisted2ConfigProvider.class).in(Scopes.SINGLETON); * } * }) * ) * </pre> * * @author elandau * */ public class Persisted2ConfigProvider implements Provider<Config> { private final Logger LOG = LoggerFactory.getLogger(Persisted2ConfigProvider.class); private final Provider<Persisted2ClientConfig> config; private final Optional<AccessMonitorUtil> accessMonitorUtilOptional; private volatile PollingDynamicConfig dynamicConfig; @Inject public Persisted2ConfigProvider( Provider<Persisted2ClientConfig> config, Optional<AccessMonitorUtil> accessMonitorUtilOptional) throws Exception { this.config = config; this.accessMonitorUtilOptional = accessMonitorUtilOptional; } public static String getFilterString(Map<String, Set<String>> scopes) { StringBuilder sb = new StringBuilder(); for (Entry<String, Set<String>> scope : scopes.entrySet()) { if (scope.getValue().isEmpty()) continue; if (sb.length() > 0) { sb.append(" and "); } sb.append("("); boolean first = true; for (String value : scope.getValue()) { if (!first) { sb.append(" or "); } else { first = false; } sb.append(scope.getKey()); if (null == value) { sb.append(" is null"); } else if (value.isEmpty()) { sb.append("=''"); } else { sb.append("='").append(value).append("'"); } } sb.append(")"); } return sb.toString(); } @Override public Config get() { try { Persisted2ClientConfig clientConfig = config.get(); LOG.info("Remote config : " + clientConfig); String url = new StringBuilder() .append(clientConfig.getServiceUrl()) .append("?skipPropsWithExtraScopes=").append(clientConfig.getSkipPropsWithExtraScopes()) .append("&filter=").append(URLEncoder.encode(getFilterString(clientConfig.getQueryScopes()), "UTF-8")) .toString(); if (!clientConfig.isEnabled()) { return EmptyConfig.INSTANCE; } JsonPersistedV2Reader reader = JsonPersistedV2Reader.builder(new HTTPStreamLoader(new URL(url))) .withPath("propertiesList") .withScopes(clientConfig.getPrioritizedScopes()) .withPredicate(ScopePredicates.fromMap(clientConfig.getScopes())) // If instrumentation flushing is enabled, we need to read the id fields as well to uniquely // identify the property being used. .withReadIdField(accessMonitorUtilOptional.isPresent()) .build(); dynamicConfig = new PollingDynamicConfig( reader, new FixedPollingStrategy(clientConfig.getRefreshRate(), TimeUnit.SECONDS), accessMonitorUtilOptional.orElse(null)); return dynamicConfig; } catch (Exception e1) { throw new RuntimeException(e1); } } @PreDestroy public void shutdown() { if (dynamicConfig != null) { dynamicConfig.shutdown(); } } }
9,202
0
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius/persisted2/JsonPersistedV2Reader.java
package com.netflix.archaius.persisted2; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Callable; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.archaius.config.polling.PollingResponse; /** * Reader for Netflix persisted properties (not yet available in OSS). * * Properties are read as a single JSON blob that contains a full list of properties. * Multiple property values may exist for different scopes and are resolved into * a single property value using a ProperyValueResolver. * * Example, * * <pre> * {@code * JsonPersistedV2Reader reader = * JsonPersistedV2Reader.builder(new HTTPStreamLoader(url)) // url from which config is fetched * .withPredicate(ScopePredicates.fromMap(instanceScopes)) // Map of scope values for the running instance * .build(); * * appConfig.addConfigFirst(new PollingDynamicConfig("dyn", reader, new FixedPollingStrategy(30, TimeUnit.SECONDS))); * * } * </pre> * * @author elandau * */ public class JsonPersistedV2Reader implements Callable<PollingResponse> { private static final Logger LOG = LoggerFactory.getLogger(JsonPersistedV2Reader.class); private final static List<String> DEFAULT_ORDERED_SCOPES = Arrays.asList("serverId", "asg", "ami", "cluster", "appId", "env", "countries", "stack", "zone", "region"); private final static String DEFAULT_KEY_FIELD = "key"; private final static String DEFAULT_VALUE_FIELD = "value"; private final static String DEFAULT_ID_FIELD = "propertyId"; private final static List<String> DEFAULT_PATH = Arrays.asList("persistedproperties", "properties", "property"); public static class Builder { private final Callable<InputStream> reader; private List<String> path = DEFAULT_PATH; private List<String> scopeFields = DEFAULT_ORDERED_SCOPES; private String keyField = DEFAULT_KEY_FIELD; private String valueField = DEFAULT_VALUE_FIELD; private String idField = DEFAULT_ID_FIELD; private ScopePredicate predicate = ScopePredicates.alwaysTrue(); private ScopedValueResolver resolver = new ScopePriorityPropertyValueResolver(); private boolean readIdField = false; public Builder(Callable<InputStream> reader) { this.reader = reader; } public Builder withPath(String path) { return withPath(Arrays.asList(StringUtils.split(path, "/"))); } public Builder withPath(List<String> path) { List<String> copy = new ArrayList<String>(); copy.addAll(path); this.path = Collections.unmodifiableList(copy); return this; } public Builder withScopes(List<String> scopes) { this.scopeFields = scopes; return this; } public Builder withPredicate(ScopePredicate predicate) { this.predicate = predicate; return this; } public Builder withKeyField(String keyField) { this.keyField = keyField; return this; } public Builder withValueField(String valueField) { this.valueField = valueField; return this; } public Builder withIdField(String idField) { this.idField = idField; return this; } public Builder withValueResolver(ScopedValueResolver resolver) { this.resolver = resolver; return this; } public Builder withReadIdField(boolean readIdField) { this.readIdField = readIdField; return this; } public JsonPersistedV2Reader build() { return new JsonPersistedV2Reader(this); } } public static Builder builder(Callable<InputStream> reader) { return new Builder(reader); } private final Callable<InputStream> reader; private final ScopePredicate predicate; private final ScopedValueResolver valueResolver; private final ObjectMapper mapper = new ObjectMapper(); private final List<String> scopeFields; private final String keyField; private final String idField; private final String valueField; private final List<String> path; private final boolean readIdField; private JsonPersistedV2Reader(Builder builder) { this.reader = builder.reader; this.predicate = builder.predicate; this.valueResolver = builder.resolver; this.keyField = builder.keyField; this.valueField = builder.valueField; this.idField = builder.idField; this.scopeFields = builder.scopeFields; this.path = builder.path; this.readIdField = builder.readIdField; } @Override public PollingResponse call() throws Exception { Map<String, List<ScopedValue>> props = new HashMap<String, List<ScopedValue>>(); Map<String, List<ScopedValue>> propIds = new HashMap<>(); InputStream is = reader.call(); if (is == null) { return PollingResponse.noop(); } try { JsonNode node = mapper.readTree(is); for (String part : this.path) { node = node.path(part); } for (final JsonNode property : node) { String key = null; try { key = property.get(keyField).asText(); String value = property.has(valueField) ? property.get(valueField).asText() : ""; LinkedHashMap<String, Set<String>> scopes = new LinkedHashMap<String, Set<String>>(); for (String scope : this.scopeFields) { String[] values = StringUtils.splitByWholeSeparator(property.has(scope) ? property.get(scope).asText().toLowerCase() : "", ","); scopes.put(scope, values.length == 0 ? Collections.<String>emptySet() : immutableSetFrom(values)); } // Filter out scopes that don't match at all if (!this.predicate.evaluate(scopes)) { continue; } // Build up a list of valid scopes List<ScopedValue> variations = props.get(key); if (variations == null) { variations = new ArrayList<ScopedValue>(); props.put(key, variations); } variations.add(new ScopedValue(value, scopes)); if (readIdField) { propIds.putIfAbsent(key, new ArrayList<>()); propIds.get(key).add( new ScopedValue(property.has(idField) ? property.get(idField).asText() : "", scopes)); } } catch (Exception e) { LOG.warn("Unable to process property '{}'", key); } } } finally { try { is.close(); } catch (Exception e) { // OK to ignore } } // Resolve to a single property value final Map<String, String> result = new HashMap<String, String>(); for (Entry<String, List<ScopedValue>> entry : props.entrySet()) { result.put(entry.getKey(), valueResolver.resolve(entry.getKey(), entry.getValue())); } if (readIdField) { final Map<String, String> idResult = new HashMap<>(); for (Entry<String, List<ScopedValue>> entry : propIds.entrySet()) { idResult.put(entry.getKey(), valueResolver.resolve(entry.getKey(), entry.getValue())); } return PollingResponse.forSnapshot(result, idResult); } return PollingResponse.forSnapshot(result); } private static Set<String> immutableSetFrom(String[] values) { if (values.length == 0) { return Collections.<String>emptySet(); } else { HashSet<String> set = new HashSet<String>(); set.addAll(Arrays.asList(values)); return Collections.unmodifiableSet(set); } } }
9,203
0
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius/persisted2/ScopedValue.java
package com.netflix.archaius.persisted2; import java.util.LinkedHashMap; import java.util.Set; /** * Encapsulate a single property value and its scopes. * * @author elandau */ public class ScopedValue { private final String value; private final LinkedHashMap<String, Set<String>> scopes; public ScopedValue(String value, LinkedHashMap<String, Set<String>> scopes) { this.value = value; this.scopes = scopes; } public String getValue() { return value; } public LinkedHashMap<String, Set<String>> getScopes() { return scopes; } }
9,204
0
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius/persisted2/DefaultPersisted2ClientConfig.java
package com.netflix.archaius.persisted2; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class DefaultPersisted2ClientConfig implements Persisted2ClientConfig { private int refreshRate = 30; private List<String> prioritizedScopes = new ArrayList<>(); private Map<String, Set<String>> queryScopes = new HashMap<>(); private String serviceUrl; private Map<String, String> scopes = new HashMap<>(); private boolean skipPropsWithExtraScopes = false; private boolean isEnabled = true; private boolean instrumentationEnabled = false; public DefaultPersisted2ClientConfig withRefreshRate(int refreshRate) { this.refreshRate = refreshRate; return this; } @Override public int getRefreshRate() { return refreshRate; } public DefaultPersisted2ClientConfig withPrioritizedScopes(List<String> scopes) { this.prioritizedScopes = scopes; return this; } public DefaultPersisted2ClientConfig withPrioritizedScopes(String ... scopes) { this.prioritizedScopes = Arrays.asList(scopes); return this; } @Override public List<String> getPrioritizedScopes() { return this.prioritizedScopes; } public DefaultPersisted2ClientConfig withScope(String name, String value) { this.scopes.put(name, value); return this; } @Override public Map<String, String> getScopes() { return scopes; } public DefaultPersisted2ClientConfig withQueryScope(String name, String ... values) { Set<String> unique = new HashSet<>(); unique.addAll(Arrays.asList(values)); queryScopes.put(name, unique); return this; } @Override public Map<String, Set<String>> getQueryScopes() { return queryScopes; } public DefaultPersisted2ClientConfig withServiceUrl(String url) { this.serviceUrl = url; return this; } @Override public String getServiceUrl() { return this.serviceUrl; } public DefaultPersisted2ClientConfig withSkipPropsWithExtraScopes(boolean value) { this.skipPropsWithExtraScopes = value; return this; } @Override public boolean getSkipPropsWithExtraScopes() { return skipPropsWithExtraScopes; } public DefaultPersisted2ClientConfig setEnabled(boolean value) { this.isEnabled = value; return this; } @Override public boolean isEnabled() { return isEnabled; } @Override public String toString() { return new StringBuilder() .append("DefaultPersisted2ClientConfig[") .append("url=" + serviceUrl) .append(" scopes=" + scopes) .append(" priority=" + prioritizedScopes) .append(" queryScopes=" + queryScopes) .append(" enabled=" + isEnabled) .append("]") .toString(); } }
9,205
0
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius/persisted2/AbstractScopePredicate.java
package com.netflix.archaius.persisted2; import java.util.Map; import java.util.Set; import java.util.Map.Entry; public abstract class AbstractScopePredicate implements ScopePredicate { @Override public boolean evaluate(Map<String, Set<String>> scopes) { for (Entry<String, Set<String>> scope : scopes.entrySet()) { // TODO: split into list if (!scope.getValue().isEmpty() && !scope.getValue().contains(getScope(scope.getKey()).toLowerCase())) { return false; } } return true; } protected abstract String getScope(String key); }
9,206
0
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius/persisted2/ScopePriorityPropertyValueResolver.java
package com.netflix.archaius.persisted2; import java.util.Iterator; import java.util.List; import java.util.Set; /** * PropertyValueResolver that picks the first PropervyValue that has a higher * scope value. * * Each PropertyValue is assumed to have the same number of scopes and scopes are * assumed to be in the same index location for all PropervyValue instances. * A PropertyValue should not contain different scope values since those would * have been filtered out by the predicate (see JsonPersistedV2Poller) and all properties * for an instance can only match one scope value. Any deviation from the above * assumptions will result either in NoSuchElementException or undefined behavior. * * For example, * * value1 : cluster="", app="foo" * value2 : cluster="foo-1", app="foo" * * The resolver will choose value2 since cluster is a higher scope and value2 has * a value for it. * * @author elandau */ public class ScopePriorityPropertyValueResolver implements ScopedValueResolver { @Override public String resolve(String propName, List<ScopedValue> scopesValues) { // Select the first as the starting candidate Iterator<ScopedValue> iter = scopesValues.iterator(); ScopedValue p1 = iter.next(); // For each subsequent variation while (iter.hasNext()) { ScopedValue p2 = iter.next(); Iterator<Set<String>> s1 = p1.getScopes().values().iterator(); Iterator<Set<String>> s2 = p2.getScopes().values().iterator(); // Iterate through scopes in priority order while (s1.hasNext()) { Set<String> v1 = s1.next(); Set<String> v2 = s2.next(); if (v1.isEmpty() && !v2.isEmpty()) { p1 = p2; break; } else if (!v1.isEmpty() && v2.isEmpty()) { break; } // Continue as long as no scope yet or both have scopes } } return p1.getValue(); } }
9,207
0
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius/persisted2
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius/persisted2/loader/HTTPStreamLoader.java
package com.netflix.archaius.persisted2.loader; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.concurrent.Callable; import java.util.zip.GZIPInputStream; public class HTTPStreamLoader implements Callable<InputStream> { private String lastEtag; private final URL url; public HTTPStreamLoader(URL url) { this.url = url; } @Override public InputStream call() throws Exception { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(6000); conn.setReadTimeout(10000); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Accept-Encoding", "gzip"); if (lastEtag != null) { conn.setRequestProperty("If-None-Match", lastEtag); } conn.connect(); // force a connection to test if the URL is reachable final int status = conn.getResponseCode(); if (status == 200) { lastEtag = conn.getHeaderField("ETag"); InputStream input = conn.getInputStream(); if ("gzip".equals(conn.getContentEncoding())) { input = new GZIPInputStream(input); } return input; } else if (status == 304) { // It is expected the reader will treat this as a noop response return null; } else { throw new RuntimeException("Failed to read input " + conn.getResponseCode()); } } }
9,208
0
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius/persisted2
Create_ds/archaius/archaius2-persisted2/src/main/java/com/netflix/archaius/persisted2/loader/FileStreamLoader.java
package com.netflix.archaius.persisted2.loader; import java.io.FileInputStream; import java.io.InputStream; import java.util.concurrent.Callable; public class FileStreamLoader implements Callable<InputStream>{ private String filename; public FileStreamLoader(String filename) { this.filename = filename; } @Override public InputStream call() throws Exception { return new FileInputStream(filename); } }
9,209
0
Create_ds/archaius/archaius2-typesafe/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-typesafe/src/test/java/com/netflix/archaius/typesafe/TypesafeConfigTest.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.typesafe; import com.netflix.archaius.api.Config; import com.netflix.archaius.test.ConfigInterfaceTest; import com.typesafe.config.ConfigFactory; import org.junit.Assert; import org.junit.Test; import com.netflix.archaius.config.MapConfig; import com.netflix.archaius.api.exceptions.ConfigException; import java.util.Iterator; import java.util.Map; public class TypesafeConfigTest extends ConfigInterfaceTest { @Test public void simple() throws ConfigException { Config config = new TypesafeConfig(ConfigFactory.parseString("a=b")); Assert.assertEquals("b", config.getString("a")); Assert.assertTrue(config.containsKey("a")); } @Test public void simplePath() throws ConfigException { Config config = new TypesafeConfig(ConfigFactory.parseString("a.b.c=foo")); Assert.assertEquals("foo", config.getString("a.b.c")); Assert.assertTrue(config.containsKey("a.b.c")); } @Test public void nested() throws ConfigException { Config config = new TypesafeConfig(ConfigFactory.parseString("a { b { c=foo } }")); Assert.assertEquals("foo", config.getString("a.b.c")); Assert.assertTrue(config.containsKey("a.b.c")); } @Test public void keyWithAt() throws ConfigException { Config config = new TypesafeConfig(ConfigFactory.parseString("\"@a\"=b")); Assert.assertEquals("b", config.getString("@a")); Assert.assertTrue(config.containsKey("@a")); } @Test public void pathWithAt() throws ConfigException { Config config = new TypesafeConfig(ConfigFactory.parseString("a.\"@b\".c=foo")); Assert.assertEquals("foo", config.getString("a.@b.c")); Assert.assertTrue(config.containsKey("a.@b.c")); } @Test public void specialChars() throws ConfigException { for (char c = '!'; c <= '~'; ++c) { if (c == '.') continue; String k = c + "a"; String escaped = k.replace("\\", "\\\\").replace("\"", "\\\""); Config mc = MapConfig.builder().put(k, "b").build(); Config tc = new TypesafeConfig(ConfigFactory.parseString("\"" + escaped + "\"=b")); Assert.assertEquals(mc.getString(k), tc.getString(k)); Assert.assertEquals(mc.containsKey(k), tc.containsKey(k)); } } @Test public void iterate() throws Exception { Config config = new TypesafeConfig(ConfigFactory.parseString("a { \"@env\"=prod }")); Assert.assertEquals("prod", config.getString("a.@env")); // Make sure we can get all keys we get back from the iterator Iterator<String> ks = config.getKeys(); while (ks.hasNext()) { String k = ks.next(); config.getString(k); } } @Override protected Config getInstance(Map<String, String> properties) { return new TypesafeConfig(ConfigFactory.parseMap(properties)); } }
9,210
0
Create_ds/archaius/archaius2-typesafe/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-typesafe/src/test/java/com/netflix/archaius/typesafe/TypesafeConfigLoaderTest.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.typesafe; import com.netflix.archaius.config.DefaultCompositeConfig; import org.junit.Assert; import org.junit.Test; import com.netflix.archaius.DefaultConfigLoader; import com.netflix.archaius.cascade.ConcatCascadeStrategy; import com.netflix.archaius.api.config.CompositeConfig; import com.netflix.archaius.config.MapConfig; import com.netflix.archaius.api.exceptions.ConfigException; public class TypesafeConfigLoaderTest { @Test public void test() throws ConfigException { CompositeConfig config = new DefaultCompositeConfig(); config.addConfig("prop", MapConfig.builder() .put("env", "prod") .put("region", "us-east") .build()); DefaultConfigLoader loader = DefaultConfigLoader.builder() .withConfigReader(new TypesafeConfigReader()) .withStrLookup(config) .build(); config.replaceConfig("foo", loader.newLoader() .withCascadeStrategy(ConcatCascadeStrategy.from("${env}", "${region}")) .load("foo")); Assert.assertEquals("prod", config.getString("@environment")); Assert.assertEquals("foo-prod", config.getString("foo.prop1")); Assert.assertEquals("foo", config.getString("foo.prop2")); } }
9,211
0
Create_ds/archaius/archaius2-typesafe/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-typesafe/src/main/java/com/netflix/archaius/typesafe/TypesafeConfigReader.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.typesafe; import java.net.URL; import com.netflix.archaius.api.ConfigReader; import com.netflix.archaius.api.StrInterpolator; import com.netflix.archaius.api.exceptions.ConfigException; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigParseOptions; public class TypesafeConfigReader implements ConfigReader { @Override public com.netflix.archaius.api.Config load(ClassLoader loader, String resourceName, StrInterpolator strInterpolator, StrInterpolator.Lookup lookup) throws ConfigException { Config config = ConfigFactory.parseResourcesAnySyntax(loader, resourceName); return new TypesafeConfig(config); } @Override public com.netflix.archaius.api.Config load(ClassLoader loader, URL url, StrInterpolator strInterpolator, StrInterpolator.Lookup lookup) throws ConfigException { Config config = ConfigFactory.parseURL(url, ConfigParseOptions.defaults().setClassLoader(loader)); return new TypesafeConfig(config); } @Override public boolean canLoad(ClassLoader loader, String name) { return true; } @Override public boolean canLoad(ClassLoader loader, URL uri) { return true; } }
9,212
0
Create_ds/archaius/archaius2-typesafe/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-typesafe/src/main/java/com/netflix/archaius/typesafe/TypesafeConfig.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.typesafe; import com.netflix.archaius.config.AbstractConfig; import com.typesafe.config.Config; import com.typesafe.config.ConfigException; import com.typesafe.config.ConfigUtil; import com.typesafe.config.ConfigValue; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; public class TypesafeConfig extends AbstractConfig { private final Config config; public TypesafeConfig(Config config) { this.config = config; } @Override public boolean containsKey(String key) { return config.hasPath(quoteKey(key)); } @Override public boolean isEmpty() { return config.isEmpty(); } @Override public Object getRawProperty(String key) { // TODO: Handle lists try { return config.getValue(quoteKey(key)).unwrapped().toString(); } catch (ConfigException.Missing ex) { return null; } } @Override public List getList(String key) { throw new UnsupportedOperationException("Not supported yet"); } private String quoteKey(String key) { final String[] path = key.split("\\."); return ConfigUtil.joinPath(path); } private String unquoteKey(String key) { final List<String> path = ConfigUtil.splitPath(key); StringBuilder buf = new StringBuilder(); buf.append(path.get(0)); for (String p : path.subList(1, path.size())) { buf.append('.').append(p); } return buf.toString(); } @Override public Iterator<String> getKeys() { return new Iterator<String>() { Iterator<Entry<String, ConfigValue>> iter = config.entrySet().iterator(); @Override public boolean hasNext() { return iter.hasNext(); } @Override public String next() { return unquoteKey(iter.next().getKey()); } @Override public void remove() { iter.remove(); } }; } }
9,213
0
Create_ds/archaius/archaius2-guice/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-guice/src/test/java/com/netflix/archaius/guice/ProxyTest.java
package com.netflix.archaius.guice; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provides; import com.google.inject.ProvisionException; import com.netflix.archaius.ConfigProxyFactory; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.ConfigurationSource; import com.netflix.archaius.api.annotations.DefaultValue; import com.netflix.archaius.api.config.SettableConfig; import com.netflix.archaius.api.exceptions.ConfigException; import com.netflix.archaius.api.inject.RuntimeLayer; import com.netflix.archaius.config.MapConfig; import com.netflix.archaius.guice.ArchaiusModuleTest.MyCascadingStrategy; import com.netflix.archaius.visitor.PrintStreamVisitor; import org.junit.Assert; import org.junit.Test; import javax.inject.Singleton; public class ProxyTest { public static interface MyConfig { @DefaultValue("0") int getInteger(); String getString(); MySubConfig getSubConfig(); default String getDefault() { return getInteger() + "-" + getString(); } } public static interface MySubConfig { @DefaultValue("0") int getInteger(); } @Configuration(prefix="foo") public static interface MyConfigWithPrefix { @DefaultValue("0") int getInteger(); String getString(); } @Test public void testConfigWithNoPrefix() throws ConfigException { Injector injector = Guice.createInjector( new ArchaiusModule() { @Override protected void configureArchaius() { this.bindApplicationConfigurationOverride().toInstance(MapConfig.builder() .put("integer", 1) .put("string", "bar") .put("subConfig.integer", 2) .build()); } @Provides @Singleton public MyConfig getMyConfig(ConfigProxyFactory factory) { return factory.newProxy(MyConfig.class); } } ); SettableConfig cfg = injector.getInstance(Key.get(SettableConfig.class, RuntimeLayer.class)); MyConfig config = injector.getInstance(MyConfig.class); Assert.assertEquals("bar", config.getString()); Assert.assertEquals(1, config.getInteger()); Assert.assertEquals(2, config.getSubConfig().getInteger()); Assert.assertEquals("1-bar", config.getDefault()); cfg.setProperty("subConfig.integer", 3); Assert.assertEquals(3, config.getSubConfig().getInteger()); } @Test public void testConfigWithProvidedPrefix() throws ConfigException { Injector injector = Guice.createInjector( new ArchaiusModule() { @Override protected void configureArchaius() { this.bindApplicationConfigurationOverride().toInstance(MapConfig.builder() .put("prefix.integer", 1) .put("prefix.string", "bar") .build()); } @Provides @Singleton public MyConfig getMyConfig(ConfigProxyFactory factory) { return factory.newProxy(MyConfig.class, "prefix"); } }); MyConfig config = injector.getInstance(MyConfig.class); Assert.assertEquals("bar", config.getString()); Assert.assertEquals(1, config.getInteger()); } @Configuration(prefix="prefix-${env}", allowFields=true) @ConfigurationSource(value={"moduleTest"}, cascading=MyCascadingStrategy.class) public interface ModuleTestConfig { Boolean isLoaded(); String getProp1(); } @Test public void confirmConfigurationSourceWorksWithProxy() { Injector injector = Guice.createInjector( new ArchaiusModule() { @Provides @Singleton public ModuleTestConfig getMyConfig(ConfigProxyFactory factory) { return factory.newProxy(ModuleTestConfig.class, "moduleTest"); } }); ModuleTestConfig config = injector.getInstance(ModuleTestConfig.class); Assert.assertTrue(config.isLoaded()); Assert.assertEquals("fromFile", config.getProp1()); injector.getInstance(Config.class).accept(new PrintStreamVisitor()); } public static interface DefaultMethodWithAnnotation { @DefaultValue("fromAnnotation") default String getValue() { return "fromDefault"; } } @Test public void annotationAndDefaultImplementationNotAllowed() throws ConfigException { try { Injector injector = Guice.createInjector( new ArchaiusModule() { @Override protected void configureArchaius() { } @Provides @Singleton public DefaultMethodWithAnnotation getMyConfig(ConfigProxyFactory factory) { return factory.newProxy(DefaultMethodWithAnnotation.class); } }); injector.getInstance(DefaultMethodWithAnnotation.class); Assert.fail("Exepcted ProvisionException"); } catch (ProvisionException e) { e.printStackTrace(); Assert.assertEquals(IllegalArgumentException.class, e.getCause().getCause().getClass()); } catch (Exception e) { Assert.fail("Expected ProvisionException"); } } }
9,214
0
Create_ds/archaius/archaius2-guice/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-guice/src/test/java/com/netflix/archaius/guice/ArchaiusModuleTest.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.guice; import java.util.Properties; import javax.inject.Inject; import com.netflix.archaius.DefaultConfigLoader; import com.netflix.archaius.api.exceptions.ConfigException; import org.junit.Assert; import org.junit.Test; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provides; import com.google.inject.Singleton; import com.google.inject.multibindings.MapBinder; import com.google.inject.name.Names; import com.netflix.archaius.ConfigMapper; import com.netflix.archaius.ConfigProxyFactory; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.Property; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.ConfigurationSource; import com.netflix.archaius.api.annotations.DefaultValue; import com.netflix.archaius.api.config.CompositeConfig; import com.netflix.archaius.api.config.SettableConfig; import com.netflix.archaius.api.inject.LibrariesLayer; import com.netflix.archaius.api.inject.RuntimeLayer; import com.netflix.archaius.cascade.ConcatCascadeStrategy; import com.netflix.archaius.config.MapConfig; import com.netflix.archaius.exceptions.MappingException; import com.netflix.archaius.visitor.PrintStreamVisitor; public class ArchaiusModuleTest { public static class MyCascadingStrategy extends ConcatCascadeStrategy { public MyCascadingStrategy() { super(new String[]{"${env}"}); } } @Singleton @Configuration(prefix="prefix-${env}", allowFields=true) @ConfigurationSource(value={"moduleTest"}, cascading=MyCascadingStrategy.class) public static class MyServiceConfig { private String str_value; private Integer int_value; private Boolean bool_value; private Double double_value; private Property<Integer> fast_int; private Named named; public void setStr_value(String value) { System.out.println("Setting string value to : " + value); } public void setInt_value(Integer value) { System.out.println("Setting int value to : " + value); } public void setNamed(Named named) { this.named = named; } @Inject public MyServiceConfig() { } } @Singleton public static class MyService { private Boolean value; @Inject public MyService(Config config, MyServiceConfig serviceConfig) { value = config.getBoolean("moduleTest.loaded"); } public Boolean getValue() { return value; } } public static interface Named { } @Singleton public static class Named1 implements Named { } @Singleton public static class Named2 implements Named { } @Test public void test() { final Properties props = new Properties(); props.setProperty("prefix-prod.str_value", "str_value"); props.setProperty("prefix-prod.int_value", "123"); props.setProperty("prefix-prod.bool_value", "true"); props.setProperty("prefix-prod.double_value", "456.0"); props.setProperty("env", "prod"); Injector injector = Guice.createInjector( new ArchaiusModule() { @Override protected void configureArchaius() { bindApplicationConfigurationOverride().toInstance(MapConfig.from(props)); } }); Config config = injector.getInstance(Config.class); Assert.assertEquals("prod", config.getString("env")); config.accept(new PrintStreamVisitor(System.err)); MyService service = injector.getInstance(MyService.class); Assert.assertTrue(service.getValue()); MyServiceConfig serviceConfig = injector.getInstance(MyServiceConfig.class); Assert.assertEquals("str_value", serviceConfig.str_value); Assert.assertEquals(123, serviceConfig.int_value.intValue()); Assert.assertEquals(true, serviceConfig.bool_value); Assert.assertEquals(456.0, serviceConfig.double_value, 0); Assert.assertTrue(config.getBoolean("moduleTest.loaded")); Assert.assertTrue(config.getBoolean("moduleTest-prod.loaded")); } @Test public void testNamedInjection() { final Properties props = new Properties(); props.setProperty("prefix-prod.named", "name1"); props.setProperty("env", "prod"); Injector injector = Guice.createInjector( new ArchaiusModule() { @Override protected void configureArchaius() { bindApplicationConfigurationOverride().toInstance(MapConfig.from(props)); } }, new AbstractModule() { @Override protected void configure() { bind(Named.class).annotatedWith(Names.named("name1")).to(Named1.class); bind(Named.class).annotatedWith(Names.named("name2")).to(Named2.class); } } ); MyService service = injector.getInstance(MyService.class); Assert.assertTrue(service.getValue()); MyServiceConfig serviceConfig = injector.getInstance(MyServiceConfig.class); Assert.assertTrue(serviceConfig.named instanceof Named1); } @Configuration(prefix="prefix.${name}.${id}", params={"name", "id"}, allowFields=true) public static class ChildService { private final String name; private final Long id; private String loaded; public ChildService(String name, Long id) { this.name = name; this.id = id; } } @Test public void testPrefixReplacements() throws MappingException { Config config = MapConfig.builder() .put("prefix.foo.123.loaded", "loaded") .build(); ConfigMapper binder = new ConfigMapper(); ChildService service = new ChildService("foo", 123L); binder.mapConfig(service, config); Assert.assertEquals("loaded", service.loaded); } public static interface TestProxyConfig { @DefaultValue("default") String getString(); @DefaultValue("foo,bar") String[] getStringArray(); @DefaultValue("1,2") Integer[] getIntArray(); } @Test public void testProxy() { Injector injector = Guice.createInjector( new ArchaiusModule() { @Provides @Singleton public TestProxyConfig getProxyConfig(ConfigProxyFactory factory) { return factory.newProxy(TestProxyConfig.class); } } ); Config config = injector.getInstance(Config.class); SettableConfig settableConfig = injector.getInstance(Key.get(SettableConfig.class, RuntimeLayer.class)); TestProxyConfig object = injector.getInstance(TestProxyConfig.class); Assert.assertEquals("default", object.getString()); Assert.assertArrayEquals(new String[]{"foo", "bar"}, object.getStringArray()); Assert.assertArrayEquals(new Integer[]{1,2}, object.getIntArray()); settableConfig.setProperty("string", "new"); settableConfig.setProperty("stringArray", "foonew,barnew"); settableConfig.setProperty("intArray", "3,4"); config.accept(new PrintStreamVisitor()); Assert.assertEquals("new", object.getString()); Assert.assertArrayEquals(new String[]{"foonew", "barnew"}, object.getStringArray()); Assert.assertArrayEquals(new Integer[]{3,4}, object.getIntArray()); settableConfig.clearProperty("string"); Assert.assertEquals("default", object.getString()); } @Test public void testDefaultBindings() { Injector injector = Guice.createInjector( new ArchaiusModule() ); injector.getInstance(Key.get(SettableConfig.class, RuntimeLayer.class)); injector.getInstance(Key.get(CompositeConfig.class, LibrariesLayer.class)); injector.getInstance(Config.class); } @Test public void testApplicationOverrideLayer() { final Properties props = new Properties(); props.setProperty("a", "override"); Injector injector = Guice.createInjector( new ArchaiusModule() { @Override protected void configureArchaius() { bindApplicationConfigurationOverride().toInstance(MapConfig.from(props)); } }); Config config = injector.getInstance(Config.class); Assert.assertEquals("override", config.getString("a")); } @Test public void testBasicLibraryOverride() { final Properties props = new Properties(); props.setProperty("moduleTest.prop1", "fromOverride"); Injector injector = Guice.createInjector(new ArchaiusModule()); injector.getInstance(MyServiceConfig.class); Config config = injector.getInstance(Config.class); Assert.assertEquals("fromFile", config.getString("moduleTest.prop1")); } @Test public void testLibraryOverride() { final Properties props = new Properties(); props.setProperty("moduleTest.prop1", "fromOverride"); Injector injector = Guice.createInjector( new ArchaiusModule() { @Override protected void configureArchaius() { bindApplicationConfigurationOverride().toInstance(MapConfig.from(props)); } }, new AbstractModule() { @Override protected void configure() { MapBinder.newMapBinder(binder(), String.class, Config.class, LibrariesLayer.class) .addBinding("moduleTest") .toInstance(MapConfig.from(props)); } } ); Config config = injector.getInstance(Config.class); injector.getInstance(MyServiceConfig.class); config.accept(new PrintStreamVisitor()); Assert.assertEquals("fromOverride", config.getString("moduleTest.prop1")); } @Test public void testMultipleConfigurations() { final Properties props = new Properties(); props.setProperty("a", "override"); Injector injector = Guice.createInjector( new ArchaiusModule() { @Override protected void configureArchaius() { bindApplicationConfigurationOverride().toInstance(MapConfig.from(props)); } }, new ArchaiusModule() { @Provides @Singleton public TestProxyConfig getProxyConfig(ConfigProxyFactory factory) { return factory.newProxy(TestProxyConfig.class); } } ); Config config = injector.getInstance(Config.class); Assert.assertEquals("override", config.getString("a")); TestProxyConfig configProxy = injector.getInstance(TestProxyConfig.class); Assert.assertEquals("default", configProxy.getString()); Assert.assertArrayEquals(new String[]{"foo", "bar"}, configProxy.getStringArray()); Assert.assertArrayEquals(new Integer[]{1,2}, configProxy.getIntArray()); } @Test public void testAddingConfigFileOverride() { Injector injector = Guice.createInjector(new ArchaiusModule() { @Override protected void configureArchaius() { bindApplicationConfigurationOverrideResource("application-override"); } }); Config config = injector.getInstance(Config.class); Assert.assertEquals("b_value_no_override", config.getString("b")); Assert.assertEquals("a_value_override", config.getString("a")); Assert.assertEquals("c_value_override", config.getString("c")); } }
9,215
0
Create_ds/archaius/archaius2-guice/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-guice/src/test/java/com/netflix/archaius/guice/InternalArchaiusModuleTest.java
package com.netflix.archaius.guice; import com.google.inject.Guice; import org.junit.Test; public class InternalArchaiusModuleTest { @Test public void succeedOnDuplicateInstall() { Guice.createInjector( new InternalArchaiusModule(), new InternalArchaiusModule()); } }
9,216
0
Create_ds/archaius/archaius2-guice/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-guice/src/test/java/com/netflix/archaius/guice/ConfigurationInjectingListenerTest.java
package com.netflix.archaius.guice; import com.google.inject.Guice; import com.google.inject.Injector; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.annotations.ConfigurationSource; import com.netflix.archaius.visitor.PrintStreamVisitor; import org.junit.Assert; import org.junit.Test; public class ConfigurationInjectingListenerTest { @ConfigurationSource({"moduleTest", "moduleTest-prod"}) public static class Foo { } @Test public void confirmLoadOrder() { Injector injector = Guice.createInjector(new ArchaiusModule()); injector.getInstance(Foo.class); Config config = injector.getInstance(Config.class); config.accept(new PrintStreamVisitor()); Assert.assertEquals("prod", config.getString("moduleTest.value")); } }
9,217
0
Create_ds/archaius/archaius2-guice/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-guice/src/main/java/com/netflix/archaius/guice/ApplicationOverride.java
package com.netflix.archaius.guice; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.inject.Qualifier; /** * To be used only for components meant to extend Archaius's functionality via bindings * where injecting a named Config will result in a circular dependency. */ @Target({ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Qualifier public @interface ApplicationOverride { }
9,218
0
Create_ds/archaius/archaius2-guice/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-guice/src/main/java/com/netflix/archaius/guice/ArchaiusModule.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.guice; import java.util.Properties; import com.google.inject.AbstractModule; import com.google.inject.binder.LinkedBindingBuilder; import com.google.inject.multibindings.Multibinder; import com.google.inject.multibindings.OptionalBinder; import com.google.inject.name.Names; import com.netflix.archaius.api.CascadeStrategy; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.inject.DefaultLayer; import com.netflix.archaius.api.inject.RemoteLayer; import com.netflix.archaius.config.MapConfig; import com.netflix.archaius.instrumentation.AccessMonitorUtil; /** * Guice Module for enabling archaius and making its components injectable. Installing this * module also enables the following functionality. * * <ul> * <li>Injectable Config</li> * <li>Configuration Proxy</li> * <li>Configuration mapping</li> * </uL> * * This module creates an injectable Config instance that has the following override structure in * order of precedence. * * RUNTIME - properties set from code * REMOTE - properties loaded from a remote source * SYSTEM - System properties * ENVIRONMENT - Environment properties * APPLICATION - Configuration loaded by the application * LIBRARIES - Configuration loaded by libraries used by the application * DEFAULT - Default properties driven by bindings * * Runtime properties may be set in code by injecting and calling one of the setXXX methods of, * {@literal @}RuntimeLayer SettableConfig config * * A remote configuration may be specified by binding to {@literal @}RemoteLayer Config * When setting up a remote configuration that needs access to Archaius's Config * make sure to inject the qualified {@literal @}Raw Config otherwise the injector will fail * with a circular dependency error. Note that the injected config will have * system, environment and application properties loaded into it. * * <code> * public class FooRemoteModule extends ArchaiusModule { * {@literal @}Provides * {@literal @}RemoteLayer * Config getRemoteConfig({@literal @}Raw Config config) { * return new FooRemoteConfigImplementaiton(config); * } * } * </code> */ public class ArchaiusModule extends AbstractModule { @Deprecated private Class<? extends CascadeStrategy> cascadeStrategy = null; @Deprecated private Config applicationOverride; @Deprecated private String configName; @Deprecated public ArchaiusModule withConfigName(String value) { this.configName = value; return this; } @Deprecated public ArchaiusModule withApplicationOverrides(Properties prop) { return withApplicationOverrides(MapConfig.from(prop)); } @Deprecated public ArchaiusModule withApplicationOverrides(Config config) { applicationOverride = config; return this; } /** * @deprecated Customize by binding CascadeStrategy in a guice module */ @Deprecated public ArchaiusModule withCascadeStrategy(Class<? extends CascadeStrategy> cascadeStrategy) { this.cascadeStrategy = cascadeStrategy; return this; } protected void configureArchaius() { } /** * Customize the filename for the main application configuration. The default filename is * 'application'. * * <code> * install(new ArchaiusModule() { * {@literal @}Override * protected void configureArchaius() { * bindConfigurationName().toInstance("myconfig"); * } * }); * </code> * * @return LinkedBindingBuilder to which the implementation is set */ protected LinkedBindingBuilder<String> bindConfigurationName() { return bind(String.class).annotatedWith(Names.named(InternalArchaiusModule.CONFIG_NAME_KEY)); } /** * Set application overrides. This is normally done for unit tests. * * <code> * install(new ArchaiusModule() { * {@literal @}Override * protected void configureArchaius() { * bindApplicationConfigurationOverride().toInstance(MapConfig.builder() * .put("some_property_to_override", "value") * .build() * ); * } * }); * </code> * * @return LinkedBindingBuilder to which the implementation is set */ protected LinkedBindingBuilder<Config> bindApplicationConfigurationOverride() { return bind(Config.class).annotatedWith(ApplicationOverride.class); } /** * Specify the Config to use for the remote layer. * * <code> * install(new ArchaiusModule() { * {@literal @}Override * protected void configureArchaius() { * bindRemoteConfig().to(SomeRemoteConfigImpl.class); * } * }); * </code> * * @return LinkedBindingBuilder to which the implementation is set */ protected LinkedBindingBuilder<Config> bindRemoteConfig() { return bind(Config.class).annotatedWith(RemoteLayer.class); } /** * Specify the CascadeStrategy used to load environment overrides for application and * library configurations. * * <code> * install(new ArchaiusModule() { * {@literal @}Override * protected void configureArchaius() { * bindCascadeStrategy().to(MyCascadeStrategy.class); * } * }); * </code> * * @return LinkedBindingBuilder to which the implementation is set */ protected LinkedBindingBuilder<CascadeStrategy> bindCascadeStrategy() { return bind(CascadeStrategy.class); } /** * Add a config to the bottom of the Config hierarchy. Use this when configuration is added * through code. Can be called multiple times as ConfigReader is added to a multibinding. * * <code> * install(new ArchaiusModule() { * {@literal @}Override * protected void configureArchaius() { * bindDefaultConfig().to(MyDefaultConfig.class); * } * }); * </code> * * @return LinkedBindingBuilder to which the implementation is set */ protected LinkedBindingBuilder<Config> bindDefaultConfig() { return Multibinder.newSetBinder(binder(), Config.class, DefaultLayer.class).addBinding(); } /** * Add support for a new configuration format. Can be called multiple times to add support for * multiple file format. * * <code> * install(new ArchaiusModule() { * {@literal @}Override * protected void configureArchaius() { * bindConfigReader().to(SomeConfigFormatReader.class); * } * }); * </code> * * @return LinkedBindingBuilder to which the implementation is set */ protected LinkedBindingBuilder<Config> bindConfigReader() { return Multibinder.newSetBinder(binder(), Config.class, DefaultLayer.class).addBinding(); } /** * Set application overrides to a particular resource. This is normally done for unit tests. * * <code> * install(new ArchaiusModule() { * {@literal @}Override * protected void configureArchaius() { * bindApplicationConfigurationOverrideResource("laptop"); * } * }); * </code> * * @return */ protected void bindApplicationConfigurationOverrideResource(String overrideResource) { Multibinder.newSetBinder(binder(), String.class, ApplicationOverrideResources.class).permitDuplicates().addBinding().toInstance(overrideResource); } @Override protected final void configure() { install(new InternalArchaiusModule()); OptionalBinder.newOptionalBinder(binder(), AccessMonitorUtil.class); configureArchaius(); // TODO: Remove in next release if (configName != null) { this.bindConfigurationName().toInstance(configName); } // TODO: Remove in next release if (cascadeStrategy != null) { this.bindCascadeStrategy().to(cascadeStrategy); } // TODO: Remove in next release if (applicationOverride != null) { this.bindApplicationConfigurationOverride().toInstance(applicationOverride); } } }
9,219
0
Create_ds/archaius/archaius2-guice/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-guice/src/main/java/com/netflix/archaius/guice/Raw.java
package com.netflix.archaius.guice; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.inject.Qualifier; /** * To be used only for components meant to extend Archaius's functionality via bindings * where injecting a named Config will result in a circular dependency. */ @Target({ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Qualifier public @interface Raw { }
9,220
0
Create_ds/archaius/archaius2-guice/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-guice/src/main/java/com/netflix/archaius/guice/ConfigurationInjectingListener.java
package com.netflix.archaius.guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.ProvisionException; import com.google.inject.name.Names; import com.google.inject.spi.ProvisionListener; import com.netflix.archaius.ConfigMapper; import com.netflix.archaius.api.CascadeStrategy; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.ConfigLoader; import com.netflix.archaius.api.IoCContainer; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.ConfigurationSource; import com.netflix.archaius.api.config.CompositeConfig; import com.netflix.archaius.api.exceptions.ConfigException; import com.netflix.archaius.api.inject.LibrariesLayer; import com.netflix.archaius.cascade.NoCascadeStrategy; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; public class ConfigurationInjectingListener implements ProvisionListener { private static final Logger LOG = LoggerFactory.getLogger(ConfigurationInjectingListener.class); @Inject private Config config; @Inject private Injector injector; @Inject private ConfigLoader loader; @Inject private @LibrariesLayer CompositeConfig libraries; @com.google.inject.Inject(optional = true) private CascadeStrategy cascadeStrategy; @Inject public static void init(ConfigurationInjectingListener listener) { LOG.info("Initializing ConfigurationInjectingListener"); } CascadeStrategy getCascadeStrategy() { return cascadeStrategy != null ? cascadeStrategy : NoCascadeStrategy.INSTANCE; } private ConfigMapper mapper = new ConfigMapper(); @Override public <T> void onProvision(ProvisionInvocation<T> provision) { Class<?> clazz = provision.getBinding().getKey().getTypeLiteral().getRawType(); // // Configuration Loading // final ConfigurationSource source = clazz.getDeclaredAnnotation(ConfigurationSource.class); if (source != null) { if (injector == null) { LOG.warn("Can't inject configuration into {} until ConfigurationInjectingListener has been initialized", clazz.getName()); return; } CascadeStrategy strategy = source.cascading() != ConfigurationSource.NullCascadeStrategy.class ? injector.getInstance(source.cascading()) : getCascadeStrategy(); List<String> sources = Arrays.asList(source.value()); Collections.reverse(sources); for (String resourceName : sources) { LOG.debug("Trying to loading configuration resource {}", resourceName); try { CompositeConfig loadedConfig = loader .newLoader() .withCascadeStrategy(strategy) .load(resourceName); libraries.addConfig(resourceName, loadedConfig); } catch (ConfigException e) { throw new ProvisionException("Unable to load configuration for " + resourceName, e); } } } // // Configuration binding // Configuration configAnnot = clazz.getAnnotation(Configuration.class); if (configAnnot != null) { if (injector == null) { LOG.warn("Can't inject configuration into {} until ConfigurationInjectingListener has been initialized", clazz.getName()); return; } try { mapper.mapConfig(provision.provision(), config, new IoCContainer() { @Override public <S> S getInstance(String name, Class<S> type) { return injector.getInstance(Key.get(type, Names.named(name))); } }); } catch (Exception e) { throw new ProvisionException("Unable to bind configuration to " + clazz, e); } } } }
9,221
0
Create_ds/archaius/archaius2-guice/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-guice/src/main/java/com/netflix/archaius/guice/ApplicationOverrideResources.java
package com.netflix.archaius.guice; import javax.inject.Qualifier; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Qualifier public @interface ApplicationOverrideResources { }
9,222
0
Create_ds/archaius/archaius2-guice/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-guice/src/main/java/com/netflix/archaius/guice/InternalArchaiusModule.java
package com.netflix.archaius.guice; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Provides; import com.google.inject.Scopes; import com.google.inject.Singleton; import com.google.inject.matcher.Matchers; import com.google.inject.multibindings.Multibinder; import com.netflix.archaius.ConfigProxyFactory; import com.netflix.archaius.DefaultConfigLoader; import com.netflix.archaius.DefaultDecoder; import com.netflix.archaius.DefaultPropertyFactory; import com.netflix.archaius.api.CascadeStrategy; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.ConfigLoader; import com.netflix.archaius.api.ConfigReader; import com.netflix.archaius.api.Decoder; import com.netflix.archaius.api.PropertyFactory; import com.netflix.archaius.api.PropertyRepository; import com.netflix.archaius.api.config.CompositeConfig; import com.netflix.archaius.api.config.SettableConfig; import com.netflix.archaius.api.exceptions.ConfigException; import com.netflix.archaius.api.inject.DefaultLayer; import com.netflix.archaius.api.inject.LibrariesLayer; import com.netflix.archaius.api.inject.RemoteLayer; import com.netflix.archaius.api.inject.RuntimeLayer; import com.netflix.archaius.cascade.NoCascadeStrategy; import com.netflix.archaius.config.DefaultCompositeConfig; import com.netflix.archaius.config.DefaultSettableConfig; import com.netflix.archaius.config.EnvironmentConfig; import com.netflix.archaius.config.SystemConfig; import com.netflix.archaius.interpolate.ConfigStrLookup; import com.netflix.archaius.readers.PropertiesConfigReader; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import javax.inject.Named; import javax.inject.Provider; final class InternalArchaiusModule extends AbstractModule { static final String CONFIG_NAME_KEY = "archaius.config.name"; private static final String DEFAULT_CONFIG_NAME = "application"; private static final String RUNTIME_LAYER_NAME = "RUNTIME"; private static final String REMOTE_LAYER_NAME = "REMOTE"; private static final String SYSTEM_LAYER_NAME = "SYSTEM"; private static final String ENVIRONMENT_LAYER_NAME = "ENVIRONMENT"; private static final String APPLICATION_LAYER_NAME = "APPLICATION"; private static final String LIBRARIES_LAYER_NAME = "LIBRARIES"; private static final String DEFAULT_LAYER_NAME = "DEFAULT"; private static AtomicInteger uniqueNameCounter = new AtomicInteger(); private static String getUniqueName(String prefix) { return prefix +"-" + uniqueNameCounter.incrementAndGet(); } @Override protected void configure() { ConfigurationInjectingListener listener = new ConfigurationInjectingListener(); requestInjection(listener); bind(ConfigurationInjectingListener.class).toInstance(listener); requestStaticInjection(ConfigurationInjectingListener.class); bindListener(Matchers.any(), listener); Multibinder.newSetBinder(binder(), ConfigReader.class) .addBinding().to(PropertiesConfigReader.class).in(Scopes.SINGLETON); } @Provides @Singleton @RuntimeLayer SettableConfig getSettableConfig() { return new DefaultSettableConfig(); } @Provides @Singleton @LibrariesLayer CompositeConfig getLibrariesLayer() { return new DefaultCompositeConfig(); } @Singleton private static class ConfigParameters { @Inject(optional=true) @Named(CONFIG_NAME_KEY) String configName; @Inject @RuntimeLayer SettableConfig runtimeLayer; @Inject @LibrariesLayer CompositeConfig librariesLayer; @Inject(optional=true) @RemoteLayer Provider<Config> remoteLayerProvider; @Inject(optional=true) @DefaultLayer Set<Config> defaultConfigs; @Inject(optional=true) @ApplicationOverride Config applicationOverride; @Inject(optional =true) @ApplicationOverrideResources Set<String> overrideResources; boolean hasApplicationOverride() { return applicationOverride != null; } boolean hasDefaultConfigs() { return defaultConfigs != null; } boolean hasRemoteLayer() { return remoteLayerProvider != null; } boolean hasOverrideResources() { return overrideResources != null; } String getConfigName() { return configName == null ? DEFAULT_CONFIG_NAME : configName; } } @Provides @Singleton @Raw CompositeConfig getRawCompositeConfig() throws Exception { return new DefaultCompositeConfig(); } @Provides @Singleton @Raw Config getRawConfig(@Raw CompositeConfig config) throws Exception { return config; } @Provides @Singleton Config getConfig(ConfigParameters params, @Raw CompositeConfig config, ConfigLoader loader) throws Exception { CompositeConfig applicationLayer = new DefaultCompositeConfig(); CompositeConfig remoteLayer = new DefaultCompositeConfig(); config.addConfig(RUNTIME_LAYER_NAME, params.runtimeLayer); config.addConfig(REMOTE_LAYER_NAME, remoteLayer); config.addConfig(SYSTEM_LAYER_NAME, SystemConfig.INSTANCE); config.addConfig(ENVIRONMENT_LAYER_NAME, EnvironmentConfig.INSTANCE); config.addConfig(APPLICATION_LAYER_NAME, applicationLayer); config.addConfig(LIBRARIES_LAYER_NAME, params.librariesLayer); // Load defaults layer if (params.hasDefaultConfigs()) { CompositeConfig defaultLayer = new DefaultCompositeConfig(); config.addConfig(DEFAULT_LAYER_NAME, defaultLayer); for (Config c : params.defaultConfigs) { defaultLayer.addConfig(getUniqueName("default"), c); } } if (params.hasOverrideResources()) { for (String resourceName : params.overrideResources) { applicationLayer.addConfig(resourceName, loader.newLoader().load(resourceName)); } } if (params.hasApplicationOverride()) { applicationLayer.addConfig(getUniqueName("override"), params.applicationOverride); } applicationLayer.addConfig(params.getConfigName(), loader .newLoader() .load(params.getConfigName())); // Load remote properties if (params.hasRemoteLayer()) { remoteLayer.addConfig(getUniqueName("remote"), params.remoteLayerProvider.get()); } return config; } @Singleton private static class OptionalCascadeStrategy { @Inject(optional=true) CascadeStrategy cascadingStrategy; CascadeStrategy get() { return cascadingStrategy == null ? new NoCascadeStrategy() : cascadingStrategy; } } @Provides @Singleton ConfigLoader getLoader( @Raw CompositeConfig rawConfig, Set<ConfigReader> readers, OptionalCascadeStrategy cascadeStrategy ) throws ConfigException { return DefaultConfigLoader.builder() .withConfigReaders(readers) .withDefaultCascadingStrategy(cascadeStrategy.get()) .withStrLookup(ConfigStrLookup.from(rawConfig)) .build(); } @Provides @Singleton Decoder getDecoder() { return DefaultDecoder.INSTANCE; } @Provides @Singleton PropertyFactory getPropertyFactory(Config config) { return DefaultPropertyFactory.from(config); } @Provides @Singleton PropertyRepository getPropertyRespository(PropertyFactory propertyFactory) { return propertyFactory; } @Provides @Singleton ConfigProxyFactory getProxyFactory(Config config, Decoder decoder, PropertyFactory factory) { return new ConfigProxyFactory(config, decoder, factory); } @Override public int hashCode() { return getClass().hashCode(); } @Override public boolean equals(Object obj) { return InternalArchaiusModule.class.equals(obj.getClass()); } }
9,223
0
Create_ds/archaius/archaius2-commons-configuration/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-commons-configuration/src/main/java/com/netflix/archaius/commons/CommonsToConfig.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.commons; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.function.BiConsumer; import org.apache.commons.configuration.AbstractConfiguration; import org.apache.commons.lang.StringUtils; import com.netflix.archaius.config.AbstractConfig; /** * Adaptor to allow an Apache Commons Configuration AbstractConfig to be used * as an Archaius2 Config */ public class CommonsToConfig extends AbstractConfig { private final AbstractConfiguration config; public CommonsToConfig(AbstractConfiguration config) { this.config = config; } @Override public boolean containsKey(String key) { return config.containsKey(key); } @Override public boolean isEmpty() { return config.isEmpty(); } @Override public Object getRawProperty(String key) { return config.getString(key); } @Override public Iterator<String> getKeys() { return config.getKeys(); } @Override public <T> List<T> getList(String key, Class<T> type) { List value = config.getList(key); if (value == null) { return notFound(key); } ; List<T> result = new ArrayList<T>(); for (Object part : value) { if (type.isInstance(part)) { result.add((T)part); } else if (part instanceof String) { result.add(getDecoder().decode(type, (String) part)); } else { throw new UnsupportedOperationException( "Property values other than " + type.getCanonicalName() +" or String not supported"); } } return result; } @Override public List getList(String key) { List value = config.getList(key); if (value == null) { return notFound(key); } return value; } @Override public String getString(String key, String defaultValue) { List value = config.getList(key); if (value == null) { return notFound(key, defaultValue != null ? getStrInterpolator().create(getLookup()).resolve(defaultValue) : null); } List<String> interpolatedResult = new ArrayList<>(); for (Object part : value) { if (part instanceof String) { interpolatedResult.add(getStrInterpolator().create(getLookup()).resolve(part.toString())); } else { throw new UnsupportedOperationException( "Property values other than String not supported"); } } return StringUtils.join(interpolatedResult, getListDelimiter()); } @Override public String getString(String key) { List value = config.getList(key); if (value == null) { return notFound(key); } List<String> interpolatedResult = new ArrayList<>(); for (Object part : value) { if (part instanceof String) { interpolatedResult.add(getStrInterpolator().create(getLookup()).resolve(part.toString())); } else { throw new UnsupportedOperationException( "Property values other than String not supported"); } } return StringUtils.join(interpolatedResult, getListDelimiter()); } }
9,224
0
Create_ds/archaius/archaius2-test/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-test/src/test/java/com/netflix/archaius/test/Archaius2RuleTest.java
package com.netflix.archaius.test; import static org.junit.Assert.*; import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.Test; import org.junit.runners.MethodSorters; @TestPropertyOverride({"classLevelProperty=present", "cascading=type"}) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class Archaius2RuleTest extends Archaius2RuleTestParentTest { @Rule public Archaius2TestConfig config = new Archaius2TestConfig(); @Test @TestPropertyOverride({"testLevelProperty=present"}) public void testBasicPropertyResolution() { assertNotNull(config); assertEquals("present", config.getString("parentClassLevelProperty")); assertEquals("present", config.getString("classLevelProperty")); assertEquals("present", config.getString("testLevelProperty")); assertEquals("type", config.getString("cascading")); } @Test public void testRuntimeOverrides() { config.setProperty("runtimeLevelProperty", "present"); assertEquals("present", config.getRawProperty("runtimeLevelProperty")); } @Test @TestPropertyOverride({"cascading=test"}) public void testOverridesTypeLevelProperties() { assertEquals("test", config.getString("cascading")); } @Test @TestPropertyOverride({"cascading=test"}) public void testRuntimePropertyOverridesTestLevelProperties() { assertEquals("test", config.getString("cascading")); config.setProperty("cascading", "runtime"); assertEquals("runtime", config.getString("cascading")); } @Test @TestPropertyOverride({"=foo"}) public void testEmptyKey() { assertEquals("foo", config.getString("")); } @Test @TestPropertyOverride({"foo="}) public void testEmptyValue() { assertEquals("", config.getString("foo")); } @Test @TestPropertyOverride({"foo=bar=bad"}) public void testMultipleDelimiter() { assertEquals("bar=bad", config.getString("foo")); } @Test @TestPropertyOverride(propertyFiles={"archaiusRuleTest.properties"}) public void testPropertyFromFile() { assertEquals("present", config.getString("fileProperty")); } @Test public void zz_testPropertiesCleanedBetweenRuns() { assertNull(config.getRawProperty("testLevelProperty")); assertNull(config.getRawProperty("runtimeLevelProperty")); assertNull(config.getRawProperty("foo")); } }
9,225
0
Create_ds/archaius/archaius2-test/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-test/src/test/java/com/netflix/archaius/test/Archaius2RuleTestParentTest.java
package com.netflix.archaius.test; @TestPropertyOverride("parentClassLevelProperty=present") public class Archaius2RuleTestParentTest extends SuperParent { } @TestPropertyOverride("parentClassLevelProperty=super") class SuperParent { }
9,226
0
Create_ds/archaius/archaius2-test/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-test/src/test/java/com/netflix/archaius/test/Archaius2RuleFailureTest.java
package com.netflix.archaius.test; import static org.junit.Assert.fail; import java.lang.annotation.Annotation; import org.junit.Test; import org.junit.runner.Description; import org.junit.runners.model.Statement; public class Archaius2RuleFailureTest { @Test(expected = TestConfigException.class) public void testFileNotFoundExceptionThrownWhenNoPropFileFound() throws Throwable { Archaius2TestConfig conf = new Archaius2TestConfig(); // Annotation instance pointing to non-existent prop file Annotation testAnnotation = new TestPropertyOverride() { @Override public Class<? extends Annotation> annotationType() { return TestPropertyOverride.class; } @Override public String[] value() { return null; } @Override public String[] propertyFiles() { return new String[] { "doesNotExist.properties" }; } }; //No-op statement Statement base = new Statement() { @Override public void evaluate() throws Throwable { } }; Statement rule = conf.apply(base, Description.createTestDescription(getClass(), "test", testAnnotation)); rule.evaluate(); fail("Should've thrown an exception"); } }
9,227
0
Create_ds/archaius/archaius2-test/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-test/src/main/java/com/netflix/archaius/test/TestPropertyOverride.java
package com.netflix.archaius.test; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; import com.netflix.archaius.api.Config; /*** * Annotation used in conjunction with {@link Archaius2TestConfig} to create an * Archaius2 {@link Config} instance for testing. * * Property values must be specified in the form of: * <pre> * {@literal @}TestPropertyOverride(value={"propName=propValue", "propName2=propVal2", ... }, propertyFiles={someFile.properties}) * * </pre> * TestPropertyOverride's may be set at the test class, parent test class, and test method levels. * Overrides specified at the test method level take precedance over properties set at class level. */ @Documented @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) public @interface TestPropertyOverride { /** * Create properties inline. * ex. {@literal @}TestPropertyOverride({"propName=propValue", "propName2=propVal2", ... }) * * These properties will precedance over those created from the * propertyFiles attribute in the event of conflicts. */ String[] value() default {}; /*** * Use a file location to create properties. * ex. {@literal @}TestPropertyOverride(propertyFiles={"unittest.properties"}) * * These properties will be overwritten by those created from the * value attribute in the event of conflicts. */ String[] propertyFiles() default {}; }
9,228
0
Create_ds/archaius/archaius2-test/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-test/src/main/java/com/netflix/archaius/test/TestConfigException.java
package com.netflix.archaius.test; public class TestConfigException extends RuntimeException { private static final long serialVersionUID = 8598260463522600221L; public TestConfigException(String msg) { super(msg); } public TestConfigException(String msg, Throwable cause) { super(msg, cause); } }
9,229
0
Create_ds/archaius/archaius2-test/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-test/src/main/java/com/netflix/archaius/test/ConfigInterfaceTest.java
package com.netflix.archaius.test; import com.netflix.archaius.api.Config; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; public abstract class ConfigInterfaceTest { protected abstract Config getInstance(Map<String, String> properties); private final Map<String, String> props = new HashMap<>(); public ConfigInterfaceTest() { props.put("goo", "baz"); } @Test public final void getValue() throws Exception { Config instance = getInstance(props); String result = instance.getString("goo"); assertEquals("baz", result); } @Test public final void getValueWithDefault() throws Exception { Config instance = getInstance(props); String result = instance.getString("foo", "bar"); assertEquals("bar", result); } }
9,230
0
Create_ds/archaius/archaius2-test/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-test/src/main/java/com/netflix/archaius/test/TestPropertyOverrideAnnotationReader.java
package com.netflix.archaius.test; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Properties; /** * Utility class to read {@literal@}{@link TestPropertyOverride} annotations and * transform them into {@link Properties} objects. This is intended for use in * testing utilities such as the {@link Archaius2TestConfig} JUnit Rule. */ public class TestPropertyOverrideAnnotationReader { public Properties getPropertiesForAnnotation(TestPropertyOverride annotation) { Properties properties = new Properties(); if (annotation == null) { return properties; } for (String fileName : annotation.propertyFiles()) { try { InputStream propFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName); if(propFileStream != null) { properties.load(propFileStream); } else { throw new FileNotFoundException(fileName); } } catch (IOException e) { throw new TestConfigException("Failed to load property file from classpath", e); } } for (String override : annotation.value()) { String[] parts = override.split("=", 2); if (parts.length < 2) { throw new TestConfigException("Error parsing TestPropertyOverride for: " + Arrays.toString(annotation.value()) + " Please ensure you are specifying overrides in the form \"key=value\""); } properties.put(parts[0], parts[1]); } return properties; } }
9,231
0
Create_ds/archaius/archaius2-test/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-test/src/main/java/com/netflix/archaius/test/TestCompositeConfig.java
package com.netflix.archaius.test; import java.util.Iterator; import java.util.Properties; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.config.SettableConfig; import com.netflix.archaius.config.DefaultCompositeConfig; import com.netflix.archaius.config.DefaultSettableConfig; /** * Implementation of {@link DefaultCompositeConfig} and {@link SettableConfig} * for use in testing utilities. */ public class TestCompositeConfig extends DefaultCompositeConfig implements SettableConfig { private static final String CLASS_LEVEL_LAYER_NAME = "CLASS_LEVEL_TEST_OVERRIDES"; private static final String METHOD_LEVEL_LAYER_NAME = "METHOD_LEVEL_TEST_OVERRIDES"; private static final String RUNTIME_LAYER_NAME = "RUNTIME"; public TestCompositeConfig(SettableConfig runtimeOverrides, SettableConfig classLevelOverrides, SettableConfig methodLevelOverrides) { try { addConfig(RUNTIME_LAYER_NAME, runtimeOverrides); addConfig(METHOD_LEVEL_LAYER_NAME, methodLevelOverrides); addConfig(CLASS_LEVEL_LAYER_NAME, classLevelOverrides); } catch (Exception e) { throw new RuntimeException(e); } } @Deprecated public TestCompositeConfig(SettableConfig classLevelOverrides, SettableConfig methodLevelOverrides) { this(new DefaultSettableConfig(), classLevelOverrides, methodLevelOverrides); } public void resetForTest() { clear(getSettableConfig(METHOD_LEVEL_LAYER_NAME)); clear(getSettableConfig(RUNTIME_LAYER_NAME)); } private SettableConfig getSettableConfig(String configName) { return (SettableConfig) super.getConfig(configName); } private void clear(SettableConfig config) { Iterator<String> keys = config.getKeys(); while(keys.hasNext()) { config.clearProperty(keys.next()); } } @Override public void setProperties(Config config) { getSettableConfig(RUNTIME_LAYER_NAME).setProperties(config); } @Override public void setProperties(Properties properties) { getSettableConfig(RUNTIME_LAYER_NAME).setProperties(properties); } @Override public <T> void setProperty(String propName, T propValue) { getSettableConfig(RUNTIME_LAYER_NAME).setProperty(propName, propValue); } @Override public void clearProperty(String propName) { getSettableConfig(RUNTIME_LAYER_NAME).clearProperty(propName); } }
9,232
0
Create_ds/archaius/archaius2-test/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-test/src/main/java/com/netflix/archaius/test/Archaius2TestConfig.java
package com.netflix.archaius.test; import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.function.BiConsumer; import org.apache.commons.lang3.ClassUtils; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.ConfigListener; import com.netflix.archaius.api.Decoder; import com.netflix.archaius.api.StrInterpolator; import com.netflix.archaius.api.config.SettableConfig; import com.netflix.archaius.config.DefaultSettableConfig; /*** * JUnit rule which builds an Archaius2 {@link Config} instance using * annotations. * * <pre> * {@literal @}Rule * public Archaius2TestConfig config = new Archaius2TestConfig(); * * {@literal @}Test * {@literal @}TestPropertyOverride({"propName=propValue"}) * public void testBasicPropertyResolution() { * assertEquals("propValue", config.getString("propName")); * } * </pre> * * See {@link TestPropertyOverride} for additional usage information. */ public class Archaius2TestConfig implements TestRule, SettableConfig { private TestCompositeConfig testCompositeConfig; private final TestPropertyOverrideAnnotationReader annotationReader = new TestPropertyOverrideAnnotationReader(); @Override public Statement apply(final Statement base, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { SettableConfig runtimeLevelProperties = new DefaultSettableConfig(); SettableConfig classLevelProperties = new DefaultSettableConfig(); SettableConfig methodLevelProperties = new DefaultSettableConfig(); List<Class<?>> allSuperclasses = ClassUtils.getAllSuperclasses(description.getTestClass()); Collections.reverse(allSuperclasses); for(Class<?> parentClass : allSuperclasses) { classLevelProperties.setProperties(annotationReader.getPropertiesForAnnotation(parentClass.getAnnotation(TestPropertyOverride.class))); } classLevelProperties.setProperties(annotationReader.getPropertiesForAnnotation(description.getTestClass().getAnnotation(TestPropertyOverride.class))); methodLevelProperties.setProperties(annotationReader.getPropertiesForAnnotation(description.getAnnotation(TestPropertyOverride.class))); testCompositeConfig = new TestCompositeConfig(runtimeLevelProperties, classLevelProperties, methodLevelProperties); base.evaluate(); } }; } private String getKey(Description description) { return description.getClassName() + description.getMethodName() + description.getDisplayName(); } @Override public void addListener(ConfigListener listener) { testCompositeConfig.addListener(listener); } @Override public void removeListener(ConfigListener listener) { testCompositeConfig.removeListener(listener); } @Override public Object getRawProperty(String key) { return testCompositeConfig.getRawProperty(key); } @Override public Long getLong(String key) { return testCompositeConfig.getLong(key); } @Override public Long getLong(String key, Long defaultValue) { return testCompositeConfig.getLong(key, defaultValue); } @Override public String getString(String key) { return testCompositeConfig.getString(key); } @Override public String getString(String key, String defaultValue) { return testCompositeConfig.getString(key, defaultValue); } @Override public Double getDouble(String key) { return testCompositeConfig.getDouble(key); } @Override public Double getDouble(String key, Double defaultValue) { return testCompositeConfig.getDouble(key, defaultValue); } @Override public Integer getInteger(String key) { return testCompositeConfig.getInteger(key); } @Override public Integer getInteger(String key, Integer defaultValue) { return testCompositeConfig.getInteger(key, defaultValue); } @Override public Boolean getBoolean(String key) { return testCompositeConfig.getBoolean(key); } @Override public Boolean getBoolean(String key, Boolean defaultValue) { return testCompositeConfig.getBoolean(key, defaultValue); } @Override public Short getShort(String key) { return testCompositeConfig.getShort(key); } @Override public Short getShort(String key, Short defaultValue) { return testCompositeConfig.getShort(key, defaultValue); } @Override public BigInteger getBigInteger(String key) { return testCompositeConfig.getBigInteger(key); } @Override public BigInteger getBigInteger(String key, BigInteger defaultValue) { return testCompositeConfig.getBigInteger(key, defaultValue); } @Override public BigDecimal getBigDecimal(String key) { return testCompositeConfig.getBigDecimal(key); } @Override public BigDecimal getBigDecimal(String key, BigDecimal defaultValue) { return testCompositeConfig.getBigDecimal(key, defaultValue); } @Override public Float getFloat(String key) { return testCompositeConfig.getFloat(key); } @Override public Float getFloat(String key, Float defaultValue) { return testCompositeConfig.getFloat(key, defaultValue); } @Override public Byte getByte(String key) { return testCompositeConfig.getByte(key); } @Override public Byte getByte(String key, Byte defaultValue) { return testCompositeConfig.getByte(key, defaultValue); } @Override public List<?> getList(String key) { return testCompositeConfig.getList(key); } @Override public <T> List<T> getList(String key, Class<T> type) { return testCompositeConfig.getList(key, type); } @Override public List<?> getList(String key, List<?> defaultValue) { return testCompositeConfig.getList(key, defaultValue); } @Override public <T> T get(Class<T> type, String key) { return testCompositeConfig.get(type, key); } @Override public <T> T get(Class<T> type, String key, T defaultValue) { return testCompositeConfig.get(type, key, defaultValue); } @Override public <T> T get(Type type, String key) { return testCompositeConfig.get(type, key); } @Override public <T> T get(Type type, String key, T defaultValue) { return testCompositeConfig.get(type, key, defaultValue); } @Override public boolean containsKey(String key) { return testCompositeConfig.containsKey(key); } @Override public boolean isEmpty() { return testCompositeConfig.isEmpty(); } @Override public Iterator<String> getKeys() { return testCompositeConfig.getKeys(); } @Override public Iterator<String> getKeys(String prefix) { return testCompositeConfig.getKeys(prefix); } @Override public Config getPrefixedView(String prefix) { return testCompositeConfig.getPrefixedView(prefix); } @Override public Config getPrivateView() { return testCompositeConfig.getPrivateView(); } @Override public void setStrInterpolator(StrInterpolator interpolator) { testCompositeConfig.setStrInterpolator(interpolator); } @Override public StrInterpolator getStrInterpolator() { return testCompositeConfig.getStrInterpolator(); } @Override public void setDecoder(Decoder decoder) { testCompositeConfig.setDecoder(decoder); } @Override public Decoder getDecoder() { return testCompositeConfig.getDecoder(); } @Override public <T> T accept(Visitor<T> visitor) { return testCompositeConfig.accept(visitor); } @Override public void setProperties(Config config) { testCompositeConfig.setProperties(config); } @Override public void setProperties(Properties properties) { testCompositeConfig.setProperties(properties); } @Override public <T> void setProperty(String propName, T propValue) { testCompositeConfig.setProperty(propName, propValue); } @Override public void clearProperty(String propName) { testCompositeConfig.clearProperty(propName); } @Override public void forEachProperty(BiConsumer<String, Object> consumer) { testCompositeConfig.forEachProperty(consumer); } }
9,233
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/TestUtils.java
package com.netflix.archaius; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; public class TestUtils { @SafeVarargs public static <T> Set<T> set(T ... values) { return Collections.unmodifiableSet(new LinkedHashSet<>(Arrays.asList(values))); } public static <T> Set<T> set(Iterator<T> values) { Set<T> vals = new LinkedHashSet<>(); values.forEachRemaining(vals::add); return Collections.unmodifiableSet(vals); } public static <T> Set<T> set(Iterable<T> values) { return values instanceof Collection<?> ? new HashSet<>((Collection<T>) values) : set(values.iterator()); } public static <T> int size(Iterable<T> values) { if (values instanceof Collection<?>) { return ((Collection<?>) values).size(); } int count = 0; for (T el : values) { count++; } return count; } }
9,234
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/DefaultConfigLoaderTest.java
package com.netflix.archaius; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.ConfigReader; import com.netflix.archaius.api.StrInterpolator; import com.netflix.archaius.api.config.CompositeConfig; import com.netflix.archaius.api.exceptions.ConfigException; import com.netflix.archaius.cascade.ConcatCascadeStrategy; import com.netflix.archaius.config.DefaultCompositeConfig; import com.netflix.archaius.config.MapConfig; import com.netflix.archaius.readers.PropertiesConfigReader; import org.junit.Assert; import org.junit.Test; import java.util.HashSet; import java.util.Iterator; import java.util.Properties; import java.util.Set; import static org.mockito.Mockito.*; /** * @author Nikos Michalakis <nikos@netflix.com> */ public class DefaultConfigLoaderTest { @Test public void testBuildWithAllOptions() throws ConfigException { Properties props = new Properties(); props.setProperty("env", "prod"); CompositeConfig application = new DefaultCompositeConfig(); CompositeConfig config = DefaultCompositeConfig.builder() .withConfig("app", application) .withConfig("set", MapConfig.from(props)) .build(); final StrInterpolator.Context mockContext = mock(StrInterpolator.Context.class); when(mockContext.resolve(anyString())).thenReturn("resolved"); StrInterpolator mockStrInterpolator = mock(StrInterpolator.class); when(mockStrInterpolator.create(any(StrInterpolator.Lookup.class))).thenReturn(mockContext); Set<ConfigReader> readers = new HashSet<>(); ConfigReader reader1 = new PropertiesConfigReader(); ConfigReader reader2 = new PropertiesConfigReader(); readers.add(reader1); readers.add(reader2); DefaultConfigLoader loader = DefaultConfigLoader.builder() .withStrLookup(config) .withStrInterpolator(mockStrInterpolator) .withConfigReader(new PropertiesConfigReader()) .withDefaultCascadingStrategy(ConcatCascadeStrategy.from("${env}")) .withConfigReaders(readers) .build(); application.replaceConfig("application", loader.newLoader().load("application")); Assert.assertTrue(config.getBoolean("application.loaded")); } @Test public void testDefaultLoaderBehavior() throws ConfigException { CompositeConfig applicationConfig = DefaultConfigLoader.builder().build().newLoader().load("application"); Config applicationProdConfig = DefaultConfigLoader.builder().build().newLoader().load("application-prod"); applicationConfig.addConfig("prod", applicationProdConfig); Assert.assertEquals(applicationConfig.getString("application.list2"), "a,b"); Assert.assertEquals(applicationConfig.getBoolean("application-prod.loaded"), true); } }
9,235
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/DefaultDecoderTest.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius; import java.math.BigDecimal; import java.math.BigInteger; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.OffsetTime; import java.time.Period; import java.time.ZonedDateTime; import java.util.BitSet; import java.util.Currency; import java.util.Date; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import org.junit.Assert; import org.junit.Test; public class DefaultDecoderTest { @Test public void testJavaNumbers() { DefaultDecoder decoder = DefaultDecoder.INSTANCE; boolean flag = decoder.decode(boolean.class, "true"); Assert.assertTrue(flag); int int_value = decoder.decode(int.class, "123"); Assert.assertEquals(123, int_value); Assert.assertEquals(Byte.valueOf(Byte.MAX_VALUE), decoder.decode(Byte.class, String.valueOf(Byte.MAX_VALUE))); Assert.assertEquals(Short.valueOf(Short.MAX_VALUE), decoder.decode(Short.class, String.valueOf(Short.MAX_VALUE))); Assert.assertEquals(Long.valueOf(Long.MAX_VALUE), decoder.decode(Long.class, String.valueOf(Long.MAX_VALUE))); Assert.assertEquals(Integer.valueOf(Integer.MAX_VALUE), decoder.decode(Integer.class, String.valueOf(Integer.MAX_VALUE))); Assert.assertEquals(Float.valueOf(Float.MAX_VALUE), decoder.decode(Float.class, String.valueOf(Float.MAX_VALUE))); Assert.assertEquals(Double.valueOf(Double.MAX_VALUE), decoder.decode(Double.class, String.valueOf(Double.MAX_VALUE))); Assert.assertEquals(BigInteger.valueOf(Long.MAX_VALUE), decoder.decode(BigInteger.class, String.valueOf(Long.MAX_VALUE))); Assert.assertEquals(BigDecimal.valueOf(Double.MAX_VALUE), decoder.decode(BigDecimal.class, String.valueOf(Double.MAX_VALUE))); Assert.assertEquals(new AtomicInteger(Integer.MAX_VALUE).intValue(), decoder.decode(AtomicInteger.class, String.valueOf(Integer.MAX_VALUE)).intValue()); Assert.assertEquals(new AtomicLong(Long.MAX_VALUE).longValue(), decoder.decode(AtomicLong.class, String.valueOf(Long.MAX_VALUE)).longValue()); } @Test public void testJavaDateTime() { DefaultDecoder decoder = DefaultDecoder.INSTANCE; Assert.assertEquals(Duration.parse("PT20M30S"), decoder.decode(Duration.class, "PT20M30S")); Assert.assertEquals(Period.of(1, 2, 25), decoder.decode(Period.class, "P1Y2M3W4D")); Assert.assertEquals(OffsetDateTime.parse("2016-08-03T10:15:30+07:00"), decoder.decode(OffsetDateTime.class, "2016-08-03T10:15:30+07:00")); Assert.assertEquals(OffsetTime.parse("10:15:30+18:00"), decoder.decode(OffsetTime.class, "10:15:30+18:00")); Assert.assertEquals(ZonedDateTime.parse("2016-08-03T10:15:30+01:00[Europe/Paris]"), decoder.decode(ZonedDateTime.class, "2016-08-03T10:15:30+01:00[Europe/Paris]")); Assert.assertEquals(LocalDateTime.parse("2016-08-03T10:15:30"), decoder.decode(LocalDateTime.class, "2016-08-03T10:15:30")); Assert.assertEquals(LocalDate.parse("2016-08-03"), decoder.decode(LocalDate.class, "2016-08-03")); Assert.assertEquals(LocalTime.parse("10:15:30"), decoder.decode(LocalTime.class, "10:15:30")); Assert.assertEquals(Instant.from(OffsetDateTime.parse("2016-08-03T10:15:30+07:00")), decoder.decode(Instant.class, "2016-08-03T10:15:30+07:00")); Date newDate = new Date(); Assert.assertEquals(newDate, decoder.decode(Date.class, String.valueOf(newDate.getTime()))); } @Test public void testJavaMiscellaneous() throws DecoderException { DefaultDecoder decoder = DefaultDecoder.INSTANCE; Assert.assertEquals(Currency.getInstance("USD"), decoder.decode(Currency.class, "USD")); Assert.assertEquals(BitSet.valueOf(Hex.decodeHex("DEADBEEF00DEADBEEF")), decoder.decode(BitSet.class, "DEADBEEF00DEADBEEF")); Assert.assertEquals("testString", decoder.decode(String.class, "testString")); } }
9,236
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/ProxyFactoryTest.java
package com.netflix.archaius; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.Nullable; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.PropertyFactory; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; import com.netflix.archaius.api.annotations.PropertyName; import com.netflix.archaius.api.config.SettableConfig; import com.netflix.archaius.config.DefaultSettableConfig; import com.netflix.archaius.config.EmptyConfig; @SuppressWarnings("deprecation") public class ProxyFactoryTest { public enum TestEnum { NONE, A, B, C } @Configuration(immutable=true) public interface ImmutableConfig { @DefaultValue("default") String getValueWithDefault(); String getValueWithoutDefault1(); String getValueWithoutDefault2(); } @SuppressWarnings("unused") public interface BaseConfig { @DefaultValue("basedefault") String getStr(); Boolean getBaseBoolean(); @Nullable Integer getNullable(); default long getLongValueWithDefault() { return 42L; } } @SuppressWarnings("UnusedReturnValue") public interface RootConfig extends BaseConfig { @DefaultValue("default") @Override String getStr(); @DefaultValue("0") int getInteger(); @DefaultValue("NONE") TestEnum getEnum(); SubConfig getSubConfig(); @DefaultValue("default1:default2") SubConfigFromString getSubConfigFromString(); @DefaultValue("") Integer[] getIntArray(); int getRequiredValue(); default long getOtherLongValueWithDefault() { return 43L; } } public interface SubConfig { @DefaultValue("default") String str(); } public static class SubConfigFromString { private final String[] parts; public SubConfigFromString(String value) { this.parts = value.split(":"); } public String part1() { return parts[0]; } public String part2() { return parts[1]; } @Override public String toString() { return "SubConfigFromString[" + part1() + ", " + part2() + "]"; } } @Test public void testImmutableDefaultValues() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("valueWithoutDefault2", "default2"); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); ImmutableConfig c = proxy.newProxy(ImmutableConfig.class); assertThat(c.getValueWithDefault(), equalTo("default")); assertThat(c.getValueWithoutDefault2(), equalTo("default2")); assertThat(c.getValueWithoutDefault1(), nullValue()); config.setProperty("valueWithDefault", "newValue"); assertThat(c.getValueWithDefault(), equalTo("default")); } @Test public void testDefaultValues() { Config config = EmptyConfig.INSTANCE; PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); RootConfig a = proxy.newProxy(RootConfig.class); assertThat(a.getStr(), equalTo("default")); assertThat(a.getInteger(), equalTo(0)); assertThat(a.getEnum(), equalTo(TestEnum.NONE)); assertThat(a.getSubConfig().str(), equalTo("default")); assertThat(a.getSubConfigFromString().part1(), equalTo("default1")); assertThat(a.getSubConfigFromString().part2(), equalTo("default2")); assertThat(a.getNullable(), nullValue()); assertThat(a.getBaseBoolean(), nullValue()); assertThat(a.getIntArray(), equalTo(new Integer[]{})); assertThat(a.getLongValueWithDefault(), equalTo(42L)); assertThat(a.getOtherLongValueWithDefault(), equalTo(43L)); } @Test public void testDefaultValuesImmutable() { Config config = EmptyConfig.INSTANCE; PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); RootConfig a = proxy.newProxy(RootConfig.class, "", true); assertThat(a.getStr(), equalTo("default")); assertThat(a.getInteger(), equalTo(0)); assertThat(a.getEnum(), equalTo(TestEnum.NONE)); assertThat(a.getSubConfig().str(), equalTo("default")); assertThat(a.getSubConfigFromString().part1(), equalTo("default1")); assertThat(a.getSubConfigFromString().part2(), equalTo("default2")); assertThat(a.getNullable(), nullValue()); assertThat(a.getBaseBoolean(), nullValue()); assertThat(a.getIntArray(), equalTo(new Integer[]{})); } @Test public void testAllPropertiesSet() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("prefix.str", "str1"); config.setProperty("prefix.integer", 1); config.setProperty("prefix.enum", TestEnum.A.name()); config.setProperty("prefix.subConfigFromString", "a:b"); config.setProperty("prefix.subConfig.str", "str2"); config.setProperty("prefix.baseBoolean", true); config.setProperty("prefix.intArray", "0,1,2,3"); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); RootConfig a = proxy.newProxy(RootConfig.class, "prefix"); assertThat(a.getStr(), equalTo("str1")); assertThat(a.getInteger(), equalTo(1)); assertThat(a.getEnum(), equalTo(TestEnum.A)); assertThat(a.getSubConfig().str(), equalTo("str2")); assertThat(a.getSubConfigFromString().part1(), equalTo("a")); assertThat(a.getSubConfigFromString().part2(), equalTo("b")); assertThat(a.getBaseBoolean(), equalTo(true)); assertThat(a.getIntArray(), equalTo(new Integer[]{0,1,2,3})); config.setProperty("prefix.subConfig.str", "str3"); assertThat(a.getSubConfig().str(), equalTo("str3")); try { a.getRequiredValue(); Assert.fail("should have failed with no value for requiredValue"); } catch (Exception expected) { } } interface WithArguments { @PropertyName(name="${0}.abc.${1}") @DefaultValue("default") String getProperty(String part0, int part1); } @Test public void testWithArguments() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("a.abc.1", "value1"); config.setProperty("b.abc.2", "value2"); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); WithArguments withArgs = proxy.newProxy(WithArguments.class); Assert.assertEquals("value1", withArgs.getProperty("a", 1)); Assert.assertEquals("value2", withArgs.getProperty("b", 2)); Assert.assertEquals("default", withArgs.getProperty("a", 2)); } @Configuration(prefix = "foo.bar") interface WithArgumentsAndPrefix { @PropertyName(name="baz.${0}.abc.${1}") @DefaultValue("default") String getPropertyWithoutPrefix(String part0, int part1); // For backward compatibility, we need to accept PropertyNames that also include the prefix. @PropertyName(name="foo.bar.baz.${0}.abc.${1}") @DefaultValue("default") String getPropertyWithPrefix(String part0, int part1); } @Test public void testWithArgumentsAndPrefix() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("foo.bar.baz.a.abc.1", "value1"); config.setProperty("foo.bar.baz.b.abc.2", "value2"); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); WithArgumentsAndPrefix withArgs = proxy.newProxy(WithArgumentsAndPrefix.class); Assert.assertEquals("value1", withArgs.getPropertyWithPrefix("a", 1)); Assert.assertEquals("value1", withArgs.getPropertyWithoutPrefix("a", 1)); Assert.assertEquals("value2", withArgs.getPropertyWithPrefix("b", 2)); Assert.assertEquals("value2", withArgs.getPropertyWithoutPrefix("b", 2)); Assert.assertEquals("default", withArgs.getPropertyWithPrefix("a", 2)); Assert.assertEquals("default", withArgs.getPropertyWithoutPrefix("a", 2)); } @SuppressWarnings("unused") public interface WithArgumentsAndDefaultMethod { @PropertyName(name="${0}.abc.${1}") default String getPropertyWith2Placeholders(String part0, int part1) { return "defaultFor2"; } @PropertyName(name="${0}.def") default String getPropertyWith1Placeholder(String part0) { return "defaultFor1"; } } @Test public void testWithArgumentsAndDefaultMethod() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("a.abc.1", "value1"); config.setProperty("b.abc.2", "value2"); config.setProperty("c.def", "value_c"); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); WithArgumentsAndDefaultMethod withArgsAndDefM = proxy.newProxy(WithArgumentsAndDefaultMethod.class); Assert.assertEquals("value1", withArgsAndDefM.getPropertyWith2Placeholders("a", 1)); Assert.assertEquals("value2", withArgsAndDefM.getPropertyWith2Placeholders("b", 2)); Assert.assertEquals("defaultFor2", withArgsAndDefM.getPropertyWith2Placeholders("a", 2)); Assert.assertEquals("value_c", withArgsAndDefM.getPropertyWith1Placeholder("c")); Assert.assertEquals("defaultFor1", withArgsAndDefM.getPropertyWith1Placeholder("q")); } public interface ConfigWithMaps { @PropertyName(name="map") default Map<String, Long> getStringToLongMap() { return Collections.singletonMap("default", 0L); } @PropertyName(name="map2") default Map<Long, String> getLongToStringMap() { return Collections.singletonMap(0L, "default"); } } @Test public void testWithLongMap() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("map", "a=123,b=456"); config.setProperty("map2", "1=a,2=b"); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); ConfigWithMaps withMaps = proxy.newProxy(ConfigWithMaps.class); long sub1 = withMaps.getStringToLongMap().get("a"); long sub2 = withMaps.getStringToLongMap().get("b"); Assert.assertEquals(123, sub1); Assert.assertEquals(456, sub2); config.setProperty("map", "a=123,b=789"); sub2 = withMaps.getStringToLongMap().get("b"); Assert.assertEquals(789, sub2); Assert.assertEquals("a", withMaps.getLongToStringMap().get(1L)); Assert.assertEquals("b", withMaps.getLongToStringMap().get(2L)); } @Test public void testWithLongMapDefaultValue() { SettableConfig config = new DefaultSettableConfig(); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); ConfigWithMaps withArgs = proxy.newProxy(ConfigWithMaps.class); Assert.assertEquals(Collections.singletonMap("default", 0L), withArgs.getStringToLongMap()); config.setProperty("map", "foo=123"); Assert.assertEquals(Collections.singletonMap("foo", 123L), withArgs.getStringToLongMap()); } public interface ConfigWithCollections { List<Integer> getList(); Set<Integer> getSet(); SortedSet<Integer> getSortedSet(); LinkedList<Integer> getLinkedList(); } @Test public void testCollections() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("list", "5,4,3,2,1"); config.setProperty("set", "1,2,3,5,4"); config.setProperty("sortedSet", "5,4,3,2,1"); config.setProperty("linkedList", "5,4,3,2,1"); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); ConfigWithCollections withCollections = proxy.newProxy(ConfigWithCollections.class); Assert.assertEquals(Arrays.asList(5,4,3,2,1), new ArrayList<>(withCollections.getLinkedList())); Assert.assertEquals(Arrays.asList(5,4,3,2,1), new ArrayList<>(withCollections.getList())); Assert.assertEquals(Arrays.asList(1,2,3,5,4), new ArrayList<>(withCollections.getSet())); Assert.assertEquals(Arrays.asList(1,2,3,4,5), new ArrayList<>(withCollections.getSortedSet())); config.setProperty("list", "6,7,8,9,10"); Assert.assertEquals(Arrays.asList(6,7,8,9,10), new ArrayList<>(withCollections.getList())); } @Test public void testCollectionsImmutable() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("list", "5,4,3,2,1"); config.setProperty("set", "1,2,3,5,4"); config.setProperty("sortedSet", "5,4,3,2,1"); config.setProperty("linkedList", "5,4,3,2,1"); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); ConfigWithCollections withCollections = proxy.newProxy(ConfigWithCollections.class, "", true); Assert.assertEquals(Arrays.asList(5,4,3,2,1), new ArrayList<>(withCollections.getLinkedList())); Assert.assertEquals(Arrays.asList(5,4,3,2,1), new ArrayList<>(withCollections.getList())); Assert.assertEquals(Arrays.asList(1,2,3,5,4), new ArrayList<>(withCollections.getSet())); Assert.assertEquals(Arrays.asList(1,2,3,4,5), new ArrayList<>(withCollections.getSortedSet())); config.setProperty("list", "4,7,8,9,10"); Assert.assertEquals(Arrays.asList(5,4,3,2,1), new ArrayList<>(withCollections.getList())); } @Test public void emptyNonStringValuesIgnoredInCollections() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("list", ",4, ,2,1"); config.setProperty("set", ",2, ,5,4"); config.setProperty("sortedSet", ",4, ,2,1"); config.setProperty("linkedList", ",4, ,2,1"); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); ConfigWithCollections withCollections = proxy.newProxy(ConfigWithCollections.class); Assert.assertEquals(Arrays.asList(4,2,1), new ArrayList<>(withCollections.getLinkedList())); Assert.assertEquals(Arrays.asList(4,2,1), new ArrayList<>(withCollections.getList())); Assert.assertEquals(Arrays.asList(2,5,4), new ArrayList<>(withCollections.getSet())); Assert.assertEquals(Arrays.asList(1,2,4), new ArrayList<>(withCollections.getSortedSet())); } public interface ConfigWithStringCollections { List<String> getList(); Set<String> getSet(); SortedSet<String> getSortedSet(); LinkedList<String> getLinkedList(); } @Test public void emptyStringValuesAreAddedToCollection() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("list", ",4, ,2,1"); config.setProperty("set", ",2, ,5,4"); config.setProperty("sortedSet", ",4, ,2,1"); config.setProperty("linkedList", ",4, ,2,1"); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); ConfigWithStringCollections withCollections = proxy.newProxy(ConfigWithStringCollections.class); Assert.assertEquals(Arrays.asList("", "4","", "2","1"), new ArrayList<>(withCollections.getLinkedList())); Assert.assertEquals(Arrays.asList("", "4","", "2","1"), new ArrayList<>(withCollections.getList())); Assert.assertEquals(Arrays.asList("" ,"2","5","4"), new ArrayList<>(withCollections.getSet())); Assert.assertEquals(Arrays.asList("", "1","2","4"), new ArrayList<>(withCollections.getSortedSet())); } @Test public void collectionsReturnEmptySetsByDefault() { SettableConfig config = new DefaultSettableConfig(); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); ConfigWithStringCollections withCollections = proxy.newProxy(ConfigWithStringCollections.class); Assert.assertTrue(withCollections.getLinkedList().isEmpty()); Assert.assertTrue(withCollections.getList().isEmpty()); Assert.assertTrue(withCollections.getSet().isEmpty()); Assert.assertTrue(withCollections.getSortedSet().isEmpty()); } @Test public void testCollectionsWithoutValue() { SettableConfig config = new DefaultSettableConfig(); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); ConfigWithCollections withCollections = proxy.newProxy(ConfigWithCollections.class); System.out.println(withCollections.toString()); Assert.assertTrue(withCollections.getLinkedList().isEmpty()); Assert.assertTrue(withCollections.getList().isEmpty()); Assert.assertTrue(withCollections.getSet().isEmpty()); Assert.assertTrue(withCollections.getSortedSet().isEmpty()); } @SuppressWarnings("unused") public interface ConfigWithCollectionsWithDefaultValueAnnotation { @DefaultValue("") LinkedList<Integer> getLinkedList(); } @Test(expected=RuntimeException.class) public void testCollectionsWithDefaultValueAnnotation() { SettableConfig config = new DefaultSettableConfig(); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); proxy.newProxy(ConfigWithCollectionsWithDefaultValueAnnotation.class); } public interface ConfigWithDefaultStringCollections { default List<String> getList() { return Collections.singletonList("default"); } default Set<String> getSet() { return Collections.singleton("default"); } default SortedSet<String> getSortedSet() { return new TreeSet<>(Collections.singleton("default")); } } @Test public void interfaceDefaultCollections() { SettableConfig config = new DefaultSettableConfig(); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); ConfigWithDefaultStringCollections withCollections = proxy.newProxy(ConfigWithDefaultStringCollections.class); Assert.assertEquals(Collections.singletonList("default"), new ArrayList<>(withCollections.getList())); Assert.assertEquals(Collections.singletonList("default"), new ArrayList<>(withCollections.getSet())); Assert.assertEquals(Collections.singletonList("default"), new ArrayList<>(withCollections.getSortedSet())); } @SuppressWarnings("UnusedReturnValue") public interface FailingError { default String getValue() { throw new IllegalStateException("error"); } } @Test(expected=RuntimeException.class) public void interfaceWithBadDefault() { SettableConfig config = new DefaultSettableConfig(); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); FailingError c = proxy.newProxy(FailingError.class); c.getValue(); } @Test public void testObjectMethods() { // These tests just ensure that toString, equals and hashCode have implementations that don't fail. SettableConfig config = new DefaultSettableConfig(); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); WithArguments withArgs = proxy.newProxy(WithArguments.class); Assert.assertEquals("WithArguments[${0}.abc.${1}='default']", withArgs.toString()); //noinspection ObviousNullCheck Assert.assertNotNull(withArgs.hashCode()); //noinspection EqualsWithItself Assert.assertEquals(withArgs, withArgs); } @Test public void testObjectMethods_ClassWithArgumentsAndDefaultMethod() { // These tests just ensure that toString, equals and hashCode have implementations that don't fail. SettableConfig config = new DefaultSettableConfig(); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); WithArgumentsAndDefaultMethod withArgs = proxy.newProxy(WithArgumentsAndDefaultMethod.class); // Printing 'null' here is a compromise. The default method in the interface is being called with a bad signature. // There's nothing the proxy could return here that isn't a lie, but at least this is a mostly harmless lie. // This test depends implicitly on the iteration order for HashMap, which could change on future Java releases. Assert.assertEquals("WithArgumentsAndDefaultMethod[${0}.def='null',${0}.abc.${1}='null']", withArgs.toString()); //noinspection ObviousNullCheck Assert.assertNotNull(withArgs.hashCode()); //noinspection EqualsWithItself Assert.assertEquals(withArgs, withArgs); } @Ignore("Manual test. Output is just log entries, can't be verified by CI") @Test public void testLogExcessiveUse() { SettableConfig config = new DefaultSettableConfig(); PropertyFactory propertyFactory = DefaultPropertyFactory.from(config); for (int i = 0; i < 5; i++) { new ConfigProxyFactory(config, config.getDecoder(), propertyFactory); // Last one should emit a log! } SettableConfig otherConfig = new DefaultSettableConfig(); for (int i = 0; i < 4; i++) { new ConfigProxyFactory(otherConfig, config.getDecoder(), propertyFactory); // Should not log! It's only 4 and on a different config. } ConfigProxyFactory factory = new ConfigProxyFactory(config, config.getDecoder(), propertyFactory); // Should not log, because we only log every 5. for (int i = 0; i < 5; i++) { factory.newProxy(WithArguments.class, "aPrefix"); // Last one should emit a log } factory.newProxy(WithArguments.class, "somePrefix"); // This one should not log, because it's a new prefix. } }
9,237
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/DefaultPropertyContainerTest.java
package com.netflix.archaius; import org.junit.Assert; import org.junit.Test; import com.netflix.archaius.api.Property; import com.netflix.archaius.api.config.SettableConfig; import com.netflix.archaius.config.DefaultSettableConfig; public class DefaultPropertyContainerTest { @Test public void basicTest() { SettableConfig config = new DefaultSettableConfig(); DefaultPropertyFactory factory = DefaultPropertyFactory.from(config); Property<String> prop = factory.getProperty("foo").asString("default"); Assert.assertEquals("default", prop.get()); config.setProperty("foo", "value1"); Assert.assertEquals("value1", prop.get()); Assert.assertEquals("value1", prop.get()); } }
9,238
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/ConfigManagerTest.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius; import com.netflix.archaius.api.Property; import com.netflix.archaius.api.PropertyFactory; import com.netflix.archaius.config.DefaultCompositeConfig; import org.junit.Test; import com.netflix.archaius.config.MapConfig; import com.netflix.archaius.api.config.CompositeConfig; import com.netflix.archaius.config.DefaultSettableConfig; import com.netflix.archaius.api.exceptions.ConfigException; import com.netflix.archaius.property.DefaultPropertyListener; public class ConfigManagerTest { @Test public void testBasicReplacement() throws ConfigException { DefaultSettableConfig dyn = new DefaultSettableConfig(); CompositeConfig config = new DefaultCompositeConfig(); config.addConfig("dyn", dyn); config.addConfig("map", (MapConfig.builder() .put("env", "prod") .put("region", "us-east") .put("c", 123) .build())); PropertyFactory factory = DefaultPropertyFactory.from(config); Property<String> prop = factory.getProperty("abc").asString("defaultValue"); prop.addListener(new DefaultPropertyListener<String>() { @Override public void onChange(String next) { System.out.println("Configuration changed : " + next); } }); dyn.setProperty("abc", "${c}"); } }
9,239
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/config/MapConfigTest.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.config; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.exceptions.ConfigException; import com.netflix.archaius.exceptions.ParseException; import static com.netflix.archaius.TestUtils.set; import static com.netflix.archaius.TestUtils.size; public class MapConfigTest { private final MapConfig config = MapConfig.builder() .put("str", "value") .put("badnumber", "badnumber") .build(); @Test(expected=NoSuchElementException.class) public void nonExistantString() { config.getString("nonexistent"); } @Test(expected=NoSuchElementException.class) public void nonExistantBigDecimal() { config.getBigDecimal("nonexistent"); } @Test(expected=NoSuchElementException.class) public void nonExistantBigInteger() { config.getBigInteger("nonexistent"); } @Test(expected=NoSuchElementException.class) public void nonExistantBoolean() { config.getBoolean("nonexistent"); } @Test(expected=NoSuchElementException.class) public void nonExistantByte() { config.getByte("nonexistent"); } @Test(expected=NoSuchElementException.class) public void nonExistantDouble() { config.getDouble("nonexistent"); } @Test(expected=NoSuchElementException.class) public void nonExistantFloat() { config.getFloat("nonexistent"); } @Test(expected=NoSuchElementException.class) public void nonExistantInteger() { config.getInteger("nonexistent"); } @Test(expected=NoSuchElementException.class) public void nonExistantList() { config.getList("nonexistent"); } @Test(expected=NoSuchElementException.class) public void nonExistantLong() { config.getLong("nonexistent"); } @Test(expected=NoSuchElementException.class) public void nonExistantShort() { config.getShort("nonexistent"); } @Test(expected=ParseException.class) public void invalidBigDecimal() { config.getBigDecimal("badnumber"); } @Test(expected=ParseException.class) public void invalidBigInteger() { config.getBigInteger("badnumber"); } @Test(expected=ParseException.class) public void invalidBoolean() { config.getBoolean("badnumber"); } @Test(expected=Exception.class) @Ignore public void invalidByte() { config.getByte("badnumber"); } @Test(expected=ParseException.class) public void invalidDouble() { config.getDouble("badnumber"); } @Test(expected=ParseException.class) public void invalidFloat() { config.getFloat("badnumber"); } @Test(expected=ParseException.class) public void invalidInteger() { config.getInteger("badnumber"); } @Test(expected=Exception.class) @Ignore public void invalidList() { // TODO } @Test(expected=ParseException.class) public void invalidLong() { config.getLong("badnumber"); } @Test(expected=ParseException.class) public void invalidShort() { config.getShort("badnumber"); } @Test public void interpolationShouldWork() throws ConfigException { Config config = MapConfig.builder() .put("env", "prod") .put("replacement", "${env}") .build(); Assert.assertEquals("prod", config.getString("replacement")); } @Test public void interpolationWithDefaultReplacement() throws ConfigException { Config config = MapConfig.builder() .put("env", "prod") .put("replacement", "${env}") .build(); Assert.assertEquals("prod", config.getString("nonexistent", "${env}")); } @Test(expected=IllegalStateException.class) public void infiniteInterpolationRecursionShouldFail() throws ConfigException { Config config = MapConfig.builder() .put("env", "${env}") .put("replacement.env", "${env}") .build(); Assert.assertEquals("prod", config.getString("replacement.env")); } @Test public void numericInterpolationShouldWork() throws ConfigException { Config config = MapConfig.builder() .put("default", "123") .put("value", "${default}") .build(); Assert.assertEquals((long)123L, (long)config.getLong("value")); } @Test public void getKeys() { Map<String, String> props = new HashMap<>(); props.put("key1", "value1"); props.put("key2", "value2"); Config config = MapConfig.from(props); Iterator<String> keys = config.getKeys(); Assert.assertTrue(keys.hasNext()); Set<String> keySet = new HashSet<>(); while (keys.hasNext()) { keySet.add(keys.next()); } Assert.assertEquals(2, keySet.size()); Assert.assertEquals(props.keySet(), keySet); } @Test public void getKeysIteratorRemoveThrows() { Config config = MapConfig.builder() .put("key1", "value1") .put("key2", "value2") .build(); Iterator<String> keys = config.getKeys(); Assert.assertTrue(keys.hasNext()); keys.next(); Assert.assertThrows(UnsupportedOperationException.class, keys::remove); } @Test public void testKeysIterable() { Config config = MapConfig.builder() .put("key1", "value1") .put("key2", "value2") .build(); Iterable<String> keys = config.keys(); Assert.assertEquals(2, size(keys)); Assert.assertEquals(set("key1", "key2"), set(keys)); } @Test public void testKeysIterableModificationThrows() { Config config = MapConfig.builder() .put("key1", "value1") .put("key2", "value2") .build(); Assert.assertThrows(UnsupportedOperationException.class, config.keys().iterator()::remove); Assert.assertThrows(UnsupportedOperationException.class, ((Collection<String>) config.keys())::clear); } }
9,240
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/config/AbstractConfigTest.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.config; import java.util.Collections; import java.util.Iterator; import java.util.function.BiConsumer; import org.junit.Assert; import org.junit.Test; public class AbstractConfigTest { private final AbstractConfig config = new AbstractConfig() { @Override public boolean containsKey(String key) { return "foo".equals(key); } @Override public boolean isEmpty() { return false; } @Override public Iterator<String> getKeys() { return Collections.singletonList("foo").iterator(); } @Override public Object getRawProperty(String key) { if ("foo".equals(key)) { return "bar"; } return null; } @Override public void forEachProperty(BiConsumer<String, Object> consumer) { consumer.accept("foo", "bar"); } }; @Test public void testGet() throws Exception { Assert.assertEquals("bar", config.get(String.class, "foo")); } @Test public void getExistingProperty() { Assert.assertEquals("bar", config.getProperty("foo").get()); } @Test public void getNonExistentProperty() { Assert.assertFalse(config.getProperty("non_existent").isPresent()); } }
9,241
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/config/PrefixedViewTest.java
package com.netflix.archaius.config; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.ConfigListener; import com.netflix.archaius.api.PropertyDetails; import com.netflix.archaius.api.config.SettableConfig; import com.netflix.archaius.api.exceptions.ConfigException; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import com.netflix.archaius.config.polling.ManualPollingStrategy; import com.netflix.archaius.config.polling.PollingResponse; import com.netflix.archaius.instrumentation.AccessMonitorUtil; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import static com.netflix.archaius.TestUtils.set; import static com.netflix.archaius.TestUtils.size; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class PrefixedViewTest { @Test public void confirmNotifactionOnAnyChange() throws ConfigException { com.netflix.archaius.api.config.CompositeConfig config = DefaultCompositeConfig.builder() .withConfig("foo", MapConfig.builder().put("foo.bar", "value").build()) .build(); Config prefix = config.getPrefixedView("foo"); ConfigListener listener = Mockito.mock(ConfigListener.class); prefix.addListener(listener); Mockito.verify(listener, Mockito.times(0)).onConfigAdded(any()); config.addConfig("bar", DefaultCompositeConfig.builder() .withConfig("foo", MapConfig.builder().put("foo.bar", "value").build()) .build()); Mockito.verify(listener, Mockito.times(1)).onConfigAdded(any()); } @Test public void confirmNotifactionOnSettableConfigChange() throws ConfigException { SettableConfig settable = new DefaultSettableConfig(); settable.setProperty("foo.bar", "original"); com.netflix.archaius.api.config.CompositeConfig config = DefaultCompositeConfig.builder() .withConfig("settable", settable) .build(); Config prefix = config.getPrefixedView("foo"); ConfigListener listener = Mockito.mock(ConfigListener.class); prefix.addListener(listener); // Confirm original state Assert.assertEquals("original", prefix.getString("bar")); Mockito.verify(listener, Mockito.times(0)).onConfigAdded(any()); // Update the property and confirm onConfigUpdated notification settable.setProperty("foo.bar", "new"); Mockito.verify(listener, Mockito.times(1)).onConfigUpdated(any()); Assert.assertEquals("new", prefix.getString("bar")); // Add a new config and confirm onConfigAdded notification config.addConfig("new", MapConfig.builder().put("foo.bar", "new2").build()); Mockito.verify(listener, Mockito.times(1)).onConfigAdded(any()); Mockito.verify(listener, Mockito.times(1)).onConfigUpdated(any()); } @Test public void trailingDotAllowed() { SettableConfig settable = new DefaultSettableConfig(); settable.setProperty("foo.bar", "value"); Config prefixNoDot = settable.getPrefixedView("foo"); Config prefixWithDot = settable.getPrefixedView("foo."); Assert.assertEquals(prefixNoDot.getString("bar"), "value"); Assert.assertEquals(prefixWithDot.getString("bar"), "value"); } @Test public void unusedPrefixedViewIsGarbageCollected() { SettableConfig sourceConfig = new DefaultSettableConfig(); Config prefix = sourceConfig.getPrefixedView("foo."); Reference<Config> weakReference = new WeakReference<>(prefix); // No more pointers to prefix means this should be garbage collected and any additional listeners on it prefix = null; System.gc(); Assert.assertNull(weakReference.get()); } @Test public void testGetKeys() { Config config = MapConfig.builder() .put("foo.prop1", "value1") .put("foo.prop2", "value2") .build() .getPrefixedView("foo"); Iterator<String> keys = config.getKeys(); Set<String> keySet = new HashSet<>(); while (keys.hasNext()) { keySet.add(keys.next()); } Assert.assertEquals(2, keySet.size()); Assert.assertTrue(keySet.contains("prop1")); Assert.assertTrue(keySet.contains("prop2")); } @Test public void testGetKeysIteratorRemoveThrows() { Config config = MapConfig.builder() .put("foo.prop1", "value1") .put("foo.prop2", "value2") .build() .getPrefixedView("foo"); Iterator<String> keys = config.getKeys(); keys.next(); Assert.assertThrows(UnsupportedOperationException.class, keys::remove); } @Test public void testKeysIterable() { Config config = MapConfig.builder() .put("foo.prop1", "value1") .put("foo.prop2", "value2") .build() .getPrefixedView("foo"); Iterable<String> keys = config.keys(); Assert.assertEquals(2, size(keys)); Assert.assertEquals(set("prop1", "prop2"), set(keys)); } @Test public void testKeysIterableModificationThrows() { Config config = MapConfig.builder() .put("foo.prop1", "value1") .put("foo.prop2", "value2") .build() .getPrefixedView("foo"); Assert.assertThrows(UnsupportedOperationException.class, config.keys().iterator()::remove); Assert.assertThrows(UnsupportedOperationException.class, ((Collection<String>) config.keys())::clear); } @Test public void instrumentationNotEnabled() throws Exception { Config config = MapConfig.builder() .put("foo.prop1", "value1") .put("foo.prop2", "value2") .build() .getPrefixedView("foo"); Assert.assertFalse(config.instrumentationEnabled()); Assert.assertEquals(config.getRawProperty("prop1"), "value1"); Assert.assertEquals(config.getRawProperty("prop2"), "value2"); } @Test public void instrumentation() throws Exception { ManualPollingStrategy strategy = new ManualPollingStrategy(); Callable<PollingResponse> reader = () -> { Map<String, String> props = new HashMap<>(); props.put("foo.prop1", "foo-value"); props.put("foo.prop2", "bar-value"); Map<String, String> propIds = new HashMap<>(); propIds.put("foo.prop1", "1"); propIds.put("foo.prop2", "2"); return PollingResponse.forSnapshot(props, propIds); }; AccessMonitorUtil accessMonitorUtil = spy(AccessMonitorUtil.builder().build()); PollingDynamicConfig baseConfig = new PollingDynamicConfig(reader, strategy, accessMonitorUtil); strategy.fire(); Config config = baseConfig.getPrefixedView("foo"); Assert.assertTrue(config.instrumentationEnabled()); config.getRawProperty("prop1"); verify(accessMonitorUtil).registerUsage(eq(new PropertyDetails("foo.prop1", "1", "foo-value"))); verify(accessMonitorUtil, times(1)).registerUsage(any()); config.getRawPropertyUninstrumented("prop2"); verify(accessMonitorUtil, times(1)).registerUsage(any()); config.forEachProperty((k, v) -> {}); verify(accessMonitorUtil, times(2)).registerUsage(eq(new PropertyDetails("foo.prop1", "1", "foo-value"))); verify(accessMonitorUtil, times(1)).registerUsage(eq(new PropertyDetails("foo.prop2", "2", "bar-value"))); verify(accessMonitorUtil, times(3)).registerUsage(any()); config.forEachPropertyUninstrumented((k, v) -> {}); verify(accessMonitorUtil, times(3)).registerUsage(any()); } }
9,242
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/config/ConfigLoaderTest.java
package com.netflix.archaius.config; import org.junit.Assert; import org.junit.Test; import com.netflix.archaius.api.Config; import com.netflix.archaius.DefaultConfigLoader; import com.netflix.archaius.api.exceptions.ConfigException; public class ConfigLoaderTest { @Test public void testLoadingOfNonExistantFile() throws ConfigException { DefaultConfigLoader loader = DefaultConfigLoader.builder() .build(); Config config = loader.newLoader().load("non-existant"); Assert.assertTrue(config.isEmpty()); } }
9,243
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/config/CompositeConfigTest.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.config; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.concurrent.Callable; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.config.SettableConfig; import com.netflix.archaius.config.polling.ManualPollingStrategy; import com.netflix.archaius.config.polling.PollingResponse; import com.netflix.archaius.instrumentation.AccessMonitorUtil; import com.netflix.archaius.api.PropertyDetails; import org.junit.Assert; import org.junit.Test; import com.netflix.archaius.DefaultConfigLoader; import com.netflix.archaius.cascade.ConcatCascadeStrategy; import com.netflix.archaius.api.exceptions.ConfigException; import com.netflix.archaius.visitor.PrintStreamVisitor; import static com.netflix.archaius.TestUtils.set; import static com.netflix.archaius.TestUtils.size; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class CompositeConfigTest { @Test public void basicTest() throws ConfigException { Properties props = new Properties(); props.setProperty("env", "prod"); com.netflix.archaius.api.config.CompositeConfig libraries = new DefaultCompositeConfig(); com.netflix.archaius.api.config.CompositeConfig application = new DefaultCompositeConfig(); com.netflix.archaius.api.config.CompositeConfig config = DefaultCompositeConfig.builder() .withConfig("lib", libraries) .withConfig("app", application) .withConfig("set", MapConfig.from(props)) .build(); DefaultConfigLoader loader = DefaultConfigLoader.builder() .withStrLookup(config) .withDefaultCascadingStrategy(ConcatCascadeStrategy.from("${env}")) .build(); application.replaceConfig("application", loader.newLoader().load("application")); Assert.assertTrue(config.getBoolean("application.loaded")); Assert.assertTrue(config.getBoolean("application-prod.loaded", false)); Assert.assertFalse(config.getBoolean("libA.loaded", false)); libraries.replaceConfig("libA", loader.newLoader().load("libA")); libraries.accept(new PrintStreamVisitor()); config.accept(new PrintStreamVisitor()); Assert.assertTrue(config.getBoolean("libA.loaded")); Assert.assertFalse(config.getBoolean("libB.loaded", false)); Assert.assertEquals("libA", config.getString("libA.overrideA")); libraries.replaceConfig("libB", loader.newLoader().load("libB")); System.out.println(config.toString()); Assert.assertTrue(config.getBoolean("libA.loaded")); Assert.assertTrue(config.getBoolean("libB.loaded")); Assert.assertEquals("libA", config.getString("libA.overrideA")); config.accept(new PrintStreamVisitor()); } @Test public void basicReversedTest() throws ConfigException { Properties props = new Properties(); props.setProperty("env", "prod"); com.netflix.archaius.api.config.CompositeConfig libraries = new DefaultCompositeConfig(true); com.netflix.archaius.api.config.CompositeConfig application = new DefaultCompositeConfig(); com.netflix.archaius.api.config.CompositeConfig config = DefaultCompositeConfig.builder() .withConfig("lib", libraries) .withConfig("app", application) .withConfig("set", MapConfig.from(props)) .build(); DefaultConfigLoader loader = DefaultConfigLoader.builder() .withStrLookup(config) .withDefaultCascadingStrategy(ConcatCascadeStrategy.from("${env}")) .build(); application.replaceConfig("application", loader.newLoader().load("application")); Assert.assertTrue(config.getBoolean("application.loaded")); Assert.assertTrue(config.getBoolean("application-prod.loaded", false)); Assert.assertFalse(config.getBoolean("libA.loaded", false)); libraries.replaceConfig("libA", loader.newLoader().load("libA")); libraries.accept(new PrintStreamVisitor()); config.accept(new PrintStreamVisitor()); Assert.assertTrue(config.getBoolean("libA.loaded")); Assert.assertFalse(config.getBoolean("libB.loaded", false)); Assert.assertEquals("libA", config.getString("libA.overrideA")); libraries.replaceConfig("libB", loader.newLoader().load("libB")); System.out.println(config.toString()); Assert.assertTrue(config.getBoolean("libA.loaded")); Assert.assertTrue(config.getBoolean("libB.loaded")); Assert.assertEquals("libB", config.getString("libA.overrideA")); config.accept(new PrintStreamVisitor()); } @Test public void getKeysTest() throws ConfigException { com.netflix.archaius.api.config.CompositeConfig composite = new DefaultCompositeConfig(); composite.addConfig("a", EmptyConfig.INSTANCE); Iterator<String> iter = composite.getKeys(); Assert.assertFalse(iter.hasNext()); composite.addConfig("b", MapConfig.builder().put("b1", "A").put("b2", "B").build()); iter = composite.getKeys(); Assert.assertEquals(set("b1", "b2"), set(iter)); composite.addConfig("c", EmptyConfig.INSTANCE); iter = composite.getKeys(); Assert.assertEquals(set("b1", "b2"), set(iter)); composite.addConfig("d", MapConfig.builder().put("d1", "A").put("d2", "B").build()); composite.addConfig("e", MapConfig.builder().put("e1", "A").put("e2", "B").build()); iter = composite.getKeys(); Assert.assertEquals(set("b1", "b2", "d1", "d2", "e1", "e2"), set(iter)); } @Test public void testGetKeysIteratorRemoveThrows() throws ConfigException { com.netflix.archaius.api.config.CompositeConfig composite = new DefaultCompositeConfig(); composite.addConfig("d", MapConfig.builder().put("d1", "A").put("d2", "B").build()); composite.addConfig("e", MapConfig.builder().put("e1", "A").put("e2", "B").build()); Iterator<String> keys = composite.getKeys(); Assert.assertTrue(keys.hasNext()); keys.next(); Assert.assertThrows(UnsupportedOperationException.class, keys::remove); } @Test public void testKeysIterable() throws ConfigException { com.netflix.archaius.api.config.CompositeConfig composite = new DefaultCompositeConfig(); composite.addConfig("d", MapConfig.builder().put("d1", "A").put("d2", "B").build()); composite.addConfig("e", MapConfig.builder().put("e1", "A").put("e2", "B").build()); Iterable<String> keys = composite.keys(); Assert.assertEquals(4, size(keys)); Assert.assertEquals(set("d1", "d2", "e1", "e2"), set(keys)); } @Test public void testKeysIterableModificationThrows() throws ConfigException { com.netflix.archaius.api.config.CompositeConfig composite = new DefaultCompositeConfig(); composite.addConfig("d", MapConfig.builder().put("d1", "A").put("d2", "B").build()); composite.addConfig("e", MapConfig.builder().put("e1", "A").put("e2", "B").build()); Assert.assertThrows(UnsupportedOperationException.class, composite.keys().iterator()::remove); Assert.assertThrows(UnsupportedOperationException.class, ((Collection<String>) composite.keys())::clear); } @Test public void unusedCompositeConfigIsGarbageCollected() throws ConfigException { SettableConfig sourceConfig = new DefaultSettableConfig(); com.netflix.archaius.api.config.CompositeConfig config = DefaultCompositeConfig.builder() .withConfig("settable", sourceConfig) .build(); Reference<Config> weakReference = new WeakReference<>(config); // No more pointers to prefix means this should be garbage collected and any additional listeners on it config = null; System.gc(); Assert.assertNull(weakReference.get()); } @Test public void instrumentationNotEnabled() throws Exception { com.netflix.archaius.api.config.CompositeConfig composite = new DefaultCompositeConfig(); composite.addConfig("polling", createPollingDynamicConfig("a1", "1", "b1", "2", null)); Assert.assertFalse(composite.instrumentationEnabled()); Assert.assertEquals(composite.getRawProperty("a1"), "1"); Assert.assertEquals(composite.getRawProperty("b1"), "2"); } @Test public void instrumentationPropagation() throws Exception { com.netflix.archaius.api.config.CompositeConfig composite = new DefaultCompositeConfig(); AccessMonitorUtil accessMonitorUtil = spy(AccessMonitorUtil.builder().build()); PollingDynamicConfig outerPollingDynamicConfig = createPollingDynamicConfig("a1", "1", "b1", "2", accessMonitorUtil); composite.addConfig("outer", outerPollingDynamicConfig); com.netflix.archaius.api.config.CompositeConfig innerComposite = new DefaultCompositeConfig(); PollingDynamicConfig nestedPollingDynamicConfig = createPollingDynamicConfig("b1", "1", "c1", "3", accessMonitorUtil); innerComposite.addConfig("polling", nestedPollingDynamicConfig); composite.addConfig("innerComposite", innerComposite); composite.addConfig("d", MapConfig.builder().put("c1", "4").put("d1", "5").build()); // Properties (a1: 1) and (b1: 2) are covered by the first polling config Assert.assertEquals(composite.getRawProperty("a1"), "1"); verify(accessMonitorUtil).registerUsage(eq(new PropertyDetails("a1", "a1", "1"))); Assert.assertEquals(composite.getRawPropertyUninstrumented("a1"), "1"); verify(accessMonitorUtil, times(1)).registerUsage(any()); Assert.assertEquals(composite.getRawProperty("b1"), "2"); verify(accessMonitorUtil).registerUsage(eq(new PropertyDetails("b1", "b1", "2"))); Assert.assertEquals(composite.getRawPropertyUninstrumented("b1"), "2"); verify(accessMonitorUtil, times(2)).registerUsage(any()); // Property (c1: 3) is covered by the composite config over the polling config Assert.assertEquals(composite.getRawProperty("c1"), "3"); verify(accessMonitorUtil).registerUsage(eq(new PropertyDetails("c1", "c1", "3"))); Assert.assertEquals(composite.getRawPropertyUninstrumented("c1"), "3"); verify(accessMonitorUtil, times(3)).registerUsage(any()); // Property (d1: 5) is covered by the final, uninstrumented MapConfig Assert.assertEquals(composite.getRawProperty("d1"), "5"); verify(accessMonitorUtil, times(3)).registerUsage(any()); Assert.assertEquals(composite.getRawPropertyUninstrumented("d1"), "5"); verify(accessMonitorUtil, times(3)).registerUsage(any()); // The instrumented forEachProperty endpoint updates the counts for every property composite.forEachProperty((k, v) -> {}); verify(accessMonitorUtil, times(2)).registerUsage(eq(new PropertyDetails("a1", "a1", "1"))); verify(accessMonitorUtil, times(2)).registerUsage(eq(new PropertyDetails("b1", "b1", "2"))); verify(accessMonitorUtil, times(2)).registerUsage(eq(new PropertyDetails("c1", "c1", "3"))); verify(accessMonitorUtil, times(6)).registerUsage((any())); // The uninstrumented forEachProperty leaves the counts unchanged composite.forEachPropertyUninstrumented((k, v) -> {}); verify(accessMonitorUtil, times(6)).registerUsage((any())); } private PollingDynamicConfig createPollingDynamicConfig( String key1, String value1, String key2, String value2, AccessMonitorUtil accessMonitorUtil) throws Exception { ManualPollingStrategy strategy = new ManualPollingStrategy(); Map<String, String> props = new HashMap<>(); props.put(key1, value1); props.put(key2, value2); Map<String, String> propIds = new HashMap<>(); propIds.put(key1, key1); propIds.put(key2, key2); Callable<PollingResponse> reader = () -> PollingResponse.forSnapshot(props, propIds); PollingDynamicConfig config = new PollingDynamicConfig(reader, strategy, accessMonitorUtil); strategy.fire(); return config; } }
9,244
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/config/InterpolationTest.java
package com.netflix.archaius.config; import org.junit.Assert; import org.junit.Test; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.config.CompositeConfig; import com.netflix.archaius.api.exceptions.ConfigException; import com.netflix.archaius.visitor.PrintStreamVisitor; public class InterpolationTest { @Test public void simpleStringInterpolation() { MapConfig config = MapConfig.builder() .put("foo", "${bar}") .put("bar", "value") .build(); Assert.assertEquals("value", config.getString("foo")); } @Test public void nonStringInterpolation() { MapConfig config = MapConfig.builder() .put("foo", "${bar}") .put("bar", "123") .build(); Assert.assertEquals(123, config.getInteger("foo").intValue()); } @Test public void interpolationOnlyDoneOnParent() throws ConfigException { MapConfig child1 = MapConfig.builder() .put("bar", "123") .build(); MapConfig child2 = MapConfig.builder() .put("foo", "${bar}") .build(); CompositeConfig composite = DefaultCompositeConfig.builder() .withConfig("a", child1) .withConfig("b", child2) .build(); Assert.assertEquals("123", composite.getString("foo")); Assert.assertEquals("not_found", child1.getString("foo", "not_found")); Assert.assertEquals("not_found", child2.getString("${parent}", "not_found")); } @Test public void stringInterpolationWithDefault() { MapConfig config = MapConfig.builder() .put("bar", "${foo:default}") .build(); Assert.assertEquals("default", config.getString("bar")); } @Test public void numericInterpolationWithDefault() { MapConfig config = MapConfig.builder() .put("bar", "${foo:-123}") .build(); Assert.assertEquals(-123, config.getInteger("bar").intValue()); } @Test public void interpolatePrefixedView() { Config config = MapConfig.builder() .put("prefix.key1", "${nonprefixed.key2}") .put("nonprefixed.key2", "key2_value") .build(); Assert.assertEquals("key2_value", config.getString("prefix.key1")); Config prefixedConfig = config.getPrefixedView("prefix"); prefixedConfig.accept(new PrintStreamVisitor()); Assert.assertEquals("key2_value", prefixedConfig.getString("key1")); } @Test public void interpolateNumericPrefixedView() { Config config = MapConfig.builder() .put("prefix.key1", "${nonprefixed.key2}") .put("nonprefixed.key2", "123") .build(); Assert.assertEquals(123, config.getInteger("prefix.key1").intValue()); Config prefixedConfig = config.getPrefixedView("prefix"); Assert.assertEquals(123, prefixedConfig.getInteger("key1").intValue()); } @Test public void nestedInterpolations() { Config config = MapConfig.builder() .put("a", "A") .put("b", "${c:${a}}") .build(); Assert.assertEquals("A", config.getString("b")); } @Test public void nestedInterpolationsWithResolve() { Config config = MapConfig.builder() .put("a", "A") .build(); Assert.assertEquals("A", config.resolve("${b:${c:${a}}}")); } @Test(expected=IllegalStateException.class) public void failOnCircularResolve() { Config config = MapConfig.builder() .build(); config.resolve("${b:${c:${b}}}"); } @Test public void returnStringOnMissingInterpolation() { Config config = MapConfig.builder() .build(); Assert.assertEquals("${c}", config.resolve("${b:${c}}")); } }
9,245
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/config/DefaultLayeredConfigTest.java
package com.netflix.archaius.config; import com.netflix.archaius.Layers; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.ConfigListener; import com.netflix.archaius.api.PropertyDetails; import com.netflix.archaius.api.config.LayeredConfig; import com.netflix.archaius.api.config.SettableConfig; import com.netflix.archaius.config.polling.ManualPollingStrategy; import com.netflix.archaius.config.polling.PollingResponse; import com.netflix.archaius.instrumentation.AccessMonitorUtil; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.Callable; import static com.netflix.archaius.TestUtils.set; import static com.netflix.archaius.TestUtils.size; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class DefaultLayeredConfigTest { @Test public void validateApiOnEmptyConfig() { LayeredConfig config = new DefaultLayeredConfig(); Assert.assertFalse(config.getProperty("propname").isPresent()); Assert.assertNull(config.getRawProperty("propname")); LayeredConfig.LayeredVisitor<String> visitor = Mockito.mock(LayeredConfig.LayeredVisitor.class); config.accept(visitor); Mockito.verify(visitor, Mockito.never()).visitConfig(any(), any()); Mockito.verify(visitor, Mockito.never()).visitKey(any(), any()); } @Test public void validateListenerCalled() { // Setup main config ConfigListener listener = Mockito.mock(ConfigListener.class); LayeredConfig config = new DefaultLayeredConfig(); config.addListener(listener); // Add a child config.addConfig(Layers.APPLICATION, new DefaultSettableConfig()); Mockito.verify(listener, Mockito.times(1)).onConfigUpdated(any()); } @Test public void validatePropertyUpdates() { // Setup main config ConfigListener listener = Mockito.mock(ConfigListener.class); LayeredConfig config = new DefaultLayeredConfig(); config.addListener(listener); // Add a child SettableConfig child = new DefaultSettableConfig(); child.setProperty("propname", "propvalue"); config.addConfig(Layers.APPLICATION, child); // Validate initial state Assert.assertEquals("propvalue", config.getProperty("propname").get()); Assert.assertEquals("propvalue", config.getRawProperty("propname")); // Update the property value child.setProperty("propname", "propvalue2"); // Validate new state Assert.assertEquals("propvalue2", config.getProperty("propname").get()); Assert.assertEquals("propvalue2", config.getRawProperty("propname")); Mockito.verify(listener, Mockito.times(2)).onConfigUpdated(any()); } @Test public void validateApiWhenRemovingChild() { // Setup main config ConfigListener listener = Mockito.mock(ConfigListener.class); LayeredConfig config = new DefaultLayeredConfig(); config.addListener(listener); // Add a child SettableConfig child = new DefaultSettableConfig(); child.setProperty("propname", "propvalue"); config.addConfig(Layers.APPLICATION, child); Mockito.verify(listener, Mockito.times(1)).onConfigUpdated(any()); // Validate initial state Assert.assertEquals("propvalue", config.getProperty("propname").get()); Assert.assertEquals("propvalue", config.getRawProperty("propname")); // Remove the child config.removeConfig(Layers.APPLICATION, child.getName()); // Validate new state Assert.assertFalse(config.getProperty("propname").isPresent()); Assert.assertNull(config.getRawProperty("propname")); Mockito.verify(listener, Mockito.times(2)).onConfigUpdated(any()); } @Test public void validateOverrideOrder() { MapConfig appConfig = MapConfig.builder() .put("propname", Layers.APPLICATION.getName()) .name(Layers.APPLICATION.getName()) .build(); MapConfig lib1Config = MapConfig.builder() .put("propname", Layers.LIBRARY.getName() + "1") .name(Layers.LIBRARY.getName() + "1") .build(); MapConfig lib2Config = MapConfig.builder() .put("propname", Layers.LIBRARY.getName() + "2") .name(Layers.LIBRARY.getName() + "2") .build(); MapConfig runtimeConfig = MapConfig.builder() .put("propname", Layers.RUNTIME.getName()) .name(Layers.RUNTIME.getName()) .build(); LayeredConfig config = new DefaultLayeredConfig(); Assert.assertFalse(config.getProperty("propname").isPresent()); config.addConfig(Layers.LIBRARY, lib1Config); Assert.assertEquals(lib1Config.getName(), config.getRawProperty("propname")); config.addConfig(Layers.LIBRARY, lib2Config); Assert.assertEquals(lib2Config.getName(), config.getRawProperty("propname")); config.addConfig(Layers.RUNTIME, runtimeConfig); Assert.assertEquals(runtimeConfig.getName(), config.getRawProperty("propname")); config.addConfig(Layers.APPLICATION, appConfig); Assert.assertEquals(runtimeConfig.getName(), config.getRawProperty("propname")); config.removeConfig(Layers.RUNTIME, runtimeConfig.getName()); Assert.assertEquals(appConfig.getName(), config.getRawProperty("propname")); } @Test public void unusedLayeredConfigIsGarbageCollected() { SettableConfig sourceConfig = new DefaultSettableConfig(); LayeredConfig config = new DefaultLayeredConfig(); config.addConfig(Layers.LIBRARY, sourceConfig); Reference<Config> weakReference = new WeakReference<>(config); // No more pointers to prefix means this should be garbage collected and any additional listeners on it config = null; System.gc(); Assert.assertNull(weakReference.get()); } @Test public void testGetKeys() { LayeredConfig config = new DefaultLayeredConfig(); MapConfig appConfig = MapConfig.builder() .put("propname", Layers.APPLICATION.getName()) .name(Layers.APPLICATION.getName()) .build(); MapConfig libConfig = MapConfig.builder() .put("propname", Layers.LIBRARY.getName() + "1") .name(Layers.LIBRARY.getName() + "1") .build(); config.addConfig(Layers.APPLICATION, appConfig); config.addConfig(Layers.LIBRARY, libConfig); Iterator<String> keys = config.getKeys(); Assert.assertTrue(keys.hasNext()); Assert.assertEquals("propname", keys.next()); Assert.assertFalse(keys.hasNext()); } @Test public void testGetKeysIteratorRemoveThrows() { LayeredConfig config = new DefaultLayeredConfig(); MapConfig appConfig = MapConfig.builder() .put("propname", Layers.APPLICATION.getName()) .name(Layers.APPLICATION.getName()) .build(); MapConfig libConfig = MapConfig.builder() .put("propname", Layers.LIBRARY.getName() + "1") .name(Layers.LIBRARY.getName() + "1") .build(); config.addConfig(Layers.APPLICATION, appConfig); config.addConfig(Layers.LIBRARY, libConfig); Iterator<String> keys = config.getKeys(); Assert.assertTrue(keys.hasNext()); keys.next(); Assert.assertThrows(UnsupportedOperationException.class, keys::remove); } @Test public void testKeysIterable() { LayeredConfig config = new DefaultLayeredConfig(); MapConfig appConfig = MapConfig.builder() .put("propname", Layers.APPLICATION.getName()) .name(Layers.APPLICATION.getName()) .build(); MapConfig libConfig = MapConfig.builder() .put("propname", Layers.LIBRARY.getName() + "1") .name(Layers.LIBRARY.getName() + "1") .build(); config.addConfig(Layers.APPLICATION, appConfig); config.addConfig(Layers.LIBRARY, libConfig); Iterable<String> keys = config.keys(); Assert.assertEquals(1, size(keys)); Assert.assertEquals(set("propname"), set(keys)); } @Test public void testKeysIterableModificationThrows() { LayeredConfig config = new DefaultLayeredConfig(); MapConfig appConfig = MapConfig.builder() .put("propname", Layers.APPLICATION.getName()) .name(Layers.APPLICATION.getName()) .build(); MapConfig libConfig = MapConfig.builder() .put("propname", Layers.LIBRARY.getName() + "1") .name(Layers.LIBRARY.getName() + "1") .build(); config.addConfig(Layers.APPLICATION, appConfig); config.addConfig(Layers.LIBRARY, libConfig); Assert.assertThrows(UnsupportedOperationException.class, config.keys().iterator()::remove); Assert.assertThrows(UnsupportedOperationException.class, ((Collection<String>) config.keys())::clear); } @Test public void instrumentationNotEnabled() throws Exception { LayeredConfig config = new DefaultLayeredConfig(); config.addConfig(Layers.DEFAULT, createPollingDynamicConfig("a1", "1", "b1", "2", null)); Assert.assertFalse(config.instrumentationEnabled()); Assert.assertEquals(config.getRawProperty("a1"), "1"); Assert.assertEquals(config.getRawProperty("b1"), "2"); } @Test public void instrumentationPropagation() throws Exception { com.netflix.archaius.api.config.LayeredConfig layered = new DefaultLayeredConfig(); AccessMonitorUtil accessMonitorUtil = spy(AccessMonitorUtil.builder().build()); PollingDynamicConfig outerPollingDynamicConfig = createPollingDynamicConfig("a1", "1", "b1", "2", accessMonitorUtil); layered.addConfig(Layers.RUNTIME, outerPollingDynamicConfig); com.netflix.archaius.api.config.CompositeConfig innerComposite = new DefaultCompositeConfig(); PollingDynamicConfig nestedPollingDynamicConfig = createPollingDynamicConfig("b1", "1", "c1", "3", accessMonitorUtil); innerComposite.addConfig("polling", nestedPollingDynamicConfig); layered.addConfig(Layers.SYSTEM, innerComposite); layered.addConfig(Layers.ENVIRONMENT, MapConfig.builder().put("c1", "4").put("d1", "5").build()); // Properties (a1: 1) and (b1: 2) are covered by the first polling config Assert.assertEquals(layered.getRawProperty("a1"), "1"); verify(accessMonitorUtil).registerUsage(eq(new PropertyDetails("a1", "a1", "1"))); Assert.assertEquals(layered.getRawPropertyUninstrumented("a1"), "1"); verify(accessMonitorUtil, times(1)).registerUsage(any()); Assert.assertEquals(layered.getRawProperty("b1"), "2"); verify(accessMonitorUtil).registerUsage(eq(new PropertyDetails("b1", "b1", "2"))); Assert.assertEquals(layered.getRawPropertyUninstrumented("b1"), "2"); verify(accessMonitorUtil, times(2)).registerUsage(any()); // Property (c1: 3) is covered by the composite config over the polling config Assert.assertEquals(layered.getRawProperty("c1"), "3"); verify(accessMonitorUtil).registerUsage(eq(new PropertyDetails("c1", "c1", "3"))); Assert.assertEquals(layered.getRawPropertyUninstrumented("c1"), "3"); verify(accessMonitorUtil, times(3)).registerUsage(any()); // Property (d1: 5) is covered by the final, uninstrumented MapConfig Assert.assertEquals(layered.getRawProperty("d1"), "5"); verify(accessMonitorUtil, times(3)).registerUsage(any()); Assert.assertEquals(layered.getRawPropertyUninstrumented("d1"), "5"); verify(accessMonitorUtil, times(3)).registerUsage(any()); // The instrumented forEachProperty endpoint updates the counts for every property layered.forEachProperty((k, v) -> {}); verify(accessMonitorUtil, times(2)).registerUsage(eq(new PropertyDetails("a1", "a1", "1"))); verify(accessMonitorUtil, times(2)).registerUsage(eq(new PropertyDetails("b1", "b1", "2"))); verify(accessMonitorUtil, times(2)).registerUsage(eq(new PropertyDetails("c1", "c1", "3"))); verify(accessMonitorUtil, times(6)).registerUsage((any())); // The uninstrumented forEachProperty leaves the counts unchanged layered.forEachPropertyUninstrumented((k, v) -> {}); verify(accessMonitorUtil, times(6)).registerUsage((any())); } private PollingDynamicConfig createPollingDynamicConfig( String key1, String value1, String key2, String value2, AccessMonitorUtil accessMonitorUtil) throws Exception { ManualPollingStrategy strategy = new ManualPollingStrategy(); Map<String, String> props = new HashMap<>(); props.put(key1, value1); props.put(key2, value2); Map<String, String> propIds = new HashMap<>(); propIds.put(key1, key1); propIds.put(key2, key2); Callable<PollingResponse> reader = () -> PollingResponse.forSnapshot(props, propIds); PollingDynamicConfig config = new PollingDynamicConfig(reader, strategy, accessMonitorUtil); strategy.fire(); return config; } }
9,246
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/config/PrivateViewTest.java
package com.netflix.archaius.config; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.ConfigListener; import com.netflix.archaius.api.Decoder; import com.netflix.archaius.api.PropertyDetails; import com.netflix.archaius.api.config.SettableConfig; import com.netflix.archaius.api.exceptions.ConfigException; import com.netflix.archaius.config.polling.ManualPollingStrategy; import com.netflix.archaius.config.polling.PollingResponse; import com.netflix.archaius.instrumentation.AccessMonitorUtil; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static com.netflix.archaius.TestUtils.set; import static com.netflix.archaius.TestUtils.size; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class PrivateViewTest { @Test public void decoderSettingDoesNotPropagate() throws ConfigException { com.netflix.archaius.api.config.CompositeConfig config = DefaultCompositeConfig.builder() .withConfig("foo", MapConfig.builder().put("foo.bar", "value").build()) .build(); Config privateView = config.getPrivateView(); Decoder privateDecoder = Mockito.mock(Decoder.class); privateView.setDecoder(privateDecoder); assertNotSame(config.getDecoder(), privateView.getDecoder()); Decoder newUpstreamDecoder = Mockito.mock(Decoder.class); config.setDecoder(newUpstreamDecoder); assertNotSame(config.getDecoder(), privateView.getDecoder()); assertSame(privateDecoder, privateView.getDecoder()); } @Test public void confirmNotificationOnAnyChange() throws ConfigException { com.netflix.archaius.api.config.CompositeConfig config = DefaultCompositeConfig.builder() .withConfig("foo", MapConfig.builder().put("foo.bar", "value").build()) .build(); Config privateView = config.getPrivateView(); ConfigListener listener = Mockito.mock(ConfigListener.class); privateView.addListener(listener); Mockito.verify(listener, Mockito.times(0)).onConfigAdded(any()); config.addConfig("bar", DefaultCompositeConfig.builder() .withConfig("foo", MapConfig.builder().put("foo.bar", "value").build()) .build()); Mockito.verify(listener, Mockito.times(1)).onConfigAdded(any()); } @Test public void confirmNotificationOnSettableConfigChange() throws ConfigException { SettableConfig settable = new DefaultSettableConfig(); settable.setProperty("foo.bar", "original"); com.netflix.archaius.api.config.CompositeConfig config = DefaultCompositeConfig.builder() .withConfig("settable", settable) .build(); Config privateView = config.getPrivateView(); ConfigListener listener = Mockito.mock(ConfigListener.class); privateView.addListener(listener); // Confirm original state Assert.assertEquals("original", privateView.getString("foo.bar")); Mockito.verify(listener, Mockito.times(0)).onConfigAdded(any()); // Update the property and confirm onConfigUpdated notification settable.setProperty("foo.bar", "new"); Mockito.verify(listener, Mockito.times(1)).onConfigUpdated(any()); Assert.assertEquals("new", privateView.getString("foo.bar")); // Add a new config and confirm onConfigAdded notification config.addConfig("new", MapConfig.builder().put("foo.bar", "new2").build()); Mockito.verify(listener, Mockito.times(1)).onConfigAdded(any()); Mockito.verify(listener, Mockito.times(1)).onConfigUpdated(any()); } @Test public void unusedPrivateViewIsGarbageCollected() { SettableConfig sourceConfig = new DefaultSettableConfig(); Config privateView = sourceConfig.getPrivateView(); Reference<Config> weakReference = new WeakReference<>(privateView); // No more pointers to prefix means this should be garbage collected and any additional listeners on it privateView = null; System.gc(); Assert.assertNull(weakReference.get()); } @Test public void testGetKeys() { Config config = MapConfig.builder() .put("foo", "foo-value") .put("bar", "bar-value") .build() .getPrivateView(); Iterator<String> keys = config.getKeys(); Set<String> keySet = new HashSet<>(); while (keys.hasNext()) { keySet.add(keys.next()); } Assert.assertEquals(2, keySet.size()); Assert.assertTrue(keySet.contains("foo")); Assert.assertTrue(keySet.contains("bar")); } @Test public void testGetKeysIteratorRemoveThrows() { Config config = MapConfig.builder() .put("foo", "foo-value") .put("bar", "bar-value") .build() .getPrivateView(); Iterator<String> keys = config.getKeys(); keys.next(); Assert.assertThrows(UnsupportedOperationException.class, keys::remove); } @Test public void testKeysIterable() { Config config = MapConfig.builder() .put("foo", "foo-value") .put("bar", "bar-value") .build() .getPrivateView(); Iterable<String> keys = config.keys(); Assert.assertEquals(2, size(keys)); Assert.assertEquals(set("foo", "bar"), set(keys)); } @Test public void testKeysIterableModificationThrows() { Config config = MapConfig.builder() .put("foo", "foo-value") .put("bar", "bar-value") .build() .getPrivateView(); Assert.assertThrows(UnsupportedOperationException.class, config.keys().iterator()::remove); Assert.assertThrows(UnsupportedOperationException.class, ((Collection<String>) config.keys())::clear); } @Test public void instrumentationNotEnabled() throws Exception { Config config = MapConfig.builder() .put("foo.prop1", "value1") .put("foo.prop2", "value2") .build() .getPrivateView(); Assert.assertFalse(config.instrumentationEnabled()); Assert.assertEquals(config.getRawProperty("foo.prop1"), "value1"); Assert.assertEquals(config.getRawProperty("foo.prop2"), "value2"); } @Test public void testInstrumentation() throws Exception { ManualPollingStrategy strategy = new ManualPollingStrategy(); Callable<PollingResponse> reader = () -> { Map<String, String> props = new HashMap<>(); props.put("foo.prop1", "foo-value"); props.put("foo.prop2", "bar-value"); Map<String, String> propIds = new HashMap<>(); propIds.put("foo.prop1", "1"); propIds.put("foo.prop2", "2"); return PollingResponse.forSnapshot(props, propIds); }; AccessMonitorUtil accessMonitorUtil = spy(AccessMonitorUtil.builder().build()); PollingDynamicConfig baseConfig = new PollingDynamicConfig(reader, strategy, accessMonitorUtil); strategy.fire(); Config config = baseConfig.getPrivateView(); Assert.assertTrue(config.instrumentationEnabled()); config.getRawProperty("foo.prop1"); verify(accessMonitorUtil).registerUsage(eq(new PropertyDetails("foo.prop1", "1", "foo-value"))); verify(accessMonitorUtil, times(1)).registerUsage(any()); config.getRawPropertyUninstrumented("foo.prop2"); verify(accessMonitorUtil, times(1)).registerUsage(any()); config.forEachProperty((k, v) -> {}); verify(accessMonitorUtil, times(2)).registerUsage(eq(new PropertyDetails("foo.prop1", "1", "foo-value"))); verify(accessMonitorUtil, times(1)).registerUsage(eq(new PropertyDetails("foo.prop2", "2", "bar-value"))); verify(accessMonitorUtil, times(3)).registerUsage(any()); config.forEachPropertyUninstrumented((k, v) -> {}); verify(accessMonitorUtil, times(3)).registerUsage(any()); } }
9,247
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/config/DefaultSettableConfigTest.java
package com.netflix.archaius.config; import com.netflix.archaius.api.config.SettableConfig; import org.junit.Assert; import org.junit.Test; import java.util.Collection; import java.util.Properties; import static com.netflix.archaius.TestUtils.set; import static com.netflix.archaius.TestUtils.size; public class DefaultSettableConfigTest { @Test public void testGetKeys() { SettableConfig config = new DefaultSettableConfig(); Assert.assertFalse(config.getKeys().hasNext()); config.setProperty("prop1", "value1"); config.setProperty("prop2", "value2"); config.setProperty("prop3", "value3"); Assert.assertEquals(set("prop1", "prop2", "prop3"), set(config.getKeys())); config.clearProperty("prop3"); Assert.assertEquals(set("prop1", "prop2"), set(config.getKeys())); config.setProperties(MapConfig.builder().put("prop4", "value4").build()); Assert.assertEquals(set("prop1", "prop2", "prop4"), set(config.getKeys())); Properties props = new Properties(); props.put("prop5", "value5"); config.setProperties(props); Assert.assertEquals(set("prop1", "prop2", "prop4", "prop5"), set(config.getKeys())); } @Test public void testGetKeysIteratorRemoveThrows() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("prop1", "value1"); config.setProperty("prop2", "value2"); Assert.assertThrows(UnsupportedOperationException.class, config.getKeys()::remove); config.clearProperty("prop2"); Assert.assertThrows(UnsupportedOperationException.class, config.getKeys()::remove); config.setProperties(MapConfig.builder().put("prop3", "value3").build()); Assert.assertThrows(UnsupportedOperationException.class, config.getKeys()::remove); Properties properties = new Properties(); properties.put("prop5", "value5"); config.setProperties(properties); Assert.assertThrows(UnsupportedOperationException.class, config.getKeys()::remove); } @Test public void testKeysIterable() { SettableConfig config = new DefaultSettableConfig(); Assert.assertEquals(0, size(config.keys())); config.setProperty("prop1", "value1"); config.setProperty("prop2", "value2"); config.setProperty("prop3", "value3"); Assert.assertEquals(set("prop1", "prop2", "prop3"), set(config.keys())); config.clearProperty("prop3"); Assert.assertEquals(set("prop1", "prop2"), set(config.keys())); config.setProperties(MapConfig.builder().put("prop4", "value4").build()); Assert.assertEquals(set("prop1", "prop2", "prop4"), set(config.keys())); Properties props = new Properties(); props.put("prop5", "value5"); config.setProperties(props); Assert.assertEquals(set("prop1", "prop2", "prop4", "prop5"), set(config.keys())); } @Test public void testKeysIterableModificationThrows() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("prop1", "value1"); config.setProperty("prop2", "value2"); Assert.assertThrows(UnsupportedOperationException.class, config.keys().iterator()::remove); config.clearProperty("prop2"); Assert.assertThrows(UnsupportedOperationException.class, config.keys().iterator()::remove); config.setProperties(MapConfig.builder().put("prop3", "value3").build()); Assert.assertThrows(UnsupportedOperationException.class, config.keys().iterator()::remove); Properties properties = new Properties(); properties.put("prop4", "value4"); config.setProperties(properties); Assert.assertThrows(UnsupportedOperationException.class, config.keys().iterator()::remove); Assert.assertThrows(UnsupportedOperationException.class, ((Collection<String>) config.keys())::clear); } }
9,248
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/config/PollingDynamicConfigTest.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.config; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; import com.netflix.archaius.api.PropertyDetails; import com.netflix.archaius.config.polling.PollingResponse; import com.netflix.archaius.instrumentation.AccessMonitorUtil; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import com.netflix.archaius.api.Config; import com.netflix.archaius.config.polling.ManualPollingStrategy; import com.netflix.archaius.junit.TestHttpServer; import com.netflix.archaius.property.PropertiesServerHandler; import com.netflix.archaius.readers.URLConfigReader; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static com.netflix.archaius.TestUtils.set; import static com.netflix.archaius.TestUtils.size; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class PollingDynamicConfigTest { private final PropertiesServerHandler prop1 = new PropertiesServerHandler(); private final PropertiesServerHandler prop2 = new PropertiesServerHandler(); @Rule public TestHttpServer server = new TestHttpServer() .handler("/prop1", prop1) .handler("/prop2", prop2) ; @Test(timeout=1000) public void testBasicRead() throws Exception { URLConfigReader reader = new URLConfigReader( server.getServerPathURI("/prop1").toURL() ); Map<String, String> result; prop1.setProperty("a", "a_value"); result = reader.call().getToAdd(); Assert.assertFalse(result.isEmpty()); assertEquals("a_value", result.get("a")); prop1.setProperty("a", "b_value"); result = reader.call().getToAdd(); Assert.assertFalse(result.isEmpty()); assertEquals("b_value", result.get("a")); } @Test(timeout=1000) public void testCombineSources() throws Exception { URLConfigReader reader = new URLConfigReader( server.getServerPathURI("/prop1").toURL(), server.getServerPathURI("/prop2").toURL() ); assertTrue(prop1.isEmpty()); assertTrue(prop2.isEmpty()); prop1.setProperty("a", "A"); prop2.setProperty("b", "B"); Map<String, String> result = reader.call().getToAdd(); assertEquals(2, result.size()); assertEquals("A", result.get("a")); assertEquals("B", result.get("b")); } @Test(timeout=1000, expected=IOException.class) public void testFailure() throws Exception { URLConfigReader reader = new URLConfigReader( server.getServerPathURI("/prop1").toURL()); prop1.setResponseCode(500); reader.call(); Assert.fail("Should have failed with 500 error"); } @Test(timeout=1000) public void testDynamicConfig() throws Exception { URLConfigReader reader = new URLConfigReader( server.getServerPathURI("/prop1").toURL(), server.getServerPathURI("/prop2").toURL() ); ManualPollingStrategy strategy = new ManualPollingStrategy(); PollingDynamicConfig config = new PollingDynamicConfig(reader, strategy); // Initialize // a=A // b=B prop1.setProperty("a", "A"); prop2.setProperty("b", "B"); strategy.fire(); // Modify // a=ANew // b=BNew Assert.assertFalse(config.isEmpty()); assertEquals("A", config.getString("a")); assertEquals("B", config.getString("b")); prop1.setProperty("a", "ANew"); prop2.setProperty("b", "BNew"); assertEquals("A", config.getString("a")); assertEquals("B", config.getString("b")); // Delete 1 // a deleted // b=BNew strategy.fire(); assertEquals("ANew", config.getString("a")); assertEquals("BNew", config.getString("b")); prop1.remove("a"); prop2.setProperty("b", "BNew"); strategy.fire(); Assert.assertNull(config.getString("a", null)); assertEquals("BNew", config.getString("b")); } @Test(timeout=1000) public void testDynamicConfigFailures() throws Exception { URLConfigReader reader = new URLConfigReader( server.getServerPathURI("/prop1").toURL(), server.getServerPathURI("/prop2").toURL() ); ManualPollingStrategy strategy = new ManualPollingStrategy(); PollingDynamicConfig config = new PollingDynamicConfig(reader, strategy); final AtomicInteger errorCount = new AtomicInteger(); final AtomicInteger updateCount = new AtomicInteger(); config.addListener(new DefaultConfigListener() { @Override public void onConfigUpdated(Config config) { updateCount.incrementAndGet(); } @Override public void onError(Throwable error, Config config) { errorCount.incrementAndGet(); } }); // Confirm success on first pass prop1.setProperty("a", "A"); strategy.fire(); assertEquals("A", config.getString("a")); assertEquals(0, errorCount.get()); assertEquals(1, updateCount.get()); // Confirm failure does not modify state of Config prop1.setProperty("a", "ANew"); prop1.setResponseCode(500); try { strategy.fire(); Assert.fail("Should have thrown an exception"); } catch (Exception expected) { } assertEquals(1, errorCount.get()); assertEquals(1, updateCount.get()); assertEquals("A", config.getString("a")); // Confim state updates after failure prop1.setResponseCode(200); strategy.fire(); assertEquals(1, errorCount.get()); assertEquals(2, updateCount.get()); assertEquals("ANew", config.getString("a")); } @Test public void testGetKeys() throws Exception { ManualPollingStrategy strategy = new ManualPollingStrategy(); Callable<PollingResponse> reader = () -> { Map<String, String> props = new HashMap<>(); props.put("foo", "foo-value"); props.put("bar", "bar-value"); return PollingResponse.forSnapshot(props); }; PollingDynamicConfig config = new PollingDynamicConfig(reader, strategy); Iterator<String> emptyKeys = config.getKeys(); Assert.assertFalse(emptyKeys.hasNext()); strategy.fire(); Iterator<String> keys = config.getKeys(); Set<String> keySet = new HashSet<>(); while (keys.hasNext()) { keySet.add(keys.next()); } Assert.assertEquals(2, keySet.size()); Assert.assertTrue(keySet.contains("foo")); Assert.assertTrue(keySet.contains("bar")); } @Test public void testGetKeysIteratorRemoveThrows() throws Exception { ManualPollingStrategy strategy = new ManualPollingStrategy(); Callable<PollingResponse> reader = () -> { Map<String, String> props = new HashMap<>(); props.put("foo", "foo-value"); props.put("bar", "bar-value"); return PollingResponse.forSnapshot(props); }; PollingDynamicConfig config = new PollingDynamicConfig(reader, strategy); strategy.fire(); Iterator<String> keys = config.getKeys(); Assert.assertTrue(keys.hasNext()); keys.next(); Assert.assertThrows(UnsupportedOperationException.class, keys::remove); } @Test public void testKeysIterable() throws Exception { ManualPollingStrategy strategy = new ManualPollingStrategy(); Callable<PollingResponse> reader = () -> { Map<String, String> props = new HashMap<>(); props.put("foo", "foo-value"); props.put("bar", "bar-value"); return PollingResponse.forSnapshot(props); }; PollingDynamicConfig config = new PollingDynamicConfig(reader, strategy); strategy.fire(); Iterable<String> keys = config.keys(); Assert.assertEquals(2, size(keys)); Assert.assertEquals(set("foo", "bar"), set(keys)); } @Test public void testKeysIterableModificationThrows() throws Exception { ManualPollingStrategy strategy = new ManualPollingStrategy(); Callable<PollingResponse> reader = () -> { Map<String, String> props = new HashMap<>(); props.put("foo", "foo-value"); props.put("bar", "bar-value"); return PollingResponse.forSnapshot(props); }; PollingDynamicConfig config = new PollingDynamicConfig(reader, strategy); strategy.fire(); Assert.assertThrows(UnsupportedOperationException.class, config.keys().iterator()::remove); Assert.assertThrows(UnsupportedOperationException.class, ((Collection<String>) config.keys())::clear); } @Test public void testInstrumentation() throws Exception { ManualPollingStrategy strategy = new ManualPollingStrategy(); Callable<PollingResponse> reader = () -> { Map<String, String> props = new HashMap<>(); props.put("foo", "foo-value"); props.put("bar", "bar-value"); Map<String, String> propIds = new HashMap<>(); propIds.put("foo", "1"); propIds.put("bar", "2"); return PollingResponse.forSnapshot(props, propIds); }; AccessMonitorUtil accessMonitorUtil = spy(AccessMonitorUtil.builder().build()); PollingDynamicConfig config = new PollingDynamicConfig(reader, strategy, accessMonitorUtil); strategy.fire(); Assert.assertTrue(config.instrumentationEnabled()); config.getRawProperty("foo"); verify(accessMonitorUtil).registerUsage(eq(new PropertyDetails("foo", "1", "foo-value"))); verify(accessMonitorUtil, times(1)).registerUsage(any()); config.getRawPropertyUninstrumented("bar"); verify(accessMonitorUtil, times(1)).registerUsage(any()); config.forEachProperty((k, v) -> {}); verify(accessMonitorUtil, times(2)).registerUsage(eq(new PropertyDetails("foo", "1", "foo-value"))); verify(accessMonitorUtil, times(1)).registerUsage(eq(new PropertyDetails("bar", "2", "bar-value"))); verify(accessMonitorUtil, times(3)).registerUsage(any()); config.forEachPropertyUninstrumented((k, v) -> {}); verify(accessMonitorUtil, times(3)).registerUsage(any()); } }
9,249
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/junit/TestHttpServer.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.junit; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetSocketAddress; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import com.netflix.archaius.util.ThreadFactories; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; /** * Rule for running an embedded HTTP server for basic testing. The * server uses ephemeral ports to ensure there are no conflicts when * running concurrent unit tests * * The server uses HttpServer classes available in the JVM to avoid * pulling in any extra dependencies. * * Available endpoints are, * * / Returns a 200 * /status?code=${code} Returns a request provide code * /noresponse No response from the server * * Optional query parameters * delay=${delay} Inject a delay into the request * * @author elandau * */ public class TestHttpServer implements TestRule { public static final String INTERNALERROR_PATH = "/internalerror"; public static final String NORESPONSE_PATH = "/noresponse"; public static final String STATUS_PATH = "/status"; public static final String OK_PATH = "/ok"; public static final String ROOT_PATH = "/"; private static final int DEFAULT_THREAD_COUNT = 10; private static final String DELAY_QUERY_PARAM = "delay"; private HttpServer server; private int localHttpServerPort = 0; private ExecutorService service; private int threadCount = DEFAULT_THREAD_COUNT; private LinkedHashMap<String, HttpHandler> handlers = new LinkedHashMap<String, HttpHandler>(); private String GENERIC_RESPONSE = "GenericTestHttpServer Response"; public TestHttpServer() { handlers.put(ROOT_PATH, new TestHttpHandler() { @Override protected void handle(RequestContext context) throws IOException { context.response(200, GENERIC_RESPONSE); }}); handlers.put(OK_PATH, new TestHttpHandler() { @Override protected void handle(RequestContext context) throws IOException { context.response(200, GENERIC_RESPONSE); }}); handlers.put(STATUS_PATH, new TestHttpHandler() { @Override protected void handle(RequestContext context) throws IOException { context.response(Integer.parseInt(context.query("code")), GENERIC_RESPONSE); }}); handlers.put(NORESPONSE_PATH, new TestHttpHandler() { @Override protected void handle(RequestContext context) throws IOException { }}); handlers.put(INTERNALERROR_PATH, new TestHttpHandler() { @Override protected void handle(RequestContext context) throws IOException { throw new RuntimeException("InternalError"); }}); } public TestHttpServer handler(String path, HttpHandler handler) { handlers.put(path, handler); return this; } public TestHttpServer port(int port) { this.localHttpServerPort = port; return this; } public TestHttpServer threadCount(int threads) { this.threadCount = threads; return this; } @Override public Statement apply(final Statement statement, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { before(description); try { statement.evaluate(); } finally { after(description); } } }; } private static interface RequestContext { void response(int code, String body) throws IOException; String query(String key); } private static abstract class TestHttpHandler implements HttpHandler { @Override public final void handle(final HttpExchange t) throws IOException { try { final Map<String, String> queryParameters = queryToMap(t); if (queryParameters.containsKey(DELAY_QUERY_PARAM)) { Long delay = Long.parseLong(queryParameters.get(DELAY_QUERY_PARAM)); if (delay != null) { try { TimeUnit.MILLISECONDS.sleep(delay); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } handle(new RequestContext() { @Override public void response(int code, String body) throws IOException { OutputStream os = t.getResponseBody(); t.sendResponseHeaders(code, body.length()); os.write(body.getBytes()); os.close(); } @Override public String query(String key) { return queryParameters.get(key); } }); } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String body = sw.toString(); OutputStream os = t.getResponseBody(); t.sendResponseHeaders(500, body.length()); os.write(body.getBytes()); os.close(); } } protected abstract void handle(RequestContext context) throws IOException; private static Map<String, String> queryToMap(HttpExchange t) { String queryString = t.getRequestURI().getQuery(); Map<String, String> result = new HashMap<String, String>(); if (queryString != null) { for (String param : queryString.split("&")) { String pair[] = param.split("="); if (pair.length>1) { result.put(pair[0], pair[1]); } else{ result.put(pair[0], ""); } } } return result; } } public void before(final Description description) throws Exception { this.service = Executors.newFixedThreadPool( threadCount, ThreadFactories.newNamedDaemonThreadFactory("TestHttpServer-%d")); InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", 0); server = HttpServer.create(inetSocketAddress, 0); server.setExecutor(service); for (Entry<String, HttpHandler> handler : handlers.entrySet()) { server.createContext(handler.getKey(), handler.getValue()); } server.start(); localHttpServerPort = server.getAddress().getPort(); System.out.println(description.getClassName() + " TestServer is started: " + getServerUrl()); } public void after(final Description description) { try{ server.stop(0); ((ExecutorService) server.getExecutor()).shutdownNow(); System.out.println(description.getClassName() + " TestServer is shutdown: " + getServerUrl()); } catch (Exception e) { e.printStackTrace(); } } /** * @return Get the root server URL */ public String getServerUrl() { return "http://localhost:" + localHttpServerPort; } /** * @return Get the root server URL * @throws URISyntaxException */ public URI getServerURI() throws URISyntaxException { return new URI(getServerUrl()); } /** * @param path * @return Get a path to this server */ public String getServerPath(String path) { return getServerUrl() + path; } /** * @param path * @return Get a path to this server */ public URI getServerPathURI(String path) throws URISyntaxException { return new URI(getServerUrl() + path); } /** * @return Return the ephemeral port used by this server */ public int getServerPort() { return localHttpServerPort; } }
9,250
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/property/PropertiesServerHandler.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.property; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; /** * TestHandler to be used with TestHttpServer to simulate server responses * for property file polling * * @author elandau * */ public class PropertiesServerHandler implements HttpHandler { private volatile Properties props = new Properties(); private volatile int responseCode = 200; @Override public void handle(HttpExchange t) throws IOException { if (responseCode == 200) { // Output .properties file format ByteArrayOutputStream strm = new ByteArrayOutputStream(); props.store(strm, null); // Send response OutputStream os = t.getResponseBody(); t.sendResponseHeaders(200, strm.size()); os.write(strm.toByteArray()); os.close(); } else { t.sendResponseHeaders(responseCode, 0); } } public void setProperties(Properties props) { this.props = props; } public Properties getProperties() { return this.props; } public void setResponseCode(int code) { this.responseCode = code; } public void clear() { this.props.clear(); } public void remove(String key) { this.props.remove(key); } public <T> void setProperty(String key, T value) { this.props.setProperty(key, value.toString()); } public boolean isEmpty() { return this.props.isEmpty(); } }
9,251
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/property/PropertyTest.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.property; import java.math.BigDecimal; import java.math.BigInteger; import java.time.Duration; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Function; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import com.netflix.archaius.DefaultPropertyFactory; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.Property; import com.netflix.archaius.api.Property.Subscription; import com.netflix.archaius.api.PropertyFactory; import com.netflix.archaius.api.PropertyListener; import com.netflix.archaius.api.config.SettableConfig; import com.netflix.archaius.api.exceptions.ConfigException; import com.netflix.archaius.config.DefaultSettableConfig; import com.netflix.archaius.config.MapConfig; @SuppressWarnings("deprecation") public class PropertyTest { static class MyService { private final Property<Integer> value; private final Property<Integer> value2; AtomicInteger setValueCallsCounter; MyService(PropertyFactory config) { setValueCallsCounter = new AtomicInteger(0); value = config.getProperty("foo").asInteger(1); value.addListener(new MethodInvoker<>(this, "setValue")); value2 = config.getProperty("foo").asInteger(2); } // Called by the config listener. @SuppressWarnings("unused") public void setValue(Integer value) { setValueCallsCounter.incrementAndGet(); } } static class CustomType { static CustomType DEFAULT = new CustomType(1,1); static CustomType ONE_TWO = new CustomType(1,2); private final int x; private final int y; CustomType(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "CustomType [x=" + x + ", y=" + y + "]"; } } @Test public void test() throws ConfigException { SettableConfig config = new DefaultSettableConfig(); DefaultPropertyFactory factory = DefaultPropertyFactory.from(config); MyService service = new MyService(factory); Assert.assertEquals(1, (int)service.value.get()); Assert.assertEquals(2, (int)service.value2.get()); config.setProperty("foo", "123"); Assert.assertEquals(123, (int)service.value.get()); Assert.assertEquals(123, (int)service.value2.get()); // setValue() is called once when we init to 1 and twice when we set foo to 123. Assert.assertEquals(1, service.setValueCallsCounter.get()); } @Test public void testBasicTypes() { SettableConfig config = new DefaultSettableConfig(); DefaultPropertyFactory factory = DefaultPropertyFactory.from(config); config.setProperty("foo", "10"); config.setProperty("shmoo", "true"); config.setProperty("loo", CustomType.ONE_TWO); Property<BigDecimal> bigDecimalProp = factory.getProperty("foo").asType(BigDecimal.class, BigDecimal.ONE); Property<BigInteger> bigIntegerProp = factory.getProperty("foo").asType(BigInteger.class, BigInteger.ONE); Property<Boolean> booleanProp = factory.getProperty("shmoo").asType(Boolean.class, false); Property<Byte> byteProp = factory.getProperty("foo").asType(Byte.class, (byte) 0x1); Property<Double> doubleProp = factory.getProperty("foo").asType(Double.class, 1.0); Property<Float> floatProp = factory.getProperty("foo").asType(Float.class, 1.0f); Property<Integer> intProp = factory.getProperty("foo").asType(Integer.class, 1); Property<Long> longProp = factory.getProperty("foo").asType(Long.class, 1L); Property<Short> shortProp = factory.getProperty("foo").asType(Short.class, (short) 1); Property<String> stringProp = factory.getProperty("foo").asType(String.class, "1"); Property<CustomType> customTypeProp = factory.getProperty("loo").asType(CustomType.class, CustomType.DEFAULT); Assert.assertEquals(BigDecimal.TEN, bigDecimalProp.get()); Assert.assertEquals(BigInteger.TEN, bigIntegerProp.get()); Assert.assertEquals(true, booleanProp.get()); Assert.assertEquals(10, byteProp.get().byteValue()); Assert.assertEquals(10.0, doubleProp.get(), 0.0001); Assert.assertEquals(10.0f, floatProp.get(), 0.0001f); Assert.assertEquals(10, intProp.get().intValue()); Assert.assertEquals(10L, longProp.get().longValue()); Assert.assertEquals((short) 10, shortProp.get().shortValue()); Assert.assertEquals("10", stringProp.get()); Assert.assertEquals(CustomType.ONE_TWO, customTypeProp.get()); } @Test public void testCollectionTypes() { SettableConfig config = new DefaultSettableConfig(); DefaultPropertyFactory factory = DefaultPropertyFactory.from(config); config.setProperty("foo", "10,13,13,20"); config.setProperty("shmoo", "1=PT15M,0=PT0S"); // Test array decoding Property<Byte[]> byteArray = factory.get("foo", Byte[].class); Assert.assertEquals(new Byte[] {10, 13, 13, 20}, byteArray.get()); // Tests list creation and parsing, decoding of list elements, proper handling if user gives us a primitive type Property<List<Integer>> intList = factory.getList("foo", int.class); Assert.assertEquals(Arrays.asList(10, 13, 13, 20), intList.get()); // Tests set creation, parsing non-int elements Property<Set<Double>> doubleSet = factory.getSet("foo", Double.class); Assert.assertEquals(new HashSet<>(Arrays.asList(10.0, 13.0, 20.0)), doubleSet.get()); // Test map creation and parsing, keys and values of less-common types Property<Map<Short, Duration>> mapProp = factory.getMap("shmoo", Short.class, Duration.class); Map<Short, Duration> expectedMap = new HashMap<>(); expectedMap.put((short) 1, Duration.ofMinutes(15)); expectedMap.put((short) 0, Duration.ZERO); Assert.assertEquals(expectedMap, mapProp.get()); // Test proper handling of unset properties Property<Map<CustomType, CustomType>> emptyProperty = factory.getMap("fubar", CustomType.class, CustomType.class); Assert.assertNull(emptyProperty.get()); } @Test public void testUpdateDynamicChild() { SettableConfig config = new DefaultSettableConfig(); DefaultPropertyFactory factory = DefaultPropertyFactory.from(config); Property<Integer> intProp1 = factory.getProperty("foo").asInteger(1); Property<Integer> intProp2 = factory.getProperty("foo").asInteger(2); Property<String> strProp = factory.getProperty("foo").asString("3"); Assert.assertEquals(1, (int)intProp1.get()); Assert.assertEquals(2, (int)intProp2.get()); config.setProperty("foo", "123"); Assert.assertEquals("123", strProp.get()); Assert.assertEquals((Integer)123, intProp1.get()); Assert.assertEquals((Integer)123, intProp2.get()); } @Test public void testDefaultNull() { SettableConfig config = new DefaultSettableConfig(); DefaultPropertyFactory factory = DefaultPropertyFactory.from(config); Property<Integer> prop = factory.getProperty("foo").asInteger(null); Assert.assertNull(prop.get()); } @Test public void testDefault() { SettableConfig config = new DefaultSettableConfig(); DefaultPropertyFactory factory = DefaultPropertyFactory.from(config); Property<Integer> prop = factory.getProperty("foo").asInteger(123); Assert.assertEquals(123, prop.get().intValue()); } @Test public void testUpdateValue() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("goo", "456"); DefaultPropertyFactory factory = DefaultPropertyFactory.from(config); Property<Integer> prop = factory.getProperty("foo").asInteger(123); config.setProperty("foo", 1); Assert.assertEquals(1, prop.get().intValue()); config.clearProperty("foo"); Assert.assertEquals(123, prop.get().intValue()); config.setProperty("foo", "${goo}"); Assert.assertEquals(456, prop.get().intValue()); } @Test public void testUpdateCallback() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("goo", "456"); DefaultPropertyFactory factory = DefaultPropertyFactory.from(config); Property<Integer> prop = factory.getProperty("foo").asInteger(123); final AtomicReference<Integer> current = new AtomicReference<>(); prop.addListener(new PropertyListener<Integer>() { @Override public void onChange(Integer value) { current.set(value); } @Override public void onParseError(Throwable error) { } }); current.set(prop.get()); Assert.assertEquals(123, current.get().intValue()); config.setProperty("foo", 1); Assert.assertEquals(1, current.get().intValue()); config.setProperty("foo", 2); Assert.assertEquals(2, current.get().intValue()); config.clearProperty("foo"); Assert.assertEquals(123, current.get().intValue()); config.setProperty("foo", "${goo}"); Assert.assertEquals(456, current.get().intValue()); } @Test public void unregisterOldCallback() { SettableConfig config = new DefaultSettableConfig(); DefaultPropertyFactory factory = DefaultPropertyFactory.from(config); //noinspection unchecked PropertyListener<Integer> listener = Mockito.mock(PropertyListener.class); Property<Integer> prop = factory.getProperty("foo").asInteger(1); prop.addListener(listener); Mockito.verify(listener, Mockito.never()).accept(Mockito.anyInt()); config.setProperty("foo", "2"); Mockito.verify(listener, Mockito.times(1)).accept(Mockito.anyInt()); prop.removeListener(listener); config.setProperty("foo", "3"); Mockito.verify(listener, Mockito.times(1)).accept(Mockito.anyInt()); } @Test public void subscribePropertyChange() { SettableConfig config = new DefaultSettableConfig(); DefaultPropertyFactory factory = DefaultPropertyFactory.from(config); Property<Integer> prop = factory.get("foo", String.class) .map(Integer::parseInt) .orElse(2) ; AtomicInteger value = new AtomicInteger(); prop.subscribe(value::set); Assert.assertEquals(2, prop.get().intValue()); Assert.assertEquals(0, value.get()); config.setProperty("foo", "1"); Assert.assertEquals(1, prop.get().intValue()); Assert.assertEquals(1, value.get()); } @Test public void unsubscribeOnChange() { SettableConfig config = new DefaultSettableConfig(); DefaultPropertyFactory factory = DefaultPropertyFactory.from(config); //noinspection unchecked Consumer<Integer> consumer = Mockito.mock(Consumer.class); Property<Integer> prop = factory.getProperty("foo").asInteger(1); Subscription sub = prop.onChange(consumer); Mockito.verify(consumer, Mockito.never()).accept(Mockito.anyInt()); config.setProperty("foo", "2"); Mockito.verify(consumer, Mockito.times(1)).accept(Mockito.anyInt()); sub.unsubscribe(); config.setProperty("foo", "3"); Mockito.verify(consumer, Mockito.times(1)).accept(Mockito.anyInt()); } @Test public void chainedPropertyNoneSet() { MapConfig config = MapConfig.builder().build(); DefaultPropertyFactory factory = DefaultPropertyFactory.from(config); Property<Integer> prop = factory .get("first", Integer.class) .orElseGet("second"); Assert.assertNull(prop.get()); } @Test public void chainedPropertyDefault() { SettableConfig config = new DefaultSettableConfig(); DefaultPropertyFactory factory = DefaultPropertyFactory.from(config); Property<Integer> prop = factory .get("first", Integer.class) .orElseGet("second") .orElse(3); Assert.assertEquals(3, prop.get().intValue()); } @Test public void chainedPropertySecondSet() { MapConfig config = MapConfig.builder().put("second", 2).build(); DefaultPropertyFactory factory = DefaultPropertyFactory.from(config); Property<Integer> prop = factory .get("first", Integer.class) .orElseGet("second") .orElse(3); Assert.assertEquals(2, prop.get().intValue()); } @Test public void chainedPropertyFirstSet() { MapConfig config = MapConfig.builder().put("first", 1).build(); DefaultPropertyFactory factory = DefaultPropertyFactory.from(config); Property<Integer> prop = factory .get("first", Integer.class) .orElseGet("second") .orElse(3); Assert.assertEquals(1, prop.get().intValue()); } @Test public void chainedPropertyNotification() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("first", 1); DefaultPropertyFactory factory = DefaultPropertyFactory.from(config); //noinspection unchecked Consumer<Integer> consumer = Mockito.mock(Consumer.class); Property<Integer> prop = factory .get("first", Integer.class) .orElseGet("second") .orElse(3); prop.onChange(consumer); // Should not be called on register Mockito.verify(consumer, Mockito.never()).accept(Mockito.any()); // First changed config.setProperty("first", 11); Mockito.verify(consumer, Mockito.times(1)).accept(11); // Unrelated change ignored config.setProperty("foo", 11); Mockito.verify(consumer, Mockito.times(1)).accept(11); // Second changed has no effect because first is set config.setProperty("second", 2); Mockito.verify(consumer, Mockito.times(1)).accept(11); // First cleared, second becomes value config.clearProperty("first"); Mockito.verify(consumer, Mockito.times(1)).accept(2); // First cleared, default becomes value config.clearProperty("second"); Mockito.verify(consumer, Mockito.times(1)).accept(3); } @Test public void testCache() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("foo", "1"); DefaultPropertyFactory factory = DefaultPropertyFactory.from(config); // This can't be a lambda because then mockito can't subclass it to spy on it :-P //noinspection Convert2Lambda,Anonymous2MethodRef Function<String, Integer> mapper = Mockito.spy(new Function<String, Integer>() { @Override public Integer apply(String t) { return Integer.parseInt(t); } }); Property<Integer> prop = factory.get("foo", String.class) .map(mapper); Mockito.verify(mapper, Mockito.never()).apply(Mockito.anyString()); Assert.assertEquals(1, prop.get().intValue()); Mockito.verify(mapper, Mockito.times(1)).apply("1"); Assert.assertEquals(1, prop.get().intValue()); Mockito.verify(mapper, Mockito.times(1)).apply("1"); config.setProperty("foo", "2"); Assert.assertEquals(2, prop.get().intValue()); Mockito.verify(mapper, Mockito.times(1)).apply("1"); Mockito.verify(mapper, Mockito.times(1)).apply("2"); config.setProperty("bar", "3"); Assert.assertEquals(2, prop.get().intValue()); Mockito.verify(mapper, Mockito.times(1)).apply("1"); Mockito.verify(mapper, Mockito.times(2)).apply("2"); } @Test(expected=IllegalStateException.class) public void mapDiscardsType() { MapConfig config = MapConfig.builder().build(); DefaultPropertyFactory factory = DefaultPropertyFactory.from(config); //noinspection unused Property<Integer> prop = factory .get("first", String.class) .orElseGet("second") .map(Integer::parseInt) .orElseGet("third") ; } @Test public void customMappingWithDefault() { Config config = MapConfig.builder().build(); PropertyFactory factory = DefaultPropertyFactory.from(config); Integer value = factory.getProperty("a").asType(Integer::parseInt, "1").get(); Assert.assertEquals(1, value.intValue()); } @Test public void customMapping() { Config config = MapConfig.builder() .put("a", "2") .build(); PropertyFactory factory = DefaultPropertyFactory.from(config); Integer value = factory.getProperty("a").asType(Integer::parseInt, "1").get(); Assert.assertEquals(2, value.intValue()); } @Test public void customMappingWithError() { Config config = MapConfig.builder() .put("a", "###bad_integer_value###") .build(); PropertyFactory factory = DefaultPropertyFactory.from(config); Integer value = factory.getProperty("a").asType(Integer::parseInt, "1").get(); Assert.assertEquals(1, value.intValue()); } }
9,252
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/mapper/ProxyFactoryTest.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.mapper; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; import com.netflix.archaius.ConfigProxyFactory; import com.netflix.archaius.DefaultPropertyFactory; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.annotations.DefaultValue; import com.netflix.archaius.api.annotations.PropertyName; import com.netflix.archaius.api.exceptions.ConfigException; import com.netflix.archaius.config.EmptyConfig; import com.netflix.archaius.config.MapConfig; import org.junit.Test; import java.util.Properties; public class ProxyFactoryTest { public static interface MyConfigWithInterpolation { @DefaultValue("default") String getString(); @DefaultValue("123") int getInteger(); int getInteger2(); @DefaultValue("${prefix.integer}") int getInteger3(); @DefaultValue("true") boolean getBoolean(); Boolean getBoolean2(); @DefaultValue("${prefix.boolean}") boolean getBoolean3(); @DefaultValue("3") short getShort(); Short getShort2(); @DefaultValue("${prefix.short}") short getShort3(); @DefaultValue("3") long getLong(); Long getLong2(); @DefaultValue("${prefix.long}") long getLong3(); @DefaultValue("3.1") float getFloat(); Float getFloat2(); @DefaultValue("${prefix.float}") float getFloat3(); @DefaultValue("3.1") double getDouble(); Double getDouble2(); @DefaultValue("${prefix.double}") double getDouble3(); @DefaultValue("default") @PropertyName(name="renamed.string") String getRenamed(); @DefaultValue("default") String noVerb(); @DefaultValue("false") boolean isIs(); @DefaultValue("${replacement}") String getInterpolatedDefaultValue(); } public static interface MyConfig { @DefaultValue("default") String getString(); @DefaultValue("123") int getInteger(); Integer getInteger2(); @DefaultValue("true") boolean getBoolean(); Boolean getBoolean2(); @DefaultValue("3") short getShort(); Short getShort2(); @DefaultValue("3") long getLong(); Long getLong2(); @DefaultValue("3.1") float getFloat(); Float getFloat2(); @DefaultValue("3.1") double getDouble(); Double getDouble2(); @DefaultValue("default") @PropertyName(name="renamed.string") String getRenamed(); @DefaultValue("default") String noVerb(); @DefaultValue("false") boolean isIs(); } @Test public void testProxy() throws ConfigException { Properties props = new Properties(); props.put("prefix.string", "loaded"); props.put("prefix.integer", 1); props.put("prefix.integer2", 2); props.put("prefix.boolean", true); props.put("prefix.boolean2", true); props.put("prefix.short", 1); props.put("prefix.short2", 2); props.put("prefix.long", 1); props.put("prefix.long2", 2); props.put("prefix.float", 1.1); props.put("prefix.float2", 2.1); props.put("prefix.double", 1.1); props.put("prefix.double2", 2.1); props.put("prefix.renamed.string", "loaded"); props.put("prefix.noVerb", "loaded"); props.put("prefix.is", "true"); props.put("replacement", "replaced"); Config config = MapConfig.from(props); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), new DefaultPropertyFactory(config.getPrefixedView("prefix"))); MyConfigWithInterpolation c = proxy.newProxy(MyConfigWithInterpolation.class); assertThat((long)c.getLong(), equalTo(1L)); assertThat(c.getString(), equalTo("loaded")); assertThat(c.getInterpolatedDefaultValue(), equalTo("replaced")); assertThat(c.getRenamed(), equalTo("loaded")); assertThat(c.noVerb(), equalTo("loaded")); assertThat(c.getInteger(), equalTo(1)); assertThat(c.getInteger2(), equalTo(2)); assertThat(c.getInteger3(), equalTo(1)); assertThat(c.getBoolean(), equalTo(true)); assertThat(c.getBoolean2(), equalTo(true)); assertThat(c.getBoolean3(), equalTo(true)); assertThat(c.isIs(), equalTo(true)); assertThat((int)c.getShort(), equalTo(1)); assertThat((int)c.getShort2(), equalTo(2)); assertThat(c.getLong2(), equalTo(2L)); assertThat(c.getFloat(), equalTo(1.1f)); assertThat(c.getFloat2(), equalTo(2.1f)); assertThat(c.getDouble(), equalTo(1.1)); assertThat(c.getDouble2(), equalTo(2.1)); System.out.println(c.toString()); } @Test public void testProxyWithDefaults() throws ConfigException{ Config config = EmptyConfig.INSTANCE; ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), new DefaultPropertyFactory(config.getPrefixedView("prefix"))); MyConfig c = proxy.newProxy(MyConfig.class); assertThat(c.getInteger(), equalTo(123)); assertThat(c.getInteger2(), nullValue()); assertThat(c.getBoolean(), equalTo(true)); assertThat(c.getBoolean2(), nullValue()); assertThat((int)c.getShort(), equalTo(3)); assertThat(c.getShort2(), nullValue()); assertThat(c.getLong(), equalTo(3L)); assertThat(c.getLong2(), nullValue()); assertThat(c.getFloat(), equalTo(3.1f)); assertThat(c.getFloat2(), nullValue()); assertThat(c.getDouble(), equalTo(3.1)); assertThat(c.getDouble2(), nullValue()); System.out.println(c.toString()); } }
9,253
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/visitor/VisitorTest.java
package com.netflix.archaius.visitor; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import com.netflix.archaius.config.DefaultCompositeConfig; import org.junit.Assert; import org.junit.Test; import com.netflix.archaius.api.config.CompositeConfig; import com.netflix.archaius.config.MapConfig; import com.netflix.archaius.api.exceptions.ConfigException; public class VisitorTest { @Test public void testNotFound() throws ConfigException { CompositeConfig config = DefaultCompositeConfig.create(); LinkedHashMap<String, String> sources = config.accept(new PropertyOverrideVisitor("foo")); Assert.assertNull(sources); } @Test public void testOverrideVisitor() throws ConfigException { CompositeConfig config = createComposite(); LinkedHashMap<String, String> sources = config.accept(new PropertyOverrideVisitor("foo")); Assert.assertEquals("a_foo", config.getString("foo")); LinkedHashMap<String, String> expected = new LinkedHashMap<>(); expected.put("a", "a_foo"); expected.put("b", "b_foo"); expected.put("c/d", "d_foo"); Assert.assertEquals(expected, sources); System.out.println(expected); } @Test public void testFlattenedNames() throws ConfigException { CompositeConfig config = createComposite(); List<String> result = config.accept(new FlattenedNamesVisitor()); Assert.assertEquals(Arrays.asList("a", "b", "gap", "c", "d"), result); } /* * Root * - a * - foo : a_foo * - foo : b_foo * - b * - gap * - bar : b_bar * - c * - d * - foo : d_foo */ CompositeConfig createComposite() throws ConfigException { CompositeConfig config = DefaultCompositeConfig.create(); config.addConfig("a", MapConfig.builder().put("foo", "a_foo").build()); config.addConfig("b", MapConfig.builder().put("foo", "b_foo").build()); config.addConfig("gap", MapConfig.builder().put("bar", "b_bar").build()); config.addConfig("c", DefaultCompositeConfig.builder().withConfig("d", MapConfig.builder().put("foo", "d_foo").build()).build()); LinkedHashMap<String, String> sources = config.accept(new PropertyOverrideVisitor("foo")); return config; } }
9,254
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/readers/URLConfigReaderTest.java
package com.netflix.archaius.readers; import org.junit.Assert; import org.junit.Test; import java.net.MalformedURLException; /** * @author Nikos Michalakis <nikos@netflix.com> */ public class URLConfigReaderTest { @Test public void testStringConstructorCommonCase() { final String url1 = "http://hello:8080/hey"; final String url2 = "http://hello:8080/heytoo"; URLConfigReader reader1 = new URLConfigReader(url1); Assert.assertEquals(url1, reader1.getConfigUrls().get(0).toString()); URLConfigReader reader2 = new URLConfigReader(url1, url2); Assert.assertEquals(url1, reader2.getConfigUrls().get(0).toString()); Assert.assertEquals(url2, reader2.getConfigUrls().get(1).toString()); } @Test(expected = RuntimeException.class) public void testStringConstructorMalformedUrl() { new URLConfigReader("bad url"); } }
9,255
0
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/test/java/com/netflix/archaius/loaders/PropertyConfigReaderTest.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.loaders; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.StrInterpolator; import com.netflix.archaius.config.MapConfig; import com.netflix.archaius.api.exceptions.ConfigException; import com.netflix.archaius.interpolate.CommonsStrInterpolator; import com.netflix.archaius.interpolate.ConfigStrLookup; import com.netflix.archaius.readers.PropertiesConfigReader; import com.netflix.archaius.visitor.PrintStreamVisitor; public class PropertyConfigReaderTest { @Test public void readerTest() throws ConfigException{ PropertiesConfigReader reader = new PropertiesConfigReader(); Config config = reader.load(null, "application", CommonsStrInterpolator.INSTANCE, new StrInterpolator.Lookup() { @Override public String lookup(String key) { return null; } }); config.accept(new PrintStreamVisitor()); assertThat(Arrays.asList("b"), is(config.getList("application.list", String.class))); assertThat(Arrays.asList("a", "b"), equalTo(config.getList("application.list2", String.class))); // assertThat(Arrays.asList("b"), config.getList("application.map")); assertThat(Arrays.asList("a", "b"), is(config.getList("application.set", String.class))); assertThat("a,b,c", is(config.getString("application.valuelist"))); assertThat(Arrays.asList("a","b","c"), is(config.getList("application.valuelist", String.class))); // System.out.println(config.getBoolean("application.list")); // System.out.println(config.getInteger("application.list")); } @Test public void loadAtNext() throws ConfigException { PropertiesConfigReader reader = new PropertiesConfigReader(); Config mainConfig = MapConfig.builder().put("@region", "us-east-1").build(); Config config = reader.load(null, "test", CommonsStrInterpolator.INSTANCE, ConfigStrLookup.from(mainConfig)); config.accept(new PrintStreamVisitor()); Assert.assertEquals("test-us-east-1.properties", config.getString("cascaded.property")); } @Test public void loadMultipleAtNext() throws ConfigException { PropertiesConfigReader reader = new PropertiesConfigReader(); Config mainConfig = MapConfig.builder().put("@region", "us-east-1").build(); Config config = reader.load(null, "override", CommonsStrInterpolator.INSTANCE, ConfigStrLookup.from(mainConfig)); config.accept(new PrintStreamVisitor()); Assert.assertEquals("200", config.getString("cascaded.property")); Assert.assertEquals("true", config.getString("override.internal.style.next")); } }
9,256
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/ReadOnlyMap.java
package com.netflix.archaius; import java.util.Collection; import java.util.Map; import java.util.Set; abstract class ReadOnlyMap<K, V> implements Map<K, V> { @Override public int size() { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { throw new UnsupportedOperationException(); } @Override public boolean containsKey(Object key) { throw new UnsupportedOperationException(); } @Override public boolean containsValue(Object value) { throw new UnsupportedOperationException(); } @Override public V put(K key, V value) { throw new UnsupportedOperationException(); } @Override public V remove(Object key) { throw new UnsupportedOperationException(); } @Override public void putAll(Map<? extends K, ? extends V> m) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Set<K> keySet() { throw new UnsupportedOperationException(); } @Override public Collection<V> values() { throw new UnsupportedOperationException(); } @Override public Set<java.util.Map.Entry<K, V>> entrySet() { throw new UnsupportedOperationException(); } }
9,257
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/DefaultDecoder.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius; import com.netflix.archaius.api.Decoder; import com.netflix.archaius.api.TypeConverter; import com.netflix.archaius.converters.ArrayTypeConverterFactory; import com.netflix.archaius.converters.DefaultCollectionsTypeConverterFactory; import com.netflix.archaius.converters.DefaultTypeConverterFactory; import com.netflix.archaius.converters.EnumTypeConverterFactory; import com.netflix.archaius.exceptions.ParseException; import javax.inject.Singleton; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Stream; @Singleton public class DefaultDecoder implements Decoder, TypeConverter.Registry { private final Map<Type, TypeConverter> cache = new ConcurrentHashMap<>(); private final List<TypeConverter.Factory> factories = new ArrayList<>(); public static DefaultDecoder INSTANCE = new DefaultDecoder(); private DefaultDecoder() { factories.add(DefaultTypeConverterFactory.INSTANCE); factories.add(DefaultCollectionsTypeConverterFactory.INSTANCE); factories.add(ArrayTypeConverterFactory.INSTANCE); factories.add(EnumTypeConverterFactory.INSTANCE); } @Override public <T> T decode(Class<T> type, String encoded) { return decode((Type)type, encoded); } @Override public <T> T decode(Type type, String encoded) { try { if (encoded == null) { return null; } return (T)getOrCreateConverter(type).convert(encoded); } catch (Exception e) { throw new ParseException("Error decoding type `" + type.getTypeName() + "`", e); } } @Override public Optional<TypeConverter<?>> get(Type type) { return Optional.ofNullable(getOrCreateConverter(type)); } private TypeConverter<?> getOrCreateConverter(Type type) { TypeConverter<?> converter = cache.get(type); if (converter == null) { converter = resolve(type); if (converter == null) { throw new RuntimeException("No converter found for type '" + type + "'"); } cache.put(type, converter); } return converter; } /** * Iterate through all TypeConverter#Factory's and return the first TypeConverter that matches * @param type * @return */ private TypeConverter<?> resolve(Type type) { return factories.stream() .flatMap(factory -> factory.get(type, this).map(Stream::of).orElseGet(Stream::empty)) .findFirst() .orElseGet(() -> findValueOfTypeConverter(type)); } /** * @param type * @param <T> * @return Return a converter that uses reflection on either a static valueOf or ctor(String) to convert a string value to the * type. Will return null if neither is found */ private static <T> TypeConverter<T> findValueOfTypeConverter(Type type) { if (!(type instanceof Class)) { return null; } Class cls = (Class)type; // Next look a valueOf(String) static method Method method; try { method = cls.getMethod("valueOf", String.class); return value -> { try { return (T)method.invoke(null, value); } catch (Exception e) { throw new ParseException("Error converting value '" + value + "' to '" + type.getTypeName() + "'", e); } }; } catch (NoSuchMethodException e1) { // Next look for a T(String) constructor Constructor c; try { c = cls.getConstructor(String.class); return value -> { try { return (T)c.newInstance(value); } catch (Exception e) { throw new ParseException("Error converting value", e); } }; } catch (NoSuchMethodException e) { return null; } } } }
9,258
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/DefaultConfigLoader.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius; import com.netflix.archaius.api.CascadeStrategy; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.ConfigLoader; import com.netflix.archaius.api.ConfigReader; import com.netflix.archaius.api.StrInterpolator; import com.netflix.archaius.api.StrInterpolator.Lookup; import com.netflix.archaius.api.config.CompositeConfig; import com.netflix.archaius.api.exceptions.ConfigException; import com.netflix.archaius.cascade.NoCascadeStrategy; import com.netflix.archaius.config.DefaultCompositeConfig; import com.netflix.archaius.config.MapConfig; import com.netflix.archaius.interpolate.CommonsStrInterpolator; import com.netflix.archaius.interpolate.ConfigStrLookup; import com.netflix.archaius.readers.PropertiesConfigReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; /** * DefaultConfigLoader provides a DSL to load configurations. * * @author elandau * */ public class DefaultConfigLoader implements ConfigLoader { private static final Logger LOG = LoggerFactory.getLogger(DefaultConfigLoader.class); private static final NoCascadeStrategy DEFAULT_CASCADE_STRATEGY = new NoCascadeStrategy(); private static final Lookup DEFAULT_LOOKUP = new Lookup() { @Override public String lookup(String key) { return null; } }; private static final StrInterpolator DEFAULT_INTERPOLATOR = CommonsStrInterpolator.INSTANCE; public static class Builder { private Set<ConfigReader> loaders = new HashSet<ConfigReader>(); private CascadeStrategy defaultStrategy = DEFAULT_CASCADE_STRATEGY; private StrInterpolator interpolator = DEFAULT_INTERPOLATOR; private Lookup lookup = DEFAULT_LOOKUP; public Builder withConfigReader(ConfigReader loader) { this.loaders.add(loader); return this; } public Builder withConfigReaders(Set<ConfigReader> loaders) { if (loaders != null) this.loaders.addAll(loaders); return this; } public Builder withDefaultCascadingStrategy(CascadeStrategy strategy) { if (strategy != null) { this.defaultStrategy = strategy; } return this; } @Deprecated public Builder withFailOnFirst(boolean flag) { return this; } public Builder withStrInterpolator(StrInterpolator interpolator) { if (interpolator != null) this.interpolator = interpolator; return this; } public Builder withStrLookup(StrInterpolator.Lookup lookup) { this.lookup = lookup; return this; } public Builder withStrLookup(Config config) { this.lookup = ConfigStrLookup.from(config); return this; } public DefaultConfigLoader build() { if (loaders.isEmpty()) { loaders.add(new PropertiesConfigReader()); } return new DefaultConfigLoader(this); } } public static Builder builder() { return new Builder(); } private final Set<ConfigReader> loaders; private final CascadeStrategy defaultStrategy; private final StrInterpolator interpolator; private final Lookup lookup; public DefaultConfigLoader(Builder builder) { this.loaders = builder.loaders; this.defaultStrategy = builder.defaultStrategy; this.interpolator = builder.interpolator; this.lookup = builder.lookup; } @Override public Loader newLoader() { return new Loader() { private CascadeStrategy strategy = defaultStrategy; private ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); private Config overrides = null; @Override public Loader withCascadeStrategy(CascadeStrategy strategy) { this.strategy = strategy; return this; } @Override public Loader withClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; return this; } @Override public Loader withFailOnFirst(boolean flag) { return this; } @Override public Loader withOverrides(Properties props) { this.overrides = MapConfig.from(props); return this; } @Override public Loader withOverrides(Config config) { this.overrides = config; return this; } @Override public CompositeConfig load(String resourceName) throws ConfigException { CompositeConfig compositeConfig = new DefaultCompositeConfig(true); List<String> names = strategy.generate(resourceName, interpolator, lookup); for (String name : names) { for (ConfigReader reader : loaders) { if (reader.canLoad(classLoader, name)) { try { Config config = reader.load(classLoader, name, interpolator, lookup); if (!config.isEmpty()) { compositeConfig.addConfig(name, config); } LOG.debug("Loaded {} ", name); } catch (ConfigException e) { LOG.debug("Unable to load {}, {}", name, e.getMessage()); } break; } } } if (overrides != null) { LOG.debug("Loading overrides form {}", resourceName); compositeConfig.addConfig(resourceName + "_overrides", overrides); } return compositeConfig; } @Override public Config load(URL url) { for (ConfigReader loader : loaders) { if (loader.canLoad(classLoader, url)) { try { Config config = loader.load(classLoader, url, interpolator, lookup); LOG.info("Loaded " + url); return config; } catch (ConfigException e) { LOG.info("Unable to load file '{}'", new Object[]{url, e.getMessage()}); } catch (Exception e) { LOG.info("Unable to load file '{}'", new Object[]{url, e.getMessage()}); } } } return null; } @Override public Config load(File file) throws ConfigException { try { return load(file.toURI().toURL()); } catch (MalformedURLException e) { throw new ConfigException("Failed to load file " + file, e); } } }; } }
9,259
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/AbstractProperty.java
package com.netflix.archaius; import com.netflix.archaius.api.Property; import com.netflix.archaius.api.PropertyListener; public abstract class AbstractProperty<T> implements Property<T> { private final String key; public AbstractProperty(String key) { this.key = key; } @Override public void addListener(PropertyListener<T> listener) { throw new UnsupportedOperationException(); } @Override public void removeListener(PropertyListener<T> listener) { throw new UnsupportedOperationException(); } @Override public String getKey() { return key; } }
9,260
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/DelegatingProperty.java
package com.netflix.archaius; import com.netflix.archaius.api.Property; import com.netflix.archaius.api.PropertyListener; public abstract class DelegatingProperty<T> implements Property<T> { protected Property<T> delegate; public DelegatingProperty(Property<T> delegate) { this.delegate = delegate; } @Override public void addListener(PropertyListener<T> listener) { delegate.addListener(listener); } @Override public void removeListener(PropertyListener<T> listener) { delegate.removeListener(listener); } @Override public String getKey() { return delegate.getKey(); } }
9,261
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/ConfigMapper.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.text.StrSubstitutor; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.IoCContainer; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.exceptions.MappingException; import com.netflix.archaius.interpolate.ConfigStrLookup; public class ConfigMapper { private static final IoCContainer NULL_IOC_CONTAINER = new IoCContainer() { @Override public <T> T getInstance(String name, Class<T> type) { return null; } }; /** * Map the configuration from the provided config object onto the injectee and use * the provided IoCContainer to inject named bindings. * * @param injectee * @param config * @throws MappingException */ public <T> void mapConfig(T injectee, Config config) throws MappingException { mapConfig(injectee, config, NULL_IOC_CONTAINER); } /** * Map the configuration from the provided config object onto the injectee. * * @param injectee * @param config * @param ioc * @throws MappingException */ public <T> void mapConfig(T injectee, final Config config, IoCContainer ioc) throws MappingException { Configuration configAnnot = injectee.getClass().getAnnotation(Configuration.class); if (configAnnot == null) { return; } Class<T> injecteeType = (Class<T>) injectee.getClass(); String prefix = configAnnot.prefix(); // Extract parameters from the object. For each parameter // look for either file 'paramname' or method 'getParamnam' String[] params = configAnnot.params(); if (params.length > 0) { Map<String, String> map = new HashMap<String, String>(); for (String param : params) { try { Field f = injecteeType.getDeclaredField(param); f.setAccessible(true); map.put(param, f.get(injectee).toString()); } catch (NoSuchFieldException e) { try { Method method = injecteeType.getDeclaredMethod( "get" + Character.toUpperCase(param.charAt(0)) + param.substring(1)); method.setAccessible(true); map.put(param, method.invoke(injectee).toString()); } catch (Exception e1) { throw new MappingException(e1); } } catch (Exception e) { throw new MappingException(e); } } prefix = StrSubstitutor.replace(prefix, map, "${", "}"); } // Interpolate using any replacements loaded into the configuration prefix = config.getStrInterpolator().create(ConfigStrLookup.from(config)).resolve(prefix); if (!prefix.isEmpty() && !prefix.endsWith(".")) prefix += "."; // Iterate and set fields if (configAnnot.allowFields()) { for (Field field : injecteeType.getDeclaredFields()) { if ( Modifier.isFinal(field.getModifiers()) || Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) { continue; } String name = field.getName(); Class<?> type = field.getType(); Object value = null; if (type.isInterface()) { // TODO: Do Class.newInstance() if objName is a classname String objName = config.getString(prefix + name, null); if (objName != null) { value = ioc.getInstance(objName, type); } } else { value = config.get(type, prefix + name, null); } if (value != null) { try { field.setAccessible(true); field.set(injectee, value); } catch (Exception e) { throw new MappingException("Unable to inject field " + injectee.getClass() + "." + name + " with value " + value, e); } } } } // map to setter methods if (configAnnot.allowSetters()) { for (Method method : injectee.getClass().getDeclaredMethods()) { // Only support methods with one parameter // Ex. setTimeout(int timeout); if (method.getParameterCount() != 1) { continue; } // Extract field name from method name // Ex. setTimeout => timeout String name = method.getName(); if (name.startsWith("set") && name.length() > 3) { name = name.substring(3,4).toLowerCase() + name.substring(4); } // Or from builder // Ex. withTimeout => timeout else if (name.startsWith("with") && name.length() > 4) { name = name.substring(4,1).toLowerCase() + name.substring(5); } else { continue; } method.setAccessible(true); Class<?> type = method.getParameterTypes()[0]; Object value = null; if (type.isInterface()) { String objName = config.getString(prefix + name, null); if (objName != null) { value = ioc.getInstance(objName, type); } } else { value = config.get(type, prefix + name, null); } if (value != null) { try { method.invoke(injectee, value); } catch (Exception e) { throw new MappingException("Unable to inject field " + injectee.getClass() + "." + name + " with value " + value, e); } } } } if (!configAnnot.postConfigure().isEmpty()) { try { Method m = injecteeType.getMethod(configAnnot.postConfigure()); m.invoke(injectee); } catch (Exception e) { throw new MappingException("Unable to invoke postConfigure method " + configAnnot.postConfigure(), e); } } } }
9,262
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/ConfigProxyFactory.java
package com.netflix.archaius; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.Decoder; import com.netflix.archaius.api.Property; import com.netflix.archaius.api.PropertyFactory; import com.netflix.archaius.api.PropertyRepository; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; import com.netflix.archaius.api.annotations.PropertyName; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; import org.apache.commons.lang3.text.StrLookup; import org.apache.commons.lang3.text.StrSubstitutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.SortedSet; import java.util.WeakHashMap; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; /** * Factory for binding a configuration interface to properties in a {@link PropertyFactory} * instance. Getter methods on the interface are mapped by naming convention * by the property name may be overridden using the @PropertyName annotation. * <p> * For example, * <pre> * {@code * @Configuration(prefix="foo") * interface FooConfiguration { * int getTimeout(); // maps to "foo.timeout" * * String getName(); // maps to "foo.name" * } * } * </pre> * * Default values may be set by adding a {@literal @}DefaultValue with a default value string. Note * that the default value type is a string to allow for interpolation. Alternatively, methods can * provide a default method implementation. Note that {@literal @}DefaultValue cannot be added to a default * method as it would introduce ambiguity as to which mechanism wins. * <p> * For example, * <pre> * {@code * @Configuration(prefix="foo") * interface FooConfiguration { * @DefaultValue("1000") * int getReadTimeout(); // maps to "foo.timeout" * * default int getWriteTimeout() { * return 1000; * } * } * } * * To create a proxy instance, * <pre> * {@code * FooConfiguration fooConfiguration = configProxyFactory.newProxy(FooConfiguration.class); * } * </pre> * * To override the prefix in {@literal @}Configuration or provide a prefix when there is no * {@literal @}Configuration annotation simply pass in a prefix in the call to newProxy. * * <pre> * {@code * FooConfiguration fooConfiguration = configProxyFactory.newProxy(FooConfiguration.class, "otherprefix.foo"); * } * </pre> * * By default, all properties are dynamic and can therefore change from call to call. To make the * configuration static set the immutable attributes of @Configuration to true. * <p> * Note that an application should normally have just one instance of ConfigProxyFactory * and PropertyFactory since PropertyFactory caches {@link com.netflix.archaius.api.Property} objects. * * @see Configuration */ @SuppressWarnings("deprecation") public class ConfigProxyFactory { private static final Logger LOG = LoggerFactory.getLogger(ConfigProxyFactory.class); // Users sometimes leak both factories and proxies, leading to hard-to-track-down memory problems. // We use these maps to keep track of how many instances of each are created and make log noise to help them // track down the culprits. WeakHashMaps to avoid holding onto objects ourselves. /** * Global count of proxy factories, indexed by Config object. An application could legitimately have more * than one proxy factory per config, if they want to use different Decoders or PropertyFactories. */ private static final Map<Config, Integer> FACTORIES_COUNT = Collections.synchronizedMap(new WeakHashMap<>()); private static final String EXCESSIVE_PROXIES_LIMIT = "archaius.excessiveProxiesLogging.limit"; /** * Per-factory count of proxies, indexed by implemented interface and prefix. Because this count is kept per-proxy, * it's also implicitly indexed by Config object :-) */ private final Map<InterfaceAndPrefix, Integer> PROXIES_COUNT = Collections.synchronizedMap(new WeakHashMap<>()); /** * The decoder is used for the purpose of decoding any @DefaultValue annotation */ private final Decoder decoder; private final PropertyRepository propertyRepository; private final Config config; private final int excessiveProxyLimit; /** * Build a proxy factory from the provided config, decoder and PropertyFactory. Normal usage from most applications * is to just set up injection bindings for those 3 objects and let your DI framework find this constructor. * * @param config Used to perform string interpolation in values from {@link DefaultValue} annotations. Weird things * will happen if this is not the same Config that the PropertyFactory exposes! * @param decoder Used to parse strings from {@link DefaultValue} annotations into the proper types. * @param factory Used to access the config values that are returned by proxies created by this factory. */ @SuppressWarnings("DIAnnotationInspectionTool") @Inject public ConfigProxyFactory(Config config, Decoder decoder, PropertyFactory factory) { this.decoder = decoder; this.config = config; this.propertyRepository = factory; excessiveProxyLimit = config.getInteger(EXCESSIVE_PROXIES_LIMIT, 5); warnWhenTooMany(FACTORIES_COUNT, config, excessiveProxyLimit, () -> String.format("ProxyFactory(Config:%s)", config.hashCode())); } /** * Build a proxy factory for a given Config. Use this ONLY if you need proxies associated with a different Config * that your DI framework would normally give you. * <p> * The constructed factory will use the Config's Decoder and a {@link DefaultPropertyFactory} built from that same * Config object. * @see #ConfigProxyFactory(Config, Decoder, PropertyFactory) */ @Deprecated public ConfigProxyFactory(Config config) { this(config, config.getDecoder(), DefaultPropertyFactory.from(config)); } /** * Build a proxy factory for a given Config and PropertyFactory. Use ONLY if you need to use a specialized * PropertyFactory in your proxies. The constructed proxy factory will use the Config's Decoder. * @see #ConfigProxyFactory(Config, Decoder, PropertyFactory) */ @Deprecated public ConfigProxyFactory(Config config, PropertyFactory factory) { this(config, config.getDecoder(), factory); } /** * Create a proxy for the provided interface type for which all getter methods are bound * to a Property. */ public <T> T newProxy(final Class<T> type) { return newProxy(type, null); } /** * Create a proxy for the provided interface type for which all getter methods are bound * to a Property. The proxy uses the provided prefix, even if there is a {@link Configuration} annotation in TYPE. */ public <T> T newProxy(final Class<T> type, final String initialPrefix) { Configuration annot = type.getAnnotation(Configuration.class); return newProxy(type, initialPrefix, annot != null && annot.immutable()); } /** * Encapsulate the invocation of a single method of the interface */ interface PropertyValueGetter<T> { /** * Invoke the method with the provided arguments */ T invoke(Object[] args); } /** * Providers of "empty" defaults for the known collection types that we support as proxy method return types. */ private static final Map<Type, Function<Object[], ?>> knownCollections = new HashMap<>(); static { knownCollections.put(Map.class, (ignored) -> Collections.emptyMap()); knownCollections.put(Set.class, (ignored) -> Collections.emptySet()); knownCollections.put(SortedSet.class, (ignored) -> Collections.emptySortedSet()); knownCollections.put(List.class, (ignored) -> Collections.emptyList()); knownCollections.put(LinkedList.class, (ignored) -> new LinkedList<>()); } @SuppressWarnings({"unchecked", "rawtypes"}) <T> T newProxy(final Class<T> type, final String initialPrefix, boolean immutable) { Configuration annot = type.getAnnotation(Configuration.class); final String prefix = derivePrefix(annot, initialPrefix); warnWhenTooMany(PROXIES_COUNT, new InterfaceAndPrefix(type, prefix), excessiveProxyLimit, () -> String.format("Proxy(%s, %s)", type, prefix)); // There's a circular dependency between these maps and the proxy object. They must be created first because the // proxy's invocation handler needs to keep a reference to them, but the proxy must be created before they get // filled because we may need to call methods on the interface in order to fill the maps :-| final Map<Method, PropertyValueGetter<?>> invokers = new HashMap<>(); final Map<Method, String> propertyNames = new HashMap<>(); final InvocationHandler handler = new ConfigProxyInvocationHandler<>(type, prefix, invokers, propertyNames); final T proxyObject = (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type }, handler); // Iterate through all declared methods of the class looking for setter methods. // Each setter will be mapped to a Property<T> for the property name: // prefix + lowerCamelCaseDerivedPropertyName for (Method method : type.getMethods()) { MethodInvokerHolder methodInvokerHolder = buildInvokerForMethod(type, prefix, method, proxyObject, immutable); propertyNames.put(method, methodInvokerHolder.propertyName); if (immutable) { // Cache the current value of the property and always return that. // Note that this will fail for parameterized properties! Object value = methodInvokerHolder.invoker.invoke(new Object[]{}); invokers.put(method, (args) -> value); } else { invokers.put(method, methodInvokerHolder.invoker); } } return proxyObject; } /** * Build the actual prefix to use for config values read by a proxy. * @param annot The (possibly null) annotation from the proxied interface. * @param prefix A (possibly null) explicit prefix being passed by the user (or by an upper level proxy, * in the case of nested interfaces). If present, it always overrides the annotation. * @return A prefix to be prepended to all the config keys read by the methods in the proxy. If not empty, it will * always end in a period <code>.</code> */ private String derivePrefix(Configuration annot, String prefix) { if (prefix == null && annot != null) { prefix = annot.prefix(); if (prefix == null) { prefix = ""; } } if (prefix == null) return ""; if (prefix.endsWith(".") || prefix.isEmpty()) return prefix; return prefix + "."; } @SuppressWarnings({"unchecked", "rawtypes"}) private <T> MethodInvokerHolder buildInvokerForMethod(Class<T> type, String prefix, Method m, T proxyObject, boolean immutable) { try { final Class<?> returnType = m.getReturnType(); final PropertyName nameAnnot = m.getAnnotation(PropertyName.class); final String propName = getPropertyName(prefix, m, nameAnnot); // A supplier for the value to be returned when the method's associated property is not set final Function defaultValueSupplier; if (m.getAnnotation(DefaultValue.class) != null) { defaultValueSupplier = createAnnotatedMethodSupplier(m, returnType, config, decoder); } else if (m.isDefault()) { defaultValueSupplier = createDefaultMethodSupplier(m, type, proxyObject); } else { // No default specified in proxied interface. Return "empty" for collection types, null for any other type. defaultValueSupplier = knownCollections.getOrDefault(returnType, (ignored) -> null); } // This object encapsulates the way to get the value for the current property. final PropertyValueGetter propertyValueGetter; if (!knownCollections.containsKey(returnType) && returnType.isInterface()) { // Our return type is an interface but not a known collection. We treat it as a nested Config proxy // interface and create a proxy with it, with the current property name as the initial prefix for nesting. propertyValueGetter = createInterfaceProperty(propName, newProxy(returnType, propName, immutable)); } else if (m.getParameterCount() > 0) { // A parameterized property. Note that this requires a @PropertyName annotation to extract the interpolation positions! if (nameAnnot == null) { throw new IllegalArgumentException("Missing @PropertyName annotation on " + m.getDeclaringClass().getName() + "#" + m.getName()); } // A previous version allowed the full name to be specified, even if the prefix was specified. So, for // backwards compatibility, we allow both including or excluding the prefix for parameterized names. String propertyNameTemplate; if (!StringUtils.isBlank(prefix) && !nameAnnot.name().startsWith(prefix)) { propertyNameTemplate = prefix + nameAnnot.name(); } else { propertyNameTemplate = nameAnnot.name(); } propertyValueGetter = createParameterizedProperty(returnType, propertyNameTemplate, defaultValueSupplier); } else { // Anything else. propertyValueGetter = createScalarProperty(m.getGenericReturnType(), propName, defaultValueSupplier); } return new MethodInvokerHolder(propertyValueGetter, propName); } catch (Exception e) { throw new RuntimeException("Error proxying method " + m.getName(), e); } } /** * Compute the name of the property that will be returned by this method. */ private static String getPropertyName(String prefix, Method m, PropertyName nameAnnot) { final String verb; if (m.getName().startsWith("get")) { verb = "get"; } else if (m.getName().startsWith("is")) { verb = "is"; } else { verb = ""; } return nameAnnot != null && nameAnnot.name() != null ? prefix + nameAnnot.name() : prefix + Character.toLowerCase(m.getName().charAt(verb.length())) + m.getName().substring(verb.length() + 1); } /** Build a supplier that returns the (interpolated and decoded) value from the method's @DefaultValue annotation */ private static <T> Function<Object[], T> createAnnotatedMethodSupplier(Method m, Class<T> returnType, Config config, Decoder decoder) { if (m.isDefault()) { throw new IllegalArgumentException("@DefaultValue cannot be defined on a method with a default implementation for method " + m.getDeclaringClass().getName() + "#" + m.getName()); } else if ( Map.class.isAssignableFrom(returnType) || List.class.isAssignableFrom(returnType) || Set.class.isAssignableFrom(returnType) ) { throw new IllegalArgumentException("@DefaultValue cannot be used with collections. Use default method implemenation instead " + m.getDeclaringClass().getName() + "#" + m.getName()); } String value = m.getAnnotation(DefaultValue.class).value(); if (returnType == String.class) { //noinspection unchecked return memoize((T) config.resolve(value)); // The cast is actually a no-op, T == String here! } else { return memoize(decoder.decode(returnType, config.resolve(value))); } } /** Build a supplier that always returns VALUE */ private static <T> Function<Object[], T> memoize(T value) { return (ignored) -> value; } /** A supplier that calls a default method in the proxied interface and returns its output */ private static <T> Function<Object[], T> createDefaultMethodSupplier(Method method, Class<T> type, T proxyObject) { final MethodHandle methodHandle; try { if (SystemUtils.IS_JAVA_1_8) { Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class .getDeclaredConstructor(Class.class, int.class); constructor.setAccessible(true); methodHandle = constructor.newInstance(type, MethodHandles.Lookup.PRIVATE) .unreflectSpecial(method, type) .bindTo(proxyObject); } else { // Java 9 onwards methodHandle = MethodHandles.lookup() .findSpecial(type, method.getName(), MethodType.methodType(method.getReturnType(), method.getParameterTypes()), type) .bindTo(proxyObject); } } catch (ReflectiveOperationException e) { throw new RuntimeException("Failed to create temporary object for " + type.getName(), e); } return (args) -> { try { if (methodHandle.type().parameterCount() == 0) { //noinspection unchecked return (T) methodHandle.invokeWithArguments(); } else if (args != null) { //noinspection unchecked return (T) methodHandle.invokeWithArguments(args); } else { // This is a handle to a method WITH arguments, being called with none. This happens when toString() // is trying to build a representation of a proxy that has a parameterized property AND the interface // provides a default method for it. There's no good default to return here, so we'll just use null return null; } } catch (Throwable e) { maybeWrapThenRethrow(e); return null; // Unreachable, but the compiler doesn't know } }; } /** A value getter for a nested Config proxy */ protected <T> PropertyValueGetter<T> createInterfaceProperty(String propName, final T proxy) { LOG.debug("Creating interface property `{}` for type `{}`", propName, proxy.getClass()); return (args) -> proxy; } /** * A value getter for a "simple" property. Returns the value set in config for the given propName, * or calls the defaultValueSupplier if the property is not set. */ protected <T> PropertyValueGetter<T> createScalarProperty(final Type type, final String propName, Function<Object[], T> defaultValueSupplier) { LOG.debug("Creating scalar property `{}` for type `{}`", propName, type.getClass()); final Property<T> prop = propertyRepository.get(propName, type); return args -> { T value = prop.get(); return value != null ? value : defaultValueSupplier.apply(null); }; } /** * A value getter for a parameterized property. Takes the arguments passed to the method call and interpolates them * into the property name from the method's @PropertyName annotation, then returns the value set in config for the * computed property name. If not set, it forwards the call with the same parameters to the defaultValueSupplier. */ protected <T> PropertyValueGetter<T> createParameterizedProperty(final Class<T> returnType, final String propertyNameTemplate, Function<Object[], T> defaultValueSupplier) { LOG.debug("Creating parameterized property `{}` for type `{}`", propertyNameTemplate, returnType); return args -> { if (args == null) { // Why would args be null if this is a parameterized property? Because toString() abuses its // access to this internal representation :-/ // We'll fall back to trying to call the provider for the default value. That works properly if // it comes from an annotation or the known collections. Our wrapper for default interface methods // catches this case and just returns a null, which is probably the least bad response. return defaultValueSupplier.apply(null); } // Determine the actual property name by replacing with arguments using the argument index // to the method. For example, // @PropertyName(name="foo.${1}.${0}") // String getFooValue(String arg0, Integer arg1) // // called as getFooValue("bar", 1) would look for the property 'foo.1.bar' String interpolatedPropertyName = new StrSubstitutor(new ArrayLookup<>(args), "${", "}", '$') .replace(propertyNameTemplate); T result = propertyRepository.get(interpolatedPropertyName, returnType).get(); if (result == null) { result = defaultValueSupplier.apply(args); } return result; }; } private static void maybeWrapThenRethrow(Throwable t) { if (t instanceof RuntimeException) { throw (RuntimeException) t; } if (t instanceof Error) { throw (Error) t; } throw new RuntimeException(t); } private static <T> void warnWhenTooMany(Map<T, Integer> counters, T countKey, int limit, Supplier<String> objectDescription) { int currentCount = counters.merge(countKey, 1, Integer::sum); // Emit warning if we're over the limit BUT only when the current count is a multiple of the limit :-) // This is to avoid being *too* noisy if (LOG.isWarnEnabled() && currentCount >= limit && (currentCount % limit == 0 )) { LOG.warn( "Too many {} objects are being created ({} so far).\n" + "Please review the calling code to prevent memory leaks.\n" + "Normal usage for ConfigProxyFactory is to create singletons via your DI mechanism.\n" + "For special use cases that *require* creating multiple instances you can tune reporting\n" + "by setting the `{}` config key to a higher threshold.\nStack trace for debugging follows:", objectDescription.get(), currentCount, EXCESSIVE_PROXIES_LIMIT, new Throwable()); } } /** InvocationHandler for config proxies. */ private static class ConfigProxyInvocationHandler<P> implements InvocationHandler { private final Map<Method, PropertyValueGetter<?>> invokers; private final Class<P> type; private final String prefix; private final Map<Method, String> propertyNames; public ConfigProxyInvocationHandler(Class<P> proxiedClass, String prefix, Map<Method, PropertyValueGetter<?>> invokers, Map<Method, String> propertyNames) { this.invokers = invokers; this.type = proxiedClass; this.prefix = prefix; this.propertyNames = propertyNames; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws NoSuchMethodError{ PropertyValueGetter<?> invoker = invokers.get(method); if (invoker != null) { return invoker.invoke(args); } switch (method.getName()) { case "equals": return proxy == args[0]; case "hashCode": return System.identityHashCode(proxy); case "toString": return proxyToString(); default: throw new NoSuchMethodError(method.getName() + " not found on interface " + type.getName()); } } /** * Create a reasonable string representation of the proxy object: "InterfaceName[propName=currentValue, ...]". * For the case of parameterized properties, fudges it and just uses "null" as the value. */ private String proxyToString() { String propertyNamesAndValues = invokers.entrySet().stream() .map(this::toNameAndValue) .collect(Collectors.joining(",")); return String.format("%s[%s]", type.getSimpleName(), propertyNamesAndValues); } /** Maps one (method, valueGetter) entry to a "propertyName=value" string */ private String toNameAndValue(Map.Entry<Method, PropertyValueGetter<?>> entry) { String propertyName = propertyNames.get(entry.getKey()).substring(prefix.length()); Object propertyValue; try { // This call should fail for parameterized properties, because the PropertyValueGetter has a non-empty // argument list. Fortunately, the implementation there cooperates with us and returns a null instead :-) propertyValue = entry.getValue().invoke(null); } catch (Exception e) { // Just in case propertyValue = e.getMessage(); } return String.format("%s='%s'", propertyName, propertyValue); } } /** * A holder for the two pieces of information we compute for each method: Its invoker and the property's name. * This would just be a record in Java 17 :-) */ private static class MethodInvokerHolder<T> { final PropertyValueGetter<T> invoker; final String propertyName; private MethodInvokerHolder(PropertyValueGetter<T> invoker, String propertyName) { this.invoker = invoker; this.propertyName = propertyName; } } /** Key to index counts of created proxies */ private static final class InterfaceAndPrefix { final Class<?> configInterface; final String prefix; private InterfaceAndPrefix(Class<?> configInterface, String prefix) { this.configInterface = configInterface; this.prefix = prefix; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InterfaceAndPrefix that = (InterfaceAndPrefix) o; return Objects.equals(configInterface, that.configInterface) && Objects.equals(prefix, that.prefix); } @Override public int hashCode() { return Objects.hash(configInterface, prefix); } } /** Implement apache-commons StrLookup by interpreting the key as an index into an array */ private static class ArrayLookup<V> extends StrLookup<V> { private final V[] elements; private ArrayLookup(V[] elements) { super(); this.elements = elements; } @Override public String lookup(String key) { if (elements == null || elements.length == 0 || StringUtils.isBlank(key)) { return null; } try { int index = Integer.parseInt(key); if (index < 0 || index >= elements.length || elements[index] == null) { return null; } return elements[index].toString(); } catch (NumberFormatException e) { return null; } } } }
9,263
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/DefaultPropertyFactory.java
package com.netflix.archaius; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.ConfigListener; import com.netflix.archaius.api.Property; import com.netflix.archaius.api.PropertyContainer; import com.netflix.archaius.api.PropertyFactory; import com.netflix.archaius.api.PropertyListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicStampedReference; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; public class DefaultPropertyFactory implements PropertyFactory, ConfigListener { private static final Logger LOG = LoggerFactory.getLogger(DefaultPropertyFactory.class); /** * Create a Property factory that is attached to a specific config * @param config * @return */ public static DefaultPropertyFactory from(final Config config) { return new DefaultPropertyFactory(config); } /** * Config from which properties are retrieved. Config may be a composite. */ private final Config config; /** * Cache of properties so PropertyContainer may be re-used */ private final ConcurrentMap<KeyAndType<?>, Property<?>> properties = new ConcurrentHashMap<>(); /** * Monotonically incrementing version number whenever a change in the Config * is identified. This version is used as a global dirty flag indicating that * properties should be updated when fetched next. */ private final AtomicInteger masterVersion = new AtomicInteger(); /** * Array of all active callbacks. ListenerWrapper#update will be called for any * change in config. */ private final List<Runnable> listeners = new CopyOnWriteArrayList<>(); public DefaultPropertyFactory(Config config) { this.config = config; this.config.addListener(this); } @Override public PropertyContainer getProperty(String propName) { return new PropertyContainer() { @Override public Property<String> asString(String defaultValue) { return get(propName, String.class).orElse(defaultValue); } @Override public Property<Integer> asInteger(Integer defaultValue) { return get(propName, Integer.class).orElse(defaultValue); } @Override public Property<Long> asLong(Long defaultValue) { return get(propName, Long.class).orElse(defaultValue); } @Override public Property<Double> asDouble(Double defaultValue) { return get(propName, Double.class).orElse(defaultValue); } @Override public Property<Float> asFloat(Float defaultValue) { return get(propName, Float.class).orElse(defaultValue); } @Override public Property<Short> asShort(Short defaultValue) { return get(propName, Short.class).orElse(defaultValue); } @Override public Property<Byte> asByte(Byte defaultValue) { return get(propName, Byte.class).orElse(defaultValue); } @Override public Property<Boolean> asBoolean(Boolean defaultValue) { return get(propName, Boolean.class).orElse(defaultValue); } @Override public Property<BigDecimal> asBigDecimal(BigDecimal defaultValue) { return get(propName, BigDecimal.class).orElse(defaultValue); } @Override public Property<BigInteger> asBigInteger(BigInteger defaultValue) { return get(propName, BigInteger.class).orElse(defaultValue); } @Override public <T> Property<T> asType(Class<T> type, T defaultValue) { return get(propName, type).orElse(defaultValue); } @Override public <T> Property<T> asType(Function<String, T> mapper, String defaultValue) { T typedDefaultValue = mapper.apply(defaultValue); return getFromSupplier(propName, null, () -> { String value = config.getString(propName, null); if (value != null) { try { return mapper.apply(value); } catch (Exception e) { LOG.warn("Invalid value '{}' for property '{}'", propName, value); } } return typedDefaultValue; }); } }; } @Override public void onConfigAdded(Config config) { invalidate(); } @Override public void onConfigRemoved(Config config) { invalidate(); } @Override public void onConfigUpdated(Config config) { invalidate(); } @Override public void onError(Throwable error, Config config) { // TODO } public void invalidate() { // Incrementing the version will cause all PropertyContainer instances to invalidate their // cache on the next call to get masterVersion.incrementAndGet(); // We expect a small set of callbacks and invoke all of them whenever there is any change // in the configuration regardless of change. The blanket update is done since we don't track // a dependency graph of replacements. listeners.forEach(Runnable::run); } protected Config getConfig() { return this.config; } @Override public <T> Property<T> get(String key, Class<T> type) { return getFromSupplier(key, type, () -> config.get(type, key, null)); } @Override public <T> Property<T> get(String key, Type type) { return getFromSupplier(key, type, () -> config.get(type, key, null)); } private <T> Property<T> getFromSupplier(String key, Type type, Supplier<T> supplier) { return getFromSupplier(new KeyAndType<T>(key, type), supplier); } @SuppressWarnings("unchecked") private <T> Property<T> getFromSupplier(KeyAndType<T> keyAndType, Supplier<T> supplier) { return (Property<T>) properties.computeIfAbsent(keyAndType, (ignore) -> new PropertyImpl<T>(keyAndType, supplier)); } private class PropertyImpl<T> implements Property<T> { private final KeyAndType<T> keyAndType; private final Supplier<T> supplier; private final AtomicStampedReference<T> cache = new AtomicStampedReference<>(null, -1); private final ConcurrentMap<PropertyListener<?>, Subscription> oldSubscriptions = new ConcurrentHashMap<>(); public PropertyImpl(KeyAndType<T> keyAndType, Supplier<T> supplier) { this.keyAndType = keyAndType; this.supplier = supplier; } @Override public T get() { int cacheVersion = cache.getStamp(); int latestVersion = masterVersion.get(); if (cacheVersion != latestVersion) { T currentValue = cache.getReference(); T newValue = null; try { newValue = supplier.get(); } catch (Exception e) { LOG.warn("Unable to get current version of property '{}'", keyAndType.key, e); } if (cache.compareAndSet(currentValue, newValue, cacheVersion, latestVersion)) { // Possible race condition here but not important enough to warrant locking return newValue; } } return cache.getReference(); } @Override public String getKey() { return keyAndType.key; } @Override public Subscription subscribe(Consumer<T> consumer) { Runnable action = new Runnable() { private T current = get(); @Override public synchronized void run() { T newValue = get(); if (current == newValue && current == null) { return; } else if (current == null) { current = newValue; } else if (newValue == null) { current = null; } else if (current.equals(newValue)) { return; } else { current = newValue; } consumer.accept(current); } }; listeners.add(action); return () -> listeners.remove(action); } @Deprecated public void addListener(PropertyListener<T> listener) { Subscription cancel = onChange(new Consumer<T>() { @Override public void accept(T t) { listener.accept(t); } }); oldSubscriptions.put(listener, cancel); } /** * Remove a listener previously registered by calling addListener * @param listener */ @Deprecated public void removeListener(PropertyListener<T> listener) { Optional.ofNullable(oldSubscriptions.remove(listener)).ifPresent(Subscription::unsubscribe); } @Override public Property<T> orElse(T defaultValue) { return new PropertyImpl<T>(keyAndType, () -> Optional.ofNullable(supplier.get()).orElse(defaultValue)); } @Override public Property<T> orElseGet(String key) { if (!keyAndType.hasType()) { throw new IllegalStateException("Type information lost due to map() operation. All calls to orElse[Get] must be made prior to calling map"); } KeyAndType<T> keyAndType = this.keyAndType.withKey(key); Property<T> next = DefaultPropertyFactory.this.get(key, keyAndType.type); return new PropertyImpl<T>(keyAndType, () -> Optional.ofNullable(supplier.get()).orElseGet(next)); } @Override public <S> Property<S> map(Function<T, S> mapper) { return new PropertyImpl<>(keyAndType.discardType(), () -> { T value = supplier.get(); if (value != null) { return mapper.apply(value); } else { return null; } }); } @Override public String toString() { return "Property [Key=" + getKey() + "; value="+get() + "]"; } } private static final class KeyAndType<T> { private final String key; private final Type type; public KeyAndType(String key, Type type) { this.key = key; this.type = type; } public <S> KeyAndType<S> discardType() { return new KeyAndType<S>(key, null); } public KeyAndType<T> withKey(String newKey) { return new KeyAndType<T>(newKey, type); } public boolean hasType() { return type != null; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; KeyAndType other = (KeyAndType) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } } }
9,264
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/util/Maps.java
package com.netflix.archaius.util; import java.util.HashMap; import java.util.LinkedHashMap; public final class Maps { private Maps() {} /** * Calculate initial capacity from expected size and default load factor (0.75). */ private static int calculateCapacity(int numMappings) { return (int) Math.ceil(numMappings / 0.75d); } /** * Creates a new, empty HashMap suitable for the expected number of mappings. * The returned map is large enough so that the expected number of mappings can be * added without resizing the map. * * This is essentially a backport of HashMap.newHashMap which was added in JDK19. */ public static <K, V> HashMap<K, V> newHashMap(int numMappings) { return new HashMap<>(calculateCapacity(numMappings)); } /** * Creates a new, empty LinkedHashMap suitable for the expected number of mappings. * The returned map is large enough so that the expected number of mappings can be * added without resizing the map. * * This is essentially a backport of LinkedHashMap.newLinkedHashMap which was added in JDK19. */ public static <K, V> LinkedHashMap<K, V> newLinkedHashMap(int numMappings) { return new LinkedHashMap<>(calculateCapacity(numMappings)); } }
9,265
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/util/ThreadFactories.java
package com.netflix.archaius.util; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; public class ThreadFactories { private static final AtomicInteger counter = new AtomicInteger(); public static ThreadFactory newNamedDaemonThreadFactory(final String name) { return new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread thread = Executors.defaultThreadFactory().newThread(runnable); thread.setDaemon(true); thread.setName(String.format(name, counter.incrementAndGet())); return thread; } }; } }
9,266
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/util/Futures.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.util; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class Futures { public static <T> Future<T> immediateFailure(final Exception e) { return new Future<T>() { @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return true; } @Override public T get() throws InterruptedException, ExecutionException { throw new ExecutionException(e); } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { throw new ExecutionException(e); } }; } }
9,267
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/util/ShardedReentrantLock.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.util; import java.util.concurrent.locks.ReentrantLock; public class ShardedReentrantLock { private final ReentrantLock locks[]; private final int size; private final int mask; public ShardedReentrantLock(int count) { this.size = (int)(count * Math.ceil((double)count / 2)); mask = size-1; locks = new ReentrantLock[size]; for (int i = 0; i < size; i++) { locks[i] = new ReentrantLock(); } } public ReentrantLock get(String key) { return locks[key.hashCode() & mask]; } }
9,268
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config/CachedState.java
package com.netflix.archaius.config; import com.netflix.archaius.api.Config; import java.util.Collections; import java.util.Map; /** Represents an immutable, current view of a dependent config over its parent configs. */ class CachedState { private final Map<String, Object> data; private final Map<String, Config> instrumentedKeys; CachedState(Map<String, Object> data, Map<String, Config> instrumentedKeys) { this.data = Collections.unmodifiableMap(data); this.instrumentedKeys = Collections.unmodifiableMap(instrumentedKeys); } Map<String, Object> getData() { return data; } Map<String, Config> getInstrumentedKeys() { return instrumentedKeys; } }
9,269
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config/PrefixedViewConfig.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.config; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.ConfigListener; import com.netflix.archaius.api.Decoder; import com.netflix.archaius.api.PropertyDetails; import com.netflix.archaius.api.StrInterpolator; import com.netflix.archaius.api.StrInterpolator.Lookup; import com.netflix.archaius.interpolate.ConfigStrLookup; /** * View into another Config for properties starting with a specified prefix. * * This class is meant to work with dynamic Config object that may have properties * added and removed. */ public class PrefixedViewConfig extends AbstractDependentConfig { private final Config config; private final String prefix; private final Lookup nonPrefixedLookup; private volatile CachedState state; /** Listener to update the state of the PrefixedViewConfig on any changes in the source config. */ private static class PrefixedViewConfigListener extends DependentConfigListener<PrefixedViewConfig> { private PrefixedViewConfigListener(PrefixedViewConfig pvc) { super(pvc); } @Override public void onSourceConfigAdded(PrefixedViewConfig pvc, Config config) { pvc.updateState(config); } @Override public void onSourceConfigRemoved(PrefixedViewConfig pvc, Config config) { pvc.updateState(config); } @Override public void onSourceConfigUpdated(PrefixedViewConfig pvc, Config config) { pvc.updateState(config); } @Override public void onSourceError(Throwable error, PrefixedViewConfig pvc, Config config) { } } public PrefixedViewConfig(final String prefix, final Config config) { this.config = config; this.prefix = prefix.endsWith(".") ? prefix : prefix + "."; this.nonPrefixedLookup = ConfigStrLookup.from(config); this.state = createState(config); this.config.addListener(new PrefixedViewConfigListener(this)); } private void updateState(Config config) { this.state = createState(config); } private CachedState createState(Config config) { Map<String, Object> data = new LinkedHashMap<>(); Map<String, Config> instrumentedKeys = new LinkedHashMap<>(); boolean instrumented = config.instrumentationEnabled(); config.forEachPropertyUninstrumented((k, v) -> { if (k.startsWith(prefix)) { String key = k.substring(prefix.length()); data.put(key, v); if (instrumented) { instrumentedKeys.put(key, config); } } }); return new CachedState(data, instrumentedKeys); } @Override public CachedState getState() { return state; } @Override public <T> T accept(Visitor<T> visitor) { T t = null; for (Entry<String, Object> entry : state.getData().entrySet()) { t = visitor.visitKey(entry.getKey(), entry.getValue()); } return t; } @Override protected Lookup getLookup() { return nonPrefixedLookup; } @Override public synchronized void setDecoder(Decoder decoder) { super.setDecoder(decoder); config.setDecoder(decoder); } @Override public synchronized void setStrInterpolator(StrInterpolator interpolator) { super.setStrInterpolator(interpolator); config.setStrInterpolator(interpolator); } @Override public synchronized void addListener(ConfigListener listener) { super.addListener(listener); config.addListener(listener); } @Override public synchronized void removeListener(ConfigListener listener) { super.removeListener(listener); config.removeListener(listener); } @Override protected PropertyDetails createPropertyDetails(String key, Object value) { return new PropertyDetails(prefix + key, null, value); } }
9,270
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config/EnvironmentConfig.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.config; import java.util.Iterator; import java.util.Map; import java.util.function.BiConsumer; public class EnvironmentConfig extends AbstractConfig { public static final EnvironmentConfig INSTANCE = new EnvironmentConfig(); private final Map<String, String> properties; public EnvironmentConfig() { this.properties = System.getenv(); } @Override public Object getRawProperty(String key) { return properties.get(key); } @Override public boolean containsKey(String key) { return properties.containsKey(key); } @Override public boolean isEmpty() { return properties.isEmpty(); } @Override public Iterator<String> getKeys() { return properties.keySet().iterator(); } @Override public Iterable<String> keys() { return properties.keySet(); } @Override public void forEachProperty(BiConsumer<String, Object> consumer) { properties.forEach(consumer); } }
9,271
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config/CompositeConfig.java
package com.netflix.archaius.config; /** * @deprecated Please use {@link com.netflix.archaius.config.DefaultCompositeConfig} as the * default impl of {@link com.netflix.archaius.api.config.CompositeConfig} * * @author David Liu */ @Deprecated public class CompositeConfig extends DefaultCompositeConfig { }
9,272
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config/DefaultSettableConfig.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.config; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.config.SettableConfig; import com.netflix.archaius.util.Maps; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.function.BiConsumer; public class DefaultSettableConfig extends AbstractConfig implements SettableConfig { private volatile Map<String, Object> props = Collections.emptyMap(); public DefaultSettableConfig(String name) { super(name); } public DefaultSettableConfig() { super(generateUniqueName("settable-")); } @Override public synchronized <T> void setProperty(String propName, T propValue) { Map<String, Object> copy = Maps.newHashMap(props.size() + 1); copy.putAll(props); copy.put(propName, propValue); props = Collections.unmodifiableMap(copy); notifyConfigUpdated(this); } @Override public void clearProperty(String propName) { if (props.containsKey(propName)) { synchronized (this) { Map<String, Object> copy = new HashMap<>(props); copy.remove(propName); props = Collections.unmodifiableMap(copy); notifyConfigUpdated(this); } } } @Override public boolean containsKey(String key) { return props.containsKey(key); } @Override public boolean isEmpty() { return props.isEmpty(); } @Override public Object getRawProperty(String key) { return props.get(key); } @Override public Iterator<String> getKeys() { return props.keySet().iterator(); } @Override public Iterable<String> keys() { return props.keySet(); } @Override public void setProperties(Properties src) { if (null != src) { synchronized (this) { Map<String, Object> copy = Maps.newHashMap(props.size() + src.size()); copy.putAll(props); for (Entry<Object, Object> prop : src.entrySet()) { copy.put(prop.getKey().toString(), prop.getValue()); } props = Collections.unmodifiableMap(copy); notifyConfigUpdated(this); } } } @Override public void setProperties(Config src) { if (null != src) { synchronized (this) { Map<String, Object> copy = new HashMap<>(props); src.forEachProperty(copy::put); props = Collections.unmodifiableMap(copy); notifyConfigUpdated(this); } } } @Override public void forEachProperty(BiConsumer<String, Object> consumer) { props.forEach(consumer); } }
9,273
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config/MapConfig.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.config; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.function.BiConsumer; /** * Config backed by an immutable map. */ public class MapConfig extends AbstractConfig { /** * The builder only provides convenience for fluent style adding of properties * * {@code * <pre> * MapConfig.builder() * .put("foo", "bar") * .put("baz", 123) * .build() * </pre> * } */ public static class Builder { Map<String, String> map = new HashMap<>(); String named; public <T> Builder put(String key, T value) { map.put(key, value.toString()); return this; } public <T> Builder putAll(Map<String, String> props) { map.putAll(props); return this; } public <T> Builder putAll(Properties props) { props.forEach((k, v) -> map.put(k.toString(), v.toString())); return this; } public Builder name(String name) { this.named = name; return this; } public MapConfig build() { return new MapConfig(named == null ? generateUniqueName("immutable-") : named, map); } } public static Builder builder() { return new Builder(); } public static MapConfig from(Properties props) { return new MapConfig(props); } public static MapConfig from(Map<String, String> props) { return new MapConfig(props); } private final Map<String, String> props; public MapConfig(String name, Map<String, String> props) { super(name); this.props = Collections.unmodifiableMap(new HashMap<>(props)); } /** * Construct a MapConfig as a copy of the provided Map * @param name * @param props */ public MapConfig(Map<String, String> props) { super(generateUniqueName("immutable-")); this.props = Collections.unmodifiableMap(new HashMap<>(props)); } /** * Construct a MapConfig as a copy of the provided properties * @param props */ public MapConfig(Properties props) { super(generateUniqueName("immutable-")); Map<String, String> properties = new HashMap<>(); for (Entry<Object, Object> entry : props.entrySet()) { properties.put(entry.getKey().toString(), entry.getValue().toString()); } this.props = Collections.unmodifiableMap(properties); } @Override public Object getRawProperty(String key) { return props.get(key); } @Override public boolean containsKey(String key) { return props.containsKey(key); } @Override public boolean isEmpty() { return props.isEmpty(); } @Override public Iterator<String> getKeys() { return props.keySet().iterator(); } @Override public Iterable<String> keys() { return props.keySet(); } @Override public void forEachProperty(BiConsumer<String, Object> consumer) { props.forEach(consumer); } }
9,274
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config/DependentConfigListener.java
package com.netflix.archaius.config; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.ConfigListener; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.util.Optional; /** * ConfigListener for the dependent/wrapper config paradigm. Most notably makes the reference to the dependent config * a weak reference and removes this listener from the source config so that any abandoned dependent configs can be * properly garbage collected. * * @param <T> The type of the dependent config */ abstract class DependentConfigListener<T extends AbstractConfig> implements ConfigListener { private final Reference<T> dependentConfigRef; DependentConfigListener(T dependentConfig) { dependentConfigRef = new WeakReference<>(dependentConfig); } @Override public void onConfigAdded(Config config) { updateState(config).ifPresent(depConfig -> onSourceConfigAdded(depConfig, config)); } @Override public void onConfigRemoved(Config config) { updateState(config).ifPresent(depConfig -> onSourceConfigRemoved(depConfig, config)); } @Override public void onConfigUpdated(Config config) { updateState(config).ifPresent(depConfig -> onSourceConfigUpdated(depConfig, config)); } @Override public void onError(Throwable error, Config config) { updateState(config).ifPresent(depConfig -> onSourceError(error, depConfig, config)); } public abstract void onSourceConfigAdded(T dependentConfig, Config sourceConfig); public abstract void onSourceConfigRemoved(T dependentConfig, Config sourceConfig); public abstract void onSourceConfigUpdated(T dependentConfig, Config sourceConfig); public abstract void onSourceError(Throwable error, T dependentConfig, Config sourceConfig); /** * Checks that the dependent Config object is still alive, and if so it updates its local state from the wrapped * source. * * @return An Optional with the dependent Config object IFF the weak reference to it is still alive, empty otherwise. */ private Optional<T> updateState(Config updatedSourceConfig) { T dependentConfig = dependentConfigRef.get(); if (dependentConfig != null) { return Optional.of(dependentConfig); } else { // The view is gone, cleanup time! updatedSourceConfig.removeListener(this); return Optional.empty(); } } }
9,275
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config/DefaultCompositeConfig.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.config; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicReference; import com.netflix.archaius.util.Maps; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.ConfigListener; import com.netflix.archaius.api.exceptions.ConfigException; /** * Config that is a composite of multiple configuration and as such doesn't track * properties of its own. The composite does not merge the configurations but instead * treats them as overrides so that a property existing in a configuration supersedes * the same property in configuration that was added later. It is however possible * to set a flag that reverses the override order. * * TODO: Optional cache of queried properties * TODO: Resolve method to collapse all the child configurations into a single config * TODO: Combine children and lookup into a single LinkedHashMap */ public class DefaultCompositeConfig extends AbstractDependentConfig implements com.netflix.archaius.api.config.CompositeConfig { private static final Logger LOG = LoggerFactory.getLogger(DefaultCompositeConfig.class); /** * The builder provides a fluent style API to create a CompositeConfig */ public static class Builder { LinkedHashMap<String, Config> configs = new LinkedHashMap<>(); public Builder withConfig(String name, Config config) { configs.put(name, config); return this; } public com.netflix.archaius.api.config.CompositeConfig build() throws ConfigException { com.netflix.archaius.api.config.CompositeConfig config = new DefaultCompositeConfig(); for (Entry<String, Config> entry : configs.entrySet()) { config.addConfig(entry.getKey(), entry.getValue()); } return config; } } public static Builder builder() { return new Builder(); } public static com.netflix.archaius.api.config.CompositeConfig create() throws ConfigException { return DefaultCompositeConfig.builder().build(); } private class State { private final Map<String, Config> children; private final CachedState cachedState; public State(Map<String, Config> children, int size) { this.children = children; Map<String, Object> data = Maps.newHashMap(size); Map<String, Config> instrumentedKeys = new HashMap<>(); for (Config child : children.values()) { boolean instrumented = child.instrumentationEnabled(); child.forEachPropertyUninstrumented( (k, v) -> updateData(data, instrumentedKeys, k, v, child, instrumented)); } this.cachedState = new CachedState(data, instrumentedKeys); } private void updateData( Map<String, Object> data, Map<String, Config> instrumentedKeys, String key, Object value, Config childConfig, boolean instrumented) { if (!data.containsKey(key)) { if (instrumented) { instrumentedKeys.put(key, childConfig); } data.put(key, value); } } State addConfig(String name, Config config) { LinkedHashMap<String, Config> children = Maps.newLinkedHashMap(this.children.size() + 1); if (reversed) { children.put(name, config); children.putAll(this.children); } else { children.putAll(this.children); children.put(name, config); } Iterable<String> keysIterable = config.keys(); int size = keysIterable instanceof Collection<?> ? ((Collection<String>) keysIterable).size() : 16; return new State(children, cachedState.getData().size() + size); } State removeConfig(String name) { if (children.containsKey(name)) { LinkedHashMap<String, Config> children = new LinkedHashMap<>(this.children); children.remove(name); return new State(children, cachedState.getData().size()); } return this; } public State refresh() { return new State(children, cachedState.getData().size()); } Config getConfig(String name) { return children.get(name); } boolean containsConfig(String name) { return getConfig(name) != null; } } /** * Listener to be added to any component configs which updates the config map and triggers updates on all listeners * when any of the components are updated. */ private static class CompositeConfigListener extends DependentConfigListener<DefaultCompositeConfig> { private CompositeConfigListener(DefaultCompositeConfig config) { super(config); } @Override public void onSourceConfigAdded(DefaultCompositeConfig dcc, Config config) { dcc.refreshState(); dcc.notifyConfigAdded(dcc); } @Override public void onSourceConfigRemoved(DefaultCompositeConfig dcc, Config config) { dcc.refreshState(); dcc.notifyConfigRemoved(dcc); } @Override public void onSourceConfigUpdated(DefaultCompositeConfig dcc, Config config) { dcc.refreshState(); dcc.notifyConfigUpdated(dcc); } @Override public void onSourceError(Throwable error, DefaultCompositeConfig dcc, Config config) { dcc.notifyError(error, dcc); } } private final ConfigListener listener; private final boolean reversed; private volatile State state; public DefaultCompositeConfig() { this(false); } public DefaultCompositeConfig(boolean reversed) { this.reversed = reversed; this.listener = new CompositeConfigListener(this); this.state = new State(Collections.emptyMap(), 0); } @Override CachedState getState() { return state.cachedState; } private void refreshState() { this.state = state.refresh(); } @Override public synchronized boolean addConfig(String name, Config child) throws ConfigException { return internalAddConfig(name, child); } private synchronized boolean internalAddConfig(String name, Config child) throws ConfigException { LOG.info("Adding config {} to {}", name, hashCode()); if (child == null) { // TODO: Log a warning? return false; } if (name == null) { throw new ConfigException("Child configuration must be named"); } if (state.containsConfig(name)) { LOG.info("Configuration with name'{}' already exists", name); return false; } state = state.addConfig(name, child); postConfigAdded(child); return true; } @Override public synchronized void addConfigs(LinkedHashMap<String, Config> configs) throws ConfigException { for (Entry<String, Config> entry : configs.entrySet()) { internalAddConfig(entry.getKey(), entry.getValue()); } } @Override public void replaceConfigs(LinkedHashMap<String, Config> configs) throws ConfigException { for (Entry<String, Config> entry : configs.entrySet()) { replaceConfig(entry.getKey(), entry.getValue()); } } @Override public synchronized Collection<String> getConfigNames() { return state.children.keySet(); } protected void postConfigAdded(Config child) { child.setStrInterpolator(getStrInterpolator()); child.setDecoder(getDecoder()); notifyConfigAdded(child); child.addListener(listener); } @Override public synchronized void replaceConfig(String name, Config child) throws ConfigException { internalRemoveConfig(name); internalAddConfig(name, child); } @Override public synchronized Config removeConfig(String name) { return internalRemoveConfig(name); } public synchronized Config internalRemoveConfig(String name) { Config child = state.getConfig(name); if (child != null) { state = state.removeConfig(name); child.removeListener(listener); this.notifyConfigRemoved(child); } return child; } @Override public Config getConfig(String name) { return state.children.get(name); } @Override public synchronized <T> T accept(Visitor<T> visitor) { AtomicReference<T> result = new AtomicReference<>(null); if (visitor instanceof CompositeVisitor) { CompositeVisitor<T> cv = (CompositeVisitor<T>)visitor; state.children.forEach((key, config) -> { result.set(cv.visitChild(key, config)); }); } else { state.cachedState.getData().forEach(visitor::visitKey); } return result.get(); } public static com.netflix.archaius.api.config.CompositeConfig from(LinkedHashMap<String, Config> load) throws ConfigException { Builder builder = builder(); for (Entry<String, Config> config : load.entrySet()) { builder.withConfig(config.getKey(), config.getValue()); } return builder.build(); } @Override public String toString() { return "[" + String.join(" ", state.children.keySet()) + "]"; } }
9,276
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config/PollingDynamicConfig.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.config; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiConsumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.archaius.api.config.PollingStrategy; import com.netflix.archaius.api.PropertyDetails; import com.netflix.archaius.config.polling.PollingResponse; import com.netflix.archaius.instrumentation.AccessMonitorUtil; /** * Special DynamicConfig that reads an entire snapshot of the configuration * from a source and performs a delta comparison. Each new snapshot becomes * the new immutable Map backing this config. */ public class PollingDynamicConfig extends AbstractConfig { private static final Logger LOG = LoggerFactory.getLogger(PollingDynamicConfig.class); private volatile Map<String, String> current = Collections.emptyMap(); private volatile Map<String, String> currentIds = Collections.emptyMap(); private final AtomicBoolean busy = new AtomicBoolean(); private final Callable<PollingResponse> reader; private final AtomicLong updateCounter = new AtomicLong(); private final AtomicLong errorCounter = new AtomicLong(); private final PollingStrategy strategy; // Holds the AccessMonitorUtil and whether instrumentation is enabled. This is encapsulated to avoid // race conditions while also allowing for on-the-fly enabling and disabling of instrumentation. private volatile Instrumentation instrumentation; public PollingDynamicConfig(Callable<PollingResponse> reader, PollingStrategy strategy) { this(reader, strategy, null); } public PollingDynamicConfig( Callable<PollingResponse> reader, PollingStrategy strategy, AccessMonitorUtil accessMonitorUtil) { this.reader = reader; this.strategy = strategy; this.instrumentation = new Instrumentation(accessMonitorUtil, accessMonitorUtil != null); strategy.execute(new Runnable() { @Override public void run() { try { update(); } catch (Exception e) { throw new RuntimeException("Failed to poll configuration", e); } } }); } @Override public boolean containsKey(String key) { return current.containsKey(key); } @Override public boolean isEmpty() { return current.isEmpty(); } @Override public Object getRawProperty(String key) { Object rawProperty = current.get(key); if (instrumentationEnabled() && rawProperty != null) { recordUsage(new PropertyDetails(key, currentIds.get(key), rawProperty)); } return rawProperty; } @Override public Object getRawPropertyUninstrumented(String key) { return current.get(key); } private void update() throws Exception { // OK to ignore calls to update() if already busy updating if (busy.compareAndSet(false, true)) { updateCounter.incrementAndGet(); try { PollingResponse response = reader.call(); if (response.hasData()) { current = Collections.unmodifiableMap(response.getToAdd()); currentIds = Collections.unmodifiableMap(response.getNameToIdsMap()); notifyConfigUpdated(this); } } catch (Exception e) { LOG.trace("Error reading data from remote server ", e); errorCounter.incrementAndGet(); try { notifyError(e, this); } catch (Exception e2) { LOG.warn("Failed to notify error observer", e2); } throw e; } finally { busy.set(false); } } } public void shutdown() { strategy.shutdown(); } public long getUpdateCounter() { return updateCounter.get(); } public long getErrorCounter() { return errorCounter.get(); } @Override public Iterator<String> getKeys() { return current.keySet().iterator(); } @Override public Iterable<String> keys() { return current.keySet(); } @Override public void forEachProperty(BiConsumer<String, Object> consumer) { boolean instrumentationEnabled = instrumentationEnabled(); current.forEach((k, v) -> { if (instrumentationEnabled) { recordUsage(new PropertyDetails(k, currentIds.get(k), v)); } consumer.accept(k, v); }); } @Override public void forEachPropertyUninstrumented(BiConsumer<String, Object> consumer) { current.forEach(consumer); } @Override public void recordUsage(PropertyDetails propertyDetails) { // Once the instrumentation object is being actively changed (i.e. we have a runtime-disabling mechanism), // there is a potential race condition here. Ensure that this is addressed when this is being changed. if (instrumentationEnabled()) { // Instrumentation calls from outside PollingDynamicConfig may not have ids populated, so we replace the id // here if the id isn't present. if (propertyDetails.getId() == null) { propertyDetails = new PropertyDetails( propertyDetails.getKey(), currentIds.get(propertyDetails.getKey()), propertyDetails.getValue()); } instrumentation.getAccessMonitorUtil().registerUsage(propertyDetails); } } @Override public boolean instrumentationEnabled() { return instrumentation.getEnabled() && instrumentation.getAccessMonitorUtil() != null; } private static class Instrumentation { private final AccessMonitorUtil accessMonitorUtil; private final boolean enabled; Instrumentation(AccessMonitorUtil accessMonitorUtil, boolean enabled) { this.accessMonitorUtil = accessMonitorUtil; this.enabled = enabled; } private AccessMonitorUtil getAccessMonitorUtil() { return accessMonitorUtil; } private boolean getEnabled() { return enabled; } } }
9,277
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config/DefaultConfigListener.java
package com.netflix.archaius.config; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.ConfigListener; /** * Default implementation with noops for all ConfigListener events * @author elandau * */ public class DefaultConfigListener implements ConfigListener { @Override public void onConfigAdded(Config config) { } @Override public void onConfigRemoved(Config config) { } @Override public void onConfigUpdated(Config config) { } @Override public void onError(Throwable error, Config config) { } }
9,278
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config/SystemConfig.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.config; import java.util.Iterator; import java.util.function.BiConsumer; public class SystemConfig extends AbstractConfig { public static final SystemConfig INSTANCE = new SystemConfig(); @Override public Object getRawProperty(String key) { return System.getProperty(key); } @Override public boolean containsKey(String key) { return System.getProperty(key) != null; } @Override public boolean isEmpty() { return false; } @Override public Iterator<String> getKeys() { return new Iterator<String>() { Iterator<Object> obj = System.getProperties().keySet().iterator(); @Override public boolean hasNext() { return obj.hasNext(); } @Override public String next() { return obj.next().toString(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override public void forEachProperty(BiConsumer<String, Object> consumer) { System.getProperties().forEach((k, v) -> consumer.accept(k.toString(), v)); } }
9,279
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config/EmptyConfig.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.config; import java.util.Collections; import java.util.Iterator; import java.util.Optional; import java.util.function.BiConsumer; public final class EmptyConfig extends AbstractConfig { public static final EmptyConfig INSTANCE = new EmptyConfig(); private EmptyConfig() { } @Override public boolean containsKey(String key) { return false; } @Override public boolean isEmpty() { return true; } @Override public Iterator<String> getKeys() { return Collections.emptyIterator(); } @Override public Iterable<String> keys() { return Collections.emptySet(); } @Override public Optional<Object> getProperty(String key) { return Optional.empty(); } @Override public Object getRawProperty(String key) { return null; } @Override public void forEachProperty(BiConsumer<String, Object> consumer) { } }
9,280
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config/AbstractDependentConfig.java
package com.netflix.archaius.config; import com.netflix.archaius.api.PropertyDetails; import java.util.Iterator; import java.util.function.BiConsumer; /** * Extendable base class for the dependent config paradigm. Dependent configs are assumed to be configs which inherit * values from some number (1+) of parent configs. Dependent configs hold onto caches of the property data and operate * independently of the parent configs except in cases of propagation of instrumentation data and property value * changes. * * TODO: Move DependentConfigListener logic here as well? */ public abstract class AbstractDependentConfig extends AbstractConfig { public AbstractDependentConfig(String name) { super(name); } public AbstractDependentConfig() { super(); } abstract CachedState getState(); @Override public Object getRawProperty(String key) { Object value = getState().getData().get(key); if (getState().getInstrumentedKeys().containsKey(key)) { getState().getInstrumentedKeys().get(key).recordUsage(createPropertyDetails(key, value)); } return value; } @Override public Object getRawPropertyUninstrumented(String key) { return getState().getData().get(key); } /** Return a set of all unique keys tracked by any child of this composite. */ @Override public Iterator<String> getKeys() { return getState().getData().keySet().iterator(); } @Override public Iterable<String> keys() { return getState().getData().keySet(); } @Override public void forEachProperty(BiConsumer<String, Object> consumer) { getState().getData().forEach((k, v) -> { if (getState().getInstrumentedKeys().containsKey(k)) { getState().getInstrumentedKeys().get(k).recordUsage(createPropertyDetails(k, v)); } consumer.accept(k, v); }); } @Override public void forEachPropertyUninstrumented(BiConsumer<String, Object> consumer) { getState().getData().forEach(consumer); } @Override public boolean containsKey(String key) { return getState().getData().containsKey(key); } @Override public boolean isEmpty() { return getState().getData().isEmpty(); } @Override public void recordUsage(PropertyDetails propertyDetails) { if (getState().getInstrumentedKeys().containsKey(propertyDetails.getKey())) { getState().getInstrumentedKeys().get(propertyDetails.getKey()).recordUsage(propertyDetails); } } @Override public boolean instrumentationEnabled() { // In the case of dependent configs, instrumentation needs to be propagated. // So, if any of the parent configs are instrumented, we mark this config as instrumented as well. return !getState().getInstrumentedKeys().isEmpty(); } protected PropertyDetails createPropertyDetails(String key, Object value) { return new PropertyDetails(key, null, value); } }
9,281
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config/PrivateViewConfig.java
/** * Copyright 2022 Netflix, Inc. * * 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 com.netflix.archaius.config; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.ConfigListener; import com.netflix.archaius.api.Decoder; import com.netflix.archaius.api.StrInterpolator; /** * View into another Config that allows usage of a private {@link Decoder}, {@link StrInterpolator}, and * {@link ConfigListener}s that will NOT be shared with the original config. * <p> * This class is meant to work with dynamic Config object that may have properties added and removed. */ public class PrivateViewConfig extends AbstractDependentConfig { /** Listener to update our own state on upstream changes and then propagate the even to our own listeners. */ private static class ViewConfigListener extends DependentConfigListener<PrivateViewConfig> { private ViewConfigListener(PrivateViewConfig dependentConfig) { super(dependentConfig); } @Override public void onSourceConfigAdded(PrivateViewConfig pvc, Config config) { pvc.updateState(config); pvc.notifyConfigAdded(pvc); } @Override public void onSourceConfigRemoved(PrivateViewConfig pvc, Config config) { pvc.updateState(config); pvc.notifyConfigRemoved(pvc); } @Override public void onSourceConfigUpdated(PrivateViewConfig pvc, Config config) { pvc.updateState(config); pvc.notifyConfigUpdated(pvc); } @Override public void onSourceError(Throwable error, PrivateViewConfig pvc, Config config) { } } private volatile CachedState state; private void updateState(Config config) { this.state = createState(config); } private CachedState createState(Config config) { Map<String, Object> data = new LinkedHashMap<>(); Map<String, Config> instrumentedKeys = new LinkedHashMap<>(); boolean instrumented = config.instrumentationEnabled(); config.forEachPropertyUninstrumented((k, v) -> { data.put(k, v); if (instrumented) { instrumentedKeys.put(k, config); } }); return new CachedState(data, instrumentedKeys); } @Override public CachedState getState() { return state; } public PrivateViewConfig(final Config wrappedConfig) { this.state = createState(wrappedConfig); wrappedConfig.addListener(new ViewConfigListener(this)); } @Override public <T> T accept(Visitor<T> visitor) { T t = null; for (Entry<String, Object> entry : state.getData().entrySet()) { t = visitor.visitKey(entry.getKey(), entry.getValue()); } return t; } }
9,282
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config/AbstractConfig.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.config; import com.netflix.archaius.DefaultDecoder; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.ConfigListener; import com.netflix.archaius.api.Decoder; import com.netflix.archaius.api.StrInterpolator; import com.netflix.archaius.api.StrInterpolator.Lookup; import com.netflix.archaius.exceptions.ParseException; import com.netflix.archaius.interpolate.CommonsStrInterpolator; import com.netflix.archaius.interpolate.ConfigStrLookup; import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; public abstract class AbstractConfig implements Config { private final CopyOnWriteArrayList<ConfigListener> listeners = new CopyOnWriteArrayList<>(); private final Lookup lookup; private Decoder decoder; private StrInterpolator interpolator; private String listDelimiter = ","; private final String name; private static final AtomicInteger idCounter = new AtomicInteger(); protected static String generateUniqueName(String prefix) { return prefix + idCounter.incrementAndGet(); } public AbstractConfig(String name) { this.decoder = DefaultDecoder.INSTANCE; this.interpolator = CommonsStrInterpolator.INSTANCE; this.lookup = ConfigStrLookup.from(this); this.name = name == null ? generateUniqueName("unnamed-") : name; } public AbstractConfig() { this(generateUniqueName("unnamed-")); } protected CopyOnWriteArrayList<ConfigListener> getListeners() { return listeners; } protected Lookup getLookup() { return lookup; } public String getListDelimiter() { return listDelimiter; } public void setListDelimiter(String delimiter) { listDelimiter = delimiter; } @Override final public Decoder getDecoder() { return this.decoder; } @Override public void setDecoder(Decoder decoder) { this.decoder = decoder; } @Override final public StrInterpolator getStrInterpolator() { return this.interpolator; } @Override public void setStrInterpolator(StrInterpolator interpolator) { this.interpolator = interpolator; } @Override public void addListener(ConfigListener listener) { listeners.add(listener); } @Override public void removeListener(ConfigListener listener) { listeners.remove(listener); } protected void notifyConfigUpdated(Config child) { for (ConfigListener listener : listeners) { listener.onConfigUpdated(child); } } protected void notifyError(Throwable t, Config child) { for (ConfigListener listener : listeners) { listener.onError(t, child); } } protected void notifyConfigAdded(Config child) { for (ConfigListener listener : listeners) { listener.onConfigAdded(child); } } protected void notifyConfigRemoved(Config child) { for (ConfigListener listener : listeners) { listener.onConfigRemoved(child); } } @Override public String getString(String key, String defaultValue) { Object value = getRawProperty(key); if (value == null) { return notFound(key, defaultValue != null ? interpolator.create(getLookup()).resolve(defaultValue) : null); } if (value instanceof String) { return resolve((String)value); } else { return value.toString(); } } @Override public String getString(String key) { Object value = getRawProperty(key); if (value == null) { return notFound(key); } if (value instanceof String) { return resolve(value.toString()); } else { return value.toString(); } } /** * Handle notFound when a defaultValue is provided. * @param defaultValue * @return */ protected <T> T notFound(String key, T defaultValue) { return defaultValue; } protected <T> T notFound(String key) { throw new NoSuchElementException("'" + key + "' not found"); } @Override @Deprecated public Iterator<String> getKeys(final String prefix) { return new Iterator<String>() { final Iterator<String> iter = getKeys(); String next; { while (iter.hasNext()) { next = iter.next(); if (next.startsWith(prefix)) { break; } else { next = null; } } } @Override public boolean hasNext() { return next != null; } @Override public String next() { if (next == null) { throw new IllegalStateException(); } String current = next; next = null; while (iter.hasNext()) { next = iter.next(); if (next.startsWith(prefix)) { break; } else { next = null; } } return current; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override public Config getPrefixedView(String prefix) { if (prefix == null || prefix.isEmpty() || prefix.equals(".")) { return this; } return new PrefixedViewConfig(prefix, this); } @Override public Config getPrivateView() { return new PrivateViewConfig(this); } @Override public <T> T accept(Visitor<T> visitor) { // The general visitor pattern is not expected to have consequences at the individual key-value pair level, // so we choose to leave visitors uninstrumented as they otherwise represent a large source of noisy data. forEachPropertyUninstrumented(visitor::visitKey); return null; } protected <T> T getValue(Type type, String key) { T value = getValueWithDefault(type, key, null); if (value == null) { return notFound(key); } else { return value; } } protected <T> T getValueWithDefault(Type type, String key, T defaultValue) { Object rawProp = getRawProperty(key); if (rawProp == null) { return defaultValue; } if (rawProp instanceof String) { try { String value = resolve(rawProp.toString()); return decoder.decode(type, value); } catch (NumberFormatException e) { return parseError(key, rawProp.toString(), e); } } else if (type instanceof Class) { Class<?> cls = (Class<?>) type; if (cls.isInstance(rawProp) || cls.isPrimitive()) { return (T) rawProp; } } return parseError(key, rawProp.toString(), new NumberFormatException("Property " + rawProp.toString() + " is of wrong format " + type.getTypeName())); } @Override public String resolve(String value) { return interpolator.create(getLookup()).resolve(value); } @Override public <T> T resolve(String value, Class<T> type) { return getDecoder().decode(type, resolve(value)); } @Override public Long getLong(String key) { return getValue(Long.class, key); } @Override public Long getLong(String key, Long defaultValue) { return getValueWithDefault(Long.class, key, defaultValue); } @Override public Double getDouble(String key) { return getValue(Double.class, key); } @Override public Double getDouble(String key, Double defaultValue) { return getValueWithDefault(Double.class, key, defaultValue); } @Override public Integer getInteger(String key) { return getValue(Integer.class, key); } @Override public Integer getInteger(String key, Integer defaultValue) { return getValueWithDefault(Integer.class, key, defaultValue); } @Override public Boolean getBoolean(String key) { return getValue(Boolean.class, key); } @Override public Boolean getBoolean(String key, Boolean defaultValue) { return getValueWithDefault(Boolean.class, key, defaultValue); } @Override public Short getShort(String key) { return getValue(Short.class, key); } @Override public Short getShort(String key, Short defaultValue) { return getValueWithDefault(Short.class, key, defaultValue); } @Override public BigInteger getBigInteger(String key) { return getValue(BigInteger.class, key); } @Override public BigInteger getBigInteger(String key, BigInteger defaultValue) { return getValueWithDefault(BigInteger.class, key, defaultValue); } @Override public BigDecimal getBigDecimal(String key) { return getValue(BigDecimal.class, key); } @Override public BigDecimal getBigDecimal(String key, BigDecimal defaultValue) { return getValueWithDefault(BigDecimal.class, key, defaultValue); } @Override public Float getFloat(String key) { return getValue(Float.class, key); } @Override public Float getFloat(String key, Float defaultValue) { return getValueWithDefault(Float.class, key, defaultValue); } @Override public Byte getByte(String key) { return getValue(Byte.class, key); } @Override public Byte getByte(String key, Byte defaultValue) { return getValueWithDefault(Byte.class, key, defaultValue); } @Override public <T> List<T> getList(String key, Class<T> type) { String value = getString(key); if (value == null) { return notFound(key); } String[] parts = value.split(getListDelimiter()); List<T> result = new ArrayList<T>(); for (String part : parts) { result.add(decoder.decode(type, part)); } return result; } @Override public List getList(String key) { String value = getString(key); if (value == null) { return notFound(key); } String[] parts = value.split(getListDelimiter()); return Arrays.asList(parts); } @Override public List getList(String key, List defaultValue) { String value = getString(key, null); if (value == null) { return notFound(key, defaultValue); } String[] parts = value.split(","); return Arrays.asList(parts); } @Override public <T> T get(Class<T> type, String key) { return getValue(type, key); } @Override public <T> T get(Class<T> type, String key, T defaultValue) { return getValueWithDefault(type, key, defaultValue); } @Override public <T> T get(Type type, String key) { return getValue(type, key); } @Override public <T> T get(Type type, String key, T defaultValue) { return getValueWithDefault(type, key, defaultValue); } private <T> T parseError(String key, String value, Exception e) { throw new ParseException("Error parsing value '" + value + "' for property '" + key + "'", e); } @Override public void forEachProperty(BiConsumer<String, Object> consumer) { for (String key : keys()) { Object value = this.getRawProperty(key); if (value != null) { consumer.accept(key, value); } } } @Override public String getName() { return name; } }
9,283
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config/DefaultLayeredConfig.java
package com.netflix.archaius.config; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.ConfigListener; import com.netflix.archaius.api.Layer; import com.netflix.archaius.api.config.LayeredConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; /** * Composite Config with child sources ordered by {@link Layer}s where there can be * multiple configs in each layer, ordered by insertion order. Layers form an override * hierarchy for property overrides. Common hierarchies are, * * Runtime -> Environment -> System -> Application -> Library -> Defaults */ public class DefaultLayeredConfig extends AbstractDependentConfig implements LayeredConfig { private static final Logger LOG = LoggerFactory.getLogger(DefaultLayeredConfig.class); private final ConfigListener listener; private volatile ImmutableCompositeState state = new ImmutableCompositeState(Collections.emptyList()); /** * Listener to be added to any component configs which updates the config map and triggers updates on all listeners * when any of the components are updated. */ private static class LayeredConfigListener extends DependentConfigListener<DefaultLayeredConfig> { private LayeredConfigListener(DefaultLayeredConfig config) { super(config); } @Override public void onSourceConfigAdded(DefaultLayeredConfig dlc, Config config) { dlc.refreshState(); dlc.notifyConfigUpdated(dlc); } @Override public void onSourceConfigRemoved(DefaultLayeredConfig dlc, Config config) { dlc.refreshState(); dlc.notifyConfigUpdated(dlc); } @Override public void onSourceConfigUpdated(DefaultLayeredConfig dlc, Config config) { dlc.refreshState(); dlc.notifyConfigUpdated(dlc); } @Override public void onSourceError(Throwable error, DefaultLayeredConfig dlc, Config config) { dlc.notifyError(error, dlc); } } public DefaultLayeredConfig() { this(generateUniqueName("layered-")); } public DefaultLayeredConfig(String name) { super(name); this.listener = new LayeredConfigListener(this); } private void refreshState() { this.state = state.refresh(); } @Override public synchronized void addConfig(Layer layer, Config config) { addConfig(layer, config, insertionOrderCounter.incrementAndGet()); } @Override public synchronized void addConfig(Layer layer, Config child, int position) { LOG.info("Adding property source '{}' at layer '{}'", child.getName(), layer); if (child == null) { return; } state = state.addChild(new LayerAndConfig(layer, child, position)); child.setStrInterpolator(getStrInterpolator()); child.setDecoder(getDecoder()); notifyConfigUpdated(this); child.addListener(listener); } @Override public Collection<Config> getConfigsAtLayer(Layer layer) { return state.children.stream() .filter(holder -> holder.layer.equals(layer)) .map(holder -> holder.config) .collect(Collectors.toList()); } @Override public synchronized Optional<Config> removeConfig(Layer layer, String name) { LOG.info("Removing property source '{}' from layer '{}'", name, layer); Optional<Config> previous = state.findChild(layer, name); if (previous.isPresent()) { this.state = state.removeChild(layer, name); this.notifyConfigUpdated(this); } return previous; } private static final AtomicInteger insertionOrderCounter = new AtomicInteger(1); /** * Instance of a single child Config within the composite structure */ private static class LayerAndConfig { private final Layer layer; private final int internalOrder; private final Config config; private LayerAndConfig(Layer layer, Config config, int internalOrder) { this.layer = layer; this.internalOrder = internalOrder; this.config = config; } @Override public int hashCode() { final int prime = 31; int result = 31 + ((config == null) ? 0 : config.hashCode()); result = prime * result + ((layer == null) ? 0 : layer.hashCode()); return result; } public Layer getLayer() { return layer; } public Config getConfig() { return config; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LayerAndConfig other = (LayerAndConfig) obj; if (config == null) { if (other.config != null) return false; } else if (!config.equals(other.config)) return false; if (layer == null) { if (other.layer != null) return false; } else if (!layer.equals(other.layer)) return false; return true; } @Override public String toString() { return "Element [layer=" + layer + ", id=" + internalOrder + ", value=" + config + "]"; } } private static final Comparator<LayerAndConfig> ByPriorityAndInsertionOrder = (LayerAndConfig o1, LayerAndConfig o2) -> { if (o1.layer != o2.layer) { int result = o1.layer.getOrder() - o2.layer.getOrder(); if (result != 0) { return result; } } return o2.internalOrder - o1.internalOrder; }; /** * Immutable composite state of the DefaultLayeredConfig. A new instance of this * will be created whenever a new Config is added or removed */ private static final class ImmutableCompositeState { private final List<LayerAndConfig> children; private final CachedState cachedState; ImmutableCompositeState(List<LayerAndConfig> entries) { this.children = entries; this.children.sort(ByPriorityAndInsertionOrder); Map<String, Object> data = new HashMap<>(); Map<String, Config> instrumentedKeys = new HashMap<>(); for (LayerAndConfig child : children) { boolean instrumented = child.config.instrumentationEnabled(); child.config.forEachPropertyUninstrumented( (k, v) -> updateData(data, instrumentedKeys, k, v, child.config, instrumented)); } this.cachedState = new CachedState(data, instrumentedKeys); } private void updateData( Map<String, Object> data, Map<String, Config> instrumentedKeys, String key, Object value, Config childConfig, boolean instrumented) { if (!data.containsKey(key)) { if (instrumented) { instrumentedKeys.put(key, childConfig); } data.put(key, value); } } public ImmutableCompositeState addChild(LayerAndConfig layerAndConfig) { List<LayerAndConfig> newChildren = new ArrayList<>(this.children); newChildren.add(layerAndConfig); return new ImmutableCompositeState(newChildren); } public ImmutableCompositeState removeChild(Layer layer, String name) { List<LayerAndConfig> newChildren = new ArrayList<>(this.children.size()); this.children.stream() .filter(source -> !(source.getLayer().equals(layer) && source.getConfig().getName() != null)) .forEach(newChildren::add); newChildren.sort(ByPriorityAndInsertionOrder); return new ImmutableCompositeState(newChildren); } public Optional<Config> findChild(Layer layer, String name) { return children .stream() .filter(source -> source.layer.equals(layer) && source.config.getName().equals(name)) .findFirst() .map(LayerAndConfig::getConfig); } ImmutableCompositeState refresh() { return new ImmutableCompositeState(children); } } @Override public CachedState getState() { return state.cachedState; } }
9,284
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config/polling/FixedPollingStrategy.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.config.polling; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.archaius.api.config.PollingStrategy; import com.netflix.archaius.util.Futures; import com.netflix.archaius.util.ThreadFactories; public class FixedPollingStrategy implements PollingStrategy { private static final Logger LOG = LoggerFactory.getLogger(FixedPollingStrategy.class); private final ScheduledExecutorService executor; private final long interval; private final TimeUnit units; public FixedPollingStrategy(long interval, TimeUnit units) { this.executor = Executors.newSingleThreadScheduledExecutor(ThreadFactories.newNamedDaemonThreadFactory("Archaius-Poller-%d")); this.interval = interval; this.units = units; } @Override public Future<?> execute(final Runnable callback) { while (true) { try { callback.run(); break; } catch (Exception e) { try { LOG.warn("Fail to poll the polling source", e); units.sleep(interval); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); return Futures.immediateFailure(e); } } } return executor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { callback.run(); } catch (Exception e) { LOG.warn("Failed to load properties", e); } } }, interval, interval, units); } @Override public void shutdown() { executor.shutdown(); } }
9,285
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config/polling/ManualPollingStrategy.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.config.polling; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import com.netflix.archaius.api.config.PollingStrategy; import com.netflix.archaius.util.ThreadFactories; /** * Polling strategy using external input to trigger a refresh. This should only be used * for testing. * * @author elandau * */ public class ManualPollingStrategy implements PollingStrategy { private final ExecutorService executor = Executors.newSingleThreadExecutor(ThreadFactories.newNamedDaemonThreadFactory("Archaius-Poller-%d")); private final LinkedBlockingQueue<Request> queue = new LinkedBlockingQueue<Request>(); private static class Request { CountDownLatch latch = new CountDownLatch(1); Exception error; } @Override public Future<?> execute(final Runnable run) { return executor.submit(new Runnable() { @Override public void run() { Request request; try { while (null != (request = queue.take())) { try { run.run(); } catch (Exception e) { request.error = e; } finally { request.latch.countDown(); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }); } public void fire(long timeout, TimeUnit units) throws Exception { Request request = new Request(); queue.put(request); request.latch.await(timeout, units); if (request.error != null) { throw request.error; } } public void fire() throws Exception { Request request = new Request(); queue.put(request); request.latch.await(); if (request.error != null) { throw request.error; } } @Override public void shutdown() { executor.shutdown(); } }
9,286
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/config/polling/PollingResponse.java
package com.netflix.archaius.config.polling; import java.util.Collection; import java.util.Collections; import java.util.Map; public abstract class PollingResponse { public static PollingResponse forSnapshot(final Map<String, String> values, final Map<String, String> ids) { return new PollingResponse() { @Override public Map<String, String> getToAdd() { return values; } @Override public Collection<String> getToRemove() { return Collections.emptyList(); } @Override public boolean hasData() { return true; } @Override public Map<String, String> getNameToIdsMap() { return ids; } }; } public static PollingResponse forSnapshot(final Map<String, String> values) { return new PollingResponse() { @Override public Map<String, String> getToAdd() { return values; } @Override public Collection<String> getToRemove() { return Collections.emptyList(); } @Override public boolean hasData() { return true; } }; } public static PollingResponse noop() { return new PollingResponse() { @Override public Map<String, String> getToAdd() { return Collections.emptyMap(); } @Override public Collection<String> getToRemove() { return Collections.emptyList(); } @Override public boolean hasData() { return false; } }; } public abstract Map<String, String> getToAdd(); public abstract Collection<String> getToRemove(); public abstract boolean hasData(); public Map<String, String> getNameToIdsMap() { return Collections.emptyMap(); } }
9,287
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/property/DefaultPropertyContainer.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.property; import com.netflix.archaius.api.Config; import com.netflix.archaius.api.Property; import com.netflix.archaius.api.PropertyContainer; import com.netflix.archaius.api.PropertyListener; import com.netflix.archaius.property.ListenerManager.ListenerUpdater; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigDecimal; import java.math.BigInteger; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicStampedReference; import java.util.function.Function; /** * Implementation of PropertyContainer which reuses the same object for each * type. This implementation assumes that each fast property is mostly accessed * as the same type but allows for additional types to be deserialized. * Instead of incurring the overhead for caching in a hash map, the objects are * stored in a CopyOnWriteArrayList and items are retrieved via a linear scan. * * Once created a PropertyContainer property cannot be removed. However, listeners may be * added and removed. */ @Deprecated public class DefaultPropertyContainer implements PropertyContainer { private final Logger LOG = LoggerFactory.getLogger(DefaultPropertyContainer.class); enum Type { INTEGER (int.class, Integer.class), BYTE (byte.class, Byte.class), SHORT (short.class, Short.class), DOUBLE (double.class, Double.class), FLOAT (float.class, Float.class), BOOLEAN (boolean.class, Boolean.class), LONG (long.class, Long.class), STRING (String.class), BIG_DECIMAL (BigDecimal.class), BIG_INTEGER (BigInteger.class), CUSTOM (); // Must be last private final Class<?>[] types; Type(Class<?> ... type) { types = type; } static Type fromClass(Class<?> clazz) { for (Type type : values()) { for (Class<?> cls : type.types) { if (cls.equals(clazz)) { return type; } } } return CUSTOM; } } /** * The property name */ private final String key; /** * Config from which property values are resolved */ private final Config config; /** * Cache for each type attached to this property. */ private final CopyOnWriteArrayList<CachedProperty<?>> cache = new CopyOnWriteArrayList<CachedProperty<?>>(); /** * Listeners are tracked globally as an optimization so it is not necessary to iterate through all * property containers when the listeners need to be invoked since the expectation is to have far * less listeners than property containers. */ private final ListenerManager listeners; /** * Reference to the externally managed master version used as the dirty flag */ private final AtomicInteger masterVersion; private volatile long lastUpdateTimeInMillis = 0; public DefaultPropertyContainer(String key, Config config, AtomicInteger version, ListenerManager listeners) { this.key = key; this.config = config; this.listeners = listeners; this.masterVersion = version; } abstract class CachedProperty<T> implements Property<T> { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((defaultValue == null) ? 0 : defaultValue.hashCode()); result = prime * result + type; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CachedProperty other = (CachedProperty) obj; if (defaultValue == null) { if (other.defaultValue != null) return false; } else if (!defaultValue.equals(other.defaultValue)) return false; if (type != other.type) return false; return true; } private final AtomicStampedReference<T> cache = new AtomicStampedReference<>(null, -1); private final int type; private final T defaultValue; CachedProperty(Type type, T defaultValue) { this.type = type.ordinal(); this.defaultValue = defaultValue; } public void addListener(final PropertyListener<T> listener) { listeners.add(listener, new ListenerUpdater() { private final AtomicReference<T> last = new AtomicReference<T>(null); @Override public void update() { final T prev = last.get(); final T value; try { value = get(); } catch (Exception e) { listener.onParseError(e); return; } if (prev != value) { if (last.compareAndSet(prev, value)) { listener.onChange(value); } } } }); } @Override public String getKey() { return DefaultPropertyContainer.this.key; } public void removeListener(PropertyListener<T> listener) { listeners.remove(listener); } /** * Fetch the latest version of the property. If not up to date then resolve to the latest * value, inline. * * TODO: Make resolving property value an offline task * * @return */ @Override public T get() { int cacheVersion = cache.getStamp(); int latestVersion = masterVersion.get(); if (cacheVersion != latestVersion) { T currentValue = cache.getReference(); T newValue = null; try { newValue = resolveCurrent(); } catch (Exception e) { LOG.warn("Unable to get current version of property '{}'", key, e); } if (cache.compareAndSet(currentValue, newValue, cacheVersion, latestVersion)) { // Slight race condition here but not important enough to warrent locking lastUpdateTimeInMillis = System.currentTimeMillis(); return firstNonNull(newValue, defaultValue); } } return firstNonNull(cache.getReference(), defaultValue); } public long getLastUpdateTime(TimeUnit units) { return units.convert(lastUpdateTimeInMillis, TimeUnit.MILLISECONDS); } private T firstNonNull(T first, T second) { return first == null ? second : first; } /** * Resolve to the most recent value * @return * @throws Exception */ protected abstract T resolveCurrent() throws Exception; } /** * Add a new property to the end of the array list but first check * to see if it already exists. * @param newProperty * @return */ @SuppressWarnings("unchecked") private <T> CachedProperty<T> add(final CachedProperty<T> newProperty) { // TODO(nikos): This while() looks like it's redundant // since we are only calling add() after a get(). while (!cache.add(newProperty)) { for (CachedProperty<?> property : cache) { if (property.equals(newProperty)) { return (CachedProperty<T>) property; } } } return newProperty; } @Override public Property<String> asString(final String defaultValue) { return add(new CachedProperty<String>(Type.STRING, defaultValue) { @Override protected String resolveCurrent() throws Exception { return config.getString(key, null); } }); } @Override public Property<Integer> asInteger(final Integer defaultValue) { return add(new CachedProperty<Integer>(Type.INTEGER, defaultValue) { @Override protected Integer resolveCurrent() throws Exception { return config.getInteger(key, null); } }); } @Override public Property<Long> asLong(final Long defaultValue) { return add(new CachedProperty<Long>(Type.LONG, defaultValue) { @Override protected Long resolveCurrent() throws Exception { return config.getLong(key, null); } }); } @Override public Property<Double> asDouble(final Double defaultValue) { return add(new CachedProperty<Double>(Type.DOUBLE, defaultValue) { @Override protected Double resolveCurrent() throws Exception { return config.getDouble(key, null); } }); } @Override public Property<Float> asFloat(final Float defaultValue) { return add(new CachedProperty<Float>(Type.FLOAT, defaultValue) { @Override protected Float resolveCurrent() throws Exception { return config.getFloat(key, null); } }); } @Override public Property<Short> asShort(final Short defaultValue) { return add(new CachedProperty<Short>(Type.SHORT, defaultValue) { @Override protected Short resolveCurrent() throws Exception { return config.getShort(key, null); } }); } @Override public Property<Byte> asByte(final Byte defaultValue) { return add(new CachedProperty<Byte>(Type.BYTE, defaultValue) { @Override protected Byte resolveCurrent() throws Exception { return config.getByte(key, defaultValue); } }); } @Override public Property<BigDecimal> asBigDecimal(final BigDecimal defaultValue) { return add(new CachedProperty<BigDecimal>(Type.BIG_DECIMAL, defaultValue) { @Override protected BigDecimal resolveCurrent() throws Exception { return config.getBigDecimal(key, defaultValue); } }); } @Override public Property<Boolean> asBoolean(final Boolean defaultValue) { return add(new CachedProperty<Boolean>(Type.BOOLEAN, defaultValue) { @Override protected Boolean resolveCurrent() throws Exception { return config.getBoolean(key, defaultValue); } }); } @Override public Property<BigInteger> asBigInteger(final BigInteger defaultValue) { return add(new CachedProperty<BigInteger>(Type.BIG_INTEGER, defaultValue) { @Override protected BigInteger resolveCurrent() throws Exception { return config.getBigInteger(key, defaultValue); } }); } /** * No caching for custom types. */ @SuppressWarnings("unchecked") @Override public <T> Property<T> asType(final Class<T> type, final T defaultValue) { switch (Type.fromClass(type)) { case INTEGER: return (Property<T>) asInteger((Integer)defaultValue); case BYTE: return (Property<T>) asByte((Byte)defaultValue); case SHORT: return (Property<T>) asShort((Short)defaultValue); case DOUBLE: return (Property<T>) asDouble((Double)defaultValue); case FLOAT: return (Property<T>) asFloat((Float)defaultValue); case BOOLEAN: return (Property<T>) asBoolean((Boolean)defaultValue); case STRING: return (Property<T>) asString((String)defaultValue); case LONG: return (Property<T>) asLong((Long)defaultValue); case BIG_DECIMAL: return (Property<T>) asBigDecimal((BigDecimal)defaultValue); case BIG_INTEGER: return (Property<T>) asBigInteger((BigInteger)defaultValue); default: { CachedProperty<T> prop = add(new CachedProperty<T>(Type.CUSTOM, defaultValue) { @Override protected T resolveCurrent() throws Exception { return config.get(type, key, defaultValue); } }); return prop; } } } @Override public <T> Property<T> asType(Function<String, T> type, String defaultValue) { return add(new CachedProperty<T>(Type.CUSTOM, null) { @Override protected T resolveCurrent() throws Exception { return type.apply(config.getString(key, defaultValue)); } }); } }
9,288
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/property/DefaultPropertyListener.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.property; import com.netflix.archaius.api.PropertyListener; public class DefaultPropertyListener<T> implements PropertyListener<T> { @Override public void onChange(T value) { } @Override public void onParseError(Throwable error) { } }
9,289
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/property/MethodInvoker.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.property; import java.lang.reflect.Method; public class MethodInvoker<T> extends DefaultPropertyListener<T> { private final Method method; private final Object obj; public MethodInvoker(Object obj, String methodName) { this.method = getMethodWithOneParameter(obj); this.obj = obj; } private static Method getMethodWithOneParameter(Object obj) { Method[] methods = obj.getClass().getMethods(); if (methods.length > 0) { for (Method method : methods) { if (method.getParameterCount() == 1) { return method; } } throw new IllegalArgumentException("Method with one argument does not exist"); } throw new IllegalArgumentException("Method does not exit"); } @Override public void onChange(T newValue) { try { method.invoke(obj, newValue); } catch (Exception e) { e.printStackTrace(); } } }
9,290
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/property/ListenerManager.java
package com.netflix.archaius.property; import com.netflix.archaius.api.PropertyListener; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; /** * Globally managed list of listeners. Listeners are tracked globally as * an optimization so it is not necessary to iterate through all property * containers when the listeners need to be invoked since the expectation * is to have far less listeners than property containers. */ public class ListenerManager { public static interface ListenerUpdater { public void update(); } private final ConcurrentMap<PropertyListener<?>, ListenerUpdater> lookup = new ConcurrentHashMap<>(); private final CopyOnWriteArrayList<ListenerUpdater> updaters = new CopyOnWriteArrayList<>(); public void add(PropertyListener<?> listener, ListenerUpdater updater) { lookup.put(listener, updater); updaters.add(updater); } public void remove(PropertyListener<?> listener) { ListenerUpdater updater = lookup.remove(listener); if (updater != null) { updaters.remove(updater); } } public void updateAll() { updaters.forEach(ListenerUpdater::update); } }
9,291
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/converters/EnumTypeConverterFactory.java
package com.netflix.archaius.converters; import com.netflix.archaius.api.TypeConverter; import java.lang.reflect.Type; import java.util.Optional; public final class EnumTypeConverterFactory implements TypeConverter.Factory { public static final EnumTypeConverterFactory INSTANCE = new EnumTypeConverterFactory(); private EnumTypeConverterFactory() {} @Override public Optional<TypeConverter<?>> get(Type type, TypeConverter.Registry registry) { Class clsType = (Class) type; if (clsType.isEnum()) { return Optional.of(create(clsType)); } return Optional.empty(); } private static TypeConverter<?> create(Class clsType) { return value -> Enum.valueOf(clsType, value); } }
9,292
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/converters/ArrayTypeConverterFactory.java
package com.netflix.archaius.converters; import com.netflix.archaius.api.TypeConverter; import java.lang.reflect.Array; import java.lang.reflect.Type; import java.util.Optional; public final class ArrayTypeConverterFactory implements TypeConverter.Factory { public static final ArrayTypeConverterFactory INSTANCE = new ArrayTypeConverterFactory(); private ArrayTypeConverterFactory() {} @Override public Optional<TypeConverter<?>> get(Type type, TypeConverter.Registry registry) { Class clsType = (Class) type; if (clsType.isArray()) { TypeConverter elementConverter = registry.get(clsType.getComponentType()).orElseThrow(() -> new RuntimeException()); return Optional.of(create(elementConverter, clsType.getComponentType())); } return Optional.empty(); } private static TypeConverter<?> create(TypeConverter elementConverter, Class type) { return value -> { value = value.trim(); if (value.isEmpty()) { return Array.newInstance(type, 0); } String[] elements = value.split(","); Object[] ar = (Object[]) Array.newInstance(type, elements.length); for (int i = 0; i < elements.length; i++) { ar[i] = elementConverter.convert(elements[i]); } return ar; }; } }
9,293
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/converters/DefaultCollectionsTypeConverterFactory.java
package com.netflix.archaius.converters; import com.netflix.archaius.api.TypeConverter; import com.netflix.archaius.exceptions.ConverterNotFoundException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.function.Supplier; public final class DefaultCollectionsTypeConverterFactory implements TypeConverter.Factory { public static final DefaultCollectionsTypeConverterFactory INSTANCE = new DefaultCollectionsTypeConverterFactory(); private DefaultCollectionsTypeConverterFactory() {} @Override public Optional<TypeConverter<?>> get(Type type, TypeConverter.Registry registry) { if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType)type; if (parameterizedType.getRawType().equals(Map.class)) { return Optional.of(createMapTypeConverter( registry.get(parameterizedType.getActualTypeArguments()[0]).orElseThrow(() -> new ConverterNotFoundException("No converter found")), registry.get(parameterizedType.getActualTypeArguments()[1]).orElseThrow(() -> new ConverterNotFoundException("No converter found")), LinkedHashMap::new)); } else if (parameterizedType.getRawType().equals(Set.class)) { return Optional.of(createCollectionTypeConverter( parameterizedType.getActualTypeArguments()[0], registry, LinkedHashSet::new)); } else if (parameterizedType.getRawType().equals(SortedSet.class)) { return Optional.of(createCollectionTypeConverter( parameterizedType.getActualTypeArguments()[0], registry, TreeSet::new)); } else if (parameterizedType.getRawType().equals(List.class)) { return Optional.of(createCollectionTypeConverter( parameterizedType.getActualTypeArguments()[0], registry, ArrayList::new)); } else if (parameterizedType.getRawType().equals(LinkedList.class)) { return Optional.of(createCollectionTypeConverter( parameterizedType.getActualTypeArguments()[0], registry, LinkedList::new)); } } return Optional.empty(); } @SuppressWarnings({ "rawtypes", "unchecked" }) private <T> TypeConverter<?> createCollectionTypeConverter(final Type type, TypeConverter.Registry registry, final Supplier<Collection<T>> collectionFactory) { TypeConverter elementConverter = registry.get(type).orElseThrow(() -> new ConverterNotFoundException("No converter found")); boolean ignoreEmpty = !String.class.equals(type); return value -> { final Collection collection = collectionFactory.get(); if (!value.isEmpty()) { Arrays.asList(value.split("\\s*,\\s*")).forEach(v -> { if (!v.isEmpty() || !ignoreEmpty) { collection.add(elementConverter.convert(v)); } }); } return collection; }; } private TypeConverter<?> createMapTypeConverter(final TypeConverter<?> keyConverter, final TypeConverter<?> valueConverter, final Supplier<Map> mapFactory) { return s -> { Map result = mapFactory.get(); Arrays .stream(s.split("\\s*,\\s*")) .filter(pair -> !pair.isEmpty()) .map(pair -> pair.split("\\s*=\\s*")) .forEach(kv -> result.put( keyConverter.convert(kv[0]), valueConverter.convert(kv[1]))); return Collections.unmodifiableMap(result); }; } }
9,294
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/converters/DefaultTypeConverterFactory.java
package com.netflix.archaius.converters; import com.netflix.archaius.api.TypeConverter; import com.netflix.archaius.exceptions.ParseException; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.OffsetTime; import java.time.Period; import java.time.ZonedDateTime; import java.util.BitSet; import java.util.Collections; import java.util.Currency; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; public final class DefaultTypeConverterFactory implements TypeConverter.Factory { public static final DefaultTypeConverterFactory INSTANCE = new DefaultTypeConverterFactory(); private static Boolean convertBoolean(String value) { if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("on")) { return Boolean.TRUE; } else if (value.equalsIgnoreCase("false") || value.equalsIgnoreCase("no") || value.equalsIgnoreCase("off")) { return Boolean.FALSE; } throw new ParseException("Error parsing value '" + value + "'", new Exception("Expected one of [true, yes, on, false, no, off]")); } private final Map<Type, TypeConverter<?>> converters; private DefaultTypeConverterFactory() { Map<Type, TypeConverter<?>> converters = new HashMap<>(); converters.put(String.class, Function.identity()::apply); converters.put(boolean.class, DefaultTypeConverterFactory::convertBoolean); converters.put(Boolean.class, DefaultTypeConverterFactory::convertBoolean); converters.put(Integer.class, Integer::valueOf); converters.put(int.class, Integer::valueOf); converters.put(long.class, Long::valueOf); converters.put(Long.class, Long::valueOf); converters.put(short.class, Short::valueOf); converters.put(Short.class, Short::valueOf); converters.put(byte.class, Byte::valueOf); converters.put(Byte.class, Byte::valueOf); converters.put(double.class, Double::valueOf); converters.put(Double.class, Double::valueOf); converters.put(float.class, Float::valueOf); converters.put(Float.class, Float::valueOf); converters.put(BigInteger.class, BigInteger::new); converters.put(BigDecimal.class, BigDecimal::new); converters.put(AtomicInteger.class, v -> new AtomicInteger(Integer.parseInt(v))); converters.put(AtomicLong.class, v -> new AtomicLong(Long.parseLong(v))); converters.put(Duration.class, Duration::parse); converters.put(Period.class, Period::parse); converters.put(LocalDateTime.class, LocalDateTime::parse); converters.put(LocalDate.class, LocalDate::parse); converters.put(LocalTime.class, LocalTime::parse); converters.put(OffsetDateTime.class, OffsetDateTime::parse); converters.put(OffsetTime.class, OffsetTime::parse); converters.put(ZonedDateTime.class, ZonedDateTime::parse); converters.put(Instant.class, v -> Instant.from(OffsetDateTime.parse(v))); converters.put(Date.class, v -> new Date(Long.parseLong(v))); converters.put(Currency.class, Currency::getInstance); converters.put(BitSet.class, v -> { try { return BitSet.valueOf(Hex.decodeHex(v)); } catch (DecoderException e) { throw new RuntimeException(e); } }); this.converters = Collections.unmodifiableMap(converters); } @Override public Optional<TypeConverter<?>> get(Type type, TypeConverter.Registry registry) { Objects.requireNonNull(type, "type == null"); Objects.requireNonNull(registry, "registry == null"); for (Map.Entry<Type, TypeConverter<?>> entry : converters.entrySet()) { if (entry.getKey().equals(type)) { return Optional.of(entry.getValue()); } } return Optional.empty(); } }
9,295
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/exceptions/ParseException.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.exceptions; public class ParseException extends RuntimeException { public ParseException(Exception e) { super(e); } public ParseException(String message, Exception e) { super(message, e); } }
9,296
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/exceptions/MappingException.java
/** * Copyright 2015 Netflix, Inc. * * 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 com.netflix.archaius.exceptions; public class MappingException extends Exception { public MappingException(Exception e) { super(e); } public MappingException(String message, Exception e) { super(message, e); } }
9,297
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/exceptions/ConverterNotFoundException.java
package com.netflix.archaius.exceptions; public class ConverterNotFoundException extends RuntimeException { public ConverterNotFoundException(String message) { super(message); } public ConverterNotFoundException(String message, Exception e) { super(message, e); } }
9,298
0
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius
Create_ds/archaius/archaius2-core/src/main/java/com/netflix/archaius/exceptions/ConfigAlreadyExistsException.java
package com.netflix.archaius.exceptions; import com.netflix.archaius.api.exceptions.ConfigException; public class ConfigAlreadyExistsException extends ConfigException { public ConfigAlreadyExistsException(String message) { super(message); } }
9,299