You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tamaya.apache.org by an...@apache.org on 2018/01/03 00:08:57 UTC
[01/18] incubator-tamaya-extensions git commit: Added full JSR
support.
Repository: incubator-tamaya-extensions
Updated Branches:
refs/heads/configjsr [created] cfb364cd4
Added full JSR support.
Signed-off-by: Anatole Tresch <an...@apache.org>
Project: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/commit/4af5f5f6
Tree: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/tree/4af5f5f6
Diff: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/diff/4af5f5f6
Branch: refs/heads/configjsr
Commit: 4af5f5f638258b3b8cb07bb5ad7f1f8f9d1cbba8
Parents: ab03433
Author: Anatole Tresch <an...@apache.org>
Authored: Wed Dec 13 22:44:20 2017 +0100
Committer: Anatole Tresch <an...@apache.org>
Committed: Wed Dec 13 22:44:20 2017 +0100
----------------------------------------------------------------------
modules/resolver/pom.xml | 5 -
.../org/apache/tamaya/resolver/Resolver.java | 16 +-
.../resolver/internal/ConfigResolver.java | 5 +-
.../internal/ExpressionResolutionFilter.java | 13 +-
.../resolver/internal/ResolvableConfig.java | 119 ++++++++++++++
.../services/org.apache.tamaya.spi.Filter | 19 +++
.../org.apache.tamaya.spi.PropertyFilter | 19 ---
.../tamaya/resolver/ConfigResolutionTest.java | 39 ++---
.../tamaya/resolver/MyTestConfigSource.java | 100 +++++++++++
.../tamaya/resolver/MyTestPropertySource.java | 106 ------------
.../tamaya/resolver/NonResolvableConfig.java | 56 +++++++
.../tamaya/resolver/ResolvableConfigTest.java | 164 +++++++++++++++++++
.../services/javax.config.spi.ConfigSource | 19 +++
.../org.apache.tamaya.spi.PropertySource | 19 ---
14 files changed, 519 insertions(+), 180 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4af5f5f6/modules/resolver/pom.xml
----------------------------------------------------------------------
diff --git a/modules/resolver/pom.xml b/modules/resolver/pom.xml
index 7691c23..2ae6782 100644
--- a/modules/resolver/pom.xml
+++ b/modules/resolver/pom.xml
@@ -34,11 +34,6 @@ under the License.
<dependencies>
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-api</artifactId>
- <version>${tamaya-apicore.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.tamaya</groupId>
<artifactId>tamaya-core</artifactId>
<version>${tamaya-apicore.version}</version>
<scope>test</scope>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4af5f5f6/modules/resolver/src/main/java/org/apache/tamaya/resolver/Resolver.java
----------------------------------------------------------------------
diff --git a/modules/resolver/src/main/java/org/apache/tamaya/resolver/Resolver.java b/modules/resolver/src/main/java/org/apache/tamaya/resolver/Resolver.java
index c2bc908..955183a 100644
--- a/modules/resolver/src/main/java/org/apache/tamaya/resolver/Resolver.java
+++ b/modules/resolver/src/main/java/org/apache/tamaya/resolver/Resolver.java
@@ -18,11 +18,12 @@
*/
package org.apache.tamaya.resolver;
-import org.apache.tamaya.ConfigException;
+import org.apache.tamaya.resolver.internal.ResolvableConfig;
import org.apache.tamaya.resolver.spi.ExpressionEvaluator;
import org.apache.tamaya.resolver.spi.ExpressionResolver;
import org.apache.tamaya.spi.ServiceContextManager;
+import javax.config.Config;
import java.util.Collection;
/**
@@ -48,7 +49,7 @@ public final class Resolver {
private static ExpressionEvaluator evaluator() {
ExpressionEvaluator evaluator = ServiceContextManager.getServiceContext().getService(ExpressionEvaluator.class);
if(evaluator==null){
- throw new ConfigException("No ExpressionEvaluator registered.");
+ throw new IllegalStateException("No ExpressionEvaluator registered.");
}
return evaluator;
}
@@ -80,4 +81,15 @@ public final class Resolver {
public static Collection<ExpressionResolver> getResolvers(){
return evaluator().getResolvers();
}
+
+
+ /**
+ * Render the given Config instance into a resolvable instance.
+ * @param config the configuration to be rendered to be resolvable.
+ * @return the resolvable instance (wrapped or the same as passed), never null.
+ * @see ResolvableConfig
+ */
+ public static Config makeResolvable(Config config){
+ return ResolvableConfig.from(config);
+ }
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4af5f5f6/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ConfigResolver.java
----------------------------------------------------------------------
diff --git a/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ConfigResolver.java b/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ConfigResolver.java
index 4708a39..22cee86 100644
--- a/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ConfigResolver.java
+++ b/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ConfigResolver.java
@@ -18,10 +18,10 @@
*/
package org.apache.tamaya.resolver.internal;
-import org.apache.tamaya.ConfigurationProvider;
import org.apache.tamaya.resolver.spi.ExpressionResolver;
import javax.annotation.Priority;
+import javax.config.ConfigProvider;
/**
* Property resolver implementation that interprets the resolver expression as a reference to another configuration
@@ -37,7 +37,8 @@ public final class ConfigResolver implements ExpressionResolver{
@Override
public String evaluate(String expression){
- return ConfigurationProvider.getConfiguration().get(expression);
+ return ConfigProvider.getConfig().getOptionalValue(expression, String.class)
+ .orElse(expression);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4af5f5f6/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ExpressionResolutionFilter.java
----------------------------------------------------------------------
diff --git a/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ExpressionResolutionFilter.java b/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ExpressionResolutionFilter.java
index e7d9ff6..75e4624 100644
--- a/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ExpressionResolutionFilter.java
+++ b/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ExpressionResolutionFilter.java
@@ -18,11 +18,9 @@
*/
package org.apache.tamaya.resolver.internal;
-import org.apache.tamaya.ConfigException;
import org.apache.tamaya.resolver.spi.ExpressionEvaluator;
-import org.apache.tamaya.spi.FilterContext;
-import org.apache.tamaya.spi.PropertyFilter;
-import org.apache.tamaya.spi.PropertyValue;
+import org.apache.tamaya.spi.ConfigValue;
+import org.apache.tamaya.spi.Filter;
import org.apache.tamaya.spi.ServiceContextManager;
import javax.annotation.Priority;
@@ -34,14 +32,14 @@ import java.util.logging.Logger;
* has the advantage that different resolvers can be active in parallel.
*/
@Priority(10000)
-public class ExpressionResolutionFilter implements PropertyFilter {
+public class ExpressionResolutionFilter implements Filter {
private static final Logger LOG = Logger.getLogger(ExpressionResolutionFilter.class.getName());
private final ExpressionEvaluator evaluator(){
ExpressionEvaluator evaluator = ServiceContextManager.getServiceContext().getService(ExpressionEvaluator.class);
if(evaluator==null){
- throw new ConfigException("No ExpressionEvaluator registered.");
+ throw new IllegalStateException("No ExpressionEvaluator registered.");
}
return evaluator;
}
@@ -80,12 +78,11 @@ public class ExpressionResolutionFilter implements PropertyFilter {
* <li><code>\${resolverId:expression}foo${resolverId2:expression2}bar</code> (first expression is escaped).</li>
* </ul>
*
- * @param context the filter context
* @param valueToBeFiltered value to be analyzed for expressions
* @return the resolved value, or the input in case where no expression was detected.
*/
@Override
- public PropertyValue filterProperty(PropertyValue valueToBeFiltered, FilterContext context){
+ public ConfigValue filterProperty(ConfigValue valueToBeFiltered){
LOG.finest("Resolving " + valueToBeFiltered);
String newVal = evaluator().evaluateExpression(valueToBeFiltered.getKey(), valueToBeFiltered.getValue(), true);
if(newVal!=null){
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4af5f5f6/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ResolvableConfig.java
----------------------------------------------------------------------
diff --git a/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ResolvableConfig.java b/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ResolvableConfig.java
new file mode 100644
index 0000000..1abed5b
--- /dev/null
+++ b/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ResolvableConfig.java
@@ -0,0 +1,119 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.resolver.internal;
+
+import org.apache.tamaya.base.DefaultConfig;
+import org.apache.tamaya.base.DefaultConfigBuilder;
+import org.apache.tamaya.base.convert.ConverterManager;
+import org.apache.tamaya.base.filter.FilterManager;
+import org.apache.tamaya.spi.ConfigContext;
+import org.apache.tamaya.spi.ConfigContextSupplier;
+import org.apache.tamaya.spi.ConfigValue;
+
+import javax.config.Config;
+import javax.config.spi.ConfigSource;
+import java.util.Objects;
+import java.util.Optional;
+
+/**
+ * Wrapper that intercepts evaluation of String configuration extending with value resolution capabilities
+ * as provided by registered instances of type {@link org.apache.tamaya.spi.Filter}.
+ */
+public final class ResolvableConfig implements Config{
+
+ /** The original instance. */
+ private Config delegate;
+ private FilterManager filterManager = new FilterManager();
+ private ConverterManager converterManager = new ConverterManager();
+
+ private ResolvableConfig(Config config){
+ this.delegate = Objects.requireNonNull(config);
+ filterManager.addDefaultFilters();
+ converterManager.addDiscoveredConverters();
+ }
+
+ /**
+ * Creates a new resolvable configuration instance, based on the given config. This actually performs the following:
+ * <ol>
+ * <li>If the instance passed is of type {@link ResolvableConfig}, the instance is passed through.</li>
+ * <li>If the instance passed is of type {@link DefaultConfig}, the instance is passed through.</li>
+ * <li>It the instance implements {@link ConfigContextSupplier}, a new {@link DefaultConfig} is
+ * created and returned, using the returned {@link org.apache.tamaya.spi.ConfigContext}.</li>
+ * <li>Otherwise a new instance of this class is created, with filtering and conversion added on top, based
+ * on the discoverable filters and converters only.</li>
+ * </ol>
+ * Summarizing this function adds filter resolution functionality to the instance, if needed (Tamaya configuration
+ * instances support filtering out of the box) and intercepts all calls for applying resolution and, as
+ * needed, subsequent type conversion.
+ *
+ * @param config the config instance, potentially not resolvable.
+ * @return a resolvable config instance.
+ */
+ public static Config from(Config config){
+ if(config instanceof ResolvableConfig){
+ return (ResolvableConfig)config;
+ }else if(config instanceof DefaultConfig){
+ return config;
+ }else if(config instanceof ConfigContextSupplier){
+ ConfigContext ctx = ((ConfigContextSupplier)config).getConfigContext();
+ return new DefaultConfigBuilder(ctx).build();
+ }else{
+ return new ResolvableConfig(config);
+ }
+ }
+
+ @Override
+ public <T> T getValue(String propertyName, Class<T> propertyType) {
+ return getOptionalValue(propertyName, propertyType).orElse(null);
+ }
+
+ @Override
+ public <T> Optional<T> getOptionalValue(String propertyName, Class<T> propertyType) {
+ ConfigValue value = ConfigValue.of(
+ propertyName, delegate.getValue(propertyName, String.class), null);
+ value = filterManager.filterValue(value);
+ if(value!=null){
+ if(String.class.equals(propertyType)) {
+ return Optional.ofNullable((T) value.getValue());
+ }
+ return Optional.ofNullable(
+ (T)converterManager.convertValue(propertyName, value.getValue(), propertyType, this));
+ }
+ return Optional.empty();
+ }
+
+ @Override
+ public Iterable<String> getPropertyNames() {
+ return delegate.getPropertyNames();
+ }
+
+ @Override
+ public Iterable<ConfigSource> getConfigSources() {
+ return delegate.getConfigSources();
+ }
+
+ @Override
+ public String toString() {
+ return "ResolvableConfig{" +
+ "delegate=" + delegate +
+ ", filterManager=" + filterManager +
+ ", converterManager=" + converterManager +
+ '}';
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4af5f5f6/modules/resolver/src/main/resources/META-INF/services/org.apache.tamaya.spi.Filter
----------------------------------------------------------------------
diff --git a/modules/resolver/src/main/resources/META-INF/services/org.apache.tamaya.spi.Filter b/modules/resolver/src/main/resources/META-INF/services/org.apache.tamaya.spi.Filter
new file mode 100644
index 0000000..c8788b5
--- /dev/null
+++ b/modules/resolver/src/main/resources/META-INF/services/org.apache.tamaya.spi.Filter
@@ -0,0 +1,19 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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 current 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.
+#
+org.apache.tamaya.resolver.internal.ExpressionResolutionFilter
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4af5f5f6/modules/resolver/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertyFilter
----------------------------------------------------------------------
diff --git a/modules/resolver/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertyFilter b/modules/resolver/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertyFilter
deleted file mode 100644
index c8788b5..0000000
--- a/modules/resolver/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertyFilter
+++ /dev/null
@@ -1,19 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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 current 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.
-#
-org.apache.tamaya.resolver.internal.ExpressionResolutionFilter
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4af5f5f6/modules/resolver/src/test/java/org/apache/tamaya/resolver/ConfigResolutionTest.java
----------------------------------------------------------------------
diff --git a/modules/resolver/src/test/java/org/apache/tamaya/resolver/ConfigResolutionTest.java b/modules/resolver/src/test/java/org/apache/tamaya/resolver/ConfigResolutionTest.java
index f795ee1..7189e36 100644
--- a/modules/resolver/src/test/java/org/apache/tamaya/resolver/ConfigResolutionTest.java
+++ b/modules/resolver/src/test/java/org/apache/tamaya/resolver/ConfigResolutionTest.java
@@ -18,102 +18,103 @@
*/
package org.apache.tamaya.resolver;
-import org.apache.tamaya.ConfigurationProvider;
import org.junit.Test;
+import javax.config.ConfigProvider;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Test class that test resolution of different values as configured within
- * {@link org.apache.tamaya.resolver.MyTestPropertySource} and on test resource path.
+ * {@link MyTestConfigSource} and on test resource path.
*/
public class ConfigResolutionTest {
@Test
public void test_Prefix_Resolution() {
- assertEquals(ConfigurationProvider.getConfiguration().get("Before Text (prefixed)"), "My Java version is " + System.getProperty("java.version"));
+ assertEquals(ConfigProvider.getConfig().getValue("Before Text (prefixed)", String.class), "My Java version is " + System.getProperty("java.version"));
}
@Test
public void test_Midfix_Resolution() {
- assertEquals(ConfigurationProvider.getConfiguration().get("Before and After Text (prefixed)"), "My Java version is " + System.getProperty("java.version") + ".");
+ assertEquals(ConfigProvider.getConfig().getValue("Before and After Text (prefixed)", String.class), "My Java version is " + System.getProperty("java.version") + ".");
}
@Test
public void test_Prefix_Resolution_BadSyntax1() {
- assertEquals(ConfigurationProvider.getConfiguration().get("Will fail1."), "V$java.version");
+ assertEquals(ConfigProvider.getConfig().getValue("Will fail1.", String.class), "V$java.version");
}
@Test
public void test_Prefix_Resolution_BadSyntax2() {
- assertEquals(ConfigurationProvider.getConfiguration().get("Will fail2."), "V$java.version}");
+ assertEquals(ConfigProvider.getConfig().getValue("Will fail2.", String.class), "V$java.version}");
}
@Test
public void test_Prefix_Resolution_BadSyntax31() {
- assertEquals(ConfigurationProvider.getConfiguration().get("Will not fail3."), "V${java.version");
+ assertEquals(ConfigProvider.getConfig().getValue("Will not fail3.", String.class), "V${java.version");
}
@Test
public void test_Prefix_Resolution_Escaped1() {
- assertEquals(ConfigurationProvider.getConfiguration().get("Will not fail1."), "V$\\{java.version");
+ assertEquals(ConfigProvider.getConfig().getValue("Will not fail1.", String.class), "V$\\{java.version");
}
@Test
public void test_Prefix_Resolution_Escaped2() {
- assertEquals(ConfigurationProvider.getConfiguration().get("Will not fail2."), "V\\${java.version");
+ assertEquals(ConfigProvider.getConfig().getValue("Will not fail2.", String.class), "V\\${java.version");
}
@Test
public void test_Prefix_Resolution_EnvKeys() {
- assertEquals(ConfigurationProvider.getConfiguration().get("env.keys"), System.getProperty("java.version") + " plus $java.version");
+ assertEquals(ConfigProvider.getConfig().getValue("env.keys", String.class), System.getProperty("java.version") + " plus $java.version");
}
@Test
public void test_Prefix_ExpressionOnly_Resolution() {
- assertEquals(ConfigurationProvider.getConfiguration().get("Expression Only"), System.getProperty("java.version"));
+ assertEquals(ConfigProvider.getConfig().getValue("Expression Only", String.class), System.getProperty("java.version"));
}
@Test
public void testConfig_Refs() {
- assertEquals(ConfigurationProvider.getConfiguration().get("config-ref"), "Expression Only -> " + System.getProperty("java.version"));
- assertEquals(ConfigurationProvider.getConfiguration().get("config-ref3"), "Config Ref 3 -> Ref 2: Config Ref 2 -> Ref 1: Expression Only -> " + System.getProperty("java.version"));
- assertEquals(ConfigurationProvider.getConfiguration().get("config-ref2"), "Config Ref 2 -> Ref 1: Expression Only -> " + System.getProperty("java.version"));
+ assertEquals(ConfigProvider.getConfig().getValue("config-ref", String.class), "Expression Only -> " + System.getProperty("java.version"));
+ assertEquals(ConfigProvider.getConfig().getValue("config-ref3", String.class), "Config Ref 3 -> Ref 2: Config Ref 2 -> Ref 1: Expression Only -> " + System.getProperty("java.version"));
+ assertEquals(ConfigProvider.getConfig().getValue("config-ref2", String.class), "Config Ref 2 -> Ref 1: Expression Only -> " + System.getProperty("java.version"));
}
@Test
public void testClasspath_Refs() {
- String value = ConfigurationProvider.getConfiguration().get("cp-ref");
+ String value = ConfigProvider.getConfig().getValue("cp-ref", String.class);
assertNotNull(value);
assertTrue(value.contains("This content comes from Testresource.txt!"));
}
@Test
public void testResource_Refs() {
- String value = ConfigurationProvider.getConfiguration().get("res-ref");
+ String value = ConfigProvider.getConfig().getValue("res-ref", String.class);
assertNotNull(value);
assertTrue(value.contains("This content comes from Testresource.txt!"));
}
@Test
public void testFile_Refs() {
- String value = ConfigurationProvider.getConfiguration().get("file-ref");
+ String value = ConfigProvider.getConfig().getValue("file-ref", String.class);
assertNotNull(value);
assertTrue(value.contains("This content comes from Testresource2.txt!"));
}
@Test
public void testURL_Refs() {
- String value = ConfigurationProvider.getConfiguration().get("url-ref");
+ String value = ConfigProvider.getConfig().getValue("url-ref", String.class);
assertNotNull(value);
assertTrue(value.contains("doctype html") || "[http://www.google.com]".equals(value));
}
@Test
public void testEscaping(){
- assertEquals(ConfigurationProvider.getConfiguration().get("escaped"),
+ assertEquals(ConfigProvider.getConfig().getValue("escaped", String.class),
"Config Ref 3 -> Ref 2: \\${conf:config-ref2 will not be evaluated and will not contain\\t tabs \\n " +
"newlines or \\r returns...YEP!");
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4af5f5f6/modules/resolver/src/test/java/org/apache/tamaya/resolver/MyTestConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/resolver/src/test/java/org/apache/tamaya/resolver/MyTestConfigSource.java b/modules/resolver/src/test/java/org/apache/tamaya/resolver/MyTestConfigSource.java
new file mode 100644
index 0000000..0b8f9d5
--- /dev/null
+++ b/modules/resolver/src/test/java/org/apache/tamaya/resolver/MyTestConfigSource.java
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.resolver;
+
+import javax.config.spi.ConfigSource;
+import java.io.File;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Created by Anatole on 04.01.2015.
+ */
+public class MyTestConfigSource implements ConfigSource{
+
+ private final Map<String,String> properties = new HashMap<>();
+
+ public MyTestConfigSource(){
+ properties.put("Expression Only", "${java.version}");
+ properties.put("Expression Only (prefixed)", "${sys:java.version}");
+ properties.put("Before Text", "My Java version is ${java.version}");
+ properties.put("Before Text (prefixed)", "My Java version is ${sys:java.version}");
+ properties.put("Before and After Text", "My Java version is ${java.version}.");
+ properties.put("Before and After Text (prefixed)", "My Java version is ${sys:java.version}.");
+ properties.put("Multi-expression", "Java version ${sys:java.version} and line.separator ${line.separator}.");
+
+ properties.put("cp-ref", "${resource:Testresource.txt}");
+ properties.put("file-ref", "${file:"+getFileRefAsString()+"}");
+ properties.put("res-ref", "${resource:Test?es*ce.txt}");
+ properties.put("url-ref", "${url:http://www.google.com}");
+ properties.put("config-ref", "Expression Only -> ${conf:Expression Only}");
+ properties.put("config-ref2", "Config Ref 2 -> Ref 1: ${conf:config-ref}");
+ properties.put("config-ref3", "Config Ref 3 -> Ref 2: ${conf:config-ref2}");
+
+ properties.put("Will fail1.", "V$java.version");
+ properties.put("Will fail2.", "V$java.version}");
+ properties.put("Will not fail3.", "V${java.version");
+ properties.put("Will not fail1.", "V$\\{java.version");
+ properties.put("Will not fail2.", "V\\${java.version");
+
+ properties.put("env.keys", "${java.version} plus $java.version");
+
+ properties.put("escaped", "Config Ref 3 -> Ref 2: \\${conf:config-ref2 will not be evaluated and will not contain\\t tabs \\n " +
+ "newlines or \\r returns...YEP!");
+ }
+
+ private String getFileRefAsString() {
+ try {
+ URL res = getClass().getClassLoader().getResource("Testresource2.txt");
+ if(res==null){
+ return null;
+ }
+ return new File(res.toURI()).getAbsolutePath().replaceAll("\\\\","/");
+ } catch (URISyntaxException e) {
+ return "Failed to evaluate file: Testresource2.txt";
+ }
+ }
+
+ @Override
+ public int getOrdinal() {
+ return 0;
+ }
+
+ @Override
+ public String getName() {
+ return "test";
+ }
+
+ @Override
+ public String getValue(String key) {
+ return properties.get(key);
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ Map<String, String> res = new HashMap<>();
+ for(Map.Entry<String,String> en:properties.entrySet()){
+ res.put(en.getKey(), en.getValue());
+ }
+ return res;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4af5f5f6/modules/resolver/src/test/java/org/apache/tamaya/resolver/MyTestPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/resolver/src/test/java/org/apache/tamaya/resolver/MyTestPropertySource.java b/modules/resolver/src/test/java/org/apache/tamaya/resolver/MyTestPropertySource.java
deleted file mode 100644
index eee7fa4..0000000
--- a/modules/resolver/src/test/java/org/apache/tamaya/resolver/MyTestPropertySource.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.resolver;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-
-import java.io.File;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Created by Anatole on 04.01.2015.
- */
-public class MyTestPropertySource implements PropertySource{
-
- private final Map<String,String> properties = new HashMap<>();
-
- public MyTestPropertySource(){
- properties.put("Expression Only", "${java.version}");
- properties.put("Expression Only (prefixed)", "${sys:java.version}");
- properties.put("Before Text", "My Java version is ${java.version}");
- properties.put("Before Text (prefixed)", "My Java version is ${sys:java.version}");
- properties.put("Before and After Text", "My Java version is ${java.version}.");
- properties.put("Before and After Text (prefixed)", "My Java version is ${sys:java.version}.");
- properties.put("Multi-expression", "Java version ${sys:java.version} and line.separator ${line.separator}.");
-
- properties.put("cp-ref", "${resource:Testresource.txt}");
- properties.put("file-ref", "${file:"+getFileRefAsString()+"}");
- properties.put("res-ref", "${resource:Test?es*ce.txt}");
- properties.put("url-ref", "${url:http://www.google.com}");
- properties.put("config-ref", "Expression Only -> ${conf:Expression Only}");
- properties.put("config-ref2", "Config Ref 2 -> Ref 1: ${conf:config-ref}");
- properties.put("config-ref3", "Config Ref 3 -> Ref 2: ${conf:config-ref2}");
-
- properties.put("Will fail1.", "V$java.version");
- properties.put("Will fail2.", "V$java.version}");
- properties.put("Will not fail3.", "V${java.version");
- properties.put("Will not fail1.", "V$\\{java.version");
- properties.put("Will not fail2.", "V\\${java.version");
-
- properties.put("env.keys", "${java.version} plus $java.version");
-
- properties.put("escaped", "Config Ref 3 -> Ref 2: \\${conf:config-ref2 will not be evaluated and will not contain\\t tabs \\n " +
- "newlines or \\r returns...YEP!");
- }
-
- private String getFileRefAsString() {
- try {
- URL res = getClass().getClassLoader().getResource("Testresource2.txt");
- if(res==null){
- return null;
- }
- return new File(res.toURI()).getAbsolutePath().replaceAll("\\\\","/");
- } catch (URISyntaxException e) {
- return "Failed to evaluate file: Testresource2.txt";
- }
- }
-
- @Override
- public int getOrdinal() {
- return 0;
- }
-
- @Override
- public String getName() {
- return "test";
- }
-
- @Override
- public PropertyValue get(String key) {
- return PropertyValue.of(key, properties.get(key), getName());
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
- Map<String, PropertyValue> res = new HashMap<>();
- for(Map.Entry<String,String> en:properties.entrySet()){
- res.put(en.getKey(), PropertyValue.of(en.getKey(), en.getValue(), "test"));
- }
- return res;
- }
-
- @Override
- public boolean isScannable() {
- return true;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4af5f5f6/modules/resolver/src/test/java/org/apache/tamaya/resolver/NonResolvableConfig.java
----------------------------------------------------------------------
diff --git a/modules/resolver/src/test/java/org/apache/tamaya/resolver/NonResolvableConfig.java b/modules/resolver/src/test/java/org/apache/tamaya/resolver/NonResolvableConfig.java
new file mode 100644
index 0000000..33429ca
--- /dev/null
+++ b/modules/resolver/src/test/java/org/apache/tamaya/resolver/NonResolvableConfig.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.resolver;
+
+import javax.config.Config;
+import javax.config.spi.ConfigSource;
+import java.util.Arrays;
+import java.util.Optional;
+
+/**
+ * Implements s simple config just based on the {@link MyTestConfigSource}, without any
+ * resolution logic.
+ */
+public class NonResolvableConfig implements Config{
+
+ private MyTestConfigSource configDelegate = new MyTestConfigSource();
+
+ @Override
+ public <T> T getValue(String propertyName, Class<T> propertyType) {
+ if(propertyType.equals(String.class)) {
+ return (T)configDelegate.getValue(propertyName);
+ }
+ return null;
+ }
+
+ @Override
+ public <T> Optional<T> getOptionalValue(String propertyName, Class<T> propertyType) {
+ return Optional.ofNullable(getValue(propertyName, propertyType));
+ }
+
+ @Override
+ public Iterable<String> getPropertyNames() {
+ return configDelegate.getPropertyNames();
+ }
+
+ @Override
+ public Iterable<ConfigSource> getConfigSources() {
+ return Arrays.asList(new ConfigSource[]{configDelegate});
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4af5f5f6/modules/resolver/src/test/java/org/apache/tamaya/resolver/ResolvableConfigTest.java
----------------------------------------------------------------------
diff --git a/modules/resolver/src/test/java/org/apache/tamaya/resolver/ResolvableConfigTest.java b/modules/resolver/src/test/java/org/apache/tamaya/resolver/ResolvableConfigTest.java
new file mode 100644
index 0000000..72199fb
--- /dev/null
+++ b/modules/resolver/src/test/java/org/apache/tamaya/resolver/ResolvableConfigTest.java
@@ -0,0 +1,164 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.resolver;
+
+import org.junit.Test;
+
+import javax.config.Config;
+import javax.config.ConfigProvider;
+
+import static org.junit.Assert.*;
+
+/**
+ * Test class that test resolution of different values as configured within
+ * {@link MyTestConfigSource} after applying {@link Resolver#makeResolvable(Config)} to a
+ * non resolvable instance.
+ */
+public class ResolvableConfigTest {
+
+ private NonResolvableConfig nonResolvableConfig = new NonResolvableConfig();
+ private Config resolvableConfig = Resolver.makeResolvable(nonResolvableConfig);
+
+ @Test
+ public void test_Prefix_Resolution() {
+ assertNotSame(nonResolvableConfig.getValue("Before Text (prefixed)", String.class), "My Java version is " + System.getProperty("java.version"));
+ assertEquals(resolvableConfig.getValue("Before Text (prefixed)", String.class), "My Java version is " + System.getProperty("java.version"));
+ }
+
+ @Test
+ public void test_Midfix_Resolution() {
+ assertNotSame(nonResolvableConfig.getValue("Before and After Text (prefixed)", String.class), "My Java version is " + System.getProperty("java.version") + ".");
+ assertEquals(resolvableConfig.getValue("Before and After Text (prefixed)", String.class), "My Java version is " + System.getProperty("java.version") + ".");
+ }
+
+ @Test
+ public void test_Prefix_Resolution_BadSyntax1() {
+ assertEquals(nonResolvableConfig.getValue("Will fail1.", String.class), "V$java.version");
+ assertEquals(resolvableConfig.getValue("Will fail1.", String.class), "V$java.version");
+ }
+
+ @Test
+ public void test_Prefix_Resolution_BadSyntax2() {
+ assertEquals(resolvableConfig.getValue("Will fail2.", String.class), "V$java.version}");
+ assertEquals(nonResolvableConfig.getValue("Will fail2.", String.class), "V$java.version}");
+ }
+
+ @Test
+ public void test_Prefix_Resolution_BadSyntax31() {
+ assertEquals(resolvableConfig.getValue("Will not fail3.", String.class), "V${java.version");
+ assertEquals(nonResolvableConfig.getValue("Will not fail3.", String.class), "V${java.version");
+ }
+
+ @Test
+ public void test_Prefix_Resolution_Escaped1() {
+ assertEquals(resolvableConfig.getValue("Will not fail1.", String.class), "V$\\{java.version");
+ assertEquals(nonResolvableConfig.getValue("Will not fail1.", String.class), "V$\\{java.version");
+ }
+
+ @Test
+ public void test_Prefix_Resolution_Escaped2() {
+ assertEquals(resolvableConfig.getValue("Will not fail2.", String.class), "V\\${java.version");
+ assertEquals(nonResolvableConfig.getValue("Will not fail2.", String.class), "V\\${java.version");
+ }
+
+ @Test
+ public void test_Prefix_Resolution_EnvKeys() {
+ assertEquals(resolvableConfig.getValue("env.keys", String.class), System.getProperty("java.version") + " plus $java.version");
+ assertNotSame(nonResolvableConfig.getValue("env.keys", String.class), System.getProperty("java.version") + " plus $java.version");
+ }
+
+ @Test
+ public void test_Prefix_ExpressionOnly_Resolution() {
+ assertEquals(resolvableConfig.getValue("Expression Only", String.class), System.getProperty("java.version"));
+ assertNotSame(nonResolvableConfig.getValue("Expression Only", String.class), System.getProperty("java.version"));
+ }
+
+ @Test
+ public void testConfig_Refs() {
+ assertEquals(resolvableConfig.getValue("config-ref", String.class), "Expression Only -> " + System.getProperty("java.version"));
+ assertEquals(resolvableConfig.getValue("config-ref3", String.class), "Config Ref 3 -> Ref 2: Config Ref 2 -> Ref 1: Expression Only -> " + System.getProperty("java.version"));
+ assertEquals(resolvableConfig.getValue("config-ref2", String.class), "Config Ref 2 -> Ref 1: Expression Only -> " + System.getProperty("java.version"));
+
+ assertNotSame(nonResolvableConfig.getValue("config-ref", String.class), "Expression Only -> " + System.getProperty("java.version"));
+ assertNotSame(nonResolvableConfig.getValue("config-ref3", String.class), "Config Ref 3 -> Ref 2: Config Ref 2 -> Ref 1: Expression Only -> " + System.getProperty("java.version"));
+ assertNotSame(nonResolvableConfig.getValue("config-ref2", String.class), "Config Ref 2 -> Ref 1: Expression Only -> " + System.getProperty("java.version"));
+ }
+
+ @Test
+ public void testClasspath_Refs() {
+ String value = resolvableConfig.getValue("cp-ref", String.class);
+ assertNotNull(value);
+ assertTrue(value.contains("This content comes from Testresource.txt!"));
+ value = nonResolvableConfig.getValue("cp-ref", String.class);
+ assertNotNull(value);
+ assertEquals("${resource:Testresource.txt}", value);
+ }
+
+ @Test
+ public void testResource_Refs() {
+ String value = resolvableConfig.getValue("res-ref", String.class);
+ assertNotNull(value);
+ assertTrue(value.contains("This content comes from Testresource.txt!"));
+ value = nonResolvableConfig.getValue("res-ref", String.class);
+ assertNotNull(value);
+ assertEquals("${resource:Test?es*ce.txt}", value);
+ }
+
+ @Test
+ public void testFile_Refs() {
+ String value = resolvableConfig.getValue("file-ref", String.class);
+ assertNotNull(value);
+ assertTrue(value.contains("This content comes from Testresource2.txt!"));
+ value = nonResolvableConfig.getValue("file-ref", String.class);
+ assertNotNull(value);
+ assertTrue(value.contains("Testresource2.txt}"));
+ assertTrue(value.contains("${file:"));
+ }
+
+ @Test
+ public void testURL_Refs() {
+ String value = resolvableConfig.getValue("url-ref", String.class);
+ assertNotNull(value);
+ assertTrue(value.contains("doctype html") || "[http://www.google.com]".equals(value));
+ value = nonResolvableConfig.getValue("url-ref", String.class);
+ assertNotNull(value);
+ assertEquals("${url:http://www.google.com}", value);
+ }
+
+ @Test
+ public void testEscaping(){
+ assertEquals(resolvableConfig.getValue("escaped", String.class),
+ "Config Ref 3 -> Ref 2: \\${conf:config-ref2 will not be evaluated and will not contain\\t tabs \\n " +
+ "newlines or \\r returns...YEP!");
+ assertEquals(nonResolvableConfig.getValue("escaped", String.class),
+ "Config Ref 3 -> Ref 2: \\${conf:config-ref2 will not be evaluated and will not contain\\t tabs \\n " +
+ "newlines or \\r returns...YEP!");
+ }
+
+ @Test
+ public void testGetPropertyNames(){
+ assertEquals(resolvableConfig.getPropertyNames(), nonResolvableConfig.getPropertyNames());
+ }
+
+ @Test
+ public void testGetConfigSources(){
+ assertEquals(resolvableConfig.getConfigSources(), nonResolvableConfig.getConfigSources());
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4af5f5f6/modules/resolver/src/test/resources/META-INF/services/javax.config.spi.ConfigSource
----------------------------------------------------------------------
diff --git a/modules/resolver/src/test/resources/META-INF/services/javax.config.spi.ConfigSource b/modules/resolver/src/test/resources/META-INF/services/javax.config.spi.ConfigSource
new file mode 100644
index 0000000..4e2300f
--- /dev/null
+++ b/modules/resolver/src/test/resources/META-INF/services/javax.config.spi.ConfigSource
@@ -0,0 +1,19 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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 current 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.
+#
+org.apache.tamaya.resolver.MyTestConfigSource
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4af5f5f6/modules/resolver/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
----------------------------------------------------------------------
diff --git a/modules/resolver/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource b/modules/resolver/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
deleted file mode 100644
index 088aca9..0000000
--- a/modules/resolver/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
+++ /dev/null
@@ -1,19 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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 current 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.
-#
-org.apache.tamaya.resolver.MyTestPropertySource
\ No newline at end of file
[11/18] incubator-tamaya-extensions git commit: Rewrite/adaptation
based on JSR API.
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/MutableConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/MutableConfiguration.java b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/MutableConfiguration.java
index 6b0e35e..580e283 100644
--- a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/MutableConfiguration.java
+++ b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/MutableConfiguration.java
@@ -18,8 +18,9 @@
*/
package org.apache.tamaya.mutableconfig;
-import org.apache.tamaya.Configuration;
+import org.apache.tamaya.mutableconfig.spi.MutableConfigSource;
+import javax.config.Config;
import java.util.Collection;
import java.util.Map;
@@ -34,26 +35,26 @@ import java.util.Map;
* As a consequence clients should first check, using the corresponding methods, if entries can be added/updated or
* removed.
*
- * This class should only used in a single threaded context, though all methods inherited from {@link Configuration}
+ * This class should only used in a single threaded context, though all methods inherited from {@link Config}
* must be thread-safe. Methods handling configuration changes are expected to be used in a single threaded environment
* only. For multi-threaded us create a new instance of {@link MutableConfiguration} for each thread.
*/
-public interface MutableConfiguration extends Configuration {
+public interface MutableConfiguration extends Config {
/**
* Storesd the changes. After a commit the change is not editable anymore. All changes applied will be written to
* the corresponding configuration backend.
*
- * NOTE that changes applied must not necessarily be visible in the current {@link Configuration} instance,
- * since visibility of changes also depends on the ordinals set on the {@link org.apache.tamaya.spi.PropertySource}s
+ * NOTE that changes applied must not necessarily be visible in the current {@link Config} instance,
+ * since visibility of changes also depends on the ordinals set on the {@link javax.config.spi.ConfigSource}s
* configured.
- * @throws org.apache.tamaya.ConfigException if the request already has been committed or cancelled, or the commit fails.
+ * @throws IllegalStateException if the request already has been committed or cancelled, or the commit fails.
*/
void store();
/**
* Access the current configuration change context, built up on all the change context of the participating
- * {@link org.apache.tamaya.mutableconfig.spi.MutablePropertySource} instances.
+ * {@link MutableConfigSource} instances.
* @return the colleted changes as one single config change for the current transaction, or null, if no transaction
* is active.
*/
@@ -61,7 +62,7 @@ public interface MutableConfiguration extends Configuration {
/**
* Access the active {@link ChangePropagationPolicy}.This policy controls how configuration changes are written/published
- * to the known {@link org.apache.tamaya.mutableconfig.spi.MutablePropertySource} instances of a {@link Configuration}.
+ * to the known {@link MutableConfigSource} instances of a {@link Config}.
* @return he active {@link ChangePropagationPolicy}, never null.
*/
ChangePropagationPolicy getChangePropagationPolicy();
@@ -72,7 +73,7 @@ public interface MutableConfiguration extends Configuration {
* @param key the property's key, not null.
* @param value the property's value, not null.
* @return the former property value, or null.
- * @throws org.apache.tamaya.ConfigException if the key/value cannot be added, or the request is read-only.
+ * @throws IllegalStateException if the key/value cannot be added, or the request is read-only.
*/
MutableConfiguration put(String key, String value);
@@ -80,14 +81,14 @@ public interface MutableConfiguration extends Configuration {
* Puts all given configuration entries. This method should check that all given properties are
* basically removable, as defined by #isWritable. If any of the passed keys is not writable during this initial
* check, the operation should not perform any configuration changes and throw a
- * {@link org.apache.tamaya.ConfigException}. If errors occur afterwards, when the properties are effectively
+ * {@link IllegalArgumentException}. If errors occur afterwards, when the properties are effectively
* written back to the backends, the errors should be collected and returned as part of the ConfigException
* payload. Nevertheless the operation should in that case remove all entries as far as possible and abort the
* writing operation.
*
* @param properties the properties tobe written, not null.
* @return the config change request
- * @throws org.apache.tamaya.ConfigException if any of the given properties could not be written, or the request
+ * @throws IllegalStateException if any of the given properties could not be written, or the request
* is read-only.
*/
MutableConfiguration putAll(Map<String, String> properties);
@@ -96,14 +97,14 @@ public interface MutableConfiguration extends Configuration {
* Removes all given configuration entries. This method should check that all given properties are
* basically removable, as defined by #isRemovable. If any of the passed keys is not removable during this initial
* check, the operation should not perform any configuration changes and throw a
- * {@link org.apache.tamaya.ConfigException}. If errors
+ * {@link IllegalArgumentException}. If errors
* occur afterwards, when the properties are effectively written back to the backends, the errors should be
* collected and returned as part of the ConfigException payload. Nevertheless the operation should in that case
* remove all entries as far as possible and abort the writing operation.
*
* @param keys the property's keys to be removedProperties, not null.
* @return the config change request
- * @throws org.apache.tamaya.ConfigException if any of the given keys could not be removedProperties, or the
+ * @throws IllegalStateException if any of the given keys could not be removedProperties, or the
* request is read-only.
*/
MutableConfiguration remove(Collection<String> keys);
@@ -111,14 +112,14 @@ public interface MutableConfiguration extends Configuration {
/**
* Removes all given configuration entries. This method should check that all given properties are
* basically removable, as defined by #isRemovable. If any of the passed keys is not removable during this initial
- * check, the operation should not perform any configuration changes and throw a {@link org.apache.tamaya.ConfigException}. If errors
+ * check, the operation should not perform any configuration changes and throw a {@link IllegalArgumentException}. If errors
* occur afterwards, when the properties are effectively written back to the backends, the errors should be
* collected and returned as part of the ConfigException payload. Nevertheless the operation should in that case
* remove all entries as far as possible and abort the writing operation.
*
* @param keys the property's keys to be removedProperties, not null.
* @return the config change request
- * @throws org.apache.tamaya.ConfigException if any of the given keys could not be removedProperties, or the request is read-only.
+ * @throws IllegalStateException if any of the given keys could not be removedProperties, or the request is read-only.
*/
MutableConfiguration remove(String... keys);
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/MutableConfigurationProvider.java
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/MutableConfigurationProvider.java b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/MutableConfigurationProvider.java
index 1198c09..179ceda 100644
--- a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/MutableConfigurationProvider.java
+++ b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/MutableConfigurationProvider.java
@@ -18,16 +18,14 @@
*/
package org.apache.tamaya.mutableconfig;
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
import org.apache.tamaya.mutableconfig.spi.MutableConfigurationProviderSpi;
-import org.apache.tamaya.mutableconfig.spi.MutablePropertySource;
-import org.apache.tamaya.spi.PropertySource;
+import org.apache.tamaya.mutableconfig.spi.MutableConfigSource;
import org.apache.tamaya.spi.ServiceContextManager;
+import javax.config.Config;
+import javax.config.ConfigProvider;
+import javax.config.spi.ConfigSource;
import java.util.Arrays;
-import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
@@ -46,7 +44,7 @@ public final class MutableConfigurationProvider {
MutableConfigurationProviderSpi spi = ServiceContextManager.getServiceContext().getService(
MutableConfigurationProviderSpi.class) ;
if(spi==null){
- throw new ConfigException("Failed to initialize MutableConfigurationProviderSpi - " +
+ throw new IllegalArgumentException("Failed to initialize MutableConfigurationProviderSpi - " +
"mutable configuration support.");
}
return spi;
@@ -58,50 +56,50 @@ public final class MutableConfigurationProvider {
/**
* Creates a new {@link MutableConfiguration} for the given default configuration, using all
- * {@link MutablePropertySource} instances found in its context and {@code autoCommit = false}.
+ * {@link MutableConfigSource} instances found in its context and {@code autoCommit = false}.
*
* @return a new MutableConfiguration instance
*/
public static MutableConfiguration createMutableConfiguration(){
return spi().createMutableConfiguration(
- ConfigurationProvider.getConfiguration(), getApplyMostSignificantOnlyChangePolicy());
+ ConfigProvider.getConfig(), getApplyMostSignificantOnlyChangePolicy());
}
/**
* Creates a new {@link MutableConfiguration} for the given default configuration, using all
- * {@link MutablePropertySource} instances found in its context and {@code autoCommit = false}.
+ * {@link MutableConfigSource} instances found in its context and {@code autoCommit = false}.
* @param changePropgationPolicy policy that defines how a change is written back and which property
* sources are finally eligible for a write operation.
* @return a new MutableConfiguration instance, with the given change policy active.
*/
public static MutableConfiguration createMutableConfiguration(ChangePropagationPolicy changePropgationPolicy){
return spi().createMutableConfiguration(
- ConfigurationProvider.getConfiguration(), changePropgationPolicy);
+ ConfigProvider.getConfig(), changePropgationPolicy);
}
/**
* Creates a new {@link MutableConfiguration} for the given configuration, using all
- * {@link MutablePropertySource} instances found in its context and {@code MOST_SIGNIFICANT_ONLY_POLICY}
+ * {@link MutableConfigSource} instances found in its context and {@code MOST_SIGNIFICANT_ONLY_POLICY}
* configuration writing policy.
*
* @param configuration the configuration to use to write the changes/config.
* @return a new MutableConfiguration instance
*/
- public static MutableConfiguration createMutableConfiguration(Configuration configuration){
+ public static MutableConfiguration createMutableConfiguration(Config configuration){
return createMutableConfiguration(configuration, MOST_SIGNIFICANT_ONLY_POLICY);
}
/**
* Creates a new {@link MutableConfiguration} for the given configuration, using all
- * {@link MutablePropertySource} instances found in its context and {@code ALL_POLICY}
+ * {@link MutableConfigSource} instances found in its context and {@code ALL_POLICY}
* configuration writing policy.
*
* @param configuration the configuration to use to write the changes/config.
* @param changePropagationPolicy the configuration writing policy.
* @return a new MutableConfiguration instance
*/
- public static MutableConfiguration createMutableConfiguration(Configuration configuration, ChangePropagationPolicy changePropagationPolicy){
+ public static MutableConfiguration createMutableConfiguration(Config configuration, ChangePropagationPolicy changePropagationPolicy){
return spi().createMutableConfiguration(configuration, changePropagationPolicy);
}
@@ -147,13 +145,13 @@ public final class MutableConfigurationProvider {
*/
private static final ChangePropagationPolicy ALL_POLICY = new ChangePropagationPolicy() {
@Override
- public void applyChange(ConfigChangeRequest change, Collection<PropertySource> propertySources) {
- for(PropertySource propertySource: propertySources){
- if(propertySource instanceof MutablePropertySource){
- MutablePropertySource target = (MutablePropertySource)propertySource;
+ public void applyChange(ConfigChangeRequest change, Iterable<ConfigSource> propertySources) {
+ for(ConfigSource propertySource: propertySources){
+ if(propertySource instanceof MutableConfigSource){
+ MutableConfigSource target = (MutableConfigSource)propertySource;
try{
target.applyChange(change);
- }catch(ConfigException e){
+ }catch(Exception e){
LOG.warning("Failed to store changes '"+change+"' not applicable to "+target.getName()
+"("+target.getClass().getName()+").");
}
@@ -169,13 +167,13 @@ public final class MutableConfigurationProvider {
*/
private static final ChangePropagationPolicy MOST_SIGNIFICANT_ONLY_POLICY = new ChangePropagationPolicy() {
@Override
- public void applyChange(ConfigChangeRequest change, Collection<PropertySource> propertySources) {
- for(PropertySource propertySource: propertySources){
- if(propertySource instanceof MutablePropertySource){
- MutablePropertySource target = (MutablePropertySource)propertySource;
+ public void applyChange(ConfigChangeRequest change, Iterable<ConfigSource> propertySources) {
+ for(ConfigSource propertySource: propertySources){
+ if(propertySource instanceof MutableConfigSource){
+ MutableConfigSource target = (MutableConfigSource)propertySource;
try{
target.applyChange(change);
- }catch(ConfigException e){
+ }catch(Exception e){
LOG.warning("Failed to store changes '"+change+"' not applicable to "+target.getName()
+"("+target.getClass().getName()+").");
}
@@ -192,7 +190,7 @@ public final class MutableConfigurationProvider {
*/
private static final ChangePropagationPolicy NONE_POLICY = new ChangePropagationPolicy() {
@Override
- public void applyChange(ConfigChangeRequest change, Collection<PropertySource> propertySources) {
+ public void applyChange(ConfigChangeRequest change, Iterable<ConfigSource> propertySources) {
LOG.warning("Cannot store changes '"+change+"': prohibited by change policy (read-only).");
}
};
@@ -209,14 +207,14 @@ public final class MutableConfigurationProvider {
}
@Override
- public void applyChange(ConfigChangeRequest change, Collection<PropertySource> propertySources) {
- for(PropertySource propertySource: propertySources){
- if(propertySource instanceof MutablePropertySource){
+ public void applyChange(ConfigChangeRequest change, Iterable<ConfigSource> propertySources) {
+ for(ConfigSource propertySource: propertySources){
+ if(propertySource instanceof MutableConfigSource){
if(this.propertySourceNames.contains(propertySource.getName())) {
- MutablePropertySource target = (MutablePropertySource) propertySource;
+ MutableConfigSource target = (MutableConfigSource) propertySource;
try{
target.applyChange(change);
- }catch(ConfigException e){
+ }catch(Exception e){
LOG.warning("Failed to store changes '"+change+"' not applicable to "+target.getName()
+"("+target.getClass().getName()+").");
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/internal/DefaultMutableConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/internal/DefaultMutableConfiguration.java b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/internal/DefaultMutableConfiguration.java
index 0fe3e23..7d331aa 100644
--- a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/internal/DefaultMutableConfiguration.java
+++ b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/internal/DefaultMutableConfiguration.java
@@ -18,25 +18,15 @@
*/
package org.apache.tamaya.mutableconfig.internal;
-import org.apache.tamaya.ConfigOperator;
-import org.apache.tamaya.ConfigQuery;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.TypeLiteral;
import org.apache.tamaya.mutableconfig.ChangePropagationPolicy;
import org.apache.tamaya.mutableconfig.MutableConfiguration;
import org.apache.tamaya.mutableconfig.ConfigChangeRequest;
-import org.apache.tamaya.mutableconfig.spi.MutablePropertySource;
-import org.apache.tamaya.spi.ConfigurationContext;
-import org.apache.tamaya.spi.PropertySource;
+import org.apache.tamaya.mutableconfig.spi.MutableConfigSource;
import org.osgi.service.component.annotations.Component;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.UUID;
+import javax.config.Config;
+import javax.config.spi.ConfigSource;
+import java.util.*;
import java.util.logging.Logger;
@@ -47,10 +37,10 @@ import java.util.logging.Logger;
public class DefaultMutableConfiguration implements MutableConfiguration {
private static final Logger LOG = Logger.getLogger(DefaultMutableConfiguration.class.getName());
private ConfigChangeRequest changeRequest = new ConfigChangeRequest(UUID.randomUUID().toString());
- private final Configuration config;
+ private final Config config;
private ChangePropagationPolicy changePropagationPolicy;
- public DefaultMutableConfiguration(Configuration config, ChangePropagationPolicy changePropagationPolicy){
+ public DefaultMutableConfiguration(Config config, ChangePropagationPolicy changePropagationPolicy){
this.config = Objects.requireNonNull(config);
this.changePropagationPolicy = Objects.requireNonNull(changePropagationPolicy);
}
@@ -65,11 +55,11 @@ public class DefaultMutableConfiguration implements MutableConfiguration {
return changeRequest;
}
- protected List<MutablePropertySource> getMutablePropertySources() {
- List<MutablePropertySource> result = new ArrayList<>();
- for(PropertySource propertySource:this.config.getContext().getPropertySources()) {
- if(propertySource instanceof MutablePropertySource){
- result.add((MutablePropertySource)propertySource);
+ protected List<MutableConfigSource> getMutablePropertySources() {
+ List<MutableConfigSource> result = new ArrayList<>();
+ for(ConfigSource propertySource:this.config.getConfigSources()) {
+ if(propertySource instanceof MutableConfigSource){
+ result.add((MutableConfigSource)propertySource);
}
}
return result;
@@ -97,69 +87,35 @@ public class DefaultMutableConfiguration implements MutableConfiguration {
@Override
public void store() {
- this.changePropagationPolicy.applyChange(changeRequest, config.getContext().getPropertySources());
+ this.changePropagationPolicy.applyChange(changeRequest, config.getConfigSources());
}
@Override
public MutableConfiguration remove(Collection<String> keys) {
- for(MutablePropertySource target:getMutablePropertySources()) {
+ for(MutableConfigSource target:getMutablePropertySources()) {
changeRequest.removeAll(keys);
}
return this;
}
@Override
- public String get(String key) {
- return this.config.get(key);
+ public <T> T getValue(String key, Class<T> type) {
+ return this.config.getValue(key, type);
}
@Override
- public String getOrDefault(String key, String defaultValue) {
- return this.config.getOrDefault(key, defaultValue);
+ public <T> Optional<T> getOptionalValue(String key, Class<T> type) {
+ return this.config.getOptionalValue(key,type);
}
@Override
- public <T> T getOrDefault(String key, Class<T> type, T defaultValue) {
- return this.config.getOrDefault(key, type, defaultValue);
+ public Iterable<String> getPropertyNames() {
+ return this.config.getPropertyNames();
}
@Override
- public <T> T get(String key, Class<T> type) {
- return this.config.get(key, type);
- }
-
- @Override
- public <T> T get(String key, TypeLiteral<T> type) {
- return this.config.get(key, type);
- }
-
- @Override
- public <T> T getOrDefault(String key, TypeLiteral<T> type, T defaultValue) {
- return this.config.getOrDefault(key, type, defaultValue);
- }
-
- @Override
- public Map<String, String> getProperties() {
- return this.config.getProperties();
- }
-
- @Override
- public Configuration with(ConfigOperator operator) {
- return operator.operate(this);
- }
-
- @Override
- public <T> T query(ConfigQuery<T> query) {
- return query.query(this);
- }
-
- @Override
- public ConfigurationContext getContext() {
- return config.getContext();
- }
-
- private Collection<PropertySource> getPropertySources() {
- return this.config.getContext().getPropertySources();
+ public Iterable<ConfigSource> getConfigSources() {
+ return this.config.getConfigSources();
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/internal/DefaultMutableConfigurationSpi.java
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/internal/DefaultMutableConfigurationSpi.java b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/internal/DefaultMutableConfigurationSpi.java
index 1ab38a8..6d7f57b 100644
--- a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/internal/DefaultMutableConfigurationSpi.java
+++ b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/internal/DefaultMutableConfigurationSpi.java
@@ -18,22 +18,23 @@
*/
package org.apache.tamaya.mutableconfig.internal;
-import org.apache.tamaya.Configuration;
import org.apache.tamaya.mutableconfig.ChangePropagationPolicy;
import org.apache.tamaya.mutableconfig.MutableConfiguration;
import org.apache.tamaya.mutableconfig.spi.MutableConfigurationProviderSpi;
import org.osgi.service.component.annotations.Component;
+import javax.config.Config;
+
/**
* SPI implementation that creates instances of {@link DefaultMutableConfiguration}, hereby for
- * each instance of {@link Configuration} a new instance has to be returned.
+ * each instance of {@link Config} a new instance has to be returned.
*/
@Component
public class DefaultMutableConfigurationSpi implements MutableConfigurationProviderSpi {
@Override
- public MutableConfiguration createMutableConfiguration(Configuration configuration,
+ public MutableConfiguration createMutableConfiguration(Config configuration,
ChangePropagationPolicy propagationPolicy){
return new DefaultMutableConfiguration(configuration, propagationPolicy);
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/propertysources/MutablePropertiesConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/propertysources/MutablePropertiesConfigSource.java b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/propertysources/MutablePropertiesConfigSource.java
new file mode 100644
index 0000000..490c568
--- /dev/null
+++ b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/propertysources/MutablePropertiesConfigSource.java
@@ -0,0 +1,159 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.mutableconfig.propertysources;
+
+import org.apache.tamaya.base.configsource.BaseConfigSource;
+import org.apache.tamaya.mutableconfig.ConfigChangeRequest;
+import org.apache.tamaya.mutableconfig.spi.MutableConfigSource;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.*;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Simple implementation of a mutable {@link javax.config.spi.ConfigSource} for .properties files.
+ */
+public class MutablePropertiesConfigSource extends BaseConfigSource
+implements MutableConfigSource {
+
+ /**
+ * The logger.
+ */
+ private static final Logger LOG = Logger.getLogger(MutablePropertiesConfigSource.class.getName());
+
+ /**
+ * The configuration resource's URL.
+ */
+ private File file;
+
+ /**
+ * The current properties.
+ */
+ private Map<String, String> properties = new HashMap<>();
+
+ /**
+ * Creates a new Properties based PropertySource based on the given URL.
+ *
+ * @param propertiesLocation the URL encoded location, not null.
+ */
+ public MutablePropertiesConfigSource(File propertiesLocation) {
+ this(propertiesLocation, 0);
+ }
+
+ /**
+ * Creates a new Properties based PropertySource based on the given URL.
+ *
+ * @param propertiesLocation the URL encoded location, not null.
+ * @param defaultOrdinal the default ordinal to be used, when no ordinal is provided with the property
+ * source's properties.
+ */
+ public MutablePropertiesConfigSource(File propertiesLocation, int defaultOrdinal) {
+ super(propertiesLocation.toString(), defaultOrdinal);
+ try {
+ this.file = propertiesLocation;
+ refresh();
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "Cannot convert file to URL: " + propertiesLocation, e);
+ }
+ }
+
+
+ @Override
+ public String getValue(String key) {
+ Map<String,String> properties = getProperties();
+ return properties.get(key);
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ return Collections.unmodifiableMap(this.properties);
+ }
+
+ /**
+ * loads the Properties from the given URL
+ *
+ * @throws IllegalStateException in case of an error while reading properties-file
+ */
+ public void refresh() {
+ try (InputStream stream = new FileInputStream(file)) {
+ Map<String, String> properties = new HashMap<>();
+ Properties props = new Properties();
+ props.load(stream);
+ for (String key : props.stringPropertyNames()) {
+ properties.put(key, props.getProperty(key));
+ }
+ LOG.log(Level.FINEST, "Loaded properties from " + file);
+ this.properties = properties;
+ } catch (IOException e) {
+ LOG.log(Level.FINEST, "Cannot load properties from " + file, e);
+ }
+ }
+
+ @Override
+ public void applyChange(ConfigChangeRequest change) {
+ if(change.isEmpty()){
+ LOG.info("Nothing to commit for transaction: " + change.getTransactionID());
+ return;
+ }
+ if(!file.exists()){
+ try {
+ if(!file.createNewFile()){
+ throw new IllegalArgumentException("Failed to create config file " + file);
+ }
+ } catch (IOException e) {
+ throw new IllegalArgumentException("Failed to create config file " + file, e);
+ }
+ }
+ for(Map.Entry<String,String> en:change.getAddedProperties().entrySet()){
+ int index = en.getKey().indexOf('?');
+ if(index>0){
+ this.properties.put(en.getKey().substring(0, index), en.getValue());
+ }else{
+ this.properties.put(en.getKey(), en.getValue());
+ }
+ }
+ for(String rmKey:change.getRemovedProperties()){
+ this.properties.remove(rmKey);
+ }
+ try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))){
+ Properties props = new Properties();
+ for (Map.Entry<String,String> en : this.properties.entrySet()) {
+ props.setProperty(en.getKey(), en.getValue());
+ }
+ props.store(bos, "Properties written from Tamaya on " + new Date());
+ bos.flush();
+ }
+ catch(Exception e){
+ throw new IllegalArgumentException("Failed to write config to " + file, e);
+ }
+ }
+
+ @Override
+ protected String toStringValues() {
+ return super.toStringValues() +
+ " file=" + file + '\n';
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/propertysources/MutablePropertiesPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/propertysources/MutablePropertiesPropertySource.java b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/propertysources/MutablePropertiesPropertySource.java
deleted file mode 100644
index 659dab2..0000000
--- a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/propertysources/MutablePropertiesPropertySource.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.mutableconfig.propertysources;
-
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.mutableconfig.ConfigChangeRequest;
-import org.apache.tamaya.mutableconfig.spi.MutablePropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-import org.apache.tamaya.spisupport.propertysource.BasePropertySource;
-
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * Simple implementation of a mutable {@link org.apache.tamaya.spi.PropertySource} for .properties files.
- */
-public class MutablePropertiesPropertySource extends BasePropertySource
-implements MutablePropertySource{
-
- /**
- * The logger.
- */
- private static final Logger LOG = Logger.getLogger(MutablePropertiesPropertySource.class.getName());
-
- /**
- * The configuration resource's URL.
- */
- private File file;
-
- /**
- * The current properties.
- */
- private Map<String, String> properties = new HashMap<>();
-
- /**
- * Creates a new Properties based PropertySource based on the given URL.
- *
- * @param propertiesLocation the URL encoded location, not null.
- */
- public MutablePropertiesPropertySource(File propertiesLocation) {
- this(propertiesLocation, 0);
- }
-
- /**
- * Creates a new Properties based PropertySource based on the given URL.
- *
- * @param propertiesLocation the URL encoded location, not null.
- * @param defaultOrdinal the default ordinal to be used, when no ordinal is provided with the property
- * source's properties.
- */
- public MutablePropertiesPropertySource(File propertiesLocation, int defaultOrdinal) {
- super(propertiesLocation.toString(), defaultOrdinal);
- try {
- this.file = propertiesLocation;
- refresh();
- } catch (Exception e) {
- LOG.log(Level.SEVERE, "Cannot convert file to URL: " + propertiesLocation, e);
- }
- }
-
-
- @Override
- public PropertyValue get(String key) {
- Map<String,PropertyValue> properties = getProperties();
- return properties.get(key);
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
- return PropertyValue.map(this.properties, getName());
- }
-
- /**
- * loads the Properties from the given URL
- *
- * @throws IllegalStateException in case of an error while reading properties-file
- */
- public void refresh() {
- try (InputStream stream = new FileInputStream(file)) {
- Map<String, String> properties = new HashMap<>();
- Properties props = new Properties();
- props.load(stream);
- for (String key : props.stringPropertyNames()) {
- properties.put(key, props.getProperty(key));
- }
- LOG.log(Level.FINEST, "Loaded properties from " + file);
- this.properties = properties;
- } catch (IOException e) {
- LOG.log(Level.FINEST, "Cannot load properties from " + file, e);
- }
- }
-
- @Override
- public void applyChange(ConfigChangeRequest change) {
- if(change.isEmpty()){
- LOG.info("Nothing to commit for transaction: " + change.getTransactionID());
- return;
- }
- if(!file.exists()){
- try {
- if(!file.createNewFile()){
- throw new ConfigException("Failed to create config file " + file);
- }
- } catch (IOException e) {
- throw new ConfigException("Failed to create config file " + file, e);
- }
- }
- for(Map.Entry<String,String> en:change.getAddedProperties().entrySet()){
- int index = en.getKey().indexOf('?');
- if(index>0){
- this.properties.put(en.getKey().substring(0, index), en.getValue());
- }else{
- this.properties.put(en.getKey(), en.getValue());
- }
- }
- for(String rmKey:change.getRemovedProperties()){
- this.properties.remove(rmKey);
- }
- try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))){
- Properties props = new Properties();
- for (Map.Entry<String,String> en : this.properties.entrySet()) {
- props.setProperty(en.getKey(), en.getValue());
- }
- props.store(bos, "Properties written from Tamaya on " + new Date());
- bos.flush();
- }
- catch(Exception e){
- throw new ConfigException("Failed to write config to " + file, e);
- }
- }
-
- @Override
- protected String toStringValues() {
- return super.toStringValues() +
- " file=" + file + '\n';
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/propertysources/MutableXmlPropertiesConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/propertysources/MutableXmlPropertiesConfigSource.java b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/propertysources/MutableXmlPropertiesConfigSource.java
new file mode 100644
index 0000000..6c654c6
--- /dev/null
+++ b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/propertysources/MutableXmlPropertiesConfigSource.java
@@ -0,0 +1,162 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.mutableconfig.propertysources;
+
+import org.apache.tamaya.base.configsource.BaseConfigSource;
+import org.apache.tamaya.mutableconfig.ConfigChangeRequest;
+import org.apache.tamaya.mutableconfig.spi.MutableConfigSource;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.*;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Simple implementation of a mutable {@link javax.config.spi.ConfigSource} for .xml properties files.
+ */
+public class MutableXmlPropertiesConfigSource extends BaseConfigSource
+implements MutableConfigSource {
+
+ /**
+ * The logger.
+ */
+ private static final Logger LOG = Logger.getLogger(MutableXmlPropertiesConfigSource.class.getName());
+
+ /**
+ * The configuration resource's URL.
+ */
+ private File file;
+
+ /**
+ * The current properties.
+ */
+ private Map<String, String> properties = new HashMap<>();
+
+
+ /**
+ * Creates a new Properties based PropertySource based on the given URL.
+ *
+ * @param propertiesLocation the URL encoded location, not null.
+ */
+ public MutableXmlPropertiesConfigSource(File propertiesLocation) {
+ this(propertiesLocation, 0);
+ }
+
+ /**
+ * Creates a new Properties based PropertySource based on the given URL.
+ *
+ * @param propertiesLocation the URL encoded location, not null.
+ * @param defaultOrdinal the default ordinal to be used, when no ordinal is provided with the property
+ * source's properties.
+ */
+ public MutableXmlPropertiesConfigSource(File propertiesLocation, int defaultOrdinal) {
+ super(propertiesLocation.toString(), defaultOrdinal);
+ try {
+ this.file = propertiesLocation;
+ load();
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "Cannot convert file to URL: " + propertiesLocation, e);
+ }
+ }
+
+
+
+ @Override
+ public String getValue(String key) {
+ return this.properties.get(key);
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ return Collections.unmodifiableMap(this.properties);
+ }
+
+ /**
+ * loads the Properties from the given URL
+ *
+ * @throws IllegalStateException in case of an error while reading properties-file
+ */
+ private void load() {
+ try (InputStream stream = new FileInputStream(file)) {
+ Map<String, String> properties = new HashMap<>();
+ Properties props = new Properties();
+ props.loadFromXML(stream);
+ for (String key : props.stringPropertyNames()) {
+ properties.put(key, props.getProperty(key));
+ }
+ this.properties = properties;
+ LOG.log(Level.FINEST, "Loaded properties from " + file);
+ this.properties = properties;
+ } catch (IOException e) {
+ LOG.log(Level.FINEST, "Cannot refresh properties from " + file, e);
+ }
+ }
+
+ @Override
+ public void applyChange(ConfigChangeRequest configChange) {
+ if(configChange.isEmpty()){
+ LOG.info("Nothing to commit for transaction: " + configChange.getTransactionID());
+ return;
+ }
+ if(!file.exists()){
+ try {
+ if(!file.createNewFile()){
+ throw new IllegalStateException("Failed to create config file " + file);
+ }
+ } catch (IOException e) {
+ throw new IllegalStateException("Failed to create config file " + file, e);
+ }
+ }
+ for(Map.Entry<String,String> en:configChange.getAddedProperties().entrySet()){
+ int index = en.getKey().indexOf('?');
+ if(index>0){
+ this.properties.put(en.getKey().substring(0, index), en.getValue());
+ }else{
+ this.properties.put(en.getKey(), en.getValue());
+ }
+ }
+ for(String rmKey:configChange.getRemovedProperties()){
+ this.properties.remove(rmKey);
+ }
+ try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))){
+ Properties props = new Properties();
+ for (Map.Entry<String,String> en : this.properties.entrySet()) {
+ props.setProperty(en.getKey(), en.getValue());
+ }
+ props.storeToXML(bos, "Properties written from Tamaya on " + new Date());
+ bos.flush();
+ }
+ catch(Exception e){
+ throw new IllegalStateException("Failed to write config to " + file, e);
+ }
+ }
+
+ @Override
+ protected String toStringValues() {
+ return super.toStringValues() +
+ " file=" + file + '\n';
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/propertysources/MutableXmlPropertiesPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/propertysources/MutableXmlPropertiesPropertySource.java b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/propertysources/MutableXmlPropertiesPropertySource.java
deleted file mode 100644
index bcba53a..0000000
--- a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/propertysources/MutableXmlPropertiesPropertySource.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.mutableconfig.propertysources;
-
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.mutableconfig.ConfigChangeRequest;
-import org.apache.tamaya.mutableconfig.spi.MutablePropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-import org.apache.tamaya.spisupport.propertysource.BasePropertySource;
-
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * Simple implementation of a mutable {@link org.apache.tamaya.spi.PropertySource} for .xml properties files.
- */
-public class MutableXmlPropertiesPropertySource extends BasePropertySource
-implements MutablePropertySource{
-
- /**
- * The logger.
- */
- private static final Logger LOG = Logger.getLogger(MutableXmlPropertiesPropertySource.class.getName());
-
- /**
- * The configuration resource's URL.
- */
- private File file;
-
- /**
- * The current properties.
- */
- private Map<String, String> properties = new HashMap<>();
-
-
- /**
- * Creates a new Properties based PropertySource based on the given URL.
- *
- * @param propertiesLocation the URL encoded location, not null.
- */
- public MutableXmlPropertiesPropertySource(File propertiesLocation) {
- this(propertiesLocation, 0);
- }
-
- /**
- * Creates a new Properties based PropertySource based on the given URL.
- *
- * @param propertiesLocation the URL encoded location, not null.
- * @param defaultOrdinal the default ordinal to be used, when no ordinal is provided with the property
- * source's properties.
- */
- public MutableXmlPropertiesPropertySource(File propertiesLocation, int defaultOrdinal) {
- super(propertiesLocation.toString(), defaultOrdinal);
- try {
- this.file = propertiesLocation;
- load();
- } catch (Exception e) {
- LOG.log(Level.SEVERE, "Cannot convert file to URL: " + propertiesLocation, e);
- }
- }
-
-
-
- @Override
- public PropertyValue get(String key) {
- String val = this.properties.get(key);
- if(val!=null) {
- return PropertyValue.of(key, val, getName());
- }
- return null;
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
- return PropertyValue.map(this.properties,getName());
- }
-
- /**
- * loads the Properties from the given URL
- *
- * @throws IllegalStateException in case of an error while reading properties-file
- */
- private void load() {
- try (InputStream stream = new FileInputStream(file)) {
- Map<String, String> properties = new HashMap<>();
- Properties props = new Properties();
- props.loadFromXML(stream);
- for (String key : props.stringPropertyNames()) {
- properties.put(key, props.getProperty(key));
- }
- this.properties = properties;
- LOG.log(Level.FINEST, "Loaded properties from " + file);
- this.properties = properties;
- } catch (IOException e) {
- LOG.log(Level.FINEST, "Cannot refresh properties from " + file, e);
- }
- }
-
- @Override
- public void applyChange(ConfigChangeRequest configChange) {
- if(configChange.isEmpty()){
- LOG.info("Nothing to commit for transaction: " + configChange.getTransactionID());
- return;
- }
- if(!file.exists()){
- try {
- if(!file.createNewFile()){
- throw new ConfigException("Failed to create config file " + file);
- }
- } catch (IOException e) {
- throw new ConfigException("Failed to create config file " + file, e);
- }
- }
- for(Map.Entry<String,String> en:configChange.getAddedProperties().entrySet()){
- int index = en.getKey().indexOf('?');
- if(index>0){
- this.properties.put(en.getKey().substring(0, index), en.getValue());
- }else{
- this.properties.put(en.getKey(), en.getValue());
- }
- }
- for(String rmKey:configChange.getRemovedProperties()){
- this.properties.remove(rmKey);
- }
- try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))){
- Properties props = new Properties();
- for (Map.Entry<String,String> en : this.properties.entrySet()) {
- props.setProperty(en.getKey(), en.getValue());
- }
- props.storeToXML(bos, "Properties written from Tamaya on " + new Date());
- bos.flush();
- }
- catch(Exception e){
- throw new ConfigException("Failed to write config to " + file, e);
- }
- }
-
- @Override
- protected String toStringValues() {
- return super.toStringValues() +
- " file=" + file + '\n';
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/spi/MutableConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/spi/MutableConfigSource.java b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/spi/MutableConfigSource.java
new file mode 100644
index 0000000..c965bee
--- /dev/null
+++ b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/spi/MutableConfigSource.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.mutableconfig.spi;
+
+import org.apache.tamaya.mutableconfig.ConfigChangeRequest;
+
+import javax.config.spi.ConfigSource;
+
+
+/**
+ * This interface models a writable backend for configuration data.
+ *
+ * As a consequence clients should first check, using the corresponding methods, if entries are to edited or removedProperties
+ * actually are eligible for change/creation or removal.
+ */
+public interface MutableConfigSource extends ConfigSource {
+
+ /**
+ * Puts all given configuration entries. This method should check that all given properties are
+ * basically removable, as defined by #isWritable. If any of the passed keys is not writable during this initial
+ * check, the operation should not perform any configuration changes and throw a {@link org.apache.tamaya.ConfigException}. If errors
+ * occur afterwards, when the properties are effectively written back to the backends, the errors should be
+ * collected and returned as part of the ConfigException payload. Nevertheless the operation should in that case
+ * remove all entries as far as possible and abort the writing operation.
+ *
+ * @param configChange the {@link ConfigChangeRequest}, containing the transactionId used to isolate
+ * the change, the properties to be added/overridden and the property keys
+ * being removed.
+ * @throws org.apache.tamaya.ConfigException if any of the given properties could not be written, or the request is read-only.
+ */
+ void applyChange(ConfigChangeRequest configChange);
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/spi/MutableConfigurationProviderSpi.java
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/spi/MutableConfigurationProviderSpi.java b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/spi/MutableConfigurationProviderSpi.java
index 4412085..bd1eca0 100644
--- a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/spi/MutableConfigurationProviderSpi.java
+++ b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/spi/MutableConfigurationProviderSpi.java
@@ -18,10 +18,11 @@
*/
package org.apache.tamaya.mutableconfig.spi;
-import org.apache.tamaya.Configuration;
import org.apache.tamaya.mutableconfig.ChangePropagationPolicy;
import org.apache.tamaya.mutableconfig.MutableConfiguration;
+import javax.config.Config;
+
/**
* Provider SPI used by {@link org.apache.tamaya.mutableconfig.MutableConfigurationProvider}. Providers may override
@@ -37,6 +38,6 @@ public interface MutableConfigurationProviderSpi {
* sources.
* @return a new mutable configuration instance.
*/
- MutableConfiguration createMutableConfiguration(Configuration configuration,
+ MutableConfiguration createMutableConfiguration(Config configuration,
ChangePropagationPolicy propagationPolicy);
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/spi/MutablePropertySource.java
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/spi/MutablePropertySource.java b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/spi/MutablePropertySource.java
deleted file mode 100644
index 211869c..0000000
--- a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/spi/MutablePropertySource.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.mutableconfig.spi;
-
-import org.apache.tamaya.mutableconfig.ConfigChangeRequest;
-import org.apache.tamaya.spi.PropertySource;
-
-
-/**
- * This interface models a writable backend for configuration data.
- *
- * As a consequence clients should first check, using the corresponding methods, if entries are to edited or removedProperties
- * actually are eligible for change/creation or removal.
- */
-public interface MutablePropertySource extends PropertySource {
-
- /**
- * Puts all given configuration entries. This method should check that all given properties are
- * basically removable, as defined by #isWritable. If any of the passed keys is not writable during this initial
- * check, the operation should not perform any configuration changes and throw a {@link org.apache.tamaya.ConfigException}. If errors
- * occur afterwards, when the properties are effectively written back to the backends, the errors should be
- * collected and returned as part of the ConfigException payload. Nevertheless the operation should in that case
- * remove all entries as far as possible and abort the writing operation.
- *
- * @param configChange the {@link ConfigChangeRequest}, containing the transactionId used to isolate
- * the change, the properties to be added/overridden and the property keys
- * being removed.
- * @throws org.apache.tamaya.ConfigException if any of the given properties could not be written, or the request is read-only.
- */
- void applyChange(ConfigChangeRequest configChange);
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/MutableConfigurationProviderTest.java
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/MutableConfigurationProviderTest.java b/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/MutableConfigurationProviderTest.java
index b316b7d..a7adbff 100644
--- a/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/MutableConfigurationProviderTest.java
+++ b/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/MutableConfigurationProviderTest.java
@@ -19,9 +19,10 @@
package org.apache.tamaya.mutableconfig;
-import org.apache.tamaya.ConfigurationProvider;
import org.junit.Test;
+import javax.config.ConfigProvider;
+
import static org.junit.Assert.*;
/**
@@ -36,7 +37,7 @@ public class MutableConfigurationProviderTest {
@Test
public void createMutableConfiguration1() throws Exception {
MutableConfiguration cfg = MutableConfigurationProvider
- .createMutableConfiguration(ConfigurationProvider.getConfiguration());
+ .createMutableConfiguration(ConfigProvider.getConfig());
assertNotNull(cfg);
assertEquals(cfg.getChangePropagationPolicy(),
MutableConfigurationProvider.getApplyMostSignificantOnlyChangePolicy());
@@ -46,7 +47,7 @@ public class MutableConfigurationProviderTest {
public void createMutableConfiguration2() throws Exception {
ChangePropagationPolicy policy = MutableConfigurationProvider.getApplySelectiveChangePolicy("blabla");
MutableConfiguration cfg = MutableConfigurationProvider
- .createMutableConfiguration(ConfigurationProvider.getConfiguration(),
+ .createMutableConfiguration(ConfigProvider.getConfig(),
policy);
assertNotNull(cfg);
assertEquals(cfg.getChangePropagationPolicy(), policy);
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/MutableConfigurationTest.java
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/MutableConfigurationTest.java b/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/MutableConfigurationTest.java
index 814f3ce..dae8478 100644
--- a/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/MutableConfigurationTest.java
+++ b/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/MutableConfigurationTest.java
@@ -18,12 +18,11 @@
*/
package org.apache.tamaya.mutableconfig;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
import org.apache.tamaya.mutableconfig.internal.WritablePropertiesSource;
import org.apache.tamaya.mutableconfig.internal.WritableXmlPropertiesSource;
import org.junit.Test;
+import javax.config.ConfigProvider;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
@@ -46,12 +45,12 @@ public class MutableConfigurationTest {
public void testCreateMutableConfiguration() throws Exception {
File f = File.createTempFile("ConfigChangeRequest",".properties");
MutableConfiguration cfg1 = MutableConfigurationProvider.createMutableConfiguration(
- ConfigurationProvider.getConfiguration(),
+ ConfigProvider.getConfig(),
MutableConfigurationProvider.getApplyAllChangePolicy());
assertNotNull(cfg1);
assertNotNull(cfg1.getConfigChangeRequest());
MutableConfiguration cfg2 = MutableConfigurationProvider.createMutableConfiguration(
- ConfigurationProvider.getConfiguration());
+ ConfigProvider.getConfig());
assertNotNull(cfg2);
assertNotNull(cfg2.getConfigChangeRequest());
assertTrue(cfg1!=cfg2);
@@ -66,7 +65,7 @@ public class MutableConfigurationTest {
@Test(expected=NullPointerException.class)
public void testNullCreateMutableConfiguration1() throws Exception {
MutableConfigurationProvider.createMutableConfiguration(
- (Configuration) null);
+ (javax.config.Config) null);
}
/**
@@ -89,7 +88,7 @@ public class MutableConfigurationTest {
public void testReadWriteProperties_WithCancel() throws IOException {
WritablePropertiesSource.target.delete();
MutableConfiguration mutConfig = MutableConfigurationProvider.createMutableConfiguration(
- ConfigurationProvider.getConfiguration()
+ ConfigProvider.getConfig()
);
mutConfig.put("key1", "value1");
Map<String,String> cm = new HashMap<>();
@@ -106,7 +105,7 @@ public class MutableConfigurationTest {
public void testReadWriteProperties_WithCommit() throws IOException {
WritablePropertiesSource.target.delete();
MutableConfiguration mutConfig = MutableConfigurationProvider.createMutableConfiguration(
- ConfigurationProvider.getConfiguration()
+ ConfigProvider.getConfig()
);
mutConfig.put("key1", "value1");
Map<String,String> cm = new HashMap<>();
@@ -116,7 +115,7 @@ public class MutableConfigurationTest {
mutConfig.store();
assertTrue(WritablePropertiesSource.target.exists());
MutableConfiguration mmutConfig2 = MutableConfigurationProvider.createMutableConfiguration(
- ConfigurationProvider.getConfiguration()
+ ConfigProvider.getConfig()
);
mmutConfig2.remove("foo");
mmutConfig2.remove("key3");
@@ -140,7 +139,7 @@ public class MutableConfigurationTest {
public void testReadWriteXmlProperties_WithCommit() throws IOException {
WritableXmlPropertiesSource.target.delete();
MutableConfiguration cfg = MutableConfigurationProvider.createMutableConfiguration(
- ConfigurationProvider.getConfiguration(), MutableConfigurationProvider.getApplyAllChangePolicy());
+ ConfigProvider.getConfig(), MutableConfigurationProvider.getApplyAllChangePolicy());
cfg.put("key1", "value1");
Map<String,String> cm = new HashMap<>();
cm.put("key2", "value2");
@@ -149,7 +148,7 @@ public class MutableConfigurationTest {
cfg.store();
assertTrue(WritableXmlPropertiesSource.target.exists());
MutableConfiguration cfg2 = MutableConfigurationProvider.createMutableConfiguration(
- ConfigurationProvider.getConfiguration());
+ ConfigProvider.getConfig());
assertTrue(cfg != cfg2);
cfg2.remove("foo");
cfg2.remove("key3");
@@ -172,7 +171,7 @@ public class MutableConfigurationTest {
public void testWriteWithNoChangePolicy() throws IOException {
WritableXmlPropertiesSource.target.delete();
MutableConfiguration cfg = MutableConfigurationProvider.createMutableConfiguration(
- ConfigurationProvider.getConfiguration(),
+ ConfigProvider.getConfig(),
MutableConfigurationProvider.getApplyNonePolicy());
cfg.put("key1", "value1");
Map<String,String> cm = new HashMap<>();
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/internal/PropertiesFileConfigBackendTest.java
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/internal/PropertiesFileConfigBackendTest.java b/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/internal/PropertiesFileConfigBackendTest.java
index e6c79f5..825b6cb 100644
--- a/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/internal/PropertiesFileConfigBackendTest.java
+++ b/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/internal/PropertiesFileConfigBackendTest.java
@@ -18,11 +18,11 @@
*/
package org.apache.tamaya.mutableconfig.internal;
-import org.apache.tamaya.mutableconfig.propertysources.MutablePropertiesPropertySource;
+import org.apache.tamaya.mutableconfig.propertysources.MutablePropertiesConfigSource;
/**
- * Tests for {@link MutablePropertiesPropertySource}.
+ * Tests for {@link MutablePropertiesConfigSource}.
*/
public class PropertiesFileConfigBackendTest {
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/internal/WritablePropertiesSource.java
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/internal/WritablePropertiesSource.java b/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/internal/WritablePropertiesSource.java
index 5257c8b..1d865f2 100644
--- a/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/internal/WritablePropertiesSource.java
+++ b/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/internal/WritablePropertiesSource.java
@@ -18,15 +18,15 @@
*/
package org.apache.tamaya.mutableconfig.internal;
-import org.apache.tamaya.mutableconfig.propertysources.MutablePropertiesPropertySource;
+import org.apache.tamaya.mutableconfig.propertysources.MutablePropertiesConfigSource;
import java.io.File;
import java.io.IOException;
/**
- * Writable test property source based on the {@link MutablePropertiesPropertySource}.
+ * Writable test property source based on the {@link MutablePropertiesConfigSource}.
*/
-public class WritablePropertiesSource extends MutablePropertiesPropertySource {
+public class WritablePropertiesSource extends MutablePropertiesConfigSource {
public static File target = createFile();
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/internal/WritableXmlPropertiesSource.java
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/internal/WritableXmlPropertiesSource.java b/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/internal/WritableXmlPropertiesSource.java
index d6aa7ec..6137c8d 100644
--- a/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/internal/WritableXmlPropertiesSource.java
+++ b/modules/mutable-config/src/test/java/org/apache/tamaya/mutableconfig/internal/WritableXmlPropertiesSource.java
@@ -18,15 +18,15 @@
*/
package org.apache.tamaya.mutableconfig.internal;
-import org.apache.tamaya.mutableconfig.propertysources.MutableXmlPropertiesPropertySource;
+import org.apache.tamaya.mutableconfig.propertysources.MutableXmlPropertiesConfigSource;
import java.io.File;
import java.io.IOException;
/**
- * Writable test property source based on the {@link MutableXmlPropertiesPropertySource}.
+ * Writable test property source based on the {@link MutableXmlPropertiesConfigSource}.
*/
-public class WritableXmlPropertiesSource extends MutableXmlPropertiesPropertySource {
+public class WritableXmlPropertiesSource extends MutableXmlPropertiesConfigSource {
public static File target = createFile();
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/test/resources/META-INF/services/javax.config.spi.ConfigSource
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/test/resources/META-INF/services/javax.config.spi.ConfigSource b/modules/mutable-config/src/test/resources/META-INF/services/javax.config.spi.ConfigSource
new file mode 100644
index 0000000..609b9fe
--- /dev/null
+++ b/modules/mutable-config/src/test/resources/META-INF/services/javax.config.spi.ConfigSource
@@ -0,0 +1,20 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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 current 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.
+#
+org.apache.tamaya.mutableconfig.internal.WritablePropertiesSource
+org.apache.tamaya.mutableconfig.internal.WritableXmlPropertiesSource
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource b/modules/mutable-config/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
deleted file mode 100644
index 609b9fe..0000000
--- a/modules/mutable-config/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
+++ /dev/null
@@ -1,20 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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 current 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.
-#
-org.apache.tamaya.mutableconfig.internal.WritablePropertiesSource
-org.apache.tamaya.mutableconfig.internal.WritableXmlPropertiesSource
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/optional/pom.xml
----------------------------------------------------------------------
diff --git a/modules/optional/pom.xml b/modules/optional/pom.xml
index 341f547..566056b 100644
--- a/modules/optional/pom.xml
+++ b/modules/optional/pom.xml
@@ -37,13 +37,6 @@ under the License.
<dependencies>
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-api</artifactId>
- <version>${tamaya-apicore.version}</version>
- <scope>provided</scope>
- <optional>true</optional>
- </dependency>
- <dependency>
- <groupId>org.apache.tamaya</groupId>
<artifactId>tamaya-core</artifactId>
<version>${tamaya-apicore.version}</version>
<scope>provided</scope>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/optional/src/main/java/org/apache/tamaya/optional/OptionalConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/optional/src/main/java/org/apache/tamaya/optional/OptionalConfiguration.java b/modules/optional/src/main/java/org/apache/tamaya/optional/OptionalConfiguration.java
index 1d59cda..10789c4 100644
--- a/modules/optional/src/main/java/org/apache/tamaya/optional/OptionalConfiguration.java
+++ b/modules/optional/src/main/java/org/apache/tamaya/optional/OptionalConfiguration.java
@@ -20,8 +20,7 @@ package org.apache.tamaya.optional;
import java.util.Objects;
-
-import org.apache.tamaya.ConfigurationProvider;
+import javax.config.ConfigProvider;
/**
* Simplified configuration API, that can be used by code that only wants Tamaya to optionally enhance its configuration
@@ -32,21 +31,21 @@ public final class OptionalConfiguration {
/**
* Flag only true, if Tamaya is on the classpath.
*/
- private static final boolean TAMAYA_LOADED = initTamayaLoaded();
+ private static final boolean CONFIG_LOADED = initConfigLoaded();
/**
* Configuration API to be loaded.
*/
- private static final String TAMAYA_CONFIGURATION = "org.apache.tamaya.Configuration";
+ private static final String JAVAX_CONFIGURATION = "javax.config.Config";
/**
* Tries to load the Tamaya Configuration interface from the classpath.
*
* @return true, if the interface is available.
*/
- private static boolean initTamayaLoaded() {
+ private static boolean initConfigLoaded() {
try {
- Class.forName(TAMAYA_CONFIGURATION);
+ Class.forName(JAVAX_CONFIGURATION);
return true;
} catch (final Exception e) {
return false;
@@ -57,8 +56,8 @@ public final class OptionalConfiguration {
* Allows to check if Tamaya is on the classpath.
* @return true, if Tamaya is available.
*/
- public static boolean isTamayaLoaded(){
- return TAMAYA_LOADED;
+ public static boolean isConfigLoaded(){
+ return CONFIG_LOADED;
}
/**
@@ -178,7 +177,7 @@ public final class OptionalConfiguration {
case THROWS_EXCEPTION:
if (tamayaValue != value) {
if ((tamayaValue != null && !tamayaValue.equals(value)) ||
- (value != null && TAMAYA_LOADED && !value.equals(tamayaValue))) {
+ (value != null && CONFIG_LOADED && !value.equals(tamayaValue))) {
throw new IllegalStateException("Incompatible configuration values: key=" + key +
"=" + value + "(provider)/" + tamayaValue + "(Tamaya");
}
@@ -214,11 +213,11 @@ public final class OptionalConfiguration {
* @param <T> The type param
* @return the corresponding value from Tamaya, or null.
* @throws IllegalStateException if Tamaya is not loaded.
- * @see #isTamayaLoaded()
+ * @see #isConfigLoaded()
*/
private <T> T getTamaya(String key, Class<T> type) {
- if (TAMAYA_LOADED) {
- return ConfigurationProvider.getConfiguration().get(key, type);
+ if (CONFIG_LOADED) {
+ return ConfigProvider.getConfig().getValue(key, type);
}
throw new IllegalStateException("Tamaya is not loaded.");
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/common/bnd.bnd
----------------------------------------------------------------------
diff --git a/modules/osgi/common/bnd.bnd b/modules/osgi/common/bnd.bnd
index e937379..fc550e2 100644
--- a/modules/osgi/common/bnd.bnd
+++ b/modules/osgi/common/bnd.bnd
@@ -29,5 +29,5 @@ Import-Package: \
org.apache.tamaya,\
org.apache.tamaya.spi,\
org.apache.tamaya.functions,\
- org.apache.tamaya.spisupport
+ org.apache.tamaya.base
Export-Service: org.apache.tamaya.osgi.commands.TamayaConfigService
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/common/pom.xml
----------------------------------------------------------------------
diff --git a/modules/osgi/common/pom.xml b/modules/osgi/common/pom.xml
index 57c56c3..847e2b3 100644
--- a/modules/osgi/common/pom.xml
+++ b/modules/osgi/common/pom.xml
@@ -53,12 +53,7 @@
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-api</artifactId>
- <version>${project.parent.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-core</artifactId>
+ <artifactId>tamaya-base</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
@@ -68,8 +63,9 @@
</dependency>
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-spisupport</artifactId>
+ <artifactId>tamaya-core</artifactId>
<version>${project.parent.version}</version>
+ <scope>test</scope>
</dependency>
<!-- Testing -->
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/common/src/main/java/org/apache/tamaya/osgi/ConfigChanger.java
----------------------------------------------------------------------
diff --git a/modules/osgi/common/src/main/java/org/apache/tamaya/osgi/ConfigChanger.java b/modules/osgi/common/src/main/java/org/apache/tamaya/osgi/ConfigChanger.java
index 0969a59..170cebf 100644
--- a/modules/osgi/common/src/main/java/org/apache/tamaya/osgi/ConfigChanger.java
+++ b/modules/osgi/common/src/main/java/org/apache/tamaya/osgi/ConfigChanger.java
@@ -18,7 +18,6 @@
*/
package org.apache.tamaya.osgi;
-import org.apache.tamaya.ConfigurationProvider;
import org.apache.tamaya.functions.ConfigurationFunctions;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
@@ -26,6 +25,8 @@ import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
+import javax.config.Config;
+import javax.config.ConfigProvider;
import java.io.IOException;
import java.util.Date;
import java.util.Dictionary;
@@ -102,7 +103,7 @@ final class ConfigChanger {
LOG.finest("Stored OSGI configuration backup for PID: " + pid);
}
LOG.finest("Evaluating Tamaya Config for PID: " + pid);
- org.apache.tamaya.Configuration tamayaConfig = getTamayaConfiguration(root);
+ Config tamayaConfig = getJavaConfiguration(root);
if (tamayaConfig == null) {
LOG.finest("No Tamaya configuration for root: " + root);
}else {
@@ -136,7 +137,7 @@ final class ConfigChanger {
}
}
- public void modifyConfiguration(String pid, org.apache.tamaya.Configuration config, Dictionary<String, Object> dictionary, Policy opMode) {
+ public void modifyConfiguration(String pid, Config config, Dictionary<String, Object> dictionary, Policy opMode) {
LOG.info(() -> "Updating configuration for PID: " + pid + "...");
dictionary.put("tamaya.modified.at", new Date().toString());
@@ -148,7 +149,7 @@ final class ConfigChanger {
dictionaryMap.put(key, value);
}
for (Map.Entry<String, Object> dictEntry : dictionaryMap.entrySet()) {
- Object configuredValue = config.getOrDefault(dictEntry.getKey(), dictEntry.getValue().getClass(), null);
+ Object configuredValue = config.getOptionalValue(dictEntry.getKey(), dictEntry.getValue().getClass()).orElse(null);
if (configuredValue != null) {
if(configuredValue.equals(dictEntry.getValue())){
continue;
@@ -168,39 +169,40 @@ final class ConfigChanger {
}
}
}
- for (Map.Entry<String, String> configEntry : config.getProperties().entrySet()) {
- Object dictValue = dictionary.get(configEntry.getKey());
- if(dictValue!=null && dictValue.equals(configEntry.getValue())){
+ for (String configKey : config.getPropertyNames()) {
+ Object dictValue = dictionary.get(configKey);
+ String configValue = config.getValue(configKey, String.class);
+ if(dictValue!=null && dictValue.equals(configValue)){
continue;
}
switch (opMode) {
case EXTEND:
if(dictValue==null){
- LOG.info(() -> "Setting key " + configEntry.getKey() + " to " + configEntry.getValue());
- ConfigHistory.propertySet(pid,configEntry.getKey(), configEntry.getValue(), null);
- dictionary.put(configEntry.getKey(), configEntry.getValue());
+ LOG.info(() -> "Setting key " + configKey + " to " + configValue);
+ ConfigHistory.propertySet(pid,configKey, configValue, null);
+ dictionary.put(configKey, configValue);
}
break;
case OVERRIDE:
- LOG.info(() -> "Setting key " + configEntry.getKey() + " to " + configEntry.getValue());
- ConfigHistory.propertySet(pid,configEntry.getKey(), configEntry.getValue(), null);
- dictionary.put(configEntry.getKey(), configEntry.getValue());
+ LOG.info(() -> "Setting key " + configKey + " to " + configValue);
+ ConfigHistory.propertySet(pid,configKey, configValue, null);
+ dictionary.put(configKey, configValue);
break;
case UPDATE_ONLY:
if(dictValue!=null){
- LOG.info(() -> "Setting key " + configEntry.getKey() + " to " + configEntry.getValue());
- ConfigHistory.propertySet(pid,configEntry.getKey(), configEntry.getValue(), dictValue);
- dictionary.put(configEntry.getKey(), configEntry.getValue());
+ LOG.info(() -> "Setting key " + configKey + " to " + configValue);
+ ConfigHistory.propertySet(pid,configKey, configValue, dictValue);
+ dictionary.put(configKey, configValue);
}
break;
}
}
}
- public org.apache.tamaya.Configuration getTamayaConfiguration(String root) {
+ public Config getJavaConfiguration(String root) {
if (root != null) {
- return ConfigurationProvider.getConfiguration()
- .with(ConfigurationFunctions.section(root, true));
+ return ConfigurationFunctions.section(root, true)
+ .apply(ConfigProvider.getConfig());
}
return null;
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/common/src/main/java/org/apache/tamaya/osgi/TamayaConfigPlugin.java
----------------------------------------------------------------------
diff --git a/modules/osgi/common/src/main/java/org/apache/tamaya/osgi/TamayaConfigPlugin.java b/modules/osgi/common/src/main/java/org/apache/tamaya/osgi/TamayaConfigPlugin.java
index 6c9c685..5d16ba7 100644
--- a/modules/osgi/common/src/main/java/org/apache/tamaya/osgi/TamayaConfigPlugin.java
+++ b/modules/osgi/common/src/main/java/org/apache/tamaya/osgi/TamayaConfigPlugin.java
@@ -23,6 +23,7 @@ import org.osgi.framework.*;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
+import javax.config.Config;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
@@ -323,8 +324,8 @@ public class TamayaConfigPlugin implements TamayaConfigService,BundleListener, S
}
- public org.apache.tamaya.Configuration getTamayaConfiguration(String root) {
- return configChanger.getTamayaConfiguration(root);
+ public Config getJavaConfiguration(String root) {
+ return configChanger.getJavaConfiguration(root);
}
@Override
[14/18] incubator-tamaya-extensions git commit: Rewrite/adaptation
based on JSR API.
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredFieldImpl.java
----------------------------------------------------------------------
diff --git a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredFieldImpl.java b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredFieldImpl.java
index e39b070..699208e 100644
--- a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredFieldImpl.java
+++ b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredFieldImpl.java
@@ -18,18 +18,18 @@
*/
package org.apache.tamaya.inject.internal;
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
-import org.apache.tamaya.TypeLiteral;
import org.apache.tamaya.inject.api.DynamicValue;
-import org.apache.tamaya.inject.spi.InjectionUtils;
+import org.apache.tamaya.inject.spi.InjectionEvaluator;
import org.apache.tamaya.inject.spi.ConfiguredField;
+import javax.config.Config;
+import javax.config.ConfigProvider;
import java.lang.reflect.Field;
+import java.lang.reflect.Type;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.util.Collection;
+import java.util.NoSuchElementException;
import java.util.Objects;
/**
@@ -58,9 +58,9 @@ public class ConfiguredFieldImpl implements ConfiguredField{
* Evaluate the initial keys from the configuration and apply changes to the field.
*
* @param target the target instance.
- * @throws ConfigException if evaluation or conversion failed.
+ * @throws java.util.NoSuchElementException if evaluation or conversion failed.
*/
- public void configure(Object target, Configuration config) throws ConfigException {
+ public void configure(Object target, Config config) {
if (this.annotatedField.getType() == DynamicValue.class) {
applyDynamicValue(target);
} else {
@@ -73,9 +73,9 @@ public class ConfiguredFieldImpl implements ConfiguredField{
* This method instantiates and assigns a dynamic value.
*
* @param target the target instance, not null.
- * @throws ConfigException if the configuration required could not be resolved or converted.
+ * @throws NoSuchElementException if the configuration required could not be resolved or converted.
*/
- private void applyDynamicValue(Object target) throws ConfigException {
+ private void applyDynamicValue(Object target) {
Objects.requireNonNull(target);
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@@ -83,13 +83,13 @@ public class ConfiguredFieldImpl implements ConfiguredField{
public Object run() throws Exception {
annotatedField.setAccessible(true);
annotatedField.set(target,
- DefaultDynamicValue.of(target, annotatedField, ConfigurationProvider.getConfiguration()));
+ DefaultDynamicValue.of(target, annotatedField, ConfigProvider.getConfig()));
return annotatedField;
}
});
} catch (Exception e) {
- throw new ConfigException("Failed to annotation configured field: " + this.annotatedField.getDeclaringClass()
- .getName() + '.' + annotatedField.getName(), e);
+ throw new NoSuchElementException("Failed to annotation configured field: " + this.annotatedField.getDeclaringClass()
+ .getName() + '.' + annotatedField.getName()+": " + e);
}
}
@@ -99,34 +99,28 @@ public class ConfiguredFieldImpl implements ConfiguredField{
* @param target the target instance, not null.
* @param config The configuration to be used.
* @param resolve set to true, if expression resolution should be applied on the keys passed.
- * @throws ConfigException if the configuration required could not be resolved or converted.
+ * @throws NoSuchElementException if the configuration required could not be resolved or converted.
*/
- private void applyValue(Object target, Configuration config, boolean resolve) throws ConfigException {
+ private void applyValue(Object target, Config config, boolean resolve) {
Objects.requireNonNull(target);
try {
- String[] retKey = new String[1];
- String configValue = InjectionHelper.getConfigValue(this.annotatedField, retKey, config);
- // Next step perform expression resolution, if any
- String evaluatedValue = resolve && configValue != null
- ? InjectionHelper.evaluateValue(configValue)
- : configValue;
-
- // Check for adapter/filter
- Object value = InjectionHelper.adaptValue(this.annotatedField,
- TypeLiteral.of(this.annotatedField.getType()), retKey[0], evaluatedValue);
+ Class targetType = this.annotatedField.getType();
+ Object configValue = InjectionHelper.getConfigValue(this.annotatedField, targetType, config);
+
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
annotatedField.setAccessible(true);
- if(value!=null) {
- annotatedField.set(target, value);
+ if(configValue!=null) {
+ annotatedField.set(target, configValue);
}
return annotatedField;
}
});
} catch (Exception e) {
- throw new ConfigException("Failed to evaluate annotated field: " + this.annotatedField.getDeclaringClass()
- .getName() + '.' + annotatedField.getName(), e);
+ e.printStackTrace();
+ throw new NoSuchElementException("Failed to evaluate annotated field: " + this.annotatedField.getDeclaringClass()
+ .getName() + '.' + annotatedField.getName()+": "+ e);
}
}
@@ -145,7 +139,7 @@ public class ConfiguredFieldImpl implements ConfiguredField{
*/
@Override
public Collection<String> getConfiguredKeys(){
- return InjectionUtils.getKeys(this.annotatedField);
+ return InjectionEvaluator.getKeys(this.annotatedField);
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredSetterMethod.java
----------------------------------------------------------------------
diff --git a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredSetterMethod.java b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredSetterMethod.java
index b10300e..7ea94d0 100644
--- a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredSetterMethod.java
+++ b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredSetterMethod.java
@@ -18,16 +18,16 @@
*/
package org.apache.tamaya.inject.internal;
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.TypeLiteral;
-import org.apache.tamaya.inject.spi.InjectionUtils;
+import org.apache.tamaya.inject.spi.InjectionEvaluator;
import org.apache.tamaya.inject.spi.ConfiguredMethod;
+import javax.config.Config;
import java.lang.reflect.Method;
+import java.lang.reflect.Type;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.util.Collection;
+import java.util.NoSuchElementException;
import java.util.Objects;
/**
@@ -55,20 +55,11 @@ public class ConfiguredSetterMethod implements ConfiguredMethod {
}
@Override
- public void configure(Object target, Configuration config) throws ConfigException {
- String[] retKey = new String[1];
- String configValue = InjectionHelper.getConfigValue(this.setterMethod, retKey, config);
+ public void configure(Object target, Config config) {
+ Class targetType = this.setterMethod.getParameterTypes()[0];
+ Object configValue = InjectionHelper.getConfigValue(this.setterMethod, targetType, config);
Objects.requireNonNull(target);
try {
- String evaluatedString = configValue != null
- ? InjectionHelper.evaluateValue(configValue)
- : configValue;
-
- // Check for adapter/filter
- Object value = InjectionHelper.adaptValue(
- this.setterMethod, TypeLiteral.of(this.setterMethod.getParameterTypes()[0]),
- retKey[0], evaluatedString);
-
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
@@ -76,11 +67,10 @@ public class ConfiguredSetterMethod implements ConfiguredMethod {
return setterMethod;
}
});
-
- setterMethod.invoke(target, value);
+ setterMethod.invoke(target, configValue);
} catch (Exception e) {
- throw new ConfigException("Failed to annotation configured method: " + this.setterMethod.getDeclaringClass()
- .getName() + '.' + setterMethod.getName(), e);
+ throw new NoSuchElementException("Failed to annotation configured method: " + this.setterMethod.getDeclaringClass()
+ .getName() + '.' + setterMethod.getName()+": "+ e);
}
}
@@ -92,7 +82,7 @@ public class ConfiguredSetterMethod implements ConfiguredMethod {
*/
@Override
public Collection<String> getConfiguredKeys() {
- return InjectionUtils.getKeys(this.setterMethod);
+ return InjectionEvaluator.getKeys(this.setterMethod);
}
/**
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredTypeImpl.java
----------------------------------------------------------------------
diff --git a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredTypeImpl.java b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredTypeImpl.java
index 85f1f4a..25bd051 100644
--- a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredTypeImpl.java
+++ b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfiguredTypeImpl.java
@@ -24,17 +24,17 @@ import java.lang.reflect.Modifier;
import java.util.*;
import java.util.logging.Logger;
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
-import org.apache.tamaya.inject.api.ConfigAutoInject;
+import org.apache.tamaya.inject.api.ConfigAutoDetect;
+import org.apache.tamaya.inject.api.ConfigFallbackKeys;
import org.apache.tamaya.inject.api.NoConfig;
-import org.apache.tamaya.inject.api.Config;
import org.apache.tamaya.inject.api.ConfigDefaultSections;
import org.apache.tamaya.inject.spi.ConfiguredField;
import org.apache.tamaya.inject.spi.ConfiguredMethod;
import org.apache.tamaya.inject.spi.ConfiguredType;
+import javax.config.ConfigProvider;
+import javax.config.inject.ConfigProperty;
+
/**
* Structure that contains and manages configuration related things for a configured type registered.
* Created by Anatole on 03.10.2014.
@@ -69,7 +69,7 @@ public class ConfiguredTypeImpl implements ConfiguredType{
initFields(type, true);
initMethods(type, true);
}else {
- ConfigAutoInject autoInject = (ConfigAutoInject) type.getAnnotation(ConfigAutoInject.class);
+ ConfigAutoDetect autoInject = (ConfigAutoDetect) type.getAnnotation(ConfigAutoDetect.class);
if (autoInject != null) {
initFields(type, autoInject != null);
initMethods(type, autoInject != null);
@@ -108,8 +108,8 @@ public class ConfiguredTypeImpl implements ConfiguredType{
f.toGenericString());
}
} catch (Exception e) {
- throw new ConfigException("Failed to initialized configured field: " +
- f.getDeclaringClass().getName() + '.' + f.getName(), e);
+ throw new NoSuchElementException("Failed to initialized configured field: " +
+ f.getDeclaringClass().getName() + '.' + f.getName()+": "+ e);
}
}
}
@@ -131,8 +131,10 @@ public class ConfiguredTypeImpl implements ConfiguredType{
continue;
}
if(isConfiguredMethod(m) || autoConfigure) {
- Config propAnnot = m.getAnnotation(Config.class);
- if (addPropertySetter(m, propAnnot)) {
+ if (addPropertySetter(
+ m,
+ m.getAnnotation(ConfigProperty.class),
+ m.getAnnotation(ConfigFallbackKeys.class))) {
LOG.finer("Added configured setter: " + m.getClass().getName() + "#" +
m.toGenericString());
}
@@ -140,7 +142,7 @@ public class ConfiguredTypeImpl implements ConfiguredType{
}
}
- private boolean addPropertySetter(Method m, Config prop) {
+ private boolean addPropertySetter(Method m, ConfigProperty prop, ConfigFallbackKeys fallbackKeys) {
if (prop!=null) {
if (m.getParameterTypes().length == 1) {
// getter method
@@ -150,8 +152,8 @@ public class ConfiguredTypeImpl implements ConfiguredType{
configuredSetterMethods.add(new ConfiguredSetterMethod(m));
return true;
} catch (Exception e) {
- throw new ConfigException("Failed to initialize configured setter method: " +
- m.getDeclaringClass().getName() + '.' + m.getName(), e);
+ throw new NoSuchElementException("Failed to initialize configured setter method: " +
+ m.getDeclaringClass().getName() + '.' + m.getName()+": "+ e);
}
}
}
@@ -166,11 +168,11 @@ public class ConfiguredTypeImpl implements ConfiguredType{
* @param instance The instance to be configured.
*/
public void configure(Object instance) {
- configure(instance, ConfigurationProvider.getConfiguration());
+ configure(instance, ConfigProvider.getConfig());
}
@Override
- public void configure(Object instance, Configuration config) {
+ public void configure(Object instance, javax.config.Config config) {
for (ConfiguredField field : configuredFields) {
field.configure(instance, config);
}
@@ -204,11 +206,11 @@ public class ConfiguredTypeImpl implements ConfiguredType{
}
public static boolean isConfiguredField(Field field) {
- return field.isAnnotationPresent(Config.class);
+ return field.isAnnotationPresent(ConfigProperty.class);
}
public static boolean isConfiguredMethod(Method method) {
- return method.isAnnotationPresent(Config.class);
+ return method.isAnnotationPresent(ConfigProperty.class);
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultConfigurationInjector.java
----------------------------------------------------------------------
diff --git a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultConfigurationInjector.java b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultConfigurationInjector.java
index 7b3fb61..b3fa28a 100644
--- a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultConfigurationInjector.java
+++ b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultConfigurationInjector.java
@@ -18,11 +18,11 @@
*/
package org.apache.tamaya.inject.internal;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
import org.apache.tamaya.inject.ConfigurationInjector;
import javax.annotation.Priority;
+import javax.config.ConfigProvider;
+import javax.config.inject.ConfigProperty;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
@@ -33,7 +33,6 @@ import java.util.function.Supplier;
import java.util.logging.Logger;
import org.apache.tamaya.inject.api.NoConfig;
-import org.apache.tamaya.inject.api.Config;
import org.apache.tamaya.inject.api.ConfigDefaultSections;
import org.apache.tamaya.inject.spi.ConfiguredType;
import org.osgi.service.component.annotations.Component;
@@ -57,13 +56,26 @@ public class DefaultConfigurationInjector implements ConfigurationInjector {
* @param type the type to be configured.
* @return the configured type registered.
*/
- public ConfiguredType registerType(Class<?> type) {
+ public ConfiguredType getConfiguredType(Class<?> type) {
ConfiguredType confType = configuredTypes.get(type);
if (confType == null) {
if(!isConfigAnnotated(type) && !autoConfigureEnabled){
return null;
}
confType = new ConfiguredTypeImpl(type);
+ }
+ return confType;
+ }
+
+ /**
+ * Extract the configuration annotation config and registers it per class, for later reuse.
+ *
+ * @param type the type to be configured.
+ * @return the configured type registered.
+ */
+ public ConfiguredType registerType(Class<?> type) {
+ ConfiguredType confType = getConfiguredType(type);
+ if (confType != null) {
configuredTypes.put(type, confType);
InjectionHelper.sendConfigurationEvent(confType);
}
@@ -97,12 +109,12 @@ public class DefaultConfigurationInjector implements ConfigurationInjector {
return true;
}
for (Field f : type.getDeclaredFields()) {
- if (f.isAnnotationPresent(NoConfig.class) || f.isAnnotationPresent(Config.class)) {
+ if (f.isAnnotationPresent(NoConfig.class) || f.isAnnotationPresent(ConfigProperty.class)) {
return true;
}
}
for (Method m : type.getDeclaredMethods()) {
- if (m.isAnnotationPresent(NoConfig.class) || m.isAnnotationPresent(Config.class)) {
+ if (m.isAnnotationPresent(NoConfig.class) || m.isAnnotationPresent(ConfigProperty.class)) {
return true;
}
}
@@ -117,7 +129,7 @@ public class DefaultConfigurationInjector implements ConfigurationInjector {
*/
@Override
public <T> T configure(T instance) {
- return configure(instance, ConfigurationProvider.getConfiguration());
+ return configure(instance, ConfigProvider.getConfig());
}
/**
@@ -128,7 +140,7 @@ public class DefaultConfigurationInjector implements ConfigurationInjector {
* @param config the target configuration, not null.
*/
@Override
- public <T> T configure(T instance, Configuration config) {
+ public <T> T configure(T instance, javax.config.Config config) {
Class<?> type = Objects.requireNonNull(instance).getClass();
ConfiguredType configuredType = registerType(type);
if(configuredType!=null){
@@ -146,7 +158,7 @@ public class DefaultConfigurationInjector implements ConfigurationInjector {
*/
@Override
public <T> T createTemplate(Class<T> templateType) {
- return createTemplate(templateType, ConfigurationProvider.getConfiguration());
+ return createTemplate(templateType, ConfigProvider.getConfig());
}
/**
@@ -156,7 +168,7 @@ public class DefaultConfigurationInjector implements ConfigurationInjector {
* @param config the target configuration, not null.
*/
@Override
- public <T> T createTemplate(Class<T> templateType, Configuration config) {
+ public <T> T createTemplate(Class<T> templateType, javax.config.Config config) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if(cl==null){
cl = this.getClass().getClassLoader();
@@ -167,15 +179,16 @@ public class DefaultConfigurationInjector implements ConfigurationInjector {
@Override
public <T> Supplier<T> getConfiguredSupplier(final Supplier<T> supplier) {
- return getConfiguredSupplier(supplier, ConfigurationProvider.getConfiguration());
+ return getConfiguredSupplier(supplier, ConfigProvider.getConfig());
}
@Override
- public <T> Supplier<T> getConfiguredSupplier(final Supplier<T> supplier, final Configuration config) {
- return new Supplier<T>() {
- public T get() {
- return configure(supplier.get(), config);
- }
- };
+ public <T> Supplier<T> getConfiguredSupplier(final Supplier<T> supplier, final javax.config.Config config) {
+ return () -> configure(supplier.get(), config);
+ }
+
+ @Override
+ public boolean isConfigured(Object o) {
+ return getConfiguredType(o.getClass())!=null;
}
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultDynamicValue.java
----------------------------------------------------------------------
diff --git a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultDynamicValue.java b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultDynamicValue.java
index ac7e977..f0763a8 100644
--- a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultDynamicValue.java
+++ b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/DefaultDynamicValue.java
@@ -18,34 +18,26 @@
*/
package org.apache.tamaya.inject.internal;
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.TypeLiteral;
import org.apache.tamaya.inject.api.DynamicValue;
-import org.apache.tamaya.inject.spi.InjectionUtils;
+import org.apache.tamaya.inject.spi.InjectionEvaluator;
import org.apache.tamaya.inject.api.LoadPolicy;
import org.apache.tamaya.inject.api.UpdatePolicy;
-import org.apache.tamaya.inject.api.WithPropertyConverter;
+import org.apache.tamaya.inject.api.WithConverter;
import org.apache.tamaya.inject.spi.BaseDynamicValue;
-import org.apache.tamaya.spi.ConversionContext;
-import org.apache.tamaya.spi.PropertyConverter;
-import java.beans.PropertyChangeEvent;
-import java.beans.PropertyChangeListener;
+import javax.config.Config;
+import javax.config.spi.Converter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
-import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.LinkedList;
import java.util.List;
+import java.util.NoSuchElementException;
import java.util.Objects;
-import java.util.function.Supplier;
+import java.util.Optional;
import java.util.logging.Logger;
/**
@@ -70,11 +62,11 @@ final class DefaultDynamicValue<T> extends BaseDynamicValue<T> {
* Back reference to the base configuration instance. This reference is used reevaluate the given property and
* compare the result with the previous value after a configuration change was triggered.
*/
- private final Configuration configuration;
+ private final Config configuration;
/**
* The property converter to be applied, may be null. In the ladder case targetType is not null.
*/
- private final PropertyConverter<T> propertyConverter;
+ private final Converter<T> propertyConverter;
/**
* Load policy.
@@ -90,8 +82,8 @@ final class DefaultDynamicValue<T> extends BaseDynamicValue<T> {
* @param targetType the target type, not null.
* @param propertyConverter the optional converter to be used.
*/
- private DefaultDynamicValue(Object owner, String propertyName, Configuration configuration, TypeLiteral<T> targetType,
- PropertyConverter<T> propertyConverter, List<String> keys, LoadPolicy loadPolicy,
+ private DefaultDynamicValue(Object owner, String propertyName, Config configuration, Type targetType,
+ Converter<T> propertyConverter, List<String> keys, LoadPolicy loadPolicy,
UpdatePolicy updatePolicy) {
super(owner, propertyName, targetType, keys);
this.configuration = Objects.requireNonNull(configuration);
@@ -103,102 +95,102 @@ final class DefaultDynamicValue<T> extends BaseDynamicValue<T> {
}
}
- public static DynamicValue<?> of(Object owner, Field annotatedField, Configuration configuration) {
+ public static DynamicValue<?> of(Object owner, Field annotatedField, Config configuration) {
return of(owner, annotatedField, configuration, LoadPolicy.ALWAYS, UpdatePolicy.IMMEDIATE);
}
- public static DynamicValue<?> of(Object owner, Field annotatedField, Configuration configuration, LoadPolicy loadPolicy) {
+ public static DynamicValue<?> of(Object owner, Field annotatedField, Config configuration, LoadPolicy loadPolicy) {
return of(owner, annotatedField, configuration, loadPolicy, UpdatePolicy.IMMEDIATE);
}
- public static DynamicValue<?> of(Object owner, Field annotatedField, Configuration configuration, UpdatePolicy updatePolicy) {
+ public static DynamicValue<?> of(Object owner, Field annotatedField, Config configuration, UpdatePolicy updatePolicy) {
return of(owner, annotatedField, configuration, LoadPolicy.ALWAYS, updatePolicy);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
- public static DynamicValue<?> of(Object owner, Field annotatedField, Configuration configuration, LoadPolicy loadPolicy, UpdatePolicy updatePolicy) {
+ public static DynamicValue<?> of(Object owner, Field annotatedField, Config configuration, LoadPolicy loadPolicy, UpdatePolicy updatePolicy) {
// Check for adapter/filter
Type targetType = annotatedField.getGenericType();
if (targetType == null) {
- throw new ConfigException("Failed to evaluate target type for " + annotatedField.getDeclaringClass().getName()
+ throw new IllegalArgumentException("Failed to evaluate target type for " + annotatedField.getDeclaringClass().getName()
+ '.' + annotatedField.getName());
}
if (targetType instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) targetType;
Type[] types = pt.getActualTypeArguments();
if (types.length != 1) {
- throw new ConfigException("Failed to evaluate target type for " + annotatedField.getDeclaringClass().getName()
+ throw new IllegalArgumentException("Failed to evaluate target type for " + annotatedField.getDeclaringClass().getName()
+ '.' + annotatedField.getName());
}
targetType = types[0];
}
- PropertyConverter<?> propertyConverter = null;
- WithPropertyConverter annot = annotatedField.getAnnotation(WithPropertyConverter.class);
+ Converter<?> propertyConverter = null;
+ WithConverter annot = annotatedField.getAnnotation(WithConverter.class);
if (annot != null) {
try {
propertyConverter = annot.value().newInstance();
} catch (Exception e) {
- throw new ConfigException("Failed to instantiate annotated PropertyConverter on " +
+ throw new IllegalArgumentException("Failed to instantiate annotated PropertyConverter on " +
annotatedField.getDeclaringClass().getName()
+ '.' + annotatedField.getName(), e);
}
}
- List<String> keys = InjectionUtils.getKeys(annotatedField);
+ List<String> keys = InjectionEvaluator.getKeys(annotatedField);
return new DefaultDynamicValue(owner, annotatedField.getName(), configuration,
- TypeLiteral.of(targetType), propertyConverter, keys, loadPolicy, updatePolicy);
+ targetType, propertyConverter, keys, loadPolicy, updatePolicy);
}
- public static DynamicValue<?> of(Object owner, Method method, Configuration configuration) {
+ public static DynamicValue<?> of(Object owner, Method method, Config configuration) {
return of(owner, method, configuration, LoadPolicy.ALWAYS, UpdatePolicy.IMMEDIATE);
}
- public static DynamicValue<?> of(Object owner, Method method, Configuration configuration, UpdatePolicy updatePolicy) {
+ public static DynamicValue<?> of(Object owner, Method method, Config configuration, UpdatePolicy updatePolicy) {
return of(owner, method, configuration, LoadPolicy.ALWAYS, updatePolicy);
}
- public static DynamicValue<?> of(Object owner, Method method, Configuration configuration, LoadPolicy loadPolicy) {
+ public static DynamicValue<?> of(Object owner, Method method, Config configuration, LoadPolicy loadPolicy) {
return of(owner, method, configuration, loadPolicy, UpdatePolicy.IMMEDIATE);
}
@SuppressWarnings("unchecked")
- public static DynamicValue<?> of(Object owner, Method method, Configuration configuration, LoadPolicy loadPolicy, UpdatePolicy updatePolicy) {
+ public static DynamicValue<?> of(Object owner, Method method, Config configuration, LoadPolicy loadPolicy, UpdatePolicy updatePolicy) {
// Check for adapter/filter
Type targetType = method.getGenericReturnType();
if (targetType == null) {
- throw new ConfigException("Failed to evaluate target type for " + method.getDeclaringClass()
+ throw new IllegalArgumentException("Failed to evaluate target type for " + method.getDeclaringClass()
.getName() + '.' + method.getName());
}
if (targetType instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) targetType;
Type[] types = pt.getActualTypeArguments();
if (types.length != 1) {
- throw new ConfigException("Failed to evaluate target type for " + method.getDeclaringClass()
+ throw new IllegalArgumentException("Failed to evaluate target type for " + method.getDeclaringClass()
.getName() + '.' + method.getName());
}
targetType = types[0];
}
- PropertyConverter<Object> propertyConverter = null;
- WithPropertyConverter annot = method.getAnnotation(WithPropertyConverter.class);
+ Converter<Object> propertyConverter = null;
+ WithConverter annot = method.getAnnotation(WithConverter.class);
if (annot != null) {
try {
- propertyConverter = (PropertyConverter<Object>) annot.value().newInstance();
+ propertyConverter = (Converter<Object>) annot.value().newInstance();
} catch (Exception e) {
- throw new ConfigException("Failed to instantiate annotated PropertyConverter on " +
+ throw new IllegalArgumentException("Failed to instantiate annotated PropertyConverter on " +
method.getDeclaringClass().getName()
+ '.' + method.getName(), e);
}
}
- return new DefaultDynamicValue<>(owner, method.getName(),
- configuration, TypeLiteral.of(targetType), propertyConverter, InjectionUtils.getKeys(method),
+ return new DefaultDynamicValue(owner, method.getName(),
+ configuration, targetType, propertyConverter, InjectionEvaluator.getKeys(method),
loadPolicy, updatePolicy);
}
- protected PropertyConverter getCustomConverter(){
+ protected Converter getCustomConverter(){
return this.propertyConverter;
}
@Override
- protected Configuration getConfiguration() {
+ protected Config getConfiguration() {
return configuration;
}
@@ -207,10 +199,23 @@ final class DefaultDynamicValue<T> extends BaseDynamicValue<T> {
* otherwise throws {@code ConfigException}.
*
* @return the non-null value held by this {@code Optional}
- * @throws ConfigException if there is no value present
+ * @throws java.util.NoSuchElementException if there is no value present
* @see DefaultDynamicValue#isPresent()
*/
- public T get() {
+ public T getValue() {
+ return getOptionalValue()
+ .orElseThrow(() -> new NoSuchElementException("No config value for: " + getKeys()));
+ }
+
+ /**
+ * If a value is present in this {@code DynamicValue}, returns the value,
+ * otherwise throws {@code ConfigException}.
+ *
+ * @return the non-null value held by this {@code Optional}
+ * @throws java.util.NoSuchElementException if there is no value present
+ * @see DefaultDynamicValue#isPresent()
+ */
+ public Optional<T> getOptionalValue() {
T newLocalValue;
if(loadPolicy!=LoadPolicy.INITIAL) {
newLocalValue = evaluateValue();
@@ -219,11 +224,9 @@ final class DefaultDynamicValue<T> extends BaseDynamicValue<T> {
}
if(!Objects.equals(this.value, newLocalValue)){
switch (getUpdatePolicy()){
- case IMMEDEATE:
case IMMEDIATE:
commit();
break;
- case EXPLCIT:
case EXPLICIT:
this.newValue = newLocalValue;
break;
@@ -240,7 +243,7 @@ final class DefaultDynamicValue<T> extends BaseDynamicValue<T> {
}
}
}
- return value;
+ return Optional.ofNullable(value);
}
/**
@@ -268,8 +271,9 @@ final class DefaultDynamicValue<T> extends BaseDynamicValue<T> {
case NEVER:
this.newValue = null;
break;
- case EXPLCIT:
- case IMMEDEATE:
+ case EXPLICIT:
+ this.newValue = newValue;
+ break;
default:
this.newValue = newValue;
commit();
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/InjectionHelper.java
----------------------------------------------------------------------
diff --git a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/InjectionHelper.java b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/InjectionHelper.java
index 06f3556..d404b3e 100644
--- a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/InjectionHelper.java
+++ b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/InjectionHelper.java
@@ -18,31 +18,28 @@
*/
package org.apache.tamaya.inject.internal;
-import java.lang.reflect.AnnotatedElement;
-import java.lang.reflect.Field;
-import java.lang.reflect.Member;
-import java.lang.reflect.Method;
+import java.lang.reflect.*;
import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
-import org.apache.tamaya.TypeLiteral;
+import org.apache.tamaya.base.convert.ConversionContext;
import org.apache.tamaya.events.ConfigEventManager;
import org.apache.tamaya.events.spi.BaseConfigEvent;
-import org.apache.tamaya.inject.api.Config;
-import org.apache.tamaya.inject.api.ConfigDefaultSections;
-import org.apache.tamaya.inject.spi.InjectionUtils;
-import org.apache.tamaya.inject.api.WithPropertyConverter;
+import org.apache.tamaya.inject.spi.InjectionEvaluator;
+import org.apache.tamaya.inject.api.WithConverter;
import org.apache.tamaya.inject.spi.ConfiguredType;
import org.apache.tamaya.resolver.spi.ExpressionEvaluator;
-import org.apache.tamaya.spi.ConfigurationContext;
-import org.apache.tamaya.spi.ConversionContext;
-import org.apache.tamaya.spi.PropertyConverter;
+import org.apache.tamaya.spi.ConfigContext;
+import org.apache.tamaya.spi.ConfigContextSupplier;
import org.apache.tamaya.spi.ServiceContextManager;
+import javax.config.Config;
+import javax.config.inject.ConfigProperty;
+import javax.config.spi.Converter;
+
/**
* Utility class containing several aspects used in this module.
@@ -58,7 +55,7 @@ final class InjectionHelper {
private static boolean checkForEvents() {
try{
- Class.forName("org.apache.tamaya.events.FrozenConfiguration");
+ Class.forName("org.apache.tamaya.events.FrozenConfig");
LOG.info("Detected tamaya-events is loaded, will trigger ConfigEvents...");
return true;
} catch(Exception e){
@@ -81,123 +78,134 @@ final class InjectionHelper {
/**
* Internally evaluated the current valid configuration keys based on the given annotations present.
- * @param method the method
+ * @param method the method, not null.
+ * @param config the config, not null.
* @return the keys to be returned, or null.
*/
- public static String getConfigValue(Method method, Configuration config) {
- return getConfigValue(method, null, config);
+ public static <T> T getConfigValue(Method method, Class<T> type, javax.config.Config config) {
+ return getConfigValue(method, type, null, config);
}
/**
* Internally evaluated the current valid configuration keys based on the given annotations present.
- * @param method the method
- * @param retKey the array to return the key found, or null.
+ * @param field the field, not null.
+ * @param config the config, not null.
* @return the keys to be returned, or null.
*/
- public static String getConfigValue(Method method, String[] retKey, Configuration config) {
- ConfigDefaultSections areasAnnot = method.getDeclaringClass().getAnnotation(ConfigDefaultSections.class);
- return getConfigValueInternal(method, areasAnnot, retKey, config);
+ public static <T> T getConfigValue(Field field, Class<T> type, javax.config.Config config) {
+ return getConfigValue(field, type, null, config);
}
- /**
- * Internally evaluated the current valid configuration keys based on the given annotations present.
- * @param field the field
- * @return the keys to be returned, or null.
- */
- public static String getConfigValue(Field field, Configuration config) {
- return getConfigValue(field, null, config);
- }
/**
* Internally evaluated the current valid configuration keys based on the given annotations present.
- * @param field the field
+ * @param member the member, not null.
* @param retKey the array to return the key found, or null.
* @return the keys to be returned, or null.
*/
- public static String getConfigValue(Field field, String[] retKey, Configuration config) {
- ConfigDefaultSections areasAnnot = field.getDeclaringClass().getAnnotation(ConfigDefaultSections.class);
- return getConfigValueInternal(field, areasAnnot, retKey, config);
- }
+ private static <T> T getConfigValue(AccessibleObject member, Class<T> targetType,
+ String[] retKey,
+ javax.config.Config config) {
+ Objects.requireNonNull(targetType);
+ targetType = unboxType(targetType);
+ List<String> keys = InjectionEvaluator.getKeys(member);
+
+ WithConverter converterAnnot = member.getAnnotation(WithConverter.class);
+ if(converterAnnot!=null && !converterAnnot.value().getName().equals(WithConverter.class.getName())){
+ return getCustomConvertedConfigValue(member, converterAnnot, targetType, keys, config);
+ }
- /**
- * Internally evaluated the current valid configuration keys based on the given annotations present.
- *
- * @return the keys to be returned, or null.
- */
- private static String getConfigValueInternal(AnnotatedElement element, ConfigDefaultSections areasAnnot, String[] retKey, Configuration config) {
- Config prop = element.getAnnotation(Config.class);
- List<String> keys;
- if (prop == null) {
- keys = InjectionUtils.evaluateKeys((Member) element, areasAnnot);
- } else {
- keys = InjectionUtils.evaluateKeys((Member) element, areasAnnot, prop);
+ Optional<T> result = null;
+ for(String key:keys) {
+ result = config.getOptionalValue(key, targetType);
+ if (result.isPresent()) {
+ if (retKey != null) {
+ retKey[0] = key;
+ }
+ return result.get();
+ }
}
- String configValue = evaluteConfigValue(keys, retKey, config);
- if (configValue == null) {
- if(prop!=null && !prop.defaultValue().equals(Config.UNCONFIGURED_VALUE)){
- return prop.defaultValue();
+ ConfigProperty prop = member.getAnnotation(ConfigProperty.class);
+ if(prop!=null && !prop.defaultValue().equals(ConfigProperty.UNCONFIGURED_VALUE)){
+ String textValue = prop.defaultValue();
+ // How tp convert the default value in a portable way?
+ if(config instanceof ConfigContextSupplier){
+ ConfigContext ctx = ((ConfigContextSupplier)config).getConfigContext();
+ for(Converter converter:ctx.getConverters(targetType)){
+ try{
+ Object o = converter.convert(textValue);
+ if(o!=null){
+ return (T)o;
+ }
+ }catch(Exception e){
+ LOG.log(Level.SEVERE, "Failed to convert using Converter on " +
+ converter.getClass().getName(), e);
+ }
+ }
+ if(String.class.equals(targetType) || CharSequence.class.equals(targetType)){
+ return (T)textValue;
+ }
+ throw new IllegalArgumentException("Non convertible value: " + textValue + ", target: " + targetType.getName());
}
}
- return configValue;
+ return null;
}
- private static String evaluteConfigValue(List<String> keys, String[] retKey, Configuration config) {
- String configValue = null;
- for (String key : keys) {
- configValue = config.get(key);
- if (configValue != null) {
- if(retKey!=null && retKey.length>0){
- retKey[0] = key;
- }
- break;
- }
+ private static Class unboxType(Class targetType) {
+ switch(targetType.getName()){
+ case "byte":
+ return Byte.class;
+ case "char":
+ return Character.class;
+ case "boolean":
+ return Boolean.class;
+ case "int":
+ return Integer.class;
+ case "short":
+ return Short.class;
+ case "long":
+ return Long.class;
+ case "float":
+ return Float.class;
+ case "double":
+ return Double.class;
+ default:
+ return targetType;
+
}
- return configValue;
}
- public static <T> T adaptValue(AnnotatedElement element, TypeLiteral<T> targetType, String key, String configValue) {
+ public static <T> T getCustomConvertedConfigValue(AccessibleObject element, WithConverter converterAnnot,
+ Class<T> targetType, List<String> keys, Config config) {
// Check for adapter/filter
- T adaptedValue = null;
- WithPropertyConverter converterAnnot = element.getAnnotation(WithPropertyConverter.class);
- Class<? extends PropertyConverter<T>> converterType;
- if (converterAnnot != null) {
- converterType = (Class<? extends PropertyConverter<T>>) converterAnnot.value();
- if (!converterType.getName().equals(WithPropertyConverter.class.getName())) {
+ Class<? extends Converter<T>> converterType = (Class<? extends Converter<T>>) converterAnnot.value();
+ if (!converterType.getName().equals(WithConverter.class.getName())) {
+ Converter<T> converter = null;
+ try {
+ converter = Converter.class.cast(converterType.newInstance());
+ } catch (Exception e) {
+ throw new IllegalArgumentException("Failed to instantiate converter: " + converterType.getName(), e);
+ }
+ for (String key : keys) {
try {
- // TODO cache here...
- ConversionContext ctx = new ConversionContext.Builder(key,targetType)
+ ConversionContext ctx = new ConversionContext.Builder(key, targetType)
.setAnnotatedElement(element).build();
-
- PropertyConverter<T> converter = PropertyConverter.class.cast(converterType.newInstance());
- adaptedValue = converter.convert(configValue, ctx);
+ ConversionContext.setContext(ctx);
+ Optional<String> textValue = config.getOptionalValue(key, String.class);
+ if (textValue.isPresent()) {
+ T adaptedValue = converter.convert(textValue.get());
+ if (adaptedValue != null) {
+ return adaptedValue;
+ }
+ }
} catch (Exception e) {
- LOG.log(Level.SEVERE, "Failed to convert using explicit PropertyConverter on " + element +
- ", trying default conversion.", e);
- }
- }
- }
- if (adaptedValue != null) {
- return adaptedValue;
- }
- if (String.class == targetType.getType()) {
- return (T) configValue;
- } else{
- if(configValue==null) {
- return null;
- }
- ConfigurationContext configContext = ConfigurationProvider.getConfiguration().getContext();
- List<PropertyConverter<T>> converters = configContext
- .getPropertyConverters(targetType);
- ConversionContext ctx = new ConversionContext.Builder(ConfigurationProvider.getConfiguration(),
- configContext, key, targetType).setAnnotatedElement(element).build();
- for (PropertyConverter<T> converter : converters) {
- adaptedValue = converter.convert(configValue, ctx);
- if (adaptedValue != null) {
- return adaptedValue;
+ LOG.log(Level.SEVERE, "Failed to convert using explicit PropertyConverter on " + element, e);
+ } finally {
+ ConversionContext.reset();
}
}
}
- throw new ConfigException("Non convertible property type: " + element);
+ return null;
}
/**
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigBean.java
----------------------------------------------------------------------
diff --git a/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigBean.java b/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigBean.java
index 3420977..5c0fe98 100644
--- a/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigBean.java
+++ b/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigBean.java
@@ -18,10 +18,11 @@
*/
package annottext;
+import org.apache.tamaya.inject.api.ConfigFallbackKeys;
import org.apache.tamaya.inject.api.DynamicValue;
import org.apache.tamaya.inject.api.NoConfig;
-import org.apache.tamaya.inject.api.Config;
+import javax.config.inject.ConfigProperty;
import java.util.ArrayList;
import java.util.List;
@@ -32,20 +33,20 @@ import java.util.List;
*/
public class AnnotatedConfigBean {
- @Config(value = {"foo.bar.myprop", "mp", "common.testdata.myProperty"}, defaultValue = "ET")
- // @ConfigLoadPolicy(listener = MyListener.class)
+ @ConfigProperty(name="foo.bar.myprop", defaultValue = "ET")
+ @ConfigFallbackKeys({"mp", "common.testdata.myProperty"})
public String myParameter;
- @Config("simple_value")
+ @ConfigProperty(name="simple_value")
public String simpleValue;
- @Config
+ @ConfigProperty
String anotherValue;
- @Config("host.name")
+ @ConfigProperty(name="host.name")
private String hostName;
- @Config("host.name")
+ @ConfigProperty(name="host.name")
private DynamicValue<String> dynamicHostname;
@NoConfig
@@ -70,7 +71,7 @@ public class AnnotatedConfigBean {
public static final String CONSTANT = "a constant";
- @Config("java.version")
+ @ConfigProperty(name="java.version")
void setJavaVersion(String version){
this.javaVersion = version;
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigTemplate.java
----------------------------------------------------------------------
diff --git a/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigTemplate.java b/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigTemplate.java
index 8c6d692..6dbcde7 100644
--- a/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigTemplate.java
+++ b/modules/injection/standalone/src/test/java/annottext/AnnotatedConfigTemplate.java
@@ -18,8 +18,10 @@
*/
package annottext;
+import org.apache.tamaya.inject.api.ConfigFallbackKeys;
import org.apache.tamaya.inject.api.DynamicValue;
-import org.apache.tamaya.inject.api.Config;
+
+import javax.config.inject.ConfigProperty;
/**
* An example showing some basic annotations, using an interface to be proxied by the
@@ -28,20 +30,20 @@ import org.apache.tamaya.inject.api.Config;
*/
public interface AnnotatedConfigTemplate {
- @Config(value = {"foo.bar.myprop", "mp","common.testdata.myProperty"}, defaultValue = "ET")
- // @ConfigLoadPolicy(listener = MyListener.class)
+ @ConfigProperty(name = "foo.bar.myprop", defaultValue = "ET")
+ @ConfigFallbackKeys({"mp","common.testdata.myProperty"})
String myParameter();
- @Config("simple_value")
+ @ConfigProperty(name="simple_value")
String simpleValue();
- @Config
+ @ConfigProperty
String simplestValue();
- @Config("host.name")
+ @ConfigProperty(name="host.name")
String hostName();
- @Config("host.name")
+ @ConfigProperty(name="host.name")
DynamicValue<String> getDynamicValue();
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/test/java/annottext/InheritedAnnotatedConfigBean.java
----------------------------------------------------------------------
diff --git a/modules/injection/standalone/src/test/java/annottext/InheritedAnnotatedConfigBean.java b/modules/injection/standalone/src/test/java/annottext/InheritedAnnotatedConfigBean.java
index 9952b18..778d689 100644
--- a/modules/injection/standalone/src/test/java/annottext/InheritedAnnotatedConfigBean.java
+++ b/modules/injection/standalone/src/test/java/annottext/InheritedAnnotatedConfigBean.java
@@ -18,11 +18,12 @@
*/
package annottext;
-import org.apache.tamaya.inject.api.Config;
+
+import javax.config.inject.ConfigProperty;
public class InheritedAnnotatedConfigBean extends AnnotatedConfigBean {
- @Config("someMoreValue")
+ @ConfigProperty(name="someMoreValue")
public String someMoreValue;
public String notConfigured;
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/test/java/annottext/NonAnnotatedConfigBean.java
----------------------------------------------------------------------
diff --git a/modules/injection/standalone/src/test/java/annottext/NonAnnotatedConfigBean.java b/modules/injection/standalone/src/test/java/annottext/NonAnnotatedConfigBean.java
index 87f8be7..03bfd54 100644
--- a/modules/injection/standalone/src/test/java/annottext/NonAnnotatedConfigBean.java
+++ b/modules/injection/standalone/src/test/java/annottext/NonAnnotatedConfigBean.java
@@ -18,13 +18,6 @@
*/
package annottext;
-import org.apache.tamaya.inject.api.Config;
-import org.apache.tamaya.inject.api.DynamicValue;
-import org.apache.tamaya.inject.api.NoConfig;
-
-import java.util.ArrayList;
-import java.util.List;
-
/**
* An example showing some basic annotations, using an interface to be proxied by the
* configuration system, nevertheless extending the overall Configuration interface.
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/TestConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/TestConfigSource.java b/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/TestConfigSource.java
new file mode 100644
index 0000000..0ae2843
--- /dev/null
+++ b/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/TestConfigSource.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.inject;
+
+import javax.config.spi.ConfigSource;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Created by Anatole on 12.01.2015.
+ */
+public class TestConfigSource implements ConfigSource {
+
+ private Map<String,String> properties = new HashMap<>();
+
+ public TestConfigSource(){
+ properties.put("env.stage", "ET");
+ properties.put("simple_value", "aSimpleValue");
+ properties.put("host.name", "tamaya01.incubator.apache.org");
+ properties.put("anotherValue", "HALLO!");
+ properties.put("NonAnnotatedConfigBean.classFieldKey", "Class-Field-Value");
+ properties.put("NonAnnotatedConfigBean.fieldKey", "Field-Value");
+ properties.put("annottext.NonAnnotatedConfigBean.fullKey", "Fullkey-Value");
+ properties.put("someMoreValue", "s'more");
+ }
+
+ @Override
+ public int getOrdinal() {
+ return 0;
+ }
+
+ @Override
+ public String getName() {
+ return getClass().getName();
+ }
+
+ @Override
+ public String getValue(String key) {
+ return properties.get(key);
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ return properties;
+ }
+
+ @Override
+ public Set<String> getPropertyNames() {
+ return properties.keySet();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/TestPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/TestPropertySource.java b/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/TestPropertySource.java
deleted file mode 100644
index 20de8e8..0000000
--- a/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/TestPropertySource.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.inject;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Created by Anatole on 12.01.2015.
- */
-public class TestPropertySource implements PropertySource {
-
- private Map<String,String> properties = new HashMap<>();
-
- public TestPropertySource(){
- properties.put("env.stage", "ET");
- properties.put("simple_value", "aSimpleValue");
- properties.put("host.name", "tamaya01.incubator.apache.org");
- properties.put("anotherValue", "HALLO!");
- properties.put("NonAnnotatedConfigBean.classFieldKey", "Class-Field-Value");
- properties.put("NonAnnotatedConfigBean.fieldKey", "Field-Value");
- properties.put("annottext.NonAnnotatedConfigBean.fullKey", "Fullkey-Value");
- properties.put("someMoreValue", "s'more");
- }
-
- @Override
- public int getOrdinal() {
- return 0;
- }
-
- @Override
- public String getName() {
- return getClass().getName();
- }
-
- @Override
- public PropertyValue get(String key) {
- return PropertyValue.of(key,properties.get(key),getName());
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
- Map<String,PropertyValue> result = new HashMap<>();
- for(Map.Entry<String,String> en:properties.entrySet()){
- result.put(en.getKey(), PropertyValue.of(en.getKey(), en.getValue(), getName()));
- }
- return result;
- }
-
- @Override
- public boolean isScannable() {
- return true;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/internal/DefaultDynamicValueTest.java
----------------------------------------------------------------------
diff --git a/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/internal/DefaultDynamicValueTest.java b/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/internal/DefaultDynamicValueTest.java
index a071584..856ca4c 100644
--- a/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/internal/DefaultDynamicValueTest.java
+++ b/modules/injection/standalone/src/test/java/org/apache/tamaya/inject/internal/DefaultDynamicValueTest.java
@@ -18,18 +18,15 @@
*/
package org.apache.tamaya.inject.internal;
-import org.apache.tamaya.ConfigurationProvider;
import org.apache.tamaya.inject.api.DynamicValue;
-import org.apache.tamaya.inject.api.Config;
import org.apache.tamaya.inject.api.UpdatePolicy;
-import org.apache.tamaya.spi.ConversionContext;
-import org.apache.tamaya.spi.PropertyConverter;
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
import org.junit.Test;
-import org.apache.tamaya.Configuration;
-
+import javax.config.ConfigProvider;
+import javax.config.inject.ConfigProperty;
+import javax.config.spi.ConfigProviderResolver;
+import javax.config.spi.ConfigSource;
+import javax.config.spi.Converter;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashMap;
@@ -42,13 +39,13 @@ import static org.junit.Assert.*;
*/
public class DefaultDynamicValueTest {
- @Config("a")
+ @ConfigProperty(name="a")
String myValue;
- @Config("a")
+ @ConfigProperty(name="a")
String myValue2;
- @Config("a")
+ @ConfigProperty(name="a")
void setterMethod(String value){
}
@@ -62,10 +59,10 @@ public class DefaultDynamicValueTest {
}
};
- private Map<String,PropertyValue> properties = new HashMap<>();
- private Configuration config = ConfigurationProvider.createConfiguration(
- ConfigurationProvider.getConfigurationContextBuilder().addPropertySources(
- new PropertySource() {
+ private Map<String,String> properties = new HashMap<>();
+ private javax.config.Config config = ConfigProviderResolver.instance().getBuilder()
+ .withSources(
+ new ConfigSource() {
@Override
public int getOrdinal() {
return 0;
@@ -77,26 +74,22 @@ public class DefaultDynamicValueTest {
}
@Override
- public PropertyValue get(String key) {
+ public String getValue(String key) {
return properties.get(key);
}
@Override
- public Map<String, PropertyValue> getProperties() {
+ public Map<String, String> getProperties() {
return properties;
}
- @Override
- public boolean isScannable() {
- return false;
- }
}
- ).build());
+ ).build();
@Test
public void testOf_Field() throws Exception {
DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"),
- ConfigurationProvider.getConfiguration());
+ ConfigProvider.getConfig());
assertNotNull(val);
}
@@ -109,7 +102,7 @@ public class DefaultDynamicValueTest {
@Test
public void testCommitAndGet() throws Exception {
- properties.put("a",PropertyValue.of("a","aValue","test"));
+ properties.put("a","aValue");
DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"),
config);
assertNotNull(val);
@@ -118,7 +111,7 @@ public class DefaultDynamicValueTest {
@Test
public void testCommitAndGets() throws Exception {
- properties.put("a",PropertyValue.of("a","aValue","test"));
+ properties.put("a","aValue");
DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"),
config);
val.setUpdatePolicy(UpdatePolicy.EXPLICIT);
@@ -126,14 +119,14 @@ public class DefaultDynamicValueTest {
assertEquals("aValue",val.evaluateValue());
// change config
val.get();
- properties.put("a",PropertyValue.of("a","aValue2","test"));
+ properties.put("a","aValue2");
assertTrue(val.updateValue());
assertEquals("aValue2", val.commitAndGet());
}
@Test
public void testCommit() throws Exception {
- properties.put("a",PropertyValue.of("a","aValue","test"));
+ properties.put("a","aValue");
DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"),
config);
val.setUpdatePolicy(UpdatePolicy.EXPLICIT);
@@ -141,7 +134,7 @@ public class DefaultDynamicValueTest {
assertEquals("aValue", val.evaluateValue());
// change config
val.get();
- properties.put("a",PropertyValue.of("a","aValue2","test"));
+ properties.put("a","aValue2");
assertEquals("aValue2", val.evaluateValue());
assertTrue(val.updateValue());
val.commit();
@@ -160,37 +153,37 @@ public class DefaultDynamicValueTest {
@Test
public void testAddRemoveListener() throws Exception {
- properties.put("a",PropertyValue.of("a","aValue","test"));
+ properties.put("a","aValue");
DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"),
config);
val.setUpdatePolicy(UpdatePolicy.IMMEDIATE);
val.addListener(consumer);
// change config
val.get();
- properties.put("a",PropertyValue.of("a","aValue2","test"));
+ properties.put("a","aValue2");
val.get();
assertNotNull(event);
event = null;
val.removeListener(consumer);
- properties.put("a",PropertyValue.of("a","aValue3","test"));
+ properties.put("a","aValue3");
val.updateValue();
assertNull(event);
}
@Test
public void testGet() throws Exception {
- properties.put("a",PropertyValue.of("a","aValue","test"));
+ properties.put("a","aValue");
DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"),
config);
val.setUpdatePolicy(UpdatePolicy.IMMEDIATE);
- properties.put("a",PropertyValue.of("a","aValue2","test"));
+ properties.put("a","aValue2");
val.updateValue();
assertEquals("aValue2", val.get());
}
@Test
public void testUpdateValue() throws Exception {
- properties.put("a",PropertyValue.of("a","aValue","test"));
+ properties.put("a","aValue");
DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"),
config);
val.setUpdatePolicy(UpdatePolicy.EXPLICIT);
@@ -205,25 +198,25 @@ public class DefaultDynamicValueTest {
@Test
public void testEvaluateValue() throws Exception {
- properties.put("a",PropertyValue.of("a","aValue","test"));
+ properties.put("a","aValue");
DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"),
config);
val.setUpdatePolicy(UpdatePolicy.EXPLICIT);
assertNotNull(val.get());
assertEquals("aValue",val.evaluateValue());
- properties.put("a",PropertyValue.of("a","aValue2","test"));
+ properties.put("a","aValue2");
assertEquals("aValue2", val.evaluateValue());
}
@Test
public void testGetNewValue() throws Exception {
- properties.put("a",PropertyValue.of("a","aValue","test"));
+ properties.put("a","aValue");
DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"),
config);
val.setUpdatePolicy(UpdatePolicy.EXPLICIT);
val.get();
assertNull(val.getNewValue());
- properties.put("a",PropertyValue.of("a","aValue2","test"));
+ properties.put("a","aValue2");
val.get();
assertNotNull(val.getNewValue());
assertEquals("aValue2", val.getNewValue());
@@ -239,7 +232,7 @@ public class DefaultDynamicValueTest {
@Test
public void testIfPresent() throws Exception {
- properties.put("a",PropertyValue.of("a","aValue","test"));
+ properties.put("a","aValue");
DynamicValue val = DefaultDynamicValue.of(this, getClass().getDeclaredField("myValue"),
config);
val.setUpdatePolicy(UpdatePolicy.IMMEDIATE);
@@ -255,7 +248,7 @@ public class DefaultDynamicValueTest {
config);
val.setUpdatePolicy(UpdatePolicy.IMMEDIATE);
assertEquals("bla", val.orElse("bla"));
- properties.put("a",PropertyValue.of("a","aValue","test"));
+ properties.put("a","aValue");
val.updateValue();
assertEquals("aValue", val.orElse("bla"));
}
@@ -305,10 +298,10 @@ public class DefaultDynamicValueTest {
// }));
// }
- private static final class DoublicatingConverter implements PropertyConverter<String>{
+ private static final class DoublicatingConverter implements Converter<String> {
@Override
- public String convert(String value, ConversionContext context) {
+ public String convert(String value) {
return value + value;
}
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/test/resources/META-INF/services/javax.config.spi.ConfigSource
----------------------------------------------------------------------
diff --git a/modules/injection/standalone/src/test/resources/META-INF/services/javax.config.spi.ConfigSource b/modules/injection/standalone/src/test/resources/META-INF/services/javax.config.spi.ConfigSource
new file mode 100644
index 0000000..60a2faf
--- /dev/null
+++ b/modules/injection/standalone/src/test/resources/META-INF/services/javax.config.spi.ConfigSource
@@ -0,0 +1,19 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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 current 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.
+#
+org.apache.tamaya.inject.TestConfigSource
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
----------------------------------------------------------------------
diff --git a/modules/injection/standalone/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource b/modules/injection/standalone/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
deleted file mode 100644
index 5dfb894..0000000
--- a/modules/injection/standalone/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
+++ /dev/null
@@ -1,19 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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 current 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.
-#
-org.apache.tamaya.inject.TestPropertySource
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/jndi/pom.xml
----------------------------------------------------------------------
diff --git a/modules/jndi/pom.xml b/modules/jndi/pom.xml
index 805729b..a91072f 100644
--- a/modules/jndi/pom.xml
+++ b/modules/jndi/pom.xml
@@ -35,12 +35,6 @@ under the License.
<dependencies>
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-api</artifactId>
- <version>${tamaya-apicore.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.tamaya</groupId>
<artifactId>tamaya-core</artifactId>
<version>${tamaya-apicore.version}</version>
<scope>provided</scope>
@@ -55,7 +49,7 @@ under the License.
</dependency>
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-spisupport</artifactId>
+ <artifactId>tamaya-base</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/jndi/src/main/java/org/apache/tamaya/jndi/JNDIConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/jndi/src/main/java/org/apache/tamaya/jndi/JNDIConfigSource.java b/modules/jndi/src/main/java/org/apache/tamaya/jndi/JNDIConfigSource.java
new file mode 100644
index 0000000..8e5b7ac
--- /dev/null
+++ b/modules/jndi/src/main/java/org/apache/tamaya/jndi/JNDIConfigSource.java
@@ -0,0 +1,182 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.jndi;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.NameClassPair;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+
+import org.apache.tamaya.base.configsource.BaseConfigSource;
+import org.osgi.service.component.annotations.Component;
+
+/**
+ * Propertysource that accesses JNDI as source for configuration entries.
+ */
+@Component
+public class JNDIConfigSource extends BaseConfigSource {
+ /** The logger used. */
+ private static final Logger LOG = Logger.getLogger(JNDIConfigSource.class.getName());
+
+ /**
+ * Default ordinal to be used, as defined by {@link javax.config.spi.ConfigSource#getOrdinal()} documentation.
+ */
+ private static final int DEFAULT_ORDINAL = 200;
+
+ /** The root context, not null. */
+ private Context context;
+ /** The scanable property, default is {@code false}. */
+ private boolean scannable = false;
+
+ /**
+ * Creates a new instance.
+ * @param name the name of the property source, see {@link javax.config.spi.ConfigSource#getName()}.
+ * @param context the root context to be used, not null.
+ */
+ public JNDIConfigSource(String name, Context context){
+ super(name);
+ this.context = Objects.requireNonNull(context);
+ }
+
+ /**
+ * Creates a new instance.
+ * @param name the name of the property source, see {@link javax.config.spi.ConfigSource#getName()}.
+ * @throws NamingException if {@code new InitialContext()} throws an exception.
+ */
+ public JNDIConfigSource(String name) throws NamingException {
+ super(name);
+ this.context = new InitialContext();
+ }
+
+ /**
+ * Creates a new instance, using {@code "jndi"} as property source name.
+ * @throws NamingException if {@code new InitialContext()} throws an exception.
+ */
+ public JNDIConfigSource() throws NamingException {
+ this("jndi");
+ setDefaultOrdinal(DEFAULT_ORDINAL);
+ }
+
+ /**
+ * If the property source is not scanable, an empty map is returned, otherwise
+ * the current JNDI context is mapped to configuration map:
+ * <ul>
+ * <li>For each leave entry one entry is created.</li>
+ * <li>The key is the fully path of parent contexts, separated by a '.'.</li>
+ * <li>The value is the value returned from {@code String.valueOf(leaveObject)}.</li>
+ * </ul>
+ * @return a map representation of the JNDI tree.
+ */
+ @Override
+ public Map<String, String> getProperties() {
+ if(scannable){
+ try {
+ return toMap(this.context);
+ } catch (NamingException e) {
+ LOG.log(Level.WARNING, "Error scanning JNDI tree.", e);
+ }
+ }
+ return Collections.emptyMap();
+ }
+
+
+ /**
+ * If set to true, the property source will return a String representation of the JNDI
+ * tree when calling {@code getProperties()}.
+ * @see #getProperties()
+ * @param val true, to activate scanable (default is false).
+ */
+ public void setScannable(boolean val){
+ this.scannable = val;
+ }
+
+ @Override
+ public String getValue(String key) {
+ try {
+ key = key.replace('.', '/');
+ Object o = context.lookup(key);
+ return o.toString();
+ } catch (NamingException e) {
+ LOG.log(Level.FINER, "Failed to lookup key in JNDI: " + key, e);
+ return null;
+ }
+ }
+
+ @Override
+ protected String toStringValues() {
+ return super.toStringValues() +
+ "\n context=" + context + '\'';
+ }
+
+ /**
+ * Maps the given JNDI Context to a {@code Map<String,String>}:
+ * mapped to configuration map:
+ * <ul>
+ * <li>For each leave entry one entry is created.</li>
+ * <li>The key is the fully path of parent contexts, separated by a '.'.</li>
+ * <li>The value is the value returned from {@code String.valueOf(leaveObject)}.</li>
+ * </ul>
+ * @param ctx the JNDI context, not null.
+ * @return the corresponding map, never null.
+ * @throws NamingException If some JNDI issues occur.
+ */
+ public static Map<String,String> toMap(Context ctx) throws NamingException {
+ String namespace = ctx instanceof InitialContext ? ctx.getNameInNamespace() : "";
+ Map<String, String> map = new HashMap<>();
+ NamingEnumeration<NameClassPair> list = ctx.list(namespace);
+ while (list.hasMoreElements()) {
+ NameClassPair next = list.next();
+ String name = next.getName();
+ String jndiPath = namespace + name;
+ try {
+ Object lookup = ctx.lookup(jndiPath);
+ if (namespace.isEmpty()) {
+ if (lookup instanceof Context) {
+ Map<String, String> childMap = toMap((Context) lookup);
+ for (Map.Entry<String, String> en : childMap.entrySet()) {
+ map.put(name + "." + en.getKey(), en.getValue());
+ }
+ } else {
+ map.put(name, String.valueOf(lookup));
+ }
+ }else{
+ if (lookup instanceof Context) {
+ Map<String, String> childMap = toMap((Context) lookup);
+ for (Map.Entry<String, String> en : childMap.entrySet()) {
+ map.put(namespace + "." + name + "." + en.getKey(), en.getValue());
+ }
+ } else {
+ map.put(namespace + "." + name, String.valueOf(lookup));
+ }
+ }
+ } catch (Exception t) {
+ map.put(namespace + "." + name, "ERROR: " + t.getMessage());
+ }
+ }
+ return map;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/jndi/src/main/java/org/apache/tamaya/jndi/JNDIPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/jndi/src/main/java/org/apache/tamaya/jndi/JNDIPropertySource.java b/modules/jndi/src/main/java/org/apache/tamaya/jndi/JNDIPropertySource.java
deleted file mode 100644
index d2b549b..0000000
--- a/modules/jndi/src/main/java/org/apache/tamaya/jndi/JNDIPropertySource.java
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.jndi;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NameClassPair;
-import javax.naming.NamingEnumeration;
-import javax.naming.NamingException;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-import org.apache.tamaya.spisupport.propertysource.BasePropertySource;
-import org.osgi.service.component.annotations.Component;
-
-/**
- * Propertysource that accesses JNDI as source for configuration entries.
- */
-@Component
-public class JNDIPropertySource extends BasePropertySource {
- /** The logger used. */
- private static final Logger LOG = Logger.getLogger(JNDIPropertySource.class.getName());
-
- /**
- * Default ordinal to be used, as defined by {@link PropertySource#getOrdinal()} documentation.
- */
- private static final int DEFAULT_ORDINAL = 200;
-
- /** The root context, not null. */
- private Context context;
- /** The scanable property, default is {@code false}. */
- private boolean scannable = false;
-
- /**
- * Creates a new instance.
- * @param name the name of the property source, see {@link PropertySource#getName()}.
- * @param context the root context to be used, not null.
- */
- public JNDIPropertySource(String name, Context context){
- super(name);
- this.context = Objects.requireNonNull(context);
- }
-
- /**
- * Creates a new instance.
- * @param name the name of the property source, see {@link PropertySource#getName()}.
- * @throws NamingException if {@code new InitialContext()} throws an exception.
- */
- public JNDIPropertySource(String name) throws NamingException {
- super(name);
- this.context = new InitialContext();
- }
-
- /**
- * Creates a new instance, using {@code "jndi"} as property source name.
- * @throws NamingException if {@code new InitialContext()} throws an exception.
- */
- public JNDIPropertySource() throws NamingException {
- this("jndi");
- setDefaultOrdinal(DEFAULT_ORDINAL);
- }
-
- /**
- * If the property source is not scanable, an empty map is returned, otherwise
- * the current JNDI context is mapped to configuration map:
- * <ul>
- * <li>For each leave entry one entry is created.</li>
- * <li>The key is the fully path of parent contexts, separated by a '.'.</li>
- * <li>The value is the value returned from {@code String.valueOf(leaveObject)}.</li>
- * </ul>
- * @return a map representation of the JNDI tree.
- */
- @Override
- public Map<String, PropertyValue> getProperties() {
- if(scannable){
- try {
- return PropertyValue.map(toMap(this.context), getName());
- } catch (NamingException e) {
- LOG.log(Level.WARNING, "Error scanning JNDI tree.", e);
- }
- }
- return Collections.emptyMap();
- }
-
- @Override
- public boolean isScannable() {
- return scannable;
- }
-
- /**
- * If set to true, the property source will return a String representation of the JNDI
- * tree when calling {@code getProperties()}.
- * @see #getProperties()
- * @param val true, to activate scanable (default is false).
- */
- public void setScannable(boolean val){
- this.scannable = val;
- }
-
- @Override
- public PropertyValue get(String key) {
- try {
- key = key.replace('.', '/');
- Object o = context.lookup(key);
- return PropertyValue.of(key, o.toString(), getName());
- } catch (NamingException e) {
- LOG.log(Level.FINER, "Failed to lookup key in JNDI: " + key, e);
- return null;
- }
- }
-
- @Override
- protected String toStringValues() {
- return super.toStringValues() +
- "\n context=" + context + '\'';
- }
-
- /**
- * Maps the given JNDI Context to a {@code Map<String,String>}:
- * mapped to configuration map:
- * <ul>
- * <li>For each leave entry one entry is created.</li>
- * <li>The key is the fully path of parent contexts, separated by a '.'.</li>
- * <li>The value is the value returned from {@code String.valueOf(leaveObject)}.</li>
- * </ul>
- * @param ctx the JNDI context, not null.
- * @return the corresponding map, never null.
- * @throws NamingException If some JNDI issues occur.
- */
- public static Map<String,String> toMap(Context ctx) throws NamingException {
- String namespace = ctx instanceof InitialContext ? ctx.getNameInNamespace() : "";
- Map<String, String> map = new HashMap<>();
- NamingEnumeration<NameClassPair> list = ctx.list(namespace);
- while (list.hasMoreElements()) {
- NameClassPair next = list.next();
- String name = next.getName();
- String jndiPath = namespace + name;
- try {
- Object lookup = ctx.lookup(jndiPath);
- if (namespace.isEmpty()) {
- if (lookup instanceof Context) {
- Map<String, String> childMap = toMap((Context) lookup);
- for (Map.Entry<String, String> en : childMap.entrySet()) {
- map.put(name + "." + en.getKey(), en.getValue());
- }
- } else {
- map.put(name, String.valueOf(lookup));
- }
- }else{
- if (lookup instanceof Context) {
- Map<String, String> childMap = toMap((Context) lookup);
- for (Map.Entry<String, String> en : childMap.entrySet()) {
- map.put(namespace + "." + name + "." + en.getKey(), en.getValue());
- }
- } else {
- map.put(namespace + "." + name, String.valueOf(lookup));
- }
- }
- } catch (Exception t) {
- map.put(namespace + "." + name, "ERROR: " + t.getMessage());
- }
- }
- return map;
- }
-}
[10/18] incubator-tamaya-extensions git commit: Rewrite/adaptation
based on JSR API.
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/common/src/main/java/org/apache/tamaya/osgi/commands/ConfigCommands.java
----------------------------------------------------------------------
diff --git a/modules/osgi/common/src/main/java/org/apache/tamaya/osgi/commands/ConfigCommands.java b/modules/osgi/common/src/main/java/org/apache/tamaya/osgi/commands/ConfigCommands.java
index cccbf9d..60b5fba 100644
--- a/modules/osgi/common/src/main/java/org/apache/tamaya/osgi/commands/ConfigCommands.java
+++ b/modules/osgi/common/src/main/java/org/apache/tamaya/osgi/commands/ConfigCommands.java
@@ -18,13 +18,12 @@
*/
package org.apache.tamaya.osgi.commands;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
import org.apache.tamaya.functions.ConfigurationFunctions;
import org.apache.tamaya.osgi.Policy;
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
+import javax.config.Config;
+import javax.config.ConfigProvider;
+import javax.config.spi.ConfigSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
@@ -39,26 +38,25 @@ public final class ConfigCommands {
private ConfigCommands(){}
public static String getInfo(TamayaConfigService configPlugin) throws IOException {
- Configuration config = ConfigurationProvider.getConfiguration();
+ Config config = ConfigProvider.getConfig();
return config.toString() + "\n\n"
+ StringUtil.format("Default Policy:", 30) + configPlugin.getDefaultPolicy() + '\n'
+ StringUtil.format("Default Enabled: ", 30) + configPlugin.isTamayaEnabledByDefault();
}
public static String readTamayaConfig(String section, String filter) {
- Configuration config = ConfigurationProvider.getConfiguration();
+ Config config = ConfigProvider.getConfig();
if(section!=null){
- config = config
- .with(ConfigurationFunctions.section(section, true));
+ config = ConfigurationFunctions.section(section, true).apply(config);
}
if(filter!=null){
- config = config.with(ConfigurationFunctions.section(filter, false));
+ config = ConfigurationFunctions.section(filter, false).apply(config);
}
return "Tamaya Configuration\n" +
"--------------------\n" +
"Section: "+section +"\n" +
(filter!=null?"Filter: "+filter + "\n":"") +
- config.query(ConfigurationFunctions.textInfo());
+ ConfigurationFunctions.textInfo().apply(config);
}
public static String readTamayaConfig4PID(String pid, String filter) {
@@ -123,37 +121,33 @@ public final class ConfigCommands {
}
public static String getProperty(String propertysource, String key, boolean extended) throws IOException {
- Configuration config = ConfigurationProvider.getConfiguration();
+ Config config = ConfigProvider.getConfig();
if(propertysource!=null){
- PropertySource ps = config.getContext().getPropertySource(propertysource);
+ ConfigSource ps = getPropertySource(config, propertysource);
if(ps==null){
return "ERR: No such Property Source: " + propertysource;
}else {
- PropertyValue val = ps.get(key);
+ String val = ps.getValue(key);
if(val==null){
- return "ERR: Property Source: " + propertysource + " - undefined key: " + key;
+ return "ERR: Config Source: " + propertysource + " - undefined key: " + key;
}else {
if(extended) {
- return StringUtil.format("Property Source", 25) + StringUtil.format("Value", 25) + '\n' +
+ return StringUtil.format("Config Source", 25) + StringUtil.format("Value", 25) + '\n' +
StringUtil.printRepeat("-", 50) + '\n' +
- StringUtil.format(propertysource, 25) + StringUtil.format(val.getValue(), 55);
+ StringUtil.format(propertysource, 25) + StringUtil.format(val, 55);
}else{
- return val.getValue();
+ return val;
}
}
}
}else{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
- pw.println(StringUtil.format("Property Source", 25) + StringUtil.format("Value", 25));
- for(PropertySource ps:config.getContext().getPropertySources()){
- PropertyValue val = ps.get(key);
+ pw.println(StringUtil.format("Config Source", 25) + StringUtil.format("Value", 25));
+ for(ConfigSource ps:config.getConfigSources()){
+ String val = ps.getValue(key);
if(val!=null){
- if(extended) {
- pw.println(StringUtil.format("", 25) + StringUtil.format(val.toString(), 55));
- }else{
- pw.println(StringUtil.format("", 25) + StringUtil.format(val.getValue(), 55));
- }
+ pw.println(StringUtil.format("", 25) + StringUtil.format(val, 55));
}
}
pw.flush();
@@ -161,17 +155,26 @@ public final class ConfigCommands {
}
}
+ private static ConfigSource getPropertySource(Config config, String propertysource) {
+ for(ConfigSource cs:config.getConfigSources()){
+ if(cs.getName().equals(propertysource)){
+ return cs;
+ }
+ }
+ return null;
+ }
+
public static String getPropertySource(String propertysource) throws IOException {
- Configuration config = ConfigurationProvider.getConfiguration();
+ Config config = ConfigProvider.getConfig();
if(propertysource!=null){
- PropertySource ps = config.getContext().getPropertySource(propertysource);
+ ConfigSource ps = getPropertySource(config, propertysource);
if(ps==null){
- return "No such Property Source: " + propertysource;
+ return "No such Config Source: " + propertysource;
}else {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
- pw.println("Property Source");
- pw.println("---------------");
+ pw.println("Config Source");
+ pw.println("-------------");
pw.println(StringUtil.format("ID:", 20) + ps.getName());
pw.println(StringUtil.format("Ordinal:", 20) + ps.getOrdinal());
pw.println(StringUtil.format("Class:", 20) + ps.getClass().getName());
@@ -181,11 +184,11 @@ public final class ConfigCommands {
pw.print(StringUtil.format("Source", 20));
pw.println(StringUtil.format("Meta-Entries", 20));
pw.println(" " + StringUtil.printRepeat("-", 80));
- for(PropertyValue pv:ps.getProperties().values()) {
+ for(Map.Entry<String,String> pv:ps.getProperties().entrySet()) {
pw.print(" " + StringUtil.format(pv.getKey(), 20));
pw.print(StringUtil.format(pv.getValue(), 20));
- pw.print(StringUtil.format(pv.getSource(), 20));
- pw.println(StringUtil.format(pv.getMetaEntries().toString(), 80));
+ pw.println(StringUtil.format(ps.getName(), 20));
+// pw.println(StringUtil.format(pv.getMetaEntries().toString(), 80));
}
pw.flush();
return sw.toString();
@@ -193,10 +196,10 @@ public final class ConfigCommands {
}
// Get a name of existing propertysources
List<String> result = new ArrayList<>();
- for(PropertySource ps:config.getContext().getPropertySources()){
+ for(ConfigSource ps:config.getConfigSources()){
result.add(ps.getName());
}
- StringBuilder b = new StringBuilder("Please select a property source:\n");
+ StringBuilder b = new StringBuilder("Please select a config source:\n");
for(String name:result){
b.append(name).append('\n');
}
@@ -204,17 +207,17 @@ public final class ConfigCommands {
}
public static String getPropertySourceOverview() throws IOException {
- Configuration config = ConfigurationProvider.getConfiguration();
+ Config config = ConfigProvider.getConfig();
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
- pw.println("Property Sources");
- pw.println("----------------");
+ pw.println("Config Sources");
+ pw.println("--------------");
pw.print(StringUtil.format("ID", 30));
pw.print(StringUtil.format("Ordinal", 20));
pw.print(StringUtil.format("Class", 40));
pw.println(StringUtil.format("Size", 5));
pw.println(StringUtil.printRepeat("-", 80));
- for(PropertySource ps:config.getContext().getPropertySources()){
+ for(ConfigSource ps:config.getConfigSources()){
pw.print(StringUtil.format(ps.getName(), 30));
pw.print(StringUtil.format(String.valueOf(ps.getOrdinal()), 20));
pw.print(StringUtil.format(ps.getClass().getName(), 40));
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/common/src/test/java/org/apache/tamaya/osgi/TamayaConfigPluginTest.java
----------------------------------------------------------------------
diff --git a/modules/osgi/common/src/test/java/org/apache/tamaya/osgi/TamayaConfigPluginTest.java b/modules/osgi/common/src/test/java/org/apache/tamaya/osgi/TamayaConfigPluginTest.java
index 65e8499..89eab4b 100644
--- a/modules/osgi/common/src/test/java/org/apache/tamaya/osgi/TamayaConfigPluginTest.java
+++ b/modules/osgi/common/src/test/java/org/apache/tamaya/osgi/TamayaConfigPluginTest.java
@@ -22,6 +22,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
+import javax.config.Config;
import java.util.Dictionary;
import java.util.Hashtable;
@@ -78,10 +79,10 @@ public class TamayaConfigPluginTest extends AbstractOSGITest{
@Test
public void getTMUpdateConfig() throws Exception {
- org.apache.tamaya.Configuration config = ((TamayaConfigPlugin)tamayaConfigPlugin).getTamayaConfiguration("java.");
+ Config config = ((TamayaConfigPlugin)tamayaConfigPlugin).getJavaConfiguration("java.");
assertNotNull(config);
- assertNull(config.get("jlkjllj"));
- assertEquals(System.getProperty("java.home"), config.get("home"));
+ assertNull(config.getOptionalValue("jlkjllj", String.class).orElse(null));
+ assertEquals(System.getProperty("java.home"), config.getValue("home", String.class));
}
@Test
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/common/src/test/java/org/apache/tamaya/osgi/commands/ConfigCommandsTest.java
----------------------------------------------------------------------
diff --git a/modules/osgi/common/src/test/java/org/apache/tamaya/osgi/commands/ConfigCommandsTest.java b/modules/osgi/common/src/test/java/org/apache/tamaya/osgi/commands/ConfigCommandsTest.java
index 67bb22e..69834da 100644
--- a/modules/osgi/common/src/test/java/org/apache/tamaya/osgi/commands/ConfigCommandsTest.java
+++ b/modules/osgi/common/src/test/java/org/apache/tamaya/osgi/commands/ConfigCommandsTest.java
@@ -36,10 +36,9 @@ public class ConfigCommandsTest extends AbstractOSGITest{
String result = ConfigCommands.getInfo(tamayaConfigPlugin);
assertNotNull(result);
System.out.println(result);
- assertTrue(result.contains("Property Sources"));
- assertTrue(result.contains("Property Converter"));
- assertTrue(result.contains("Property Filter"));
- assertTrue(result.contains("ConfigurationContext"));
+ assertTrue(result.contains("Config Sources"));
+ assertTrue(result.contains("Converter"));
+ assertTrue(result.contains("Filter"));
assertTrue(result.contains("Configuration"));
}
@@ -128,7 +127,7 @@ public class ConfigCommandsTest extends AbstractOSGITest{
String result = ConfigCommands.getPropertySource("system-properties");
assertNotNull(result);
System.out.println(result);
- assertTrue(result.contains("Property Source"));
+ assertTrue(result.contains("Config Source"));
assertTrue(result.contains("ID"));
assertTrue(result.contains("system-properties"));
assertTrue(result.contains("Ordinal"));
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/common/src/test/resources/META-INF/javaconfig.properties
----------------------------------------------------------------------
diff --git a/modules/osgi/common/src/test/resources/META-INF/javaconfig.properties b/modules/osgi/common/src/test/resources/META-INF/javaconfig.properties
new file mode 100644
index 0000000..d0b0cb8
--- /dev/null
+++ b/modules/osgi/common/src/test/resources/META-INF/javaconfig.properties
@@ -0,0 +1,22 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+#
+[tamaya]my.testProperty1=success1
+[tamaya]my.testProperty2=success2
+[tamaya]my.testProperty3=success3
+[tamaya]my.testProperty4=success4
+[tamaya]java.version=Java2000
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/common/src/test/resources/META-INF/javaconfiguration.properties
----------------------------------------------------------------------
diff --git a/modules/osgi/common/src/test/resources/META-INF/javaconfiguration.properties b/modules/osgi/common/src/test/resources/META-INF/javaconfiguration.properties
deleted file mode 100644
index d0b0cb8..0000000
--- a/modules/osgi/common/src/test/resources/META-INF/javaconfiguration.properties
+++ /dev/null
@@ -1,22 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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.
-#
-[tamaya]my.testProperty1=success1
-[tamaya]my.testProperty2=success2
-[tamaya]my.testProperty3=success3
-[tamaya]my.testProperty4=success4
-[tamaya]java.version=Java2000
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/gogo-shell/bnd.bnd
----------------------------------------------------------------------
diff --git a/modules/osgi/gogo-shell/bnd.bnd b/modules/osgi/gogo-shell/bnd.bnd
index 67e951a..357ffbf 100644
--- a/modules/osgi/gogo-shell/bnd.bnd
+++ b/modules/osgi/gogo-shell/bnd.bnd
@@ -28,7 +28,7 @@ Import-Package: \
org.apache.tamaya,\
org.apache.tamaya.spi,\
org.apache.tamaya.functions,\
- org.apache.tamaya.spisupport,\
+ org.apache.tamaya.base,\
org.apache.tamaya.osgi,\
org.apache.tamaya.osgi.commands,\
org.apache.felix.service.command
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/gogo-shell/pom.xml
----------------------------------------------------------------------
diff --git a/modules/osgi/gogo-shell/pom.xml b/modules/osgi/gogo-shell/pom.xml
index b1a3845..0c971d9 100644
--- a/modules/osgi/gogo-shell/pom.xml
+++ b/modules/osgi/gogo-shell/pom.xml
@@ -70,6 +70,12 @@
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.apache.tamaya</groupId>
+ <artifactId>tamaya-core</artifactId>
+ <version>${project.parent.version}</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
</project>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/gogo-shell/src/test/java/org/apache/tamaya/gogo/shell/ConfigCommandsTest.java
----------------------------------------------------------------------
diff --git a/modules/osgi/gogo-shell/src/test/java/org/apache/tamaya/gogo/shell/ConfigCommandsTest.java b/modules/osgi/gogo-shell/src/test/java/org/apache/tamaya/gogo/shell/ConfigCommandsTest.java
index dde7b42..b4e268f 100644
--- a/modules/osgi/gogo-shell/src/test/java/org/apache/tamaya/gogo/shell/ConfigCommandsTest.java
+++ b/modules/osgi/gogo-shell/src/test/java/org/apache/tamaya/gogo/shell/ConfigCommandsTest.java
@@ -56,8 +56,8 @@ public class ConfigCommandsTest extends AbstractOSGITest{
commands.tm_propertysources();
return null;
});
- assertTrue(out.startsWith("Property Sources"));
- assertTrue(out.contains( "----------------"));
+ assertTrue(out.startsWith("Config Sources"));
+ assertTrue(out.contains( "--------------"));
assertTrue(out.contains("ID"));
assertTrue(out.contains("Ordinal"));
assertTrue(out.contains("Class"));
@@ -83,7 +83,7 @@ public class ConfigCommandsTest extends AbstractOSGITest{
return null;
});
assertTrue(out.contains(System.getProperty("java.version")));
- assertTrue(out.contains("Property Source"));
+ assertTrue(out.contains("Config Source"));
assertTrue(out.contains("Value"));
assertTrue(out.contains("system-properties"));
}
@@ -94,13 +94,13 @@ public class ConfigCommandsTest extends AbstractOSGITest{
commands.tm_propertysource("system-properties");
return null;
});
- assertTrue(out.startsWith("Property Source"));
+ assertTrue(out.startsWith("Config Source"));
assertTrue(out.contains("ID"));
assertTrue(out.contains("system-properties"));
assertTrue(out.contains("Ordinal"));
assertTrue(out.contains("1000"));
assertTrue(out.contains("Class"));
- assertTrue(out.contains("SystemPropertySource"));
+ assertTrue(out.contains("SystemConfigSource"));
assertTrue(out.contains("Properties"));
assertTrue(out.contains("Key"));
assertTrue(out.contains("Value"));
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/injection/bnd.bnd
----------------------------------------------------------------------
diff --git a/modules/osgi/injection/bnd.bnd b/modules/osgi/injection/bnd.bnd
index 69e9637..cd67c72 100644
--- a/modules/osgi/injection/bnd.bnd
+++ b/modules/osgi/injection/bnd.bnd
@@ -27,7 +27,7 @@ Import-Package: \
org.apache.tamaya,\
org.apache.tamaya.spi,\
org.apache.tamaya.functions,\
- org.apache.tamaya.spisupport,\
+ org.apache.tamaya.base,\
org.apache.tamaya.osgi,\
org.apache.tamaya.inject.api,\
org.apache.tamaya.inject.spi,\
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/injection/pom.xml
----------------------------------------------------------------------
diff --git a/modules/osgi/injection/pom.xml b/modules/osgi/injection/pom.xml
index 692e98f..6c6334f 100644
--- a/modules/osgi/injection/pom.xml
+++ b/modules/osgi/injection/pom.xml
@@ -67,6 +67,12 @@
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.apache.tamaya</groupId>
+ <artifactId>tamaya-core</artifactId>
+ <version>${project.parent.version}</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
</project>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/injection/src/main/java/org/apache/tamaya/osgi/injection/OSGIConfigAdminPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/osgi/injection/src/main/java/org/apache/tamaya/osgi/injection/OSGIConfigAdminPropertySource.java b/modules/osgi/injection/src/main/java/org/apache/tamaya/osgi/injection/OSGIConfigAdminPropertySource.java
index 6c5b00a..bef34eb 100644
--- a/modules/osgi/injection/src/main/java/org/apache/tamaya/osgi/injection/OSGIConfigAdminPropertySource.java
+++ b/modules/osgi/injection/src/main/java/org/apache/tamaya/osgi/injection/OSGIConfigAdminPropertySource.java
@@ -18,8 +18,7 @@
*/
package org.apache.tamaya.osgi.injection;
-import org.apache.tamaya.spi.PropertyValue;
-import org.apache.tamaya.spisupport.propertysource.BasePropertySource;
+import org.apache.tamaya.base.configsource.BaseConfigSource;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
@@ -32,7 +31,7 @@ import java.util.logging.Logger;
* This is a Tamaya PropertySource, which internally wraps the OSGI ConfigAdmin service, preconfigured
* for a PID and (optionally) location.
*/
-public class OSGIConfigAdminPropertySource extends BasePropertySource{
+public class OSGIConfigAdminPropertySource extends BaseConfigSource{
private static final Logger LOG = Logger.getLogger(OSGIConfigAdminPropertySource.class.getName());
private ConfigurationAdmin configurationAdmin;
@@ -67,14 +66,14 @@ public class OSGIConfigAdminPropertySource extends BasePropertySource{
}
@Override
- public PropertyValue get(String key) {
+ public String getValue(String key) {
try {
Configuration osgiConfig = configurationAdmin.getConfiguration(pid, location);
Dictionary<String,Object> props = osgiConfig.getProperties();
if(props!=null){
Object value = props.get(key);
if(value!=null) {
- return PropertyValue.of(key, String.valueOf(value), "OSGI ConfigAdmin: " + pid);
+ return String.valueOf(value);
}
}
} catch (IOException e) {
@@ -84,17 +83,17 @@ public class OSGIConfigAdminPropertySource extends BasePropertySource{
}
@Override
- public Map<String, PropertyValue> getProperties() {
+ public Map<String, String> getProperties() {
try {
Configuration osgiConfig = configurationAdmin.getConfiguration(pid);
Dictionary<String,Object> props = osgiConfig.getProperties();
if(props!=null){
- Map<String, PropertyValue> result = new HashMap<>();
+ Map<String, String> result = new HashMap<>();
Enumeration<String> keys = props.keys();
while(keys.hasMoreElements()){
String key = keys.nextElement();
Object value = props.get(key);
- result.put(key, PropertyValue.of(key, String.valueOf(value), "OSGI ConfigAdmin: " + pid));
+ result.put(key, String.valueOf(value));
}
return result;
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/injection/src/main/java/org/apache/tamaya/osgi/injection/OSGIConfigurationInjector.java
----------------------------------------------------------------------
diff --git a/modules/osgi/injection/src/main/java/org/apache/tamaya/osgi/injection/OSGIConfigurationInjector.java b/modules/osgi/injection/src/main/java/org/apache/tamaya/osgi/injection/OSGIConfigurationInjector.java
index dc90449..073f5a0 100644
--- a/modules/osgi/injection/src/main/java/org/apache/tamaya/osgi/injection/OSGIConfigurationInjector.java
+++ b/modules/osgi/injection/src/main/java/org/apache/tamaya/osgi/injection/OSGIConfigurationInjector.java
@@ -18,11 +18,12 @@
*/
package org.apache.tamaya.osgi.injection;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
import org.apache.tamaya.inject.ConfigurationInjection;
import org.osgi.service.cm.ConfigurationAdmin;
+import javax.config.Config;
+import javax.config.ConfigProvider;
+import javax.config.spi.ConfigProviderResolver;
import java.util.Objects;
import java.util.function.Supplier;
@@ -34,7 +35,7 @@ final class OSGIConfigurationInjector{
/** The OSGI ConfigManager. */
private ConfigurationAdmin cm;
/** The corresponding Tamaya configuration. */
- private Configuration tamayaOSGIConfiguration;
+ private Config javaConfigOSGIConfiguration;
/** The target PID. */
private String pid;
/** The target location. */
@@ -59,12 +60,10 @@ final class OSGIConfigurationInjector{
this.cm = Objects.requireNonNull(cm);
this.pid = Objects.requireNonNull(pid);
this.location = location;
- tamayaOSGIConfiguration = ConfigurationProvider.createConfiguration(
- ConfigurationProvider.getConfigurationContextBuilder()
- .addDefaultPropertyConverters()
- .addDefaultPropertyFilters()
- .addPropertySources(new OSGIConfigAdminPropertySource(cm, pid, location))
- .build());
+ javaConfigOSGIConfiguration = ConfigProviderResolver.instance().getBuilder()
+ .addDiscoveredConverters()
+ .withSources(new OSGIConfigAdminPropertySource(cm, pid, location))
+ .build();
}
/**
@@ -91,7 +90,7 @@ final class OSGIConfigurationInjector{
*/
public <T> T configure(T instance){
return ConfigurationInjection.getConfigurationInjector()
- .configure(instance, tamayaOSGIConfiguration);
+ .configure(instance, javaConfigOSGIConfiguration);
}
/**
@@ -103,7 +102,7 @@ final class OSGIConfigurationInjector{
*/
public <T> Supplier<T> getConfiguredSupplier(java.util.function.Supplier<T> supplier){
return ConfigurationInjection.getConfigurationInjector()
- .getConfiguredSupplier(supplier, tamayaOSGIConfiguration);
+ .getConfiguredSupplier(supplier, javaConfigOSGIConfiguration);
}
/**
@@ -115,6 +114,6 @@ final class OSGIConfigurationInjector{
*/
public <T> T createTemplate(Class<T> templateType){
return ConfigurationInjection.getConfigurationInjector()
- .createTemplate(templateType, tamayaOSGIConfiguration);
+ .createTemplate(templateType, javaConfigOSGIConfiguration);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/injection/src/main/java/org/apache/tamaya/osgi/injection/TamayaOSGIInjector.java
----------------------------------------------------------------------
diff --git a/modules/osgi/injection/src/main/java/org/apache/tamaya/osgi/injection/TamayaOSGIInjector.java b/modules/osgi/injection/src/main/java/org/apache/tamaya/osgi/injection/TamayaOSGIInjector.java
index fe0fe78..18e0bd6 100644
--- a/modules/osgi/injection/src/main/java/org/apache/tamaya/osgi/injection/TamayaOSGIInjector.java
+++ b/modules/osgi/injection/src/main/java/org/apache/tamaya/osgi/injection/TamayaOSGIInjector.java
@@ -18,7 +18,6 @@
*/
package org.apache.tamaya.osgi.injection;
-import org.apache.tamaya.Configuration;
import org.apache.tamaya.osgi.TamayaConfigPlugin;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/injection/src/test/java/org/apache/tamaya/osgi/injection/Example.java
----------------------------------------------------------------------
diff --git a/modules/osgi/injection/src/test/java/org/apache/tamaya/osgi/injection/Example.java b/modules/osgi/injection/src/test/java/org/apache/tamaya/osgi/injection/Example.java
index b5726ad..ae66e94 100644
--- a/modules/osgi/injection/src/test/java/org/apache/tamaya/osgi/injection/Example.java
+++ b/modules/osgi/injection/src/test/java/org/apache/tamaya/osgi/injection/Example.java
@@ -18,7 +18,8 @@
*/
package org.apache.tamaya.osgi.injection;
-import org.apache.tamaya.inject.api.Config;
+
+import javax.config.inject.ConfigProperty;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@@ -27,11 +28,11 @@ import static org.junit.Assert.assertNotNull;
* Example class to be configured with injection.
*/
final class Example {
- @Config("java.home")
+ @ConfigProperty(name ="java.home")
String javaHome;
- @Config("java.version")
+ @ConfigProperty(name ="java.version")
String javaVersion;
- @Config(value = "java.used", defaultValue = "true")
+ @ConfigProperty(name = "java.used", defaultValue = "true")
boolean javaUsed;
static void checkExampleConfig(Example example) {
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/injection/src/test/java/org/apache/tamaya/osgi/injection/OSGIConfigAdminPropertySourceTest.java
----------------------------------------------------------------------
diff --git a/modules/osgi/injection/src/test/java/org/apache/tamaya/osgi/injection/OSGIConfigAdminPropertySourceTest.java b/modules/osgi/injection/src/test/java/org/apache/tamaya/osgi/injection/OSGIConfigAdminPropertySourceTest.java
index cff8c3f..a2b4cf4 100644
--- a/modules/osgi/injection/src/test/java/org/apache/tamaya/osgi/injection/OSGIConfigAdminPropertySourceTest.java
+++ b/modules/osgi/injection/src/test/java/org/apache/tamaya/osgi/injection/OSGIConfigAdminPropertySourceTest.java
@@ -18,7 +18,6 @@
*/
package org.apache.tamaya.osgi.injection;
-import org.apache.tamaya.spi.PropertyValue;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -62,27 +61,20 @@ public class OSGIConfigAdminPropertySourceTest extends AbstractOSGITest{
}
@Test
- public void isScannable() throws Exception {
- assertEquals(true, propertySource.isScannable());
- }
-
- @Test
- public void get() throws Exception {
- PropertyValue val = propertySource.get("java.home");
+ public void getValue() throws Exception {
+ String val = propertySource.getValue("java.home");
assertNotNull(val);
- assertEquals(val.getKey(), "java.home");
- assertEquals(val.getValue(), System.getProperty("java.home"));
- val = propertySource.get("foo.bar");
+ assertEquals(val, System.getProperty("java.home"));
+ val = propertySource.getValue("foo.bar");
assertNull(val);
}
@Test
public void getProperties() throws Exception {
- Map<String,PropertyValue> props = propertySource.getProperties();
+ Map<String,String> props = propertySource.getProperties();
assertNotNull(props);
- PropertyValue val = props.get("java.home");
- assertEquals(val.getKey(), "java.home");
- assertEquals(val.getValue(), System.getProperty("java.home"));
+ String val = props.get("java.home");
+ assertEquals(val, System.getProperty("java.home"));
val = props.get("foo.bar");
assertNull(val);
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/injection/src/test/java/org/apache/tamaya/osgi/injection/TemplateExample.java
----------------------------------------------------------------------
diff --git a/modules/osgi/injection/src/test/java/org/apache/tamaya/osgi/injection/TemplateExample.java b/modules/osgi/injection/src/test/java/org/apache/tamaya/osgi/injection/TemplateExample.java
index 4605b4d..1005d2f 100644
--- a/modules/osgi/injection/src/test/java/org/apache/tamaya/osgi/injection/TemplateExample.java
+++ b/modules/osgi/injection/src/test/java/org/apache/tamaya/osgi/injection/TemplateExample.java
@@ -18,19 +18,20 @@
*/
package org.apache.tamaya.osgi.injection;
-import org.apache.tamaya.inject.api.Config;
+
+import javax.config.inject.ConfigProperty;
/**
* Example template interface.
*/
interface TemplateExample {
- @Config("java.home")
+ @ConfigProperty(name ="java.home")
String getJavaHome();
- @Config("java.version")
+ @ConfigProperty(name ="java.version")
String javaVersion();
- @Config(value = "java.used", defaultValue = "true")
+ @ConfigProperty(name = "java.used", defaultValue = "true")
boolean isJavaUsed();
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/karaf-features/src/main/features/features.xml
----------------------------------------------------------------------
diff --git a/modules/osgi/karaf-features/src/main/features/features.xml b/modules/osgi/karaf-features/src/main/features/features.xml
index 34949b7..935dcc5 100644
--- a/modules/osgi/karaf-features/src/main/features/features.xml
+++ b/modules/osgi/karaf-features/src/main/features/features.xml
@@ -20,7 +20,7 @@ limitations under the License.
<features name="org-apache-tamaya-configadmin" version="0.4-incubating">
<bundle>mvn:org.apache.tamaya.ext/tamaya-osgi_alpha/0.4-incubating/jar</bundle>
<bundle>mvn:org.apache.tamaya.ext/tamaya-functions/0.4-incubating/jar</bundle>
- <bundle>mvn:org.apache.tamaya/tamaya-spisupport/0.4-incubating/jar</bundle>
+ <bundle>mvn:org.apache.tamaya/tamaya-base/0.4-incubating/jar</bundle>
<bundle>mvn:org.apache.tamaya.ext/tamaya-osgi-karaf_alpha/0.4-incubating/jar</bundle>
<features name="org-apache-tamaya-minimal" version="0.4-incubating">
<feature name="org-apache-tamaya-api" version="0.4-incubating">
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/karaf-shell/bnd.bnd
----------------------------------------------------------------------
diff --git a/modules/osgi/karaf-shell/bnd.bnd b/modules/osgi/karaf-shell/bnd.bnd
index 3bed7ca..a1bf0c7 100644
--- a/modules/osgi/karaf-shell/bnd.bnd
+++ b/modules/osgi/karaf-shell/bnd.bnd
@@ -27,7 +27,7 @@ Import-Package: \
org.apache.tamaya,\
org.apache.tamaya.spi,\
org.apache.tamaya.functions,\
- org.apache.tamaya.spisupport,\
+ org.apache.tamaya.base,\
org.apache.tamaya.osgi,\
org.apache.tamaya.osgi.commands,\
org.apache.felix.service.command,\
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/karaf-shell/src/main/java/org/apache/tamaya/karaf/shell/PropertySourcesCommand.java
----------------------------------------------------------------------
diff --git a/modules/osgi/karaf-shell/src/main/java/org/apache/tamaya/karaf/shell/PropertySourcesCommand.java b/modules/osgi/karaf-shell/src/main/java/org/apache/tamaya/karaf/shell/PropertySourcesCommand.java
index 7aa660d..e9d3d4d 100644
--- a/modules/osgi/karaf-shell/src/main/java/org/apache/tamaya/karaf/shell/PropertySourcesCommand.java
+++ b/modules/osgi/karaf-shell/src/main/java/org/apache/tamaya/karaf/shell/PropertySourcesCommand.java
@@ -21,10 +21,7 @@ package org.apache.tamaya.karaf.shell;
import org.apache.karaf.shell.api.action.Action;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
import org.apache.tamaya.osgi.commands.ConfigCommands;
-import org.apache.tamaya.spi.PropertySource;
import java.io.IOException;
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/updater/bnd.bnd
----------------------------------------------------------------------
diff --git a/modules/osgi/updater/bnd.bnd b/modules/osgi/updater/bnd.bnd
index 416db00..69ae1ea 100644
--- a/modules/osgi/updater/bnd.bnd
+++ b/modules/osgi/updater/bnd.bnd
@@ -29,6 +29,6 @@ Import-Package: \
org.apache.tamaya,\
org.apache.tamaya.spi,\
org.apache.tamaya.functions,\
- org.apache.tamaya.spisupport,\
+ org.apache.tamaya.base,\
org.apache.tamaya.events
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/updater/pom.xml
----------------------------------------------------------------------
diff --git a/modules/osgi/updater/pom.xml b/modules/osgi/updater/pom.xml
index 2819239..9aaa7ad 100644
--- a/modules/osgi/updater/pom.xml
+++ b/modules/osgi/updater/pom.xml
@@ -44,13 +44,9 @@
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-api</artifactId>
- <version>${project.parent.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.tamaya</groupId>
<artifactId>tamaya-core</artifactId>
<version>${project.parent.version}</version>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tamaya.ext</groupId>
@@ -59,7 +55,7 @@
</dependency>
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-spisupport</artifactId>
+ <artifactId>tamaya-base</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/updater/src/main/java/org/apache/tamaya/osgi/updater/Activator.java
----------------------------------------------------------------------
diff --git a/modules/osgi/updater/src/main/java/org/apache/tamaya/osgi/updater/Activator.java b/modules/osgi/updater/src/main/java/org/apache/tamaya/osgi/updater/Activator.java
index a83f18f..d8a8113 100644
--- a/modules/osgi/updater/src/main/java/org/apache/tamaya/osgi/updater/Activator.java
+++ b/modules/osgi/updater/src/main/java/org/apache/tamaya/osgi/updater/Activator.java
@@ -19,7 +19,7 @@
package org.apache.tamaya.osgi.updater;
import org.apache.tamaya.events.ConfigEventManager;
-import org.apache.tamaya.events.ConfigurationChange;
+import org.apache.tamaya.events.ConfigChange;
import org.apache.tamaya.osgi.commands.TamayaConfigService;
import org.osgi.framework.*;
import org.osgi.service.cm.ConfigurationAdmin;
@@ -51,7 +51,7 @@ public class Activator implements BundleActivator {
@Override
public void start(BundleContext context) throws Exception {
listener = new EventListener(context);
- ConfigEventManager.addListener(listener, ConfigurationChange.class);
+ ConfigEventManager.addListener(listener, ConfigChange.class);
LOG.info("Registered Tamaya getConfig trigger for OSGI.");
ServiceReference<TamayaConfigService> pluginRef = context.getServiceReference(TamayaConfigService.class);
TamayaConfigService tamayaPlugin = context.getService(pluginRef);
@@ -67,7 +67,7 @@ public class Activator implements BundleActivator {
public void stop(BundleContext context) throws Exception {
updateTimer.cancel();
if (listener != null) {
- ConfigEventManager.removeListener(this.listener, ConfigurationChange.class);
+ ConfigEventManager.removeListener(this.listener, ConfigChange.class);
LOG.info("Unregistered Tamaya getConfig trigger for OSGI.");
ConfigEventManager.enableChangeMonitoring(false);
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/updater/src/main/java/org/apache/tamaya/osgi/updater/EventListener.java
----------------------------------------------------------------------
diff --git a/modules/osgi/updater/src/main/java/org/apache/tamaya/osgi/updater/EventListener.java b/modules/osgi/updater/src/main/java/org/apache/tamaya/osgi/updater/EventListener.java
index 68e9bcb..97a3159 100644
--- a/modules/osgi/updater/src/main/java/org/apache/tamaya/osgi/updater/EventListener.java
+++ b/modules/osgi/updater/src/main/java/org/apache/tamaya/osgi/updater/EventListener.java
@@ -20,7 +20,7 @@ package org.apache.tamaya.osgi.updater;
import org.apache.tamaya.events.ConfigEvent;
import org.apache.tamaya.events.ConfigEventListener;
-import org.apache.tamaya.events.ConfigurationChange;
+import org.apache.tamaya.events.ConfigChange;
import org.apache.tamaya.osgi.Policy;
import org.apache.tamaya.osgi.commands.TamayaConfigService;
import org.osgi.framework.*;
@@ -47,7 +47,7 @@ final class EventListener implements ConfigEventListener{
public void onConfigEvent(ConfigEvent<?> event) {
LOG.finest("Tamya Config change triggered: " + event);
Set<String> changedPids = new HashSet<>();
- ConfigurationChange cc = (ConfigurationChange)event;
+ ConfigChange cc = (ConfigChange)event;
for(PropertyChangeEvent evt: cc.getChanges()){
String key = evt.getPropertyName();
String pid = getPid(key);
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/osgi/updater/src/test/java/org/apache/tamaya/osgi/updater/EventListenerTest.java
----------------------------------------------------------------------
diff --git a/modules/osgi/updater/src/test/java/org/apache/tamaya/osgi/updater/EventListenerTest.java b/modules/osgi/updater/src/test/java/org/apache/tamaya/osgi/updater/EventListenerTest.java
index 6ffd618..a51bc7b 100644
--- a/modules/osgi/updater/src/test/java/org/apache/tamaya/osgi/updater/EventListenerTest.java
+++ b/modules/osgi/updater/src/test/java/org/apache/tamaya/osgi/updater/EventListenerTest.java
@@ -19,7 +19,7 @@
package org.apache.tamaya.osgi.updater;
import org.apache.tamaya.events.ConfigEvent;
-import org.apache.tamaya.events.ConfigurationChangeBuilder;
+import org.apache.tamaya.events.ConfigChangeBuilder;
import org.apache.tamaya.osgi.commands.TamayaConfigService;
import org.junit.Before;
import org.junit.Test;
@@ -44,14 +44,14 @@ public class EventListenerTest extends AbstractOSGITest{
@Test
public void testEventWithNoDataDoesNotTriggerTamayaServices() throws Exception {
- ConfigEvent evt = ConfigurationChangeBuilder.of().addChange("a", "b").build();
+ ConfigEvent evt = ConfigChangeBuilder.of().addChange("a", "b").build();
eventListener.onConfigEvent(evt);
verify(bundleContext, never()).getServiceReference(TamayaConfigService.class);
}
@Test
public void testEventForPIDDoesTriggerTamayaServices() throws Exception {
- ConfigEvent evt = ConfigurationChangeBuilder.of().addChange("[PID.foo]a", "b").build();
+ ConfigEvent evt = ConfigChangeBuilder.of().addChange("[PID.foo]a", "b").build();
eventListener.onConfigEvent(evt);
verify(bundleContext).getServiceReference(TamayaConfigService.class);
verify(tamayaConfigService).updateConfig("PID.foo");
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/pom.xml
----------------------------------------------------------------------
diff --git a/modules/pom.xml b/modules/pom.xml
index bd7abe0..24675fb 100644
--- a/modules/pom.xml
+++ b/modules/pom.xml
@@ -43,7 +43,7 @@ under the License.
<module>spring</module>
<module>jndi</module>
<module>osgi</module>
- <module>microprofile</module>
+ <!--<module>microprofile</module>-->
<module>injection</module>
</modules>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ExpressionResolutionFilter.java
----------------------------------------------------------------------
diff --git a/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ExpressionResolutionFilter.java b/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ExpressionResolutionFilter.java
index 75e4624..0786a94 100644
--- a/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ExpressionResolutionFilter.java
+++ b/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ExpressionResolutionFilter.java
@@ -19,7 +19,6 @@
package org.apache.tamaya.resolver.internal;
import org.apache.tamaya.resolver.spi.ExpressionEvaluator;
-import org.apache.tamaya.spi.ConfigValue;
import org.apache.tamaya.spi.Filter;
import org.apache.tamaya.spi.ServiceContextManager;
@@ -82,11 +81,11 @@ public class ExpressionResolutionFilter implements Filter {
* @return the resolved value, or the input in case where no expression was detected.
*/
@Override
- public ConfigValue filterProperty(ConfigValue valueToBeFiltered){
- LOG.finest("Resolving " + valueToBeFiltered);
- String newVal = evaluator().evaluateExpression(valueToBeFiltered.getKey(), valueToBeFiltered.getValue(), true);
+ public String filterProperty(String key, String valueToBeFiltered){
+ LOG.finest(() -> "Resolving " + valueToBeFiltered + "("+key+")");
+ String newVal = evaluator().evaluateExpression(key, valueToBeFiltered, true);
if(newVal!=null){
- return valueToBeFiltered.toBuilder().setValue(newVal).build();
+ return newVal;
}
return null;
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ResolvableConfig.java
----------------------------------------------------------------------
diff --git a/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ResolvableConfig.java b/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ResolvableConfig.java
index 1abed5b..7dca6d0 100644
--- a/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ResolvableConfig.java
+++ b/modules/resolver/src/main/java/org/apache/tamaya/resolver/internal/ResolvableConfig.java
@@ -85,15 +85,16 @@ public final class ResolvableConfig implements Config{
@Override
public <T> Optional<T> getOptionalValue(String propertyName, Class<T> propertyType) {
- ConfigValue value = ConfigValue.of(
- propertyName, delegate.getValue(propertyName, String.class), null);
- value = filterManager.filterValue(value);
- if(value!=null){
- if(String.class.equals(propertyType)) {
- return Optional.ofNullable((T) value.getValue());
+ Optional<String> value = delegate.getOptionalValue(propertyName, String.class);
+ if(value.isPresent()) {
+ String filtered = filterManager.filterValue(propertyName, value.get(), delegate);
+ if (filtered != null) {
+ if (String.class.equals(propertyType)) {
+ return Optional.ofNullable((T) filtered);
+ }
+ return Optional.ofNullable(
+ (T) converterManager.convertValue(filtered, propertyType));
}
- return Optional.ofNullable(
- (T)converterManager.convertValue(propertyName, value.getValue(), propertyType, this));
}
return Optional.empty();
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/resolver/src/main/java/org/apache/tamaya/resolver/spi/ExpressionEvaluator.java
----------------------------------------------------------------------
diff --git a/modules/resolver/src/main/java/org/apache/tamaya/resolver/spi/ExpressionEvaluator.java b/modules/resolver/src/main/java/org/apache/tamaya/resolver/spi/ExpressionEvaluator.java
index 96dbb66..bd3aa87 100644
--- a/modules/resolver/src/main/java/org/apache/tamaya/resolver/spi/ExpressionEvaluator.java
+++ b/modules/resolver/src/main/java/org/apache/tamaya/resolver/spi/ExpressionEvaluator.java
@@ -41,7 +41,7 @@ import java.util.Collection;
* Also multiple expressions are supported, e.g. ${resource:META-INF/version.conf}, ${file:C:/temp/version.txt},
* ${url:http://configserver/name}.
* </pre>
- * Basically this service is consumed by an instance of {@link org.apache.tamaya.spi.PropertyFilter}, which
+ * Basically this service is consumed by an instance of {@link org.apache.tamaya.spi.Filter}, which
* takes the configuration values found and passes them to this evaluator, when expressions are detected. This
* also done iteratively, so also multi-stepped references (references, which themselves must be evaluated as well)
* are supported.
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/spring/pom.xml
----------------------------------------------------------------------
diff --git a/modules/spring/pom.xml b/modules/spring/pom.xml
index b3a4e1a..97604e0 100644
--- a/modules/spring/pom.xml
+++ b/modules/spring/pom.xml
@@ -55,12 +55,6 @@ under the License.
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-api</artifactId>
- <version>${tamaya-apicore.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
<groupId>org.apache.tamaya.ext</groupId>
<artifactId>tamaya-injection</artifactId>
<version>${project.version}</version>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/spring/src/main/java/org/apache/tamaya/integration/spring/SpringConfigInjectionPostProcessor.java
----------------------------------------------------------------------
diff --git a/modules/spring/src/main/java/org/apache/tamaya/integration/spring/SpringConfigInjectionPostProcessor.java b/modules/spring/src/main/java/org/apache/tamaya/integration/spring/SpringConfigInjectionPostProcessor.java
index 0bcc5c3..7cc43d6 100644
--- a/modules/spring/src/main/java/org/apache/tamaya/integration/spring/SpringConfigInjectionPostProcessor.java
+++ b/modules/spring/src/main/java/org/apache/tamaya/integration/spring/SpringConfigInjectionPostProcessor.java
@@ -21,12 +21,8 @@ package org.apache.tamaya.integration.spring;
import org.apache.tamaya.inject.ConfigurationInjection;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
-import org.springframework.cglib.core.ReflectUtils;
-import org.springframework.cglib.proxy.Enhancer;
import org.springframework.stereotype.Component;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Proxy;
/**
* PostProcessor that performs injection of configured values using Tamaya {@link ConfigurationInjection}.
@@ -36,7 +32,9 @@ public class SpringConfigInjectionPostProcessor implements BeanPostProcessor{
@Override
public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
- ConfigurationInjection.getConfigurationInjector().configure(o);
+ if(ConfigurationInjection.getConfigurationInjector().isConfigured(o)){
+ ConfigurationInjection.getConfigurationInjector().configure(o);
+ }
return o;
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/spring/src/main/java/org/apache/tamaya/integration/spring/TamayaEnvironment.java
----------------------------------------------------------------------
diff --git a/modules/spring/src/main/java/org/apache/tamaya/integration/spring/TamayaEnvironment.java b/modules/spring/src/main/java/org/apache/tamaya/integration/spring/TamayaEnvironment.java
index 7f1000e..11393c5 100644
--- a/modules/spring/src/main/java/org/apache/tamaya/integration/spring/TamayaEnvironment.java
+++ b/modules/spring/src/main/java/org/apache/tamaya/integration/spring/TamayaEnvironment.java
@@ -28,6 +28,6 @@ public class TamayaEnvironment extends StandardEnvironment{
protected void customizePropertySources(MutablePropertySources propertySources) {
super.customizePropertySources(propertySources);
- propertySources.addLast(new TamayaSpringPropertySource());
+ propertySources.addLast(new TamayaSpringConfigSource());
}
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/spring/src/main/java/org/apache/tamaya/integration/spring/TamayaSpringConfig.java
----------------------------------------------------------------------
diff --git a/modules/spring/src/main/java/org/apache/tamaya/integration/spring/TamayaSpringConfig.java b/modules/spring/src/main/java/org/apache/tamaya/integration/spring/TamayaSpringConfig.java
index 7c9966b..14b7a1e 100644
--- a/modules/spring/src/main/java/org/apache/tamaya/integration/spring/TamayaSpringConfig.java
+++ b/modules/spring/src/main/java/org/apache/tamaya/integration/spring/TamayaSpringConfig.java
@@ -30,7 +30,7 @@ import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
- * Spring Configuration Bean adding {@link TamayaSpringPropertySource} to the current
+ * Spring Configuration Bean adding {@link TamayaSpringConfigSource} to the current
* {@link org.springframework.core.env.Environment}.
*/
@Component
@@ -42,14 +42,14 @@ public class TamayaSpringConfig {
@PostConstruct
public void init() {
- env.getPropertySources().addFirst(new TamayaSpringPropertySource());
+ env.getPropertySources().addFirst(new TamayaSpringConfigSource());
}
@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
PropertySourcesPlaceholderConfigurer cfgBean = new PropertySourcesPlaceholderConfigurer();
MutablePropertySources sources = new MutablePropertySources();
- sources.addFirst(new TamayaSpringPropertySource());
+ sources.addFirst(new TamayaSpringConfigSource());
cfgBean.setPropertySources(sources);
return cfgBean;
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/spring/src/main/java/org/apache/tamaya/integration/spring/TamayaSpringConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/spring/src/main/java/org/apache/tamaya/integration/spring/TamayaSpringConfigSource.java b/modules/spring/src/main/java/org/apache/tamaya/integration/spring/TamayaSpringConfigSource.java
new file mode 100644
index 0000000..0c160e1
--- /dev/null
+++ b/modules/spring/src/main/java/org/apache/tamaya/integration/spring/TamayaSpringConfigSource.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.integration.spring;
+
+
+import org.springframework.core.env.PropertySource;
+
+import javax.config.ConfigProvider;
+
+/**
+ * Spring PropertySource bridging to Tamaya {@link javax.config.Config}.
+ */
+public class TamayaSpringConfigSource extends PropertySource<String> {
+
+ public TamayaSpringConfigSource() {
+ super("ApacheTamayaConfig");
+ }
+
+ @Override
+ public String getProperty(String name) {
+ return ConfigProvider.getConfig().getOptionalValue(name, String.class).orElse(null);
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/spring/src/main/java/org/apache/tamaya/integration/spring/TamayaSpringPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/spring/src/main/java/org/apache/tamaya/integration/spring/TamayaSpringPropertySource.java b/modules/spring/src/main/java/org/apache/tamaya/integration/spring/TamayaSpringPropertySource.java
deleted file mode 100644
index 2e8ac1c..0000000
--- a/modules/spring/src/main/java/org/apache/tamaya/integration/spring/TamayaSpringPropertySource.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.integration.spring;
-
-
-import org.apache.tamaya.ConfigurationProvider;
-import org.springframework.core.env.PropertySource;
-
-/**
- * Spring PropertySource bridging to Tamaya {@link org.apache.tamaya.Configuration}.
- */
-public class TamayaSpringPropertySource extends PropertySource<String> {
-
- public TamayaSpringPropertySource() {
- super("ApacheTamayaConfig");
- }
-
- @Override
- public String getProperty(String name) {
- return ConfigurationProvider.getConfiguration().get(name);
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/spring/src/test/java/org/apache/tamaya/integration/spring/ConfiguredSpringBean.java
----------------------------------------------------------------------
diff --git a/modules/spring/src/test/java/org/apache/tamaya/integration/spring/ConfiguredSpringBean.java b/modules/spring/src/test/java/org/apache/tamaya/integration/spring/ConfiguredSpringBean.java
index c43dde0..165baa5 100644
--- a/modules/spring/src/test/java/org/apache/tamaya/integration/spring/ConfiguredSpringBean.java
+++ b/modules/spring/src/test/java/org/apache/tamaya/integration/spring/ConfiguredSpringBean.java
@@ -18,11 +18,12 @@
*/
package org.apache.tamaya.integration.spring;
-import org.apache.tamaya.inject.api.Config;
import org.apache.tamaya.inject.api.ConfigDefaultSections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
+import javax.config.inject.ConfigProperty;
+
/**
* Created by Anatole on 25.09.2015.
*/
@@ -34,10 +35,10 @@ public class ConfiguredSpringBean {
@Autowired
private Environment env;
- @Config("java.version")
+ @ConfigProperty(name="java.version")
private String javaVersion;
- @Config(defaultValue = "23")
+ @ConfigProperty(defaultValue = "23")
private int testNumber;
public String getJavaVersion(){
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/spring/src/test/java/org/apache/tamaya/integration/spring/SpringConfigTest2.java
----------------------------------------------------------------------
diff --git a/modules/spring/src/test/java/org/apache/tamaya/integration/spring/SpringConfigTest2.java b/modules/spring/src/test/java/org/apache/tamaya/integration/spring/SpringConfigTest2.java
index 6eab61d..4e4f8d9 100644
--- a/modules/spring/src/test/java/org/apache/tamaya/integration/spring/SpringConfigTest2.java
+++ b/modules/spring/src/test/java/org/apache/tamaya/integration/spring/SpringConfigTest2.java
@@ -19,12 +19,8 @@
package org.apache.tamaya.integration.spring;
import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/spring/src/test/resources/META-INF/javaconfig.properties
----------------------------------------------------------------------
diff --git a/modules/spring/src/test/resources/META-INF/javaconfig.properties b/modules/spring/src/test/resources/META-INF/javaconfig.properties
new file mode 100644
index 0000000..3366128
--- /dev/null
+++ b/modules/spring/src/test/resources/META-INF/javaconfig.properties
@@ -0,0 +1,20 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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 current 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.
+#
+myConfiguredValue=value11
+propertyValue=value2
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/spring/src/test/resources/META-INF/javaconfiguration.properties
----------------------------------------------------------------------
diff --git a/modules/spring/src/test/resources/META-INF/javaconfiguration.properties b/modules/spring/src/test/resources/META-INF/javaconfiguration.properties
deleted file mode 100644
index 3366128..0000000
--- a/modules/spring/src/test/resources/META-INF/javaconfiguration.properties
+++ /dev/null
@@ -1,20 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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 current 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.
-#
-myConfiguredValue=value11
-propertyValue=value2
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index 4c45296..c3a17e0 100644
--- a/pom.xml
+++ b/pom.xml
@@ -44,7 +44,8 @@ under the License.
<properties>
<!-- Used version of Tamaya API&Core -->
- <tamaya-apicore.version>0.4-incubating-SNAPSHOT</tamaya-apicore.version>
+ <javaconfig.version>1.0-SNAPSHOT</javaconfig.version>
+ <tamaya-apicore.version>${project.version}</tamaya-apicore.version>
<commons-io.version>2.5</commons-io.version>
<findbugs.skip>false</findbugs.skip>
@@ -332,14 +333,27 @@ under the License.
<artifactId>johnzon-core</artifactId>
<version>${johnzon.version}</version>
</dependency>
+ <dependency>
+ <groupId>javax.config</groupId>
+ <artifactId>javaconfig-api</artifactId>
+ <version>${javaconfig.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.geronimo.specs</groupId>
+ <artifactId>geronimo-annotation_1.2_spec</artifactId>
+ <version>1.0-alpha-1</version>
+ </dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
+ <groupId>javax.config</groupId>
+ <artifactId>javaconfig-api</artifactId>
+ </dependency>
+ <dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-annotation_1.2_spec</artifactId>
- <version>1.0-alpha-1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
@@ -385,7 +399,7 @@ under the License.
<dependency>
<groupId>org.apache.tamaya</groupId>
<artifactId>buildconfigurations</artifactId>
- <version>${tamaya-apicore.version}</version>
+ <version>${tamaya.version}</version>
</dependency>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
@@ -437,7 +451,7 @@ under the License.
<dependency>
<groupId>org.apache.tamaya</groupId>
<artifactId>buildconfigurations</artifactId>
- <version>${tamaya-apicore.version}</version>
+ <version>${tamaya.version}</version>
</dependency>
</dependencies>
</plugin>
[12/18] incubator-tamaya-extensions git commit: Rewrite/adaptation
based on JSR API.
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/converter/BooleanAsIntegerConverterFix.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/converter/BooleanAsIntegerConverterFix.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/converter/BooleanAsIntegerConverterFix.java
deleted file mode 100644
index 1debc71..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/converter/BooleanAsIntegerConverterFix.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile.converter;
-
-import org.apache.tamaya.spi.ConversionContext;
-import org.apache.tamaya.spi.PropertyConverter;
-
-import javax.annotation.Priority;
-import java.util.Locale;
-import java.util.Objects;
-import java.util.logging.Logger;
-
-/**
- * Converter, converting from String to Boolean for 1 = true, otherwise false.
- */
-@Priority(-1)
-public class BooleanAsIntegerConverterFix implements PropertyConverter<Boolean> {
-
- private final Logger LOG = Logger.getLogger(getClass().getName());
-
- @Override
- public Boolean convert(String value, ConversionContext context) {
- context.addSupportedFormats(getClass(), "'1' (true), otherwise false.");
- try{
- int val = Integer.parseInt(Objects.requireNonNull(value).trim());
- if(val==1) {
- return Boolean.TRUE;
- }
- return Boolean.FALSE;
- }catch(Exception e){
- // OK
- return Boolean.FALSE;
- }
- }
-
- @Override
- public boolean equals(Object o){
- return getClass().equals(o.getClass());
- }
-
- @Override
- public int hashCode(){
- return getClass().hashCode();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/converter/ProviderConverter.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/converter/ProviderConverter.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/converter/ProviderConverter.java
deleted file mode 100644
index 163481d..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/converter/ProviderConverter.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile.converter;
-
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.ConfigQuery;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.TypeLiteral;
-import org.apache.tamaya.spi.ConversionContext;
-import org.apache.tamaya.spi.PropertyConverter;
-
-import javax.annotation.Priority;
-import javax.inject.Provider;
-import java.lang.reflect.Type;
-import java.util.List;
-import java.util.Objects;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * Converter, converting from String to Boolean for 1 = true, otherwise false.
- */
-@Priority(-1)
-public class ProviderConverter implements PropertyConverter<Provider> {
-
- private static final Logger LOG = Logger.getLogger(ProviderConverter.class.getName());
-
- @Override
- public Provider convert(String value, ConversionContext context) {
- return () -> {
- try{
- Type targetType = context.getTargetType().getType();
- ConvertQuery converter = new ConvertQuery(value, TypeLiteral.of(targetType));
- return context.getConfiguration().query(converter);
- }catch(Exception e){
- throw new ConfigException("Error evaluating config value.", e);
- }
- };
- }
-
- @Override
- public boolean equals(Object o){
- return getClass().equals(o.getClass());
- }
-
- @Override
- public int hashCode(){
- return getClass().hashCode();
- }
-
- private static final class ConvertQuery<T> implements ConfigQuery<T> {
-
- private String rawValue;
- private TypeLiteral<T> type;
-
- public ConvertQuery(String rawValue, TypeLiteral<T> type) {
- this.rawValue = Objects.requireNonNull(rawValue);
- this.type = Objects.requireNonNull(type);
- }
-
- @Override
- public T query(Configuration config) {
- List<PropertyConverter<T>> converters = config.getContext().getPropertyConverters(type);
- ConversionContext context = new ConversionContext.Builder(type).setConfigurationContext(config.getContext())
- .setConfiguration(config).setKey(ConvertQuery.class.getName()).build();
- for(PropertyConverter<?> conv: converters) {
- try{
- if(conv instanceof ProviderConverter){
- continue;
- }
- T result = (T)conv.convert(rawValue, context);
- if(result!=null){
- return result;
- }
- }catch(Exception e){
- LOG.log(Level.FINEST, e, () -> "Converter "+ conv +" failed to convert to " + type);
- }
- }
- return null;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension b/modules/microprofile/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension
deleted file mode 100644
index 21ec9d5..0000000
--- a/modules/microprofile/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension
+++ /dev/null
@@ -1,20 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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.
-#
-
-org.apache.tamaya.microprofile.cdi.MicroprofileCDIExtension
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertyConverter
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertyConverter b/modules/microprofile/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertyConverter
deleted file mode 100644
index 2205fa2..0000000
--- a/modules/microprofile/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertyConverter
+++ /dev/null
@@ -1,21 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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.
-#
-
-org.apache.tamaya.microprofile.converter.BooleanAsIntegerConverterFix
-org.apache.tamaya.microprofile.converter.ProviderConverter
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertySource b/modules/microprofile/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
deleted file mode 100644
index 585700b..0000000
--- a/modules/microprofile/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
+++ /dev/null
@@ -1,20 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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.
-#
-
-org.apache.tamaya.microprofile.MicroprofileDefaultProperties
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/resources/META-INF/services/org.eclipse.microprofile.config.spi.ConfigProviderResolver
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/resources/META-INF/services/org.eclipse.microprofile.config.spi.ConfigProviderResolver b/modules/microprofile/src/main/resources/META-INF/services/org.eclipse.microprofile.config.spi.ConfigProviderResolver
deleted file mode 100644
index 040f5fd..0000000
--- a/modules/microprofile/src/main/resources/META-INF/services/org.eclipse.microprofile.config.spi.ConfigProviderResolver
+++ /dev/null
@@ -1,20 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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.
-#
-
-org.apache.tamaya.microprofile.MicroprofileConfigProviderResolver
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/resources/beans.xml
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/resources/beans.xml b/modules/microprofile/src/main/resources/beans.xml
deleted file mode 100644
index 9b07802..0000000
--- a/modules/microprofile/src/main/resources/beans.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Licensed to the Apache Software Foundation (ASF) under one
-or more contributor license agreements. See the NOTICE file
-distributed with this work for additional information
-regarding copyright ownership. The ASF licenses this file
-to you 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 current 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.
--->
-<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://jboss.org/schema/cdi/beans_1_0.xsd">
-
-
-</beans>
-
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/BuildableConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/BuildableConfigSource.java b/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/BuildableConfigSource.java
deleted file mode 100644
index 751a866..0000000
--- a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/BuildableConfigSource.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-import org.eclipse.microprofile.config.spi.ConfigSource;
-
-import java.util.*;
-
-/**
- * The Buildable config source.
- */
-public class BuildableConfigSource implements ConfigSource{
-
- private int ordinal;
- private String name = "PropertySource-"+UUID.randomUUID().toString();
- private Map<String,String> properties = new HashMap<>();
-
- @Override
- public int getOrdinal() {
- return ordinal;
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public String getValue(String key) {
- return properties.get(key);
- }
-
- @Override
- public Map<String, String> getProperties() {
- return Collections.unmodifiableMap(properties);
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- BuildableConfigSource that = (BuildableConfigSource) o;
-
- return name.equals(that.name);
- }
-
- @Override
- public int hashCode() {
- return name.hashCode();
- }
-
- @Override
- public String toString() {
- return "BuildableConfigSource{" +
- "ordinal=" + ordinal +
- ", name='" + name + '\'' +
- ", properties=" + properties +
- '}';
- }
-
- /**
- * Builder builder.
- *
- * @return the builder
- */
- public static Builder builder() {
- return new Builder();
- }
-
-
- /**
- * The type Builder.
- */
- public static final class Builder {
- private int ordinal;
- private String source = "<on-the-fly-build>";
- private String name = "ConfigSource-"+ UUID.randomUUID().toString();
- private Map<String,String> properties = new HashMap<>();
-
- private Builder() {
- }
-
- /**
- * With ordinal builder.
- *
- * @param ordinal the ordinal
- * @return the builder
- */
- public Builder withOrdinal(int ordinal) {
- this.ordinal = ordinal;
- return this;
- }
-
- /**
- * With source builder.
- *
- * @param source the source
- * @return the builder
- */
- public Builder withSource(String source) {
- this.source = Objects.requireNonNull(source);
- return this;
- }
-
- /**
- * With name builder.
- *
- * @param name the name
- * @return the builder
- */
- public Builder withName(String name) {
- this.name = Objects.requireNonNull(name);
- return this;
- }
-
- /**
- * With simple property builder.
- *
- * @param key the key
- * @param value the value
- * @return the builder
- */
- public Builder withProperty(String key, String value) {
- this.properties.put(key, value);
- return this;
- }
-
- /**
- * With properties builder.
- *
- * @param values the values
- * @return the builder
- */
- public Builder withProperties(Map<String,String> values) {
- this.properties.putAll(values);
- return this;
- }
-
- /**
- * But builder.
- *
- * @return the builder
- */
- public Builder but() {
- return builder().withOrdinal(ordinal).withName(name).withProperties(properties);
- }
-
- /**
- * Build buildable property source.
- *
- * @return the buildable property source
- */
- public BuildableConfigSource build() {
- BuildableConfigSource buildableConfigSource = new BuildableConfigSource();
- buildableConfigSource.name = this.name;
- buildableConfigSource.properties = this.properties;
- buildableConfigSource.ordinal = this.ordinal;
- return buildableConfigSource;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/ConfigSourceParis.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/ConfigSourceParis.java b/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/ConfigSourceParis.java
deleted file mode 100644
index cb63b10..0000000
--- a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/ConfigSourceParis.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.eclipse.microprofile.config.spi.ConfigSource;
-
-import java.util.Collections;
-import java.util.Map;
-
-public class ConfigSourceParis implements ConfigSource {
- @Override
- public Map<String, String> getProperties() {
- return Collections.emptyMap();
- }
-
- @Override
- public String getValue(String s) {
- if (s.equals("config_ordinal")) {
- return "5";
- }
-
- return null;
- }
-
- @Override
- public String getName() {
- return "paris";
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/ConfigSourceProviderMinsk.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/ConfigSourceProviderMinsk.java b/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/ConfigSourceProviderMinsk.java
deleted file mode 100644
index ffc4ac8..0000000
--- a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/ConfigSourceProviderMinsk.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.eclipse.microprofile.config.spi.ConfigSource;
-import org.eclipse.microprofile.config.spi.ConfigSourceProvider;
-
-import java.util.Collections;
-
-public class ConfigSourceProviderMinsk implements ConfigSourceProvider {
- @Override
- public Iterable<ConfigSource> getConfigSources(ClassLoader classLoader) {
- return Collections::emptyIterator;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileAdapterTest.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileAdapterTest.java b/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileAdapterTest.java
deleted file mode 100644
index a8e8488..0000000
--- a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileAdapterTest.java
+++ /dev/null
@@ -1,246 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.apache.tamaya.*;
-import org.apache.tamaya.spi.ConfigurationContext;
-import org.apache.tamaya.spi.PropertyConverter;
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-import org.apache.tamaya.spisupport.propertysource.BuildablePropertySource;
-import org.assertj.core.api.Assertions;
-import org.eclipse.microprofile.config.Config;
-import org.eclipse.microprofile.config.ConfigProvider;
-import org.eclipse.microprofile.config.spi.ConfigBuilder;
-import org.eclipse.microprofile.config.spi.ConfigSource;
-import org.eclipse.microprofile.config.spi.Converter;
-import org.junit.Test;
-
-import java.util.*;
-
-import static org.junit.Assert.*;
-
-public class MicroprofileAdapterTest {
- @Test
- public void toConfig() throws Exception {
- Configuration config = ConfigurationProvider.getConfiguration();
- Config mpConfig = MicroprofileAdapter.toConfig(config);
- assertNotNull(mpConfig);
- assertEquals(config.getProperties().keySet(), mpConfig.getPropertyNames());
- }
-
- @Test
- public void toConfigWithTamayaConfiguration() throws Exception {
- Configuration configuration = new MyConfiguration();
- MicroprofileConfig config = new MicroprofileConfig(configuration);
- TamayaConfiguration tamayaConfiguration = new TamayaConfiguration(config);
-
- Config result = MicroprofileAdapter.toConfig(tamayaConfiguration);
-
- Assertions.assertThat(result).isNotNull()
- .isInstanceOf(MicroprofileConfig.class)
- .isSameAs(config);
- }
-
- @Test
- public void toConfiguration() throws Exception {
- Config mpConfig = ConfigProvider.getConfig();
- Configuration config = MicroprofileAdapter.toConfiguration(mpConfig);
- assertNotNull(config);
- assertEquals(mpConfig.getPropertyNames(), config.getProperties().keySet());
- }
-
- @Test
- public void toConfigurationWithNoneMicroprofileConfig() throws Exception {
- Config config = new MyConfig();
- Configuration result = MicroprofileAdapter.toConfiguration(config);
-
- Assertions.assertThat(result).isNotNull()
- .isInstanceOf(TamayaConfiguration.class);
- }
-
- @Test
- public void toConfigSources() throws Exception {
- BuildablePropertySource testPropertySource = BuildablePropertySource.builder()
- .withSource("toConfigSources")
- .withSimpleProperty("string0", "value0")
- .withSimpleProperty("int0", "0")
- .build();
- List<PropertySource> tamayaSources = new ArrayList<>();
- tamayaSources.add(testPropertySource);
- List<ConfigSource> configSources = MicroprofileAdapter.toConfigSources(tamayaSources);
- assertNotNull(configSources);
- assertEquals(tamayaSources.size(), configSources.size());
- compare(testPropertySource, configSources.get(0));
- }
-
- private void compare(PropertySource tamayaSource, ConfigSource mpSource) {
- assertEquals(mpSource.getName(),tamayaSource.getName());
- assertEquals(mpSource.getOrdinal(), tamayaSource.getOrdinal());
- assertEquals(mpSource.getProperties().keySet(), tamayaSource.getProperties().keySet());
- for(String key:mpSource.getPropertyNames()){
- assertEquals(mpSource.getValue(key), tamayaSource.get(key).getValue());
- }
- }
-
- @Test
- public void toPropertySources() throws Exception {
- BuildableConfigSource configSource = BuildableConfigSource.builder()
- .withSource("toConfigSources")
- .withProperty("string0", "value0")
- .withProperty("int0", "0")
- .build();
- List<ConfigSource> configSources = new ArrayList<>();
- configSources.add(configSource);
- List<PropertySource> propertySources = MicroprofileAdapter.toPropertySources(configSources);
- assertNotNull(propertySources);
- assertEquals(propertySources.size(), configSources.size());
- compare(propertySources.get(0), configSource);
- }
-
- @Test
- public void toConfigSource() throws Exception {
- BuildablePropertySource tamayaSource = BuildablePropertySource.builder()
- .withSource("toConfigSource")
- .withSimpleProperty("string0", "value0")
- .withSimpleProperty("int0", "0")
- .build();
- ConfigSource configSource = MicroprofileAdapter.toConfigSource(tamayaSource);
- assertNotNull(configSource);
- compare(tamayaSource, configSource);
- }
-
- @Test
- public void toPropertySource() throws Exception {
- BuildableConfigSource configSource = BuildableConfigSource.builder()
- .withSource("toConfigSource")
- .withProperty("string0", "value0")
- .withProperty("int0", "0")
- .build();
- PropertySource tamayaSource = MicroprofileAdapter.toPropertySource(configSource);
- assertNotNull(configSource);
- compare(tamayaSource, configSource);
- }
-
- @Test
- public void toPropertyConverter() throws Exception {
- PropertyConverter<String> tamayaConverter = MicroprofileAdapter.toPropertyConverter(new UppercaseConverter());
- assertNotNull(tamayaConverter);
- assertEquals("ABC", tamayaConverter.convert("aBC", null));
- }
-
- @Test
- public void toConverter() throws Exception {
- Converter<String> mpConverter = MicroprofileAdapter.toConverter(new UppercasePropertyConverter());
- assertNotNull(mpConverter);
- assertEquals("ABC", mpConverter.convert("aBC"));
- }
-
- @Test
- public void toConfigBuilder() throws Exception {
- ConfigBuilder builder = MicroprofileAdapter.toConfigBuilder(ConfigurationProvider.getConfigurationContextBuilder());
- assertNotNull(builder);
- }
-
- @Test
- public void toStringMap() throws Exception {
- Map<String,PropertyValue> props = new HashMap<>();
- props.put("a", PropertyValue.of("a","b", "toStringMap"));
- Map<String, String> mpProps = MicroprofileAdapter.toStringMap(props);
- assertNotNull(mpProps);
- assertEquals(props.keySet(), mpProps.keySet());
- assertEquals(mpProps.get("a"), "b");
- }
-
- @Test
- public void toPropertyValueMap() throws Exception {
- Map<String,String> props = new HashMap<>();
- props.put("a", "b");
- Map<String, PropertyValue> tamayaProps = MicroprofileAdapter.toPropertyValueMap(props, "toPropertyValueMap");
- assertNotNull(tamayaProps);
- assertEquals(tamayaProps.keySet(), props.keySet());
- assertEquals(tamayaProps.get("a").getValue(), "b");
- assertEquals("toPropertyValueMap", tamayaProps.get("a").getSource());
- }
-
- static class MyConfig implements Config {
- @Override
- public <T> T getValue(String s, Class<T> aClass) {
- throw new RuntimeException("Not implemented yet!");
- }
-
- @Override
- public <T> Optional<T> getOptionalValue(String s, Class<T> aClass) {
- throw new RuntimeException("Not implemented yet!");
- }
-
- @Override
- public Iterable<String> getPropertyNames() {
- throw new RuntimeException("Not implemented yet!");
- }
-
- @Override
- public Iterable<ConfigSource> getConfigSources() {
- throw new RuntimeException("Not implemented yet!");
- }
- }
-
- static class MyConfiguration implements Configuration {
- @Override
- public String get(String key) {
- throw new RuntimeException("Not implemented yet!");
- }
-
- @Override
- public String getOrDefault(String key, String defaultValue) {
- throw new RuntimeException("Not implemented yet!");
- }
-
- @Override
- public <T> T getOrDefault(String key, Class<T> type, T defaultValue) {
- throw new RuntimeException("Not implemented yet!");
- }
-
- @Override
- public <T> T get(String key, Class<T> type) {
- throw new RuntimeException("Not implemented yet!");
- }
-
- @Override
- public <T> T get(String key, TypeLiteral<T> type) {
- throw new RuntimeException("Not implemented yet!");
- }
-
- @Override
- public <T> T getOrDefault(String key, TypeLiteral<T> type, T defaultValue) {
- throw new RuntimeException("Not implemented yet!");
- }
-
- @Override
- public Map<String, String> getProperties() {
- throw new RuntimeException("Not implemented yet!");
- }
-
- @Override
- public ConfigurationContext getContext() {
- throw new RuntimeException("Not implemented yet!");
- }
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigBuilderTest.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigBuilderTest.java b/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigBuilderTest.java
deleted file mode 100644
index 4e9c2d1..0000000
--- a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigBuilderTest.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.assertj.core.api.Assertions;
-import org.eclipse.microprofile.config.Config;
-import org.eclipse.microprofile.config.spi.ConfigBuilder;
-import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
-import org.eclipse.microprofile.config.spi.ConfigSource;
-import org.junit.Ignore;
-import org.junit.Test;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-import java.util.stream.StreamSupport;
-
-import static org.junit.Assert.*;
-
-/**
- * Created by atsticks on 24.03.17.
- */
-public class MicroprofileConfigBuilderTest {
-
- private ConfigSource testSource = new ConfigSource() {
- @Override
- public Map<String, String> getProperties() {
- Map<String,String> map = new HashMap<>();
- map.put("timestamp", String.valueOf(System.currentTimeMillis()));
- return map;
- }
-
- @Override
- public String getValue(String propertyName) {
- if("timestamp".equals(propertyName)){
- return String.valueOf(System.currentTimeMillis());
- }
- return null;
- }
-
- @Override
- public String getName() {
- return "test";
- }
- };
-
- @Test
- public void testBuildEmptyConfig(){
- ConfigBuilder builder = ConfigProviderResolver.instance().getBuilder();
- assertNotNull(builder);
- Config config = builder.build();
- assertNotNull(config);
- assertFalse(config.getPropertyNames().iterator().hasNext());
- assertFalse(config.getConfigSources().iterator().hasNext());
- }
-
- @Test
- public void testBuildConfig(){
- ConfigBuilder builder = ConfigProviderResolver.instance().getBuilder();
- assertNotNull(builder);
- builder.withSources(testSource);
- Config config = builder.build();
- assertNotNull(config);
- assertTrue(config.getPropertyNames().iterator().hasNext());
- assertTrue(config.getConfigSources().iterator().hasNext());
- assertNotNull(config.getValue("timestamp", String.class));
- ConfigSource src = config.getConfigSources().iterator().next();
- assertNotNull(src);
- assertEquals(src, testSource);
- }
-
- @Test
- public void testBuildDefaultConfig(){
- ConfigBuilder builder = ConfigProviderResolver.instance().getBuilder();
- assertNotNull(builder);
- builder.addDefaultSources();
- Config config = builder.build();
- assertNotNull(config);
- assertTrue(config.getPropertyNames().iterator().hasNext());
- assertTrue(config.getConfigSources().iterator().hasNext());
- assertNotNull(config.getValue("java.home", String.class));
- ConfigSource src = config.getConfigSources().iterator().next();
- assertNotNull(src);
- }
-
- @Test
- public void addDiscoveredSourcesAddsAllConfigSources() throws Exception {
- ConfigBuilder builder = ConfigProviderResolver.instance().getBuilder();
-
- Config config = builder.addDiscoveredSources()
- .addDefaultSources().build();
-
- Iterable<ConfigSource> iterable = config.getConfigSources();
-
- List<String> name = StreamSupport.stream(iterable.spliterator(), false)
- .map(ConfigSource::getName)
- .collect(Collectors.toList());
-
- Assertions.assertThat(name).hasSize(4)
- .containsExactlyInAnyOrder("paris",
- "SystemPropertySource",
- "environment-properties",
- "META-INF/microprofile-config.properties");
- }
-
- @Test
- public void addDiscoveredSourcesAddsAllConfigSourceProviders() throws Exception {
- // throw new RuntimeException("Not implemented yet!");
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigProviderResolverTest.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigProviderResolverTest.java b/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigProviderResolverTest.java
deleted file mode 100644
index 9b6b554..0000000
--- a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigProviderResolverTest.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.eclipse.microprofile.config.Config;
-import org.eclipse.microprofile.config.spi.ConfigBuilder;
-import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
-import org.junit.Test;
-
-import java.net.URL;
-import java.net.URLClassLoader;
-
-import static org.junit.Assert.*;
-
-/**
- * Created by atsticks on 24.03.17.
- */
-public class MicroprofileConfigProviderResolverTest {
-
- @Test
- public void testInstance(){
- assertNotNull(ConfigProviderResolver.instance());
- }
-
- @Test
- public void testGetBuilder(){
- assertNotNull(ConfigProviderResolver.instance().getBuilder());
- }
-
- @Test
- public void testGetConfig(){
- assertNotNull(ConfigProviderResolver.instance().getConfig());
- }
-
- @Test
- public void testGetConfig_CL(){
- assertNotNull(ConfigProviderResolver.instance().getConfig(ClassLoader.getSystemClassLoader()));
- }
-
- @Test
- public void testRegisterAndReleaseConfig(){
- ClassLoader cl = new URLClassLoader(new URL[]{});
- Config emptyConfig = ConfigProviderResolver.instance().getBuilder().build();
- assertNotNull(emptyConfig);
- Config cfg = ConfigProviderResolver.instance().getConfig(cl);
- assertNotNull(cfg);
- ConfigProviderResolver.instance().registerConfig(emptyConfig, cl);
- cfg = ConfigProviderResolver.instance().getConfig(cl);
- assertNotNull(cfg);
- assertEquals(cfg, emptyConfig);
- ConfigProviderResolver.instance().releaseConfig(emptyConfig);
- cfg = ConfigProviderResolver.instance().getConfig(cl);
- assertNotNull(cfg);
- assertNotSame(cfg, emptyConfig);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigProviderTest.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigProviderTest.java b/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigProviderTest.java
deleted file mode 100644
index 039145d..0000000
--- a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigProviderTest.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.apache.tamaya.ConfigurationProvider;
-import org.eclipse.microprofile.config.Config;
-import org.eclipse.microprofile.config.ConfigProvider;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-/**
- * Created by atsticks on 24.03.17.
- */
-public class MicroprofileConfigProviderTest {
-
- @Test
- public void testDefaultConfigAccess(){
- Config config = ConfigProvider.getConfig();
- assertNotNull(config);
- Iterable<String> names = config.getPropertyNames();
- assertNotNull(names);
- int count = 0;
- for(String name:names){
- count++;
- System.out.println(count + ": " +name);
- }
- assertTrue(ConfigurationProvider.getConfiguration().getProperties().size() <= count);
- }
-
- @Test
- public void testClassloaderAccess(){
- Config config = ConfigProvider.getConfig(Thread.currentThread().getContextClassLoader());
- assertNotNull(config);
- Iterable<String> names = config.getPropertyNames();
- assertNotNull(names);
- int count = 0;
- for(String name:names){
- count++;
- }
- assertTrue(count>0);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigSourceProviderTest.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigSourceProviderTest.java b/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigSourceProviderTest.java
deleted file mode 100644
index ab792aa..0000000
--- a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigSourceProviderTest.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.apache.tamaya.spisupport.propertysource.BuildablePropertySource;
-import org.apache.tamaya.spisupport.propertysource.BuildablePropertySourceProvider;
-import org.eclipse.microprofile.config.spi.ConfigSource;
-import org.junit.Test;
-
-import static org.junit.Assert.*;
-
-public class MicroprofileConfigSourceProviderTest {
- @Test
- public void getPropertySourceProvider() throws Exception {
- BuildablePropertySourceProvider prov = BuildablePropertySourceProvider.builder()
- .withPropertySourcs(
- BuildablePropertySource.builder()
- .withSimpleProperty("a", "b").build())
- .build();
- MicroprofileConfigSourceProvider provider = new MicroprofileConfigSourceProvider(prov);
- assertNotNull(provider);
- Iterable<ConfigSource> configSources = provider.getConfigSources(null);
- assertNotNull(configSources);
- assertTrue(configSources.iterator().hasNext());
- assertEquals("b", configSources.iterator().next().getValue("a"));
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigTest.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigTest.java b/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigTest.java
deleted file mode 100644
index 5d61c8c..0000000
--- a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConfigTest.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.eclipse.microprofile.config.Config;
-import org.eclipse.microprofile.config.ConfigProvider;
-import org.eclipse.microprofile.config.spi.ConfigSource;
-import org.junit.Test;
-
-import java.util.NoSuchElementException;
-import java.util.Optional;
-
-import static org.junit.Assert.*;
-
-/**
- * Created by atsticks on 24.03.17.
- */
-public class MicroprofileConfigTest {
-
- @Test
- public void testDefaultConfigAccess() {
- Config config = ConfigProvider.getConfig();
- Iterable<ConfigSource> sources = config.getConfigSources();
- int count = 0;
- for (ConfigSource cs : sources) {
- count++;
- }
- assertEquals(4, count);
- }
-
- @Test
- public void testOptionalAccess(){
- Config config = ConfigProvider.getConfig();
- int count = 0;
- for(String key:config.getPropertyNames()){
- Optional<String> val = config.getOptionalValue(key, String.class);
- assertNotNull(val);
- val = config.getOptionalValue(key + System.currentTimeMillis(), String.class);
- assertNotNull(val);
- assertFalse(val.isPresent());
- }
- }
-
- @Test
- public void testGetValue(){
- Config config = ConfigProvider.getConfig();
- int count = 0;
- for(String key:config.getPropertyNames()){
- String val = config.getValue(key, String.class);
- assertNotNull(val);
- }
- }
-
- @Test(expected = NoSuchElementException.class)
- public void testGetValue_NoValue(){
- Config config = ConfigProvider.getConfig();
- config.getValue("fooBar", String.class);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testGetValue_InvalidType(){
- Config config = ConfigProvider.getConfig();
- config.getValue("java.version", Integer.class);
- }
-
- @Test
- public void testEmptySystemProperty(){
- System.setProperty("my.empty.property", "");
- Config config = ConfigProvider.getConfig();
- assertEquals("", config.getValue("my.empty.property", String.class));
- }
-
- @Test
- public void testEmptyConfigProperty(){
- Config config = ConfigProvider.getConfig();
- assertEquals("", config.getValue("my.empty.property.in.config.file", String.class));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConverterTest.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConverterTest.java b/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConverterTest.java
deleted file mode 100644
index 35819bc..0000000
--- a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileConverterTest.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.apache.tamaya.microprofile.converter.ProviderConverter;
-import org.apache.tamaya.spi.PropertyConverter;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-@RunWith(MockitoJUnitRunner.class)
-public class MicroprofileConverterTest {
-
- @Mock
- private PropertyConverter<String> converter;
-
- @Test
- public void returnedPropertyConverterIsTheOneOfTheDelegate() throws Exception {
- MicroprofileConverter<String> mpConverter = new MicroprofileConverter<>(converter);
-
- assertThat(mpConverter.getPropertyConverter()).isSameAs(converter);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileDefaultPropertiesTest.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileDefaultPropertiesTest.java b/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileDefaultPropertiesTest.java
deleted file mode 100644
index ec60e8d..0000000
--- a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/MicroprofileDefaultPropertiesTest.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.junit.Test;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class MicroprofileDefaultPropertiesTest {
- @Test
- public void hasOrdinalOf100() throws Exception {
- MicroprofileDefaultProperties properties = new MicroprofileDefaultProperties();
-
- assertThat(properties.getOrdinal()).isEqualTo(100);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/TamayaPropertySourceTest.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/TamayaPropertySourceTest.java b/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/TamayaPropertySourceTest.java
deleted file mode 100644
index 47567d2..0000000
--- a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/TamayaPropertySourceTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.eclipse.microprofile.config.spi.ConfigSource;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.when;
-
-@RunWith(MockitoJUnitRunner.class)
-public class TamayaPropertySourceTest {
- @Mock
- private ConfigSource configSource;
-
- @Test
- public void isScannable() throws Exception {
- TamayaPropertySource source = new TamayaPropertySource(configSource);
-
- assertThat(source.isScannable()).isTrue();
- }
-
- @Test
- public void ordinalIsTheSameAsOfTheConfigSource() throws Exception {
- when(configSource.getOrdinal()).thenReturn(44);
-
- TamayaPropertySource source = new TamayaPropertySource(configSource);
-
- assertThat(source.getOrdinal()).isEqualTo(44);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/UppercaseConverter.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/UppercaseConverter.java b/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/UppercaseConverter.java
deleted file mode 100644
index 08623be..0000000
--- a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/UppercaseConverter.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.eclipse.microprofile.config.spi.Converter;
-
-import java.util.Locale;
-
-public class UppercaseConverter implements Converter<String> {
-
- @Override
- public String convert(String s) {
- if(s==null){
- return null;
- }
- return s.toUpperCase(Locale.ENGLISH);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/UppercasePropertyConverter.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/UppercasePropertyConverter.java b/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/UppercasePropertyConverter.java
deleted file mode 100644
index de2d551..0000000
--- a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/UppercasePropertyConverter.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.apache.tamaya.spi.ConversionContext;
-import org.apache.tamaya.spi.PropertyConverter;
-import org.eclipse.microprofile.config.spi.Converter;
-
-import java.util.Locale;
-
-public class UppercasePropertyConverter implements PropertyConverter<String> {
-
- @Override
- public String convert(String s, ConversionContext context) {
- if(s==null){
- return null;
- }
- return s.toUpperCase(Locale.ENGLISH);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/tck/TamayaConfigArchiveProcessor.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/tck/TamayaConfigArchiveProcessor.java b/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/tck/TamayaConfigArchiveProcessor.java
deleted file mode 100644
index 61cd11c..0000000
--- a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/tck/TamayaConfigArchiveProcessor.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile.tck;
-
-import org.apache.tamaya.core.internal.converters.OptionalConverter;
-import org.apache.tamaya.microprofile.MicroprofileAdapter;
-import org.apache.tamaya.microprofile.MicroprofileConfigProviderResolver;
-import org.apache.tamaya.microprofile.cdi.MicroprofileCDIExtension;
-import org.apache.tamaya.microprofile.converter.BooleanAsIntegerConverterFix;
-import org.apache.tamaya.spi.PropertyConverter;
-import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
-import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor;
-import org.jboss.arquillian.test.spi.TestClass;
-import org.jboss.shrinkwrap.api.Archive;
-import org.jboss.shrinkwrap.api.ShrinkWrap;
-import org.jboss.shrinkwrap.api.asset.EmptyAsset;
-import org.jboss.shrinkwrap.api.spec.JavaArchive;
-import org.jboss.shrinkwrap.api.spec.WebArchive;
-import org.jboss.shrinkwrap.resolver.api.maven.Maven;
-
-import javax.enterprise.inject.spi.Extension;
-import java.io.File;
-
-/**
- * Adds the whole Config implementation classes and resources to the
- * Arquillian deployment archive. This is needed to have the container
- * pick up the beans from within the impl for the TCK tests.
- *
- * @author <a href="mailto:struberg@yahoo.de">Mark Struberg</a>
- */
-public class TamayaConfigArchiveProcessor implements ApplicationArchiveProcessor {
-
- @Override
- public void process(Archive<?> applicationArchive, TestClass testClass) {
- if (applicationArchive instanceof WebArchive) {
- File[] coreLibs = Maven.resolver()
- .loadPomFromFile("pom.xml").resolve("org.apache.tamaya:tamaya-core")
- .withTransitivity().asFile();
- File[] apiLibs = Maven.resolver()
- .loadPomFromFile("pom.xml").resolve("org.apache.tamaya:tamaya-api")
- .withTransitivity().asFile();
- File[] functionsLib = Maven.resolver()
- .loadPomFromFile("pom.xml").resolve("org.apache.tamaya.ext:tamaya-functions")
- .withTransitivity().asFile();
-
- JavaArchive configJar = ShrinkWrap
- .create(JavaArchive.class, "tamaya-config-impl.jar")
- .addPackage(MicroprofileAdapter.class.getPackage())
- .addPackage(MicroprofileCDIExtension.class.getPackage())
- .addPackage(BooleanAsIntegerConverterFix.class.getPackage())
- .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
- .addAsServiceProvider(ConfigProviderResolver.class, MicroprofileConfigProviderResolver.class)
- .addAsServiceProvider(PropertyConverter.class, BooleanAsIntegerConverterFix.class)
- .addAsServiceProvider(PropertyConverter.class, OptionalConverter.class)
- .addAsServiceProvider(Extension.class, MicroprofileCDIExtension.class);
- ((WebArchive) applicationArchive).addAsLibraries(
- configJar)
- .addAsLibraries(apiLibs)
- .addAsLibraries(coreLibs)
- .addAsLibraries(functionsLib);
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/tck/TamayaConfigExtension.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/tck/TamayaConfigExtension.java b/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/tck/TamayaConfigExtension.java
deleted file mode 100644
index 9c0dfd3..0000000
--- a/modules/microprofile/src/test/java/org/apache/tamaya/microprofile/tck/TamayaConfigExtension.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile.tck;
-
-import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor;
-import org.jboss.arquillian.core.spi.LoadableExtension;
-
-/**
- * Arquillian extension to load Tamaya into Arquillian context.
- * @author <a href="mailto:anatole@apache.org">Anatole Tresch</a>
- */
-public class TamayaConfigExtension implements LoadableExtension {
-
- @Override
- public void register(ExtensionBuilder extensionBuilder) {
- extensionBuilder.service(
- ApplicationArchiveProcessor.class,
- TamayaConfigArchiveProcessor.class);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/resources/META-INF/beans.xml
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/resources/META-INF/beans.xml b/modules/microprofile/src/test/resources/META-INF/beans.xml
deleted file mode 100644
index adee378..0000000
--- a/modules/microprofile/src/test/resources/META-INF/beans.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Licensed to the Apache Software Foundation (ASF) under one
-or more contributor license agreements. See the NOTICE file
-distributed with this work for additional information
-regarding copyright ownership. The ASF licenses this file
-to you 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 current 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.
--->
-<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://jboss.org/schema/cdi/beans_1_0.xsd">
-
-</beans>
-
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/resources/META-INF/microprofile-config.properties
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/resources/META-INF/microprofile-config.properties b/modules/microprofile/src/test/resources/META-INF/microprofile-config.properties
deleted file mode 100644
index 2e63bf8..0000000
--- a/modules/microprofile/src/test/resources/META-INF/microprofile-config.properties
+++ /dev/null
@@ -1,105 +0,0 @@
-#
-# Copyright (c) 2016-2017 Contributors to the Eclipse Foundation
-#
-# See the NOTICES file(s) distributed with this work for additional
-# information regarding copyright ownership.
-#
-# 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.
-#
-
-my.optional.int.property=1234
-my.optional.string.property=hello
-
-tck.config.test.javaconfig.properties.key1=VALue1
-
-
-tck.config.test.overwritten.in.custompropertyfile.key1=value from microprofile-config.properties
-
-
-tck.config.test.javaconfig.converter.integervalue = 1234
-tck.config.test.javaconfig.converter.integervalue.broken = xxx
-
-tck.config.test.javaconfig.converter.longvalue = 1234567890
-tck.config.test.javaconfig.converter.longvalue.broken = xxx
-
-tck.config.test.javaconfig.converter.floatvalue = 12.34
-tck.config.test.javaconfig.converter.floatvalue.broken = alfasdf
-
-tck.config.test.javaconfig.converter.doublevalue = 12.34
-tck.config.test.javaconfig.converter.doublevalue.broken = alfasdf
-
-tck.config.test.javaconfig.converter.durationvalue = PT15M
-tck.config.test.javaconfig.converter.durationvalue.broken = alfasdf
-
-tck.config.test.javaconfig.converter.localtimevalue = 10:37
-tck.config.test.javaconfig.converter.localtimevalue.broken = alfasdf
-
-tck.config.test.javaconfig.converter.localdatevalue = 2017-12-24
-tck.config.test.javaconfig.converter.localdatevalue.broken = alfasdf
-
-tck.config.test.javaconfig.converter.localdatetimevalue = 2017-12-24T10:25:30
-tck.config.test.javaconfig.converter.localdatetimevalue.broken = alfasdf
-
-tck.config.test.javaconfig.converter.offsetdatetimevalue = 2007-12-03T10:15:30+01:00
-tck.config.test.javaconfig.converter.offsetdatetimevalue.broken = alfasdf
-
-tck.config.test.javaconfig.converter.offsettimevalue = 13:45:30.123456789+02:00
-tck.config.test.javaconfig.converter.offsettimevalue.broken = alfasdf
-
-tck.config.test.javaconfig.converter.instantvalue = 2015-06-02T21:34:33.616Z
-tck.config.test.javaconfig.converter.instantvalue.broken = alfasdf
-
-tck.config.test.javaconfig.configvalue.key1=value1
-
-# test BooleanConverter START
-tck.config.test.javaconfig.configvalue.boolean.true=true
-tck.config.test.javaconfig.configvalue.boolean.true_uppercase=TRUE
-tck.config.test.javaconfig.configvalue.boolean.true_mixedcase=TruE
-tck.config.test.javaconfig.configvalue.boolean.false=false
-
-tck.config.test.javaconfig.configvalue.boolean.one=1
-tck.config.test.javaconfig.configvalue.boolean.zero=0
-tck.config.test.javaconfig.configvalue.boolean.seventeen=17
-
-tck.config.test.javaconfig.configvalue.boolean.yes=yes
-tck.config.test.javaconfig.configvalue.boolean.yes_uppercase=YES
-tck.config.test.javaconfig.configvalue.boolean.yes_mixedcase=Yes
-tck.config.test.javaconfig.configvalue.boolean.no=no
-
-tck.config.test.javaconfig.configvalue.boolean.y=y
-tck.config.test.javaconfig.configvalue.boolean.y_uppercase=Y
-tck.config.test.javaconfig.configvalue.boolean.n=n
-
-tck.config.test.javaconfig.configvalue.boolean.on=on
-tck.config.test.javaconfig.configvalue.boolean.on_uppercase=ON
-tck.config.test.javaconfig.configvalue.boolean.on_mixedcase=oN
-tck.config.test.javaconfig.configvalue.boolean.off=off
-
-# test BooleanConverter END
-
-# various other converter
-tck.config.test.javaconfig.configvalue.integer=1234
-tck.config.test.javaconfig.configvalue.long=1234567890123456
-tck.config.test.javaconfig.configvalue.float=12.34
-tck.config.test.javaconfig.configvalue.double=12.34567890123456
-
-# Custom Converter tests
-tck.config.test.javaconfig.converter.duckname=Hannelore
-
-# URL Converter tests
-tck.config.test.javaconfig.converter.urlvalue=http://microprofile.io
-tck.config.test.javaconfig.converter.urlvalue.broken=tt:--location$
-
-# Empty values
-my.empty.property.in.config.file=
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/resources/META-INF/services/org.eclipse.microprofile.config.spi.ConfigSource
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/resources/META-INF/services/org.eclipse.microprofile.config.spi.ConfigSource b/modules/microprofile/src/test/resources/META-INF/services/org.eclipse.microprofile.config.spi.ConfigSource
deleted file mode 100644
index b1ef0c2..0000000
--- a/modules/microprofile/src/test/resources/META-INF/services/org.eclipse.microprofile.config.spi.ConfigSource
+++ /dev/null
@@ -1,19 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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 current 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.
-#
-org.apache.tamaya.microprofile.ConfigSourceParis
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/resources/META-INF/services/org.eclipse.microprofile.config.spi.ConfigSourceProvider
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/resources/META-INF/services/org.eclipse.microprofile.config.spi.ConfigSourceProvider b/modules/microprofile/src/test/resources/META-INF/services/org.eclipse.microprofile.config.spi.ConfigSourceProvider
deleted file mode 100644
index dd554df..0000000
--- a/modules/microprofile/src/test/resources/META-INF/services/org.eclipse.microprofile.config.spi.ConfigSourceProvider
+++ /dev/null
@@ -1,19 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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 current 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.
-#
-org.apache.tamaya.microprofile.ConfigSourceProviderMinsk
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/resources/META-INF/services/org.jboss.arquillian.core.spi.LoadableExtension
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/resources/META-INF/services/org.jboss.arquillian.core.spi.LoadableExtension b/modules/microprofile/src/test/resources/META-INF/services/org.jboss.arquillian.core.spi.LoadableExtension
deleted file mode 100644
index b2af25c..0000000
--- a/modules/microprofile/src/test/resources/META-INF/services/org.jboss.arquillian.core.spi.LoadableExtension
+++ /dev/null
@@ -1,19 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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.
-#
-org.apache.tamaya.microprofile.tck.TamayaConfigExtension
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/resources/sampleconfig.yaml
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/resources/sampleconfig.yaml b/modules/microprofile/src/test/resources/sampleconfig.yaml
deleted file mode 100644
index 27f2392..0000000
--- a/modules/microprofile/src/test/resources/sampleconfig.yaml
+++ /dev/null
@@ -1,18 +0,0 @@
-#
-# Copyright (c) 2016-2017 Mark Struberg and others
-#
-# 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.
-#
-# just needed as a trigger for the ConfigSource pickup.
-# Content is hardcoded in SampleYamlConfigSource
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/test/tck-suite.xml
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/test/tck-suite.xml b/modules/microprofile/src/test/tck-suite.xml
deleted file mode 100644
index 84d36ad..0000000
--- a/modules/microprofile/src/test/tck-suite.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
-<!--
-Licensed to the Apache Software Foundation (ASF) under one
-or more contributor license agreements. See the NOTICE file
-distributed with this work for additional information
-regarding copyright ownership. The ASF licenses this file
-to you 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 current 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.
--->
-<suite name="microprofile-config-TCK" verbose="2" configfailurepolicy="continue" >
- <test name="microprofile-config 1.1 TCK">
- <packages>
- <package name="org.eclipse.microprofile.config.tck.*">
- </package>
- </packages>
- </test>
-</suite>
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/pom.xml
----------------------------------------------------------------------
diff --git a/modules/mutable-config/pom.xml b/modules/mutable-config/pom.xml
index ecbf767..874fca5 100644
--- a/modules/mutable-config/pom.xml
+++ b/modules/mutable-config/pom.xml
@@ -34,12 +34,7 @@ under the License.
<dependencies>
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-api</artifactId>
- <version>${tamaya-apicore.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-spisupport</artifactId>
+ <artifactId>tamaya-base</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/ChangePropagationPolicy.java
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/ChangePropagationPolicy.java b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/ChangePropagationPolicy.java
index 0cfd8b8..06eb43a 100644
--- a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/ChangePropagationPolicy.java
+++ b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/ChangePropagationPolicy.java
@@ -18,15 +18,15 @@
*/
package org.apache.tamaya.mutableconfig;
-import org.apache.tamaya.spi.PropertySource;
+import org.apache.tamaya.mutableconfig.spi.MutableConfigSource;
-import java.util.Collection;
+import javax.config.spi.ConfigSource;
/**
* Policy that defines how changes are applied to the available
- * {@link org.apache.tamaya.mutableconfig.spi.MutablePropertySource} instances, e.g.
+ * {@link MutableConfigSource} instances, e.g.
* <ul>
- * <li><b>ALL: </b>Changes are propagated to all {@link org.apache.tamaya.mutableconfig.spi.MutablePropertySource}
+ * <li><b>ALL: </b>Changes are propagated to all {@link MutableConfigSource}
* instances in order of significance. This means that a key added, updated or removed in each instance, if the key
* is writable/removable.</li>
* <li><b>SIGNIFICANT_ONLY: </b>A change (creation, update) is only applied, if
@@ -48,6 +48,6 @@ public interface ChangePropagationPolicy {
* never null.
* @param configChange the configuration change, not null.
*/
- void applyChange(ConfigChangeRequest configChange, Collection<PropertySource> propertySources);
+ void applyChange(ConfigChangeRequest configChange, Iterable<ConfigSource> propertySources);
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/ConfigChangeRequest.java
----------------------------------------------------------------------
diff --git a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/ConfigChangeRequest.java b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/ConfigChangeRequest.java
index a592d58..254109a 100644
--- a/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/ConfigChangeRequest.java
+++ b/modules/mutable-config/src/main/java/org/apache/tamaya/mutableconfig/ConfigChangeRequest.java
@@ -18,6 +18,8 @@
*/
package org.apache.tamaya.mutableconfig;
+import org.apache.tamaya.mutableconfig.spi.MutableConfigSource;
+
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
@@ -28,7 +30,7 @@ import java.util.Set;
/**
* Change context used for managing configuration changes within an
- * {@link org.apache.tamaya.mutableconfig.spi.MutablePropertySource}.
+ * {@link MutableConfigSource}.
*/
public final class ConfigChangeRequest {
/**
[18/18] incubator-tamaya-extensions git commit: Rewrite/adaptation
based on JSR API.
Posted by an...@apache.org.
Rewrite/adaptation based on JSR API.
Signed-off-by: Anatole Tresch <an...@apache.org>
Project: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/commit/cfb364cd
Tree: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/tree/cfb364cd
Diff: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/diff/cfb364cd
Branch: refs/heads/configjsr
Commit: cfb364cd4e201d59102343209eafbb7e4c0196ce
Parents: 4869d94
Author: Anatole Tresch <an...@apache.org>
Authored: Wed Jan 3 00:55:22 2018 +0100
Committer: Anatole Tresch <an...@apache.org>
Committed: Wed Jan 3 00:55:32 2018 +0100
----------------------------------------------------------------------
.../tamaya/ext/examples/resources/Main.java | 29 ++-
.../resources/MyPathConfigSourceProvider.java | 39 +++
.../resources/MyPathPropertySourceProvider.java | 39 ---
...org.apache.tamaya.spi.PropertySourceProvider | 2 +-
.../tamay/ext/examples/resolver/Main.java | 29 ++-
.../tamaya/ext/examples/injection/Example.java | 6 +-
.../ext/examples/injection/ExampleTemplate.java | 6 +-
.../ext/examples/injection/MinimalTest.java | 45 ++--
.../resources/META-INF/javaconfig.properties | 25 ++
.../META-INF/javaconfiguration.properties | 25 --
.../events/FileConfigSourceProvider.java | 71 ++++++
.../events/FilePropertySourceProvider.java | 73 ------
.../apache/tamaya/ext/examples/events/Main.java | 14 +-
.../javax.config.spi.ConfigSourceProvider | 20 ++
...org.apache.tamaya.spi.PropertySourceProvider | 20 --
.../tamaya/springexample/ColorConverter.java | 8 +-
.../tamaya/springexample/WelcomeController.java | 29 ++-
modules/features/pom.xml | 14 +-
.../org/apache/tamaya/features/Features.java | 16 +-
.../apache/tamaya/features/FeaturesTest.java | 9 +-
.../tamaya/features/FeaturesTestNoOnly.java | 4 +-
modules/filter/bnd.bnd | 6 +-
modules/filter/pom.xml | 13 +-
.../tamaya/filter/ConfigurationFilter.java | 114 +++++----
.../java/org/apache/tamaya/filter/Context.java | 123 ++++++++++
.../filter/internal/DefaultMetadataFilter.java | 14 +-
.../services/org.apache.tamaya.spi.Filter | 19 ++
.../org.apache.tamaya.spi.PropertyFilter | 19 --
.../tamaya/filter/ConfigurationFilterTest.java | 123 ----------
.../tamaya/filter/ProgrammableFilterTest.java | 149 -----------
.../filter/ConfigurationFilterTest.java | 95 +++++++
.../filter/ProgrammableFilterTest.java | 183 ++++++++++++++
modules/formats/base/pom.xml | 8 +-
.../format/BaseFormatConfigSourceProvider.java | 159 ++++++++++++
.../BaseFormatPropertySourceProvider.java | 160 ------------
.../tamaya/format/ConfigurationFormats.java | 46 ++--
.../MappedConfigurationDataConfigSource.java | 152 ++++++++++++
.../MappedConfigurationDataPropertySource.java | 157 ------------
.../format/formats/IniConfigurationFormat.java | 3 +-
.../format/FormatConfigSourceProviderTest.java | 58 +++++
.../FormatPropertySourceProviderTest.java | 50 ----
...ppedConfigurationDataPropertySourceTest.java | 43 ++--
modules/formats/json/pom.xml | 9 +-
.../apache/tamaya/json/JSONConfigSource.java | 148 +++++++++++
.../apache/tamaya/json/JSONPropertySource.java | 155 ------------
.../org/apache/tamaya/json/JSONVisitor.java | 54 +++-
.../org/apache/tamaya/json/JSONVisitorTest.java | 3 +-
.../yaml/CommonJSONTestCaseCollection.java | 84 +++----
.../org/apache/tamaya/yaml/JSONFormatTest.java | 8 +-
.../tamaya/yaml/JSONPropertySourceTest.java | 13 +-
.../resources/configs/invalid/with-array.json | 27 --
.../resources/configs/valid/with-array.json | 27 ++
.../configs/valid/with-explicit-priority.json | 2 +-
modules/injection/cdi/pom.xml | 8 +-
.../tamaya/cdi/CDIAwareServiceContext.java | 34 ++-
.../apache/tamaya/cdi/CDIConfiguredField.java | 4 +-
.../apache/tamaya/cdi/CDIConfiguredMethod.java | 4 +-
.../apache/tamaya/cdi/CDIConfiguredType.java | 4 +-
.../org/apache/tamaya/cdi/ConfigProducer.java | 200 +++++++++++++++
.../tamaya/cdi/ConfigurationProducer.java | 202 ---------------
.../apache/tamaya/cdi/DefaultDynamicValue.java | 67 +++--
.../tamaya/cdi/ServiceLoaderServiceContext.java | 34 ++-
.../tamaya/cdi/TamayaCDIInjectionExtension.java | 68 +++--
.../tamaya/cdi/TamayaSEInjectionExtension.java | 6 +-
.../cdi/extra/ConfiguredVetoExtension.java | 5 +-
.../tamaya/cdi/BaseTestConfiguration.java | 4 +-
.../tamaya/cdi/ConfigurationProducerTest.java | 42 ++--
.../org/apache/tamaya/cdi/ConfiguredClass.java | 25 +-
.../org/apache/tamaya/cdi/ConfiguredTest.java | 8 +-
.../org/apache/tamaya/cdi/InjectedClass.java | 21 +-
.../apache/tamaya/cdi/NotFoundNoDefault.java | 13 +-
.../tamaya/cdi/cfg/ProvidedConfigSource.java | 60 +++++
.../tamaya/cdi/cfg/ProvidedPropertySource.java | 66 -----
.../tamaya/cdi/cfg/TestConfigProvider.java | 13 +-
.../tamaya/cdi/cfg/TestPropertySource.java | 22 +-
.../cdi/extra/ConfiguredVetoExtensionTest.java | 40 ++-
.../resources/META-INF/javaconfig.properties | 35 +++
.../META-INF/javaconfiguration.properties | 35 ---
modules/injection/injection-api/pom.xml | 8 +-
.../org/apache/tamaya/inject/api/Config.java | 125 ----------
.../tamaya/inject/api/ConfigAutoDetect.java | 51 ++++
.../tamaya/inject/api/ConfigAutoInject.java | 51 ----
.../inject/api/ConfigDefaultSections.java | 2 +-
.../tamaya/inject/api/ConfigFallbackKeys.java | 45 ++++
.../apache/tamaya/inject/api/DynamicValue.java | 7 +-
.../apache/tamaya/inject/api/LoadPolicy.java | 4 +-
.../tamaya/inject/api/OptionalConfig.java | 37 +++
.../apache/tamaya/inject/api/UpdatePolicy.java | 10 -
.../tamaya/inject/api/WithConfigOperator.java | 45 ----
.../apache/tamaya/inject/api/WithConverter.java | 45 ++++
.../inject/api/WithPropertyConverter.java | 46 ----
.../apache/tamaya/inject/api/package-info.java | 2 +-
.../tamaya/inject/spi/BaseDynamicValue.java | 66 ++---
.../tamaya/inject/spi/ConfiguredField.java | 5 +-
.../tamaya/inject/spi/ConfiguredMethod.java | 7 +-
.../tamaya/inject/spi/ConfiguredType.java | 5 +-
.../tamaya/inject/spi/InjectionEvaluator.java | 159 ++++++++++++
.../tamaya/inject/spi/InjectionUtils.java | 130 ----------
.../tamaya/inject/spi/BaseDynamicValueTest.java | 14 +-
.../tamaya/inject/spi/InjectionUtilsTest.java | 24 +-
modules/injection/pom.xml | 9 +
modules/injection/standalone/pom.xml | 2 +-
.../tamaya/inject/ConfigurationInjector.java | 16 +-
.../ConfigTemplateInvocationHandler.java | 10 +-
.../inject/internal/ConfiguredFieldImpl.java | 52 ++--
.../inject/internal/ConfiguredSetterMethod.java | 32 +--
.../inject/internal/ConfiguredTypeImpl.java | 36 +--
.../internal/DefaultConfigurationInjector.java | 47 ++--
.../inject/internal/DefaultDynamicValue.java | 104 ++++----
.../tamaya/inject/internal/InjectionHelper.java | 210 ++++++++--------
.../java/annottext/AnnotatedConfigBean.java | 17 +-
.../java/annottext/AnnotatedConfigTemplate.java | 16 +-
.../annottext/InheritedAnnotatedConfigBean.java | 5 +-
.../java/annottext/NonAnnotatedConfigBean.java | 7 -
.../apache/tamaya/inject/TestConfigSource.java | 69 ++++++
.../tamaya/inject/TestPropertySource.java | 73 ------
.../internal/DefaultDynamicValueTest.java | 77 +++---
.../services/javax.config.spi.ConfigSource | 19 ++
.../org.apache.tamaya.spi.PropertySource | 19 --
modules/jndi/pom.xml | 8 +-
.../apache/tamaya/jndi/JNDIConfigSource.java | 182 ++++++++++++++
.../apache/tamaya/jndi/JNDIPropertySource.java | 188 --------------
.../org.apache.tamaya.spi.PropertySource | 2 +-
.../tamaya/jndi/JNDIConfigSourceTest.java | 72 ++++++
.../tamaya/jndi/JNDIPropertySourceTest.java | 75 ------
modules/microprofile/bnd.bnd | 34 ---
modules/microprofile/pom.xml | 166 -------------
.../microprofile/MicroprofileAdapter.java | 185 --------------
.../tamaya/microprofile/MicroprofileConfig.java | 100 --------
.../microprofile/MicroprofileConfigBuilder.java | 140 -----------
.../MicroprofileConfigProviderResolver.java | 82 -------
.../microprofile/MicroprofileConfigSource.java | 78 ------
.../MicroprofileConfigSourceProvider.java | 64 -----
.../microprofile/MicroprofileConverter.java | 50 ----
.../MicroprofileDefaultProperties.java | 33 ---
.../microprofile/TamayaConfiguration.java | 93 -------
.../microprofile/TamayaPropertyConverter.java | 48 ----
.../microprofile/TamayaPropertySource.java | 78 ------
.../TamayaPropertySourceProvider.java | 56 -----
.../microprofile/cdi/BridgingConfigBean.java | 95 -------
.../microprofile/cdi/ConfiguredField.java | 65 -----
.../microprofile/cdi/ConfiguredMethod.java | 65 -----
.../tamaya/microprofile/cdi/ConfiguredType.java | 86 -------
.../cdi/MicroprofileCDIExtension.java | 127 ----------
.../cdi/MicroprofileConfigurationProducer.java | 156 ------------
.../converter/BooleanAsIntegerConverterFix.java | 61 -----
.../converter/ProviderConverter.java | 98 --------
.../javax.enterprise.inject.spi.Extension | 20 --
.../org.apache.tamaya.spi.PropertyConverter | 21 --
.../org.apache.tamaya.spi.PropertySource | 20 --
...croprofile.config.spi.ConfigProviderResolver | 20 --
.../microprofile/src/main/resources/beans.xml | 25 --
.../microprofile/BuildableConfigSource.java | 180 --------------
.../tamaya/microprofile/ConfigSourceParis.java | 45 ----
.../microprofile/ConfigSourceProviderMinsk.java | 31 ---
.../microprofile/MicroprofileAdapterTest.java | 246 -------------------
.../MicroprofileConfigBuilderTest.java | 127 ----------
.../MicroprofileConfigProviderResolverTest.java | 73 ------
.../MicroprofileConfigProviderTest.java | 62 -----
.../MicroprofileConfigSourceProviderTest.java | 44 ----
.../microprofile/MicroprofileConfigTest.java | 95 -------
.../microprofile/MicroprofileConverterTest.java | 42 ----
.../MicroprofileDefaultPropertiesTest.java | 32 ---
.../microprofile/TamayaPropertySourceTest.java | 50 ----
.../tamaya/microprofile/UppercaseConverter.java | 34 ---
.../UppercasePropertyConverter.java | 36 ---
.../tck/TamayaConfigArchiveProcessor.java | 79 ------
.../microprofile/tck/TamayaConfigExtension.java | 36 ---
.../src/test/resources/META-INF/beans.xml | 24 --
.../META-INF/microprofile-config.properties | 105 --------
...eclipse.microprofile.config.spi.ConfigSource | 19 --
...microprofile.config.spi.ConfigSourceProvider | 19 --
....jboss.arquillian.core.spi.LoadableExtension | 19 --
.../src/test/resources/sampleconfig.yaml | 18 --
modules/microprofile/src/test/tck-suite.xml | 27 --
modules/mutable-config/pom.xml | 7 +-
.../mutableconfig/ChangePropagationPolicy.java | 10 +-
.../mutableconfig/ConfigChangeRequest.java | 4 +-
.../mutableconfig/MutableConfiguration.java | 31 +--
.../MutableConfigurationProvider.java | 60 +++--
.../internal/DefaultMutableConfiguration.java | 86 ++-----
.../DefaultMutableConfigurationSpi.java | 7 +-
.../MutablePropertiesConfigSource.java | 159 ++++++++++++
.../MutablePropertiesPropertySource.java | 164 -------------
.../MutableXmlPropertiesConfigSource.java | 162 ++++++++++++
.../MutableXmlPropertiesPropertySource.java | 171 -------------
.../mutableconfig/spi/MutableConfigSource.java | 49 ++++
.../spi/MutableConfigurationProviderSpi.java | 5 +-
.../spi/MutablePropertySource.java | 48 ----
.../MutableConfigurationProviderTest.java | 7 +-
.../mutableconfig/MutableConfigurationTest.java | 21 +-
.../PropertiesFileConfigBackendTest.java | 4 +-
.../internal/WritablePropertiesSource.java | 6 +-
.../internal/WritableXmlPropertiesSource.java | 6 +-
.../services/javax.config.spi.ConfigSource | 20 ++
.../org.apache.tamaya.spi.PropertySource | 20 --
modules/optional/pom.xml | 7 -
.../tamaya/optional/OptionalConfiguration.java | 23 +-
modules/osgi/common/bnd.bnd | 2 +-
modules/osgi/common/pom.xml | 10 +-
.../org/apache/tamaya/osgi/ConfigChanger.java | 40 +--
.../apache/tamaya/osgi/TamayaConfigPlugin.java | 5 +-
.../tamaya/osgi/commands/ConfigCommands.java | 81 +++---
.../tamaya/osgi/TamayaConfigPluginTest.java | 7 +-
.../osgi/commands/ConfigCommandsTest.java | 9 +-
.../resources/META-INF/javaconfig.properties | 22 ++
.../META-INF/javaconfiguration.properties | 22 --
modules/osgi/gogo-shell/bnd.bnd | 2 +-
modules/osgi/gogo-shell/pom.xml | 6 +
.../tamaya/gogo/shell/ConfigCommandsTest.java | 10 +-
modules/osgi/injection/bnd.bnd | 2 +-
modules/osgi/injection/pom.xml | 6 +
.../OSGIConfigAdminPropertySource.java | 15 +-
.../injection/OSGIConfigurationInjector.java | 23 +-
.../osgi/injection/TamayaOSGIInjector.java | 1 -
.../apache/tamaya/osgi/injection/Example.java | 9 +-
.../OSGIConfigAdminPropertySourceTest.java | 22 +-
.../tamaya/osgi/injection/TemplateExample.java | 9 +-
.../src/main/features/features.xml | 2 +-
modules/osgi/karaf-shell/bnd.bnd | 2 +-
.../karaf/shell/PropertySourcesCommand.java | 3 -
modules/osgi/updater/bnd.bnd | 2 +-
modules/osgi/updater/pom.xml | 8 +-
.../apache/tamaya/osgi/updater/Activator.java | 6 +-
.../tamaya/osgi/updater/EventListener.java | 4 +-
.../tamaya/osgi/updater/EventListenerTest.java | 6 +-
modules/pom.xml | 2 +-
.../internal/ExpressionResolutionFilter.java | 9 +-
.../resolver/internal/ResolvableConfig.java | 17 +-
.../resolver/spi/ExpressionEvaluator.java | 2 +-
modules/spring/pom.xml | 6 -
.../SpringConfigInjectionPostProcessor.java | 8 +-
.../integration/spring/TamayaEnvironment.java | 2 +-
.../integration/spring/TamayaSpringConfig.java | 6 +-
.../spring/TamayaSpringConfigSource.java | 40 +++
.../spring/TamayaSpringPropertySource.java | 39 ---
.../spring/ConfiguredSpringBean.java | 7 +-
.../integration/spring/SpringConfigTest2.java | 4 -
.../resources/META-INF/javaconfig.properties | 20 ++
.../META-INF/javaconfiguration.properties | 20 --
pom.xml | 22 +-
241 files changed, 3802 insertions(+), 7326 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/examples/01-resources-example/src/main/java/org/apache/tamaya/ext/examples/resources/Main.java
----------------------------------------------------------------------
diff --git a/examples/01-resources-example/src/main/java/org/apache/tamaya/ext/examples/resources/Main.java b/examples/01-resources-example/src/main/java/org/apache/tamaya/ext/examples/resources/Main.java
index db5cc3e..f6b3d6f 100644
--- a/examples/01-resources-example/src/main/java/org/apache/tamaya/ext/examples/resources/Main.java
+++ b/examples/01-resources-example/src/main/java/org/apache/tamaya/ext/examples/resources/Main.java
@@ -18,9 +18,8 @@
*/
package org.apache.tamaya.ext.examples.resources;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
-
+import javax.config.Config;
+import javax.config.ConfigProvider;
import java.io.PrintStream;
import java.util.Map;
import java.util.TreeMap;
@@ -43,7 +42,7 @@ public class Main {
}
public static void main(String[] args){
- Configuration cfg = ConfigurationProvider.getConfiguration();
+ Config cfg = ConfigProvider.getConfig();
System.out.println("****************************************************");
System.out.println("Example for an property sources using a ");
@@ -51,23 +50,23 @@ public class Main {
System.out.println("****************************************************");
System.out.println();
System.out.println("Example Metadata:");
- System.out.println("\tType : " + cfg.get("example.type"));
- System.out.println("\tName : " + cfg.get("example.name"));
- System.out.println("\tDescription : " + cfg.get("example.description"));
- System.out.println("\tVersion : " + cfg.get("example.version"));
- System.out.println("\tAuthor : " + cfg.get("example.author"));
+ System.out.println("\tType : " + cfg.getValue("example.type", String.class));
+ System.out.println("\tName : " + cfg.getValue("example.name", String.class));
+ System.out.println("\tDescription : " + cfg.getValue("example.description", String.class));
+ System.out.println("\tVersion : " + cfg.getValue("example.version", String.class));
+ System.out.println("\tAuthor : " + cfg.getValue("example.author", String.class));
System.out.println();
- System.out.println("\tPath : " + cfg.get("Path"));
- System.out.println("\taProp : " + cfg.get("aProp"));
+ System.out.println("\tPath : " + cfg.getValue("Path", String.class));
+ System.out.println("\taProp : " + cfg.getValue("aProp", String.class));
System.out.println();
- dump(cfg.getProperties(), System.out);
+ dump(cfg.getPropertyNames(), System.out, cfg);
}
- private static void dump(Map<String, String> properties, PrintStream stream) {
+ private static void dump(Iterable<String> properties, PrintStream stream, Config config) {
stream.println("FULL DUMP:\n\n");
- for (Map.Entry<String, String> en : new TreeMap<>(properties).entrySet()) {
- stream.println(format("\t%s = %s", en.getKey(), en.getValue()));
+ for (String en : properties) {
+ stream.println(format("\t%s = %s", en, config.getValue(en, String.class)));
}
}
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/examples/01-resources-example/src/main/java/org/apache/tamaya/ext/examples/resources/MyPathConfigSourceProvider.java
----------------------------------------------------------------------
diff --git a/examples/01-resources-example/src/main/java/org/apache/tamaya/ext/examples/resources/MyPathConfigSourceProvider.java b/examples/01-resources-example/src/main/java/org/apache/tamaya/ext/examples/resources/MyPathConfigSourceProvider.java
new file mode 100644
index 0000000..cbf88b6
--- /dev/null
+++ b/examples/01-resources-example/src/main/java/org/apache/tamaya/ext/examples/resources/MyPathConfigSourceProvider.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.ext.examples.resources;
+
+import org.apache.tamaya.base.configsource.SimpleConfigSource;
+import org.apache.tamaya.resource.AbstractPathConfigSourceProvider;
+
+import javax.config.spi.ConfigSource;
+import java.net.URL;
+import java.util.Arrays;
+import java.util.Collection;
+
+public class MyPathConfigSourceProvider extends AbstractPathConfigSourceProvider {
+
+ public MyPathConfigSourceProvider(){
+ super("cfgOther/**/*.properties", "META-INF/MyOtherConfigProperties.*");
+ }
+
+ @Override
+ protected Collection<ConfigSource> getConfigSources(URL url) {
+ return Arrays.asList(new ConfigSource[]{new SimpleConfigSource(url)});
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/examples/01-resources-example/src/main/java/org/apache/tamaya/ext/examples/resources/MyPathPropertySourceProvider.java
----------------------------------------------------------------------
diff --git a/examples/01-resources-example/src/main/java/org/apache/tamaya/ext/examples/resources/MyPathPropertySourceProvider.java b/examples/01-resources-example/src/main/java/org/apache/tamaya/ext/examples/resources/MyPathPropertySourceProvider.java
deleted file mode 100644
index 0348157..0000000
--- a/examples/01-resources-example/src/main/java/org/apache/tamaya/ext/examples/resources/MyPathPropertySourceProvider.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.ext.examples.resources;
-
-import org.apache.tamaya.spisupport.propertysource.SimplePropertySource;
-import org.apache.tamaya.resource.AbstractPathPropertySourceProvider;
-import org.apache.tamaya.spi.PropertySource;
-
-import java.net.URL;
-import java.util.Arrays;
-import java.util.Collection;
-
-public class MyPathPropertySourceProvider extends AbstractPathPropertySourceProvider {
-
- public MyPathPropertySourceProvider(){
- super("cfgOther/**/*.properties", "META-INF/MyOtherConfigProperties.*");
- }
-
- @Override
- protected Collection<PropertySource> getPropertySources(URL url) {
- return Arrays.asList(new PropertySource[]{new SimplePropertySource(url)});
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/examples/01-resources-example/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertySourceProvider
----------------------------------------------------------------------
diff --git a/examples/01-resources-example/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertySourceProvider b/examples/01-resources-example/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertySourceProvider
index c0a9448..f2bf636 100644
--- a/examples/01-resources-example/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertySourceProvider
+++ b/examples/01-resources-example/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertySourceProvider
@@ -16,4 +16,4 @@
# specific language governing permissions and limitations
# under the License.
#
-org.apache.tamaya.ext.examples.resources.MyPathPropertySourceProvider
\ No newline at end of file
+org.apache.tamaya.ext.examples.resources.MyPathConfigSourceProvider
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/examples/02-resolver-example/src/main/java/org/apache/tamay/ext/examples/resolver/Main.java
----------------------------------------------------------------------
diff --git a/examples/02-resolver-example/src/main/java/org/apache/tamay/ext/examples/resolver/Main.java b/examples/02-resolver-example/src/main/java/org/apache/tamay/ext/examples/resolver/Main.java
index 6b99c57..24b6f98 100644
--- a/examples/02-resolver-example/src/main/java/org/apache/tamay/ext/examples/resolver/Main.java
+++ b/examples/02-resolver-example/src/main/java/org/apache/tamay/ext/examples/resolver/Main.java
@@ -18,9 +18,8 @@
*/
package org.apache.tamay.ext.examples.resolver;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
-
+import javax.config.Config;
+import javax.config.ConfigProvider;
import java.io.PrintStream;
import java.util.Map;
import java.util.TreeMap;
@@ -47,32 +46,32 @@ public class Main {
}
public static void main(String[] args){
- Configuration cfg = ConfigurationProvider.getConfiguration();
+ Config cfg = ConfigProvider.getConfig();
System.out.println("****************************************************");
System.out.println("Resolver Example");
System.out.println("****************************************************");
System.out.println();
System.out.println("Example Metadata:");
- System.out.println("\tType : " + cfg.get("example.type"));
- System.out.println("\tName : " + cfg.get("example.name"));
- System.out.println("\tDescription : " + cfg.get("example.description"));
- System.out.println("\tVersion : " + cfg.get("example.version"));
- System.out.println("\tAuthor : " + cfg.get("example.author"));
+ System.out.println("\tType : " + cfg.getValue("example.type", String.class));
+ System.out.println("\tName : " + cfg.getValue("example.name", String.class));
+ System.out.println("\tDescription : " + cfg.getValue("example.description", String.class));
+ System.out.println("\tVersion : " + cfg.getValue("example.version", String.class));
+ System.out.println("\tAuthor : " + cfg.getValue("example.author", String.class));
System.out.println();
System.out.println("Resolved Data:");
- System.out.println("\tFullName : " + cfg.get("example.fullName"));
- System.out.println("\tFullVersion : " + cfg.get("example.fullVersion"));
+ System.out.println("\tFullName : " + cfg.getValue("example.fullName", String.class));
+ System.out.println("\tFullVersion : " + cfg.getValue("example.fullVersion", String.class));
System.out.println();
- dump(cfg.getProperties(), System.out);
+ dump(cfg.getPropertyNames(), System.out, cfg);
}
- private static void dump(Map<String, String> properties, PrintStream stream) {
+ private static void dump(Iterable<String> properties, PrintStream stream, Config config) {
stream.println("FULL DUMP:\n\n");
- for (Map.Entry<String, String> en : new TreeMap<>(properties).entrySet()) {
- stream.println(format("\t%s = %s", en.getKey(), en.getValue()));
+ for (String en : properties) {
+ stream.println(format("\t%s = %s", en, config.getValue(en, String.class)));
}
}
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/examples/03-injection-example/src/main/java/org/apache/tamaya/ext/examples/injection/Example.java
----------------------------------------------------------------------
diff --git a/examples/03-injection-example/src/main/java/org/apache/tamaya/ext/examples/injection/Example.java b/examples/03-injection-example/src/main/java/org/apache/tamaya/ext/examples/injection/Example.java
index 6f78e58..c770f02 100644
--- a/examples/03-injection-example/src/main/java/org/apache/tamaya/ext/examples/injection/Example.java
+++ b/examples/03-injection-example/src/main/java/org/apache/tamaya/ext/examples/injection/Example.java
@@ -18,8 +18,8 @@
*/
package org.apache.tamaya.ext.examples.injection;
-import org.apache.tamaya.inject.api.Config;
import org.apache.tamaya.inject.api.ConfigDefaultSections;
+import javax.config.inject.ConfigProperty;
/**
* Simple example bean, mapped by default names mostly.
@@ -30,10 +30,10 @@ public class Example {
private String type;
private String name;
- @Config(defaultValue = "No description available.")
+ @ConfigProperty(defaultValue = "No description available.")
private String description;
private int version;
- @Config("author")
+ @ConfigProperty(name="author")
private String exampleAuthor;
@Override
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/examples/03-injection-example/src/main/java/org/apache/tamaya/ext/examples/injection/ExampleTemplate.java
----------------------------------------------------------------------
diff --git a/examples/03-injection-example/src/main/java/org/apache/tamaya/ext/examples/injection/ExampleTemplate.java b/examples/03-injection-example/src/main/java/org/apache/tamaya/ext/examples/injection/ExampleTemplate.java
index 8eb6839..c5457cd 100644
--- a/examples/03-injection-example/src/main/java/org/apache/tamaya/ext/examples/injection/ExampleTemplate.java
+++ b/examples/03-injection-example/src/main/java/org/apache/tamaya/ext/examples/injection/ExampleTemplate.java
@@ -18,8 +18,8 @@
*/
package org.apache.tamaya.ext.examples.injection;
-import org.apache.tamaya.inject.api.Config;
import org.apache.tamaya.inject.api.ConfigDefaultSections;
+import javax.config.inject.ConfigProperty;
/**
* Simple example bean, mapped by default names mostly.
@@ -31,12 +31,12 @@ public interface ExampleTemplate {
String getName();
- @Config(defaultValue = "No description available.")
+ @ConfigProperty(defaultValue = "No description available.")
String getDescription();
int getVersion();
- @Config("author")
+ @ConfigProperty(name="author")
String getExampleAuthor();
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/examples/03-injection-example/src/test/java/org/apache/tamaya/ext/examples/injection/MinimalTest.java
----------------------------------------------------------------------
diff --git a/examples/03-injection-example/src/test/java/org/apache/tamaya/ext/examples/injection/MinimalTest.java b/examples/03-injection-example/src/test/java/org/apache/tamaya/ext/examples/injection/MinimalTest.java
index 022b5b8..ac03302 100644
--- a/examples/03-injection-example/src/test/java/org/apache/tamaya/ext/examples/injection/MinimalTest.java
+++ b/examples/03-injection-example/src/test/java/org/apache/tamaya/ext/examples/injection/MinimalTest.java
@@ -18,21 +18,20 @@
*/
package org.apache.tamaya.ext.examples.injection;
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
import org.junit.BeforeClass;
import org.junit.Test;
+import javax.config.Config;
+import javax.config.ConfigProvider;
import java.math.BigInteger;
public class MinimalTest {
- private static Configuration config;
+ private static Config config;
@BeforeClass
public static void before() throws InterruptedException {
- config = ConfigurationProvider.getConfiguration();
+ config = ConfigProvider.getConfig();
Thread.sleep(100L);
}
@@ -43,53 +42,53 @@ public class MinimalTest {
System.out.println("****************************************************");
System.out.println();
System.out.println("Example Metadata:");
- System.out.println("\tType : " + config.get("example.type"));
- System.out.println("\tName : " + config.get("example.name"));
- System.out.println("\tDescription : " + config.get("example.description"));
- System.out.println("\tVersion : " + config.get("example.version"));
- System.out.println("\tAuthor : " + config.get("example.author"));
+ System.out.println("\tType : " + config.getValue("example.type", String.class));
+ System.out.println("\tName : " + config.getValue("example.name", String.class));
+ System.out.println("\tDescription : " + config.getValue("example.description", String.class));
+ System.out.println("\tVersion : " + config.getValue("example.version", String.class));
+ System.out.println("\tAuthor : " + config.getValue("example.author", String.class));
System.out.println();
}
- @Test(expected = ConfigException.class)
+ @Test(expected = IllegalArgumentException.class)
public void getNumberValueTooLong() {
- String value = config.get("example.number");
+ String value = config.getValue("example.number", String.class);
System.err.println("**** example.number(String)=" + value);
- int number = config.get("example.number",int.class);
+ int number = config.getValue("example.number",int.class);
System.out.println("----\n example.number(int)=" + number);
}
@Test
public void getNumberValueAsInt_BadCase() {
- String value = config.get("example.numberAsHex");
- int number = config.get("example.numberAsHex",int.class);
+ String value = config.getValue("example.numberAsHex", String.class);
+ int number = config.getValue("example.numberAsHex",int.class);
print("example.numberAsHex", number);
}
@Test
public void getNumberValueAsBigInteger() {
- String value = config.get("example.number");
- BigInteger number = config.get("example.number", BigInteger.class);
+ String value = config.getValue("example.number", String.class);
+ BigInteger number = config.getValue("example.number", BigInteger.class);
print("example.number", number);
}
- @Test(expected = ConfigException.class)
+ @Test(expected = IllegalArgumentException.class)
public void getNumberValueAsLongHex() {
- String value = config.get("example.numberAsLongHex");
- long number = config.get("example.numberAsLongHex",int.class);
+ String value = config.getValue("example.numberAsLongHex", String.class);
+ long number = config.getValue("example.numberAsLongHex",int.class);
print("example.numberAsLongHex", number);
}
@Test
public void getEnum() {
- String value = config.get("example.testEnum");
- TestEnum en = config.get("example.testEnum", TestEnum.class);
+ String value = config.getValue("example.testEnum", String.class);
+ TestEnum en = config.getValue("example.testEnum", TestEnum.class);
print("example.testEnum", en);
}
protected void print(String key, Object value) {
System.out.println("----\n" +
- " " + key + "(String)=" + config.get(key)
+ " " + key + "(String)=" + config.getValue(key, String.class)
+ "\n " + key + "(" + value.getClass().getSimpleName() + ")=" + value);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/examples/03-injection-example/src/test/resources/META-INF/javaconfig.properties
----------------------------------------------------------------------
diff --git a/examples/03-injection-example/src/test/resources/META-INF/javaconfig.properties b/examples/03-injection-example/src/test/resources/META-INF/javaconfig.properties
new file mode 100644
index 0000000..acb9caf
--- /dev/null
+++ b/examples/03-injection-example/src/test/resources/META-INF/javaconfig.properties
@@ -0,0 +1,25 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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 current 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.
+#
+tamaya.ordinal=-1
+example.description=A minimal example only using API and RI, now partially overridden!
+
+example.number=35333333333333333333333333333333333333333333333333333333333330
+example.numberAsHex=0xFA
+example.numberAsLongHex=0xFFFSFSFF
+example.testEnum=V1
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/examples/03-injection-example/src/test/resources/META-INF/javaconfiguration.properties
----------------------------------------------------------------------
diff --git a/examples/03-injection-example/src/test/resources/META-INF/javaconfiguration.properties b/examples/03-injection-example/src/test/resources/META-INF/javaconfiguration.properties
deleted file mode 100644
index acb9caf..0000000
--- a/examples/03-injection-example/src/test/resources/META-INF/javaconfiguration.properties
+++ /dev/null
@@ -1,25 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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 current 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.
-#
-tamaya.ordinal=-1
-example.description=A minimal example only using API and RI, now partially overridden!
-
-example.number=35333333333333333333333333333333333333333333333333333333333330
-example.numberAsHex=0xFA
-example.numberAsLongHex=0xFFFSFSFF
-example.testEnum=V1
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/examples/04-events-example/src/main/java/org/apache/tamaya/ext/examples/events/FileConfigSourceProvider.java
----------------------------------------------------------------------
diff --git a/examples/04-events-example/src/main/java/org/apache/tamaya/ext/examples/events/FileConfigSourceProvider.java b/examples/04-events-example/src/main/java/org/apache/tamaya/ext/examples/events/FileConfigSourceProvider.java
new file mode 100644
index 0000000..e8c831a
--- /dev/null
+++ b/examples/04-events-example/src/main/java/org/apache/tamaya/ext/examples/events/FileConfigSourceProvider.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.ext.examples.events;
+
+
+import org.apache.tamaya.base.configsource.BaseConfigSource;
+import org.apache.tamaya.resource.AbstractPathConfigSourceProvider;
+
+import javax.config.spi.ConfigSource;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.*;
+
+import static org.apache.tamaya.ext.examples.events.Main.getPropertiesFilePath;
+
+public class FileConfigSourceProvider extends AbstractPathConfigSourceProvider {
+ public FileConfigSourceProvider() {
+ super(getPropertiesFilePath().toString());
+ }
+
+ @Override
+ protected Collection<ConfigSource> getConfigSources(URL url) {
+ return Arrays.asList(new ConfigSource[] { new DumbReloadingPropertySource(url) });
+ }
+
+ public static class DumbReloadingPropertySource extends BaseConfigSource {
+ private final URL propertiesFile;
+
+ public DumbReloadingPropertySource(URL url) {
+ propertiesFile = url;
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+
+ Map<String, String> properties = new HashMap<>();
+ try (InputStream stream = propertiesFile.openStream()) {
+ Properties props = new Properties();
+ if (stream != null) {
+ props.load(stream);
+ }
+
+ for (String key : props.stringPropertyNames()) {
+ properties.put(key, props.getProperty(key));
+ }
+ } catch (IOException e) {
+ throw new IllegalStateException("Error loading properties from " + propertiesFile, e);
+ }
+
+ return properties;
+
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/examples/04-events-example/src/main/java/org/apache/tamaya/ext/examples/events/FilePropertySourceProvider.java
----------------------------------------------------------------------
diff --git a/examples/04-events-example/src/main/java/org/apache/tamaya/ext/examples/events/FilePropertySourceProvider.java b/examples/04-events-example/src/main/java/org/apache/tamaya/ext/examples/events/FilePropertySourceProvider.java
deleted file mode 100644
index a15ad6e..0000000
--- a/examples/04-events-example/src/main/java/org/apache/tamaya/ext/examples/events/FilePropertySourceProvider.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.ext.examples.events;
-
-
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.spisupport.propertysource.BasePropertySource;
-import org.apache.tamaya.resource.AbstractPathPropertySourceProvider;
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.*;
-
-import static org.apache.tamaya.ext.examples.events.Main.getPropertiesFilePath;
-
-public class FilePropertySourceProvider extends AbstractPathPropertySourceProvider {
- public FilePropertySourceProvider() {
- super(getPropertiesFilePath().toString());
- }
-
- @Override
- protected Collection<PropertySource> getPropertySources(URL url) {
- return Arrays.asList(new PropertySource[] { new DumbReloadingPropertySource(url) });
- }
-
- public static class DumbReloadingPropertySource extends BasePropertySource {
- private final URL propertiesFile;
-
- public DumbReloadingPropertySource(URL url) {
- propertiesFile = url;
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
-
- Map<String, PropertyValue> properties = new HashMap<>();
- try (InputStream stream = propertiesFile.openStream()) {
- Properties props = new Properties();
- if (stream != null) {
- props.load(stream);
- }
-
- for (String key : props.stringPropertyNames()) {
- properties.put(key, PropertyValue.of(key, props.getProperty(key), getName()));
- }
- } catch (IOException e) {
- throw new ConfigException("Error loading properties from " + propertiesFile, e);
- }
-
- return properties;
-
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/examples/04-events-example/src/main/java/org/apache/tamaya/ext/examples/events/Main.java
----------------------------------------------------------------------
diff --git a/examples/04-events-example/src/main/java/org/apache/tamaya/ext/examples/events/Main.java b/examples/04-events-example/src/main/java/org/apache/tamaya/ext/examples/events/Main.java
index 67d680c..6b319d9 100644
--- a/examples/04-events-example/src/main/java/org/apache/tamaya/ext/examples/events/Main.java
+++ b/examples/04-events-example/src/main/java/org/apache/tamaya/ext/examples/events/Main.java
@@ -18,15 +18,15 @@
*/
package org.apache.tamaya.ext.examples.events;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
import org.apache.tamaya.events.ConfigEvent;
import org.apache.tamaya.events.ConfigEventListener;
import org.apache.tamaya.events.ConfigEventManager;
-import org.apache.tamaya.events.ConfigurationChange;
+import org.apache.tamaya.events.ConfigChange;
import org.joda.time.DateTime;
import org.joda.time.Duration;
+import javax.config.Config;
+import javax.config.ConfigProvider;
import java.beans.PropertyChangeEvent;
import java.io.IOException;
import java.nio.charset.Charset;
@@ -64,10 +64,10 @@ public class Main {
ConfigEventManager.addListener(new ConfigurationChangeListener());
ConfigEventManager.setChangeMonitoringPeriod(1_000L);
ConfigEventManager.enableChangeMonitoring(true);
- Configuration configuration = ConfigurationProvider.getConfiguration();
+ Config config = ConfigProvider.getConfig();
- for (Map.Entry<String, String> e : configuration.getProperties().entrySet()) {
- System.out.println(e.getKey() + ": " + e.getValue());
+ for (String key : config.getPropertyNames()) {
+ System.out.println(key + ": " + config.getValue(key, String.class));
}
@@ -108,7 +108,7 @@ public class Main {
@Override
public void onConfigEvent(ConfigEvent<?> event) {
- ConfigurationChange c = (ConfigurationChange) event;
+ ConfigChange c = (ConfigChange) event;
if (c.isKeyAffected("a")) {
// Looking for the change event of property a. Not recomanded
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/examples/04-events-example/src/main/resources/META-INF/services/javax.config.spi.ConfigSourceProvider
----------------------------------------------------------------------
diff --git a/examples/04-events-example/src/main/resources/META-INF/services/javax.config.spi.ConfigSourceProvider b/examples/04-events-example/src/main/resources/META-INF/services/javax.config.spi.ConfigSourceProvider
new file mode 100644
index 0000000..bc9e368
--- /dev/null
+++ b/examples/04-events-example/src/main/resources/META-INF/services/javax.config.spi.ConfigSourceProvider
@@ -0,0 +1,20 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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 current 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.
+#
+org.apache.tamaya.ext.examples.events.FileConfigSourceProvider
+
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/examples/04-events-example/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertySourceProvider
----------------------------------------------------------------------
diff --git a/examples/04-events-example/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertySourceProvider b/examples/04-events-example/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertySourceProvider
deleted file mode 100644
index a0d95fb..0000000
--- a/examples/04-events-example/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertySourceProvider
+++ /dev/null
@@ -1,20 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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 current 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.
-#
-org.apache.tamaya.ext.examples.events.FilePropertySourceProvider
-
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/examples/05-spring-example/src/main/java/org/apache/tamaya/springexample/ColorConverter.java
----------------------------------------------------------------------
diff --git a/examples/05-spring-example/src/main/java/org/apache/tamaya/springexample/ColorConverter.java b/examples/05-spring-example/src/main/java/org/apache/tamaya/springexample/ColorConverter.java
index 3ec3977..60c93a0 100644
--- a/examples/05-spring-example/src/main/java/org/apache/tamaya/springexample/ColorConverter.java
+++ b/examples/05-spring-example/src/main/java/org/apache/tamaya/springexample/ColorConverter.java
@@ -15,18 +15,16 @@
*/
package org.apache.tamaya.springexample;
-import org.apache.tamaya.spi.ConversionContext;
-import org.apache.tamaya.spi.PropertyConverter;
-
+import javax.config.spi.Converter;
import java.awt.*;
/**
* Simple demo converter for Color.
*/
-public class ColorConverter implements PropertyConverter<Color>{
+public class ColorConverter implements Converter<Color> {
@Override
- public Color convert(String value, ConversionContext context) {
+ public Color convert(String value) {
if(value.length()<7){
return null;
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/examples/05-spring-example/src/main/java/org/apache/tamaya/springexample/WelcomeController.java
----------------------------------------------------------------------
diff --git a/examples/05-spring-example/src/main/java/org/apache/tamaya/springexample/WelcomeController.java b/examples/05-spring-example/src/main/java/org/apache/tamaya/springexample/WelcomeController.java
index 172c4d5..04f1619 100644
--- a/examples/05-spring-example/src/main/java/org/apache/tamaya/springexample/WelcomeController.java
+++ b/examples/05-spring-example/src/main/java/org/apache/tamaya/springexample/WelcomeController.java
@@ -18,18 +18,18 @@ package org.apache.tamaya.springexample;
import java.awt.*;
import java.util.Date;
import java.util.Map;
+import java.util.Optional;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
import org.apache.tamaya.functions.ConfigurationFunctions;
-import org.apache.tamaya.inject.api.Config;
import org.apache.tamaya.inject.api.DynamicValue;
import org.apache.tamaya.inject.api.UpdatePolicy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
-import javax.websocket.server.PathParam;
+import javax.config.Config;
+import javax.config.ConfigProvider;
+import javax.config.inject.ConfigProperty;
@Controller
public class WelcomeController {
@@ -37,14 +37,14 @@ public class WelcomeController {
@Value("${application.message:Hello World}")
private String message = "Hello World";
- @Config(value = "background.color", required = false)
- private String backgroundColor = "#BBBBBB";
+ @ConfigProperty(name = "background.color", defaultValue = "#BBBBBB")
+ private Optional<String> backgroundColor;
- @Config(value = "foreground.color", required = false, defaultValue = "#DDDDDD")
+ @ConfigProperty(name = "foreground.color", defaultValue = "#DDDDDD")
private DynamicValue<String> foregroundColor;
- @Config(value = "background.color", required = false)
- private Color bgColor;
+ @ConfigProperty(name = "background.color")
+ private Optional<Color> bgColor;
@GetMapping("/")
public String welcome(Map<String, Object> model) {
@@ -72,19 +72,18 @@ public class WelcomeController {
@GetMapping("/config")
public String config(Map<String, Object> model) {
- Configuration config = ConfigurationProvider.getConfiguration();
+ Config config = ConfigProvider.getConfig();
model.put("filter", "NO FILTER");
- model.put("config", config
- .query(ConfigurationFunctions.textInfo()));
+ model.put("config", ConfigurationFunctions.textInfo().apply(config));
return "config";
}
@GetMapping(value="/config/{path}")
public String config(@PathVariable("path") String path, Map<String, Object> model) {
- Configuration config = ConfigurationProvider.getConfiguration();
+ Config config = ConfigProvider.getConfig();
model.put("filter", path);
- model.put("config", config.with(ConfigurationFunctions.section(path))
- .query(ConfigurationFunctions.textInfo()));
+ model.put("config", ConfigurationFunctions.textInfo()
+ .apply(ConfigurationFunctions.section(path).apply(config)));
return "config";
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/features/pom.xml
----------------------------------------------------------------------
diff --git a/modules/features/pom.xml b/modules/features/pom.xml
index db616aa..8924bb2 100644
--- a/modules/features/pom.xml
+++ b/modules/features/pom.xml
@@ -35,12 +35,6 @@ under the License.
<dependencies>
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-api</artifactId>
- <version>${tamaya-apicore.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.tamaya</groupId>
<artifactId>tamaya-core</artifactId>
<version>${tamaya-apicore.version}</version>
<scope>provided</scope>
@@ -54,6 +48,12 @@ under the License.
<artifactId>junit</artifactId>
</dependency>
<dependency>
+ <groupId>org.apache.tamaya</groupId>
+ <artifactId>tamaya-compat</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>org.apache.tamaya.ext</groupId>
<artifactId>tamaya-injection</artifactId>
<version>${project.version}</version>
@@ -109,7 +109,7 @@ under the License.
</dependency>
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-spisupport</artifactId>
+ <artifactId>tamaya-base</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/features/src/main/java/org/apache/tamaya/features/Features.java
----------------------------------------------------------------------
diff --git a/modules/features/src/main/java/org/apache/tamaya/features/Features.java b/modules/features/src/main/java/org/apache/tamaya/features/Features.java
index 32834fa..6418179 100644
--- a/modules/features/src/main/java/org/apache/tamaya/features/Features.java
+++ b/modules/features/src/main/java/org/apache/tamaya/features/Features.java
@@ -50,7 +50,7 @@ public final class Features {
* @return true, if <i>tamaya-core</i> is on the classpath.
*/
public static boolean tamayaCoreAvailable() {
- return checkClassIsLoadable("org.apache.tamaya.core.internal.CoreConfiguration");
+ return checkClassIsLoadable("org.apache.tamaya.core.TamayaConfigProviderResolver");
}
/**
@@ -105,8 +105,16 @@ public final class Features {
* Checks if <i>tamaya-spisupport</i> is on the classpath.
* @return true, if <i>tamaya-spisupport</i> is on the classpath.
*/
- public static boolean spiSupportAvailable() {
- return checkClassIsLoadable("org.apache.tamaya.spisupport.PropertySourceComparator");
+ public static boolean baseSupportAvailable() {
+ return checkClassIsLoadable("org.apache.tamaya.base.PriorityServiceComparator");
+ }
+
+ /**
+ * Checks if <i>tamaya-spisupport</i> is on the classpath.
+ * @return true, if <i>tamaya-spisupport</i> is on the classpath.
+ */
+ public static boolean compatSupportAvailable() {
+ return checkClassIsLoadable("org.apache.tamaya.spi.PropertyConverter");
}
/**
@@ -130,7 +138,7 @@ public final class Features {
* @return true, if <i>tamaya-jndi</i> is on the classpath.
*/
public static boolean jndiAvailable() {
- return checkClassIsLoadable("org.apache.tamaya.jndi.JNDIPropertySource");
+ return checkClassIsLoadable("org.apache.tamaya.jndi.JNDIConfigSource");
}
/**
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/features/src/test/java/org/apache/tamaya/features/FeaturesTest.java
----------------------------------------------------------------------
diff --git a/modules/features/src/test/java/org/apache/tamaya/features/FeaturesTest.java b/modules/features/src/test/java/org/apache/tamaya/features/FeaturesTest.java
index db6e16c..98ca520 100644
--- a/modules/features/src/test/java/org/apache/tamaya/features/FeaturesTest.java
+++ b/modules/features/src/test/java/org/apache/tamaya/features/FeaturesTest.java
@@ -72,8 +72,13 @@ public class FeaturesTest {
}
@Test
- public void spiSupportAvailable() throws Exception {
- assertTrue(Features.spiSupportAvailable());
+ public void baseSupportAvailable() throws Exception {
+ assertTrue(Features.baseSupportAvailable());
+ }
+
+ @Test
+ public void compatSupportAvailable() throws Exception {
+ assertTrue(Features.compatSupportAvailable());
}
@Test
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/features/src/test/java/org/apache/tamaya/features/FeaturesTestNoOnly.java
----------------------------------------------------------------------
diff --git a/modules/features/src/test/java/org/apache/tamaya/features/FeaturesTestNoOnly.java b/modules/features/src/test/java/org/apache/tamaya/features/FeaturesTestNoOnly.java
index 1bcb64b..8a5008a 100644
--- a/modules/features/src/test/java/org/apache/tamaya/features/FeaturesTestNoOnly.java
+++ b/modules/features/src/test/java/org/apache/tamaya/features/FeaturesTestNoOnly.java
@@ -92,8 +92,8 @@ public class FeaturesTestNoOnly {
}
@Test
- public void spiSupportAvailable() throws Exception {
- assertFalse(Features.spiSupportAvailable());
+ public void baseSupportAvailable() throws Exception {
+ assertFalse(Features.baseSupportAvailable());
}
@Test
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/filter/bnd.bnd
----------------------------------------------------------------------
diff --git a/modules/filter/bnd.bnd b/modules/filter/bnd.bnd
index 006f58e..228fd37 100644
--- a/modules/filter/bnd.bnd
+++ b/modules/filter/bnd.bnd
@@ -11,7 +11,7 @@ javac.target: 1.8
Bundle-Version: ${version}.${tstamp}
Bundle-Name: Apache Tamaya - Filter
-Bundle-SymbolicName: org.apache.tamaya.filter
+Bundle-SymbolicName: org.apache.tamaya.spisupport.filter
Bundle-Description: Apacha Tamaya Config - Filtered Config Access
Bundle-Category: Implementation
Bundle-Copyright: (C) Apache Foundation
@@ -23,6 +23,6 @@ Export-Package: \
org.apache.tamaya.filter
Import-Package: \
org.apache.tamaya,\
- org.apache.tamaya.spi
+ org.apache.tamaya.base
Export-Service: \
- org.apache.tamaya.spi.PropertyFilter
+ org.apache.tamaya.spi.Filter
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/filter/pom.xml
----------------------------------------------------------------------
diff --git a/modules/filter/pom.xml b/modules/filter/pom.xml
index 88ebfa6..20f7eca 100644
--- a/modules/filter/pom.xml
+++ b/modules/filter/pom.xml
@@ -35,15 +35,14 @@ under the License.
<dependencies>
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-api</artifactId>
- <version>${tamaya-apicore.version}</version>
- <scope>provided</scope>
+ <artifactId>tamaya-base</artifactId>
+ <version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tamaya</groupId>
<artifactId>tamaya-core</artifactId>
<version>${tamaya-apicore.version}</version>
- <scope>provided</scope>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
@@ -54,12 +53,6 @@ under the License.
<artifactId>junit</artifactId>
</dependency>
<dependency>
- <groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-spisupport</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.compendium</artifactId>
<version>5.0.0</version>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/filter/src/main/java/org/apache/tamaya/filter/ConfigurationFilter.java
----------------------------------------------------------------------
diff --git a/modules/filter/src/main/java/org/apache/tamaya/filter/ConfigurationFilter.java b/modules/filter/src/main/java/org/apache/tamaya/filter/ConfigurationFilter.java
index 7f81dcb..1c16c07 100644
--- a/modules/filter/src/main/java/org/apache/tamaya/filter/ConfigurationFilter.java
+++ b/modules/filter/src/main/java/org/apache/tamaya/filter/ConfigurationFilter.java
@@ -18,10 +18,11 @@
*/
package org.apache.tamaya.filter;
-import org.apache.tamaya.spi.PropertyFilter;
-import org.apache.tamaya.spi.PropertyValue;
+import org.apache.tamaya.spi.Filter;
import org.osgi.service.component.annotations.Component;
+import java.util.*;
+
/**
* Hereby
@@ -40,28 +41,11 @@ import org.osgi.service.component.annotations.Component;
* active.
*/
@Component
-public final class ConfigurationFilter implements PropertyFilter{
-
- static final ThreadLocal<Boolean> THREADED_METADATA_FILTERED = new ThreadLocal<Boolean>(){
- @Override
- protected Boolean initialValue() {
- return Boolean.TRUE;
- }
- };
+public final class ConfigurationFilter implements Filter{
- private static final ThreadLocal<FilterContext> THREADED_MAP_FILTERS = new ThreadLocal<FilterContext>(){
- @Override
- protected FilterContext initialValue() {
- return new FilterContext();
- }
- };
+ private static final ThreadLocal<Boolean> THREADED_METADATA_FILTERED = ThreadLocal.withInitial(() -> Boolean.TRUE);
- private static final ThreadLocal<FilterContext> THREADED_VALUE_FILTERS = new ThreadLocal<FilterContext>(){
- @Override
- protected FilterContext initialValue() {
- return new FilterContext();
- }
- };
+ private static final ThreadLocal<List<Filter>> THREADED_FILTERS = ThreadLocal.withInitial(ArrayList::new);
/**
* Flag if metadata entries (starting with an '_') are filtered out on when accessing multiple properties, default
@@ -82,44 +66,88 @@ public final class ConfigurationFilter implements PropertyFilter{
}
/**
- * Access the filtering configuration that is used on the current thread for
- * filtering single property values accessed.
+ * Access the filtering configuration that is used on the current thread.
*
* @return the filtering config, never null.
*/
- public static FilterContext getSingleValueFilterContext(){
- return THREADED_VALUE_FILTERS.get();
+ public static List<Filter> getFilters(){
+ return Collections.unmodifiableList(THREADED_FILTERS.get());
}
/**
- * Access the filtering configuration that is used used on the current thread
- * for filtering configuration properties accessed as full
- * map.
- * @return the filtering config, never null.
+ * Add a filter.
+ * @param filter the filter.
+ */
+ public static void addFilter(Filter filter){
+ if(!THREADED_FILTERS.get().contains(filter)) {
+ THREADED_FILTERS.get().add(filter);
+ }
+ }
+
+ /**
+ * Adds a filter at given position.
+ * @param pos the position.
+ * @param filter the filter.
+ */
+ public static void addFilter(int pos, Filter filter){
+ if(!THREADED_FILTERS.get().contains(filter)) {
+ THREADED_FILTERS.get().add(pos, filter);
+ }
+ }
+
+ /**
+ * Removes a filter at a given position.
+ * @param pos the position.
+ * @return the filter removed, or null.
+ */
+ public static Filter removeFilter(int pos){
+ return THREADED_FILTERS.get().remove(pos);
+ }
+
+ /**
+ * Removes a filter.
+ * @param filter the filter to be removed, not null.
+ */
+ public static void removeFilter(Filter filter) {
+ THREADED_FILTERS.get().remove(filter);
+ }
+
+ /**
+ * Clears all filters.
+ */
+ public static void clearFilters(){
+ THREADED_FILTERS.get().clear();
+ }
+
+ /**
+ * Set the filters.
+ * @param filters the filters to be applied.
+ */
+ public static void setFilters(Filter... filters){
+ setFilters(Arrays.asList(filters));
+ }
+
+ /**
+ * Set the filters.
+ * @param filters the filters to be applied.
*/
- public static FilterContext getMapFilterContext(){
- return THREADED_MAP_FILTERS.get();
+ public static void setFilters(Collection<Filter> filters) {
+ THREADED_FILTERS.get().clear();
+ THREADED_FILTERS.get().addAll(filters);
}
/**
* Removes all programmable filters active on the current thread.
*/
public static void cleanupFilterContext(){
- THREADED_MAP_FILTERS.get().clearFilters();
- THREADED_VALUE_FILTERS.get().clearFilters();
+ THREADED_FILTERS.get().clear();
THREADED_METADATA_FILTERED.set(true);
}
@Override
- public PropertyValue filterProperty(PropertyValue valueToBeFiltered, org.apache.tamaya.spi.FilterContext context) {
- if(context.isSinglePropertyScoped()){
- for(PropertyFilter pred: THREADED_VALUE_FILTERS.get().getFilters()){
- valueToBeFiltered = pred.filterProperty(valueToBeFiltered, context);
- }
- }else{
- for(PropertyFilter pred: THREADED_MAP_FILTERS.get().getFilters()){
- valueToBeFiltered = pred.filterProperty(valueToBeFiltered, context);
- }
+ public String filterProperty(String key, String valueToBeFiltered) {
+ for(Filter pred: THREADED_FILTERS.get()){
+ valueToBeFiltered = pred.filterProperty(key, valueToBeFiltered);
}
return valueToBeFiltered;
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/filter/src/main/java/org/apache/tamaya/filter/Context.java
----------------------------------------------------------------------
diff --git a/modules/filter/src/main/java/org/apache/tamaya/filter/Context.java b/modules/filter/src/main/java/org/apache/tamaya/filter/Context.java
new file mode 100644
index 0000000..c6c4ba6
--- /dev/null
+++ b/modules/filter/src/main/java/org/apache/tamaya/filter/Context.java
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.filter;
+
+import org.apache.tamaya.spi.ConfigValue;
+import org.apache.tamaya.spi.Filter;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * A set of property filter and accessor methods. This class is built for
+ * usage within a single threaded context, so it is NOT thread-safe.
+ */
+public final class Context implements Filter{
+ /** The filters. */
+ private List<Filter> filters = new ArrayList<>();
+
+ /**
+ * Add a filter.
+ * @param filter the filter.
+ */
+ public void addFilter(Filter filter){
+ if(!filters.contains(filter)) {
+ filters.add(filter);
+ }
+ }
+
+ /**
+ * Adds a filter at given position.
+ * @param pos the position.
+ * @param filter the filter.
+ */
+ public void addFilter(int pos, Filter filter){
+ if(!filters.contains(filter)) {
+ filters.add(pos, filter);
+ }
+ }
+
+ /**
+ * Removes a filter at a given position.
+ * @param pos the position.
+ * @return the filter removed, or null.
+ */
+ public Filter removeFilter(int pos){
+ return filters.remove(pos);
+ }
+
+ /**
+ * Removes a filter.
+ * @param filter the filter to be removed, not null.
+ */
+ public void removeFilter(Filter filter) {
+ filters.remove(filter);
+ }
+
+ /**
+ * Clears all filters.
+ */
+ public void clearFilters(){
+ filters.clear();
+ }
+
+ /**
+ * Set the filters.
+ * @param filters the filters to be applied.
+ */
+ public void setFilters(Filter... filters){
+ setFilters(Arrays.asList(filters));
+ }
+
+ /**
+ * Set the filters.
+ * @param filters the filters to be applied.
+ */
+ public void setFilters(Collection<Filter> filters) {
+ this.filters.clear();
+ this.filters.addAll(filters);
+ }
+
+ /**
+ * Get all filters.
+ * @return all filters.
+ */
+ public List<Filter> getFilters(){
+ return Collections.unmodifiableList(filters);
+ }
+
+ @Override
+ public String filterProperty(String key, String valueToBeFiltered) {
+ for(Filter filter: filters){
+ valueToBeFiltered = filter.filterProperty(key, valueToBeFiltered);
+ }
+ return valueToBeFiltered;
+ }
+
+ @Override
+ public String toString() {
+ return "ProgrammableFilter{" +
+ "filters=" + filters +
+ '}';
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/filter/src/main/java/org/apache/tamaya/filter/internal/DefaultMetadataFilter.java
----------------------------------------------------------------------
diff --git a/modules/filter/src/main/java/org/apache/tamaya/filter/internal/DefaultMetadataFilter.java b/modules/filter/src/main/java/org/apache/tamaya/filter/internal/DefaultMetadataFilter.java
index e9554a2..ba78930 100644
--- a/modules/filter/src/main/java/org/apache/tamaya/filter/internal/DefaultMetadataFilter.java
+++ b/modules/filter/src/main/java/org/apache/tamaya/filter/internal/DefaultMetadataFilter.java
@@ -18,23 +18,23 @@
*/
package org.apache.tamaya.filter.internal;
+import org.apache.tamaya.base.filter.FilterContext;
import org.apache.tamaya.filter.ConfigurationFilter;
-import org.apache.tamaya.spi.FilterContext;
-import org.apache.tamaya.spi.PropertyFilter;
-import org.apache.tamaya.spi.PropertyValue;
+import org.apache.tamaya.spi.Filter;
/**
* Default property filter that hides metadta entries starting with an '_', similar ti {@code etcd}.
*/
-public final class DefaultMetadataFilter implements PropertyFilter{
+public final class DefaultMetadataFilter implements Filter{
@Override
- public PropertyValue filterProperty(PropertyValue valueToBeFiltered, FilterContext context) {
- if(context.isSinglePropertyScoped()){
+ public String filterProperty(String key, String valueToBeFiltered) {
+ FilterContext context = FilterContext.getContext();
+ if(context==null || context.isSinglePropertyScoped()){
// When accessing keys explicitly, do not hide anything.
return valueToBeFiltered;
}
if(ConfigurationFilter.isMetadataFiltered()) {
- if (context.getProperty().getKey().startsWith("_")) {
+ if (key.startsWith("_")) {
// Hide metadata entries.
return null;
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/filter/src/main/resources/META-INF/services/org.apache.tamaya.spi.Filter
----------------------------------------------------------------------
diff --git a/modules/filter/src/main/resources/META-INF/services/org.apache.tamaya.spi.Filter b/modules/filter/src/main/resources/META-INF/services/org.apache.tamaya.spi.Filter
new file mode 100644
index 0000000..806b833
--- /dev/null
+++ b/modules/filter/src/main/resources/META-INF/services/org.apache.tamaya.spi.Filter
@@ -0,0 +1,19 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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 current 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.
+#
+org.apache.tamaya.filter.ConfigurationFilter
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/filter/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertyFilter
----------------------------------------------------------------------
diff --git a/modules/filter/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertyFilter b/modules/filter/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertyFilter
deleted file mode 100644
index 806b833..0000000
--- a/modules/filter/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertyFilter
+++ /dev/null
@@ -1,19 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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 current 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.
-#
-org.apache.tamaya.filter.ConfigurationFilter
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/filter/src/test/java/org/apache/tamaya/filter/ConfigurationFilterTest.java
----------------------------------------------------------------------
diff --git a/modules/filter/src/test/java/org/apache/tamaya/filter/ConfigurationFilterTest.java b/modules/filter/src/test/java/org/apache/tamaya/filter/ConfigurationFilterTest.java
deleted file mode 100644
index a3a75a3..0000000
--- a/modules/filter/src/test/java/org/apache/tamaya/filter/ConfigurationFilterTest.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.filter;
-
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
-import org.apache.tamaya.spi.FilterContext;
-import org.apache.tamaya.spi.PropertyFilter;
-import org.apache.tamaya.spi.PropertyValue;
-import org.junit.Test;
-
-import static org.junit.Assert.*;
-
-/**
- * Tests for {@link ConfigurationFilter}. Created by atsticks on 11.02.16.
- */
-public class ConfigurationFilterTest {
-
- @Test
- public void testMetadataFiltered() throws Exception {
- ConfigurationFilter.setMetadataFiltered(true);
- assertTrue(ConfigurationFilter.isMetadataFiltered());
- ConfigurationFilter.setMetadataFiltered(false);
- assertFalse(ConfigurationFilter.isMetadataFiltered());
- }
-
- @Test
- public void testGetSingleFilters() throws Exception {
- Configuration config = ConfigurationProvider.getConfiguration();
- assertNotNull(ConfigurationFilter.getSingleValueFilterContext());
- PropertyFilter testFilter = new PropertyFilter() {
- @Override
- public PropertyValue filterProperty(PropertyValue value, FilterContext context) {
- return value.toBuilder().setValue(value.getKey() + ":testGetSingleFilters").build();
- }
- };
- ConfigurationFilter.getSingleValueFilterContext().addFilter(testFilter);
- assertEquals("user.home:testGetSingleFilters", config.get("user.home"));
- ConfigurationFilter.getSingleValueFilterContext().removeFilter(testFilter);
- assertNotSame("user.home:testGetSingleFilters", config.get("user.home"));
- }
-
- @Test
- public void testRemoveSingleFiltersAt0() throws Exception {
- Configuration config = ConfigurationProvider.getConfiguration();
- assertNotNull(ConfigurationFilter.getSingleValueFilterContext());
- PropertyFilter testFilter = new PropertyFilter() {
- @Override
- public PropertyValue filterProperty(PropertyValue value, FilterContext context) {
- return value.toBuilder().setValue(value.getKey() + ":testGetSingleFilters").build();
- }
- };
- ConfigurationFilter.getSingleValueFilterContext().addFilter(testFilter);
- assertEquals("user.home:testGetSingleFilters", config.get("user.home"));
- ConfigurationFilter.getSingleValueFilterContext().removeFilter(0);
- assertNotSame("user.home:testGetSingleFilters", config.get("user.home"));
- }
-
- @Test
- public void testGetMapFilters() throws Exception {
- Configuration config = ConfigurationProvider.getConfiguration();
- assertNotNull(ConfigurationFilter.getMapFilterContext());
- PropertyFilter testFilter = new PropertyFilter() {
- @Override
- public PropertyValue filterProperty(PropertyValue value, FilterContext context) {
- return value.toBuilder().setValue(value.getKey() + ":testGetMapFilters").build();
- }
- };
- ConfigurationFilter.getMapFilterContext().addFilter(testFilter);
- assertEquals("user.home:testGetMapFilters", config.getProperties().get("user.home"));
- ConfigurationFilter.getSingleValueFilterContext().removeFilter(testFilter);
- assertNotSame("user.home:testGetSingleFilters", config.getProperties().get("user.home"));
- }
-
- @Test
- public void testRemoveMapFilterAt0() throws Exception {
- Configuration config = ConfigurationProvider.getConfiguration();
- assertNotNull(ConfigurationFilter.getMapFilterContext());
- PropertyFilter testFilter = new PropertyFilter() {
- @Override
- public PropertyValue filterProperty(PropertyValue value, FilterContext context) {
- return value .toBuilder().setValue(value.getKey() + ":testGetMapFilters").build();
- }
- };
- ConfigurationFilter.getMapFilterContext().addFilter(testFilter);
- assertEquals("user.home:testGetMapFilters", config.getProperties().get("user.home"));
- ConfigurationFilter.getMapFilterContext().removeFilter(0);
- assertNotSame("user.home:testGetSingleFilters", config.getProperties().get("user.home"));
- }
-
- @Test
- public void testClearFilters() throws Exception {
- Configuration config = ConfigurationProvider.getConfiguration();
- assertNotNull(ConfigurationFilter.getSingleValueFilterContext());
- PropertyFilter testFilter = new PropertyFilter() {
- @Override
- public PropertyValue filterProperty(PropertyValue value, FilterContext context) {
- return value.toBuilder().setValue(value.getKey() + ":testGetSingleFilters").build();
- }
- };
- ConfigurationFilter.getSingleValueFilterContext().addFilter(testFilter);
- assertEquals("user.home:testGetSingleFilters", config.get("user.home"));
- ConfigurationFilter.cleanupFilterContext();
- assertNotSame("user.home:testGetSingleFilters", config.get("user.home"));
- }
-
-}
\ No newline at end of file
[03/18] incubator-tamaya-extensions git commit: Adapted to comply
with JSR API.
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/581c92e7/modules/functions/src/test/java/org/apache/tamaya/functions/ConfigurationFunctionsTest.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/test/java/org/apache/tamaya/functions/ConfigurationFunctionsTest.java b/modules/functions/src/test/java/org/apache/tamaya/functions/ConfigurationFunctionsTest.java
index 99cb944..23a8c00 100644
--- a/modules/functions/src/test/java/org/apache/tamaya/functions/ConfigurationFunctionsTest.java
+++ b/modules/functions/src/test/java/org/apache/tamaya/functions/ConfigurationFunctionsTest.java
@@ -18,16 +18,14 @@
*/
package org.apache.tamaya.functions;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
-import org.apache.tamaya.spisupport.propertysource.EnvironmentPropertySource;
-import org.apache.tamaya.spisupport.propertysource.SystemPropertySource;
-import org.apache.tamaya.spi.ConfigurationContextBuilder;
+import org.apache.tamaya.base.configsource.EnvironmentConfigSource;
+import org.apache.tamaya.base.configsource.SystemConfigSource;
import org.junit.Test;
+import javax.config.Config;
+import javax.config.spi.ConfigBuilder;
+import javax.config.spi.ConfigProviderResolver;
import java.io.PrintStream;
-import java.util.Map;
-import java.util.TreeMap;
import static org.junit.Assert.*;
@@ -146,32 +144,32 @@ public class ConfigurationFunctionsTest {
@Test
public void testEmptyConfiguration() throws Exception {
- Configuration ps = ConfigurationFunctions.emptyConfiguration();
+ Config ps = ConfigurationFunctions.emptyConfig();
assertNotNull(ps);
- assertNotNull(ps.getProperties());
- assertTrue(ps.getProperties().isEmpty());
+ assertNotNull(ps.getPropertyNames());
+ assertFalse(ps.getPropertyNames().iterator().hasNext());
}
private void testSection(boolean stripKeys){
- ConfigurationContextBuilder b = ConfigurationProvider.getConfigurationContextBuilder();
- b.addPropertySources(new EnvironmentPropertySource(), new SystemPropertySource());
- Configuration cfg = ConfigurationProvider.createConfiguration(b.build()).with(
- ConfigurationFunctions.section("java.", stripKeys));
+ ConfigBuilder b = ConfigProviderResolver.instance().getBuilder()
+ .withSources(new EnvironmentConfigSource(), new SystemConfigSource());
+ Config cfg = ConfigurationFunctions.section("java.", stripKeys)
+ .apply(b.build());
System.out.println("*****************************************************");
System.out.println("stripKeys: " + stripKeys);
System.out.println("*****************************************************");
- dump(cfg.getProperties(), System.out);
+ dump(cfg.getPropertyNames(), cfg, System.out);
System.out.println();
System.out.println("Example Metadata:");
- System.out.println("\tjava.version : " + cfg.get("java.version"));
- System.out.println("\tversion : " + cfg.get("version"));
+ System.out.println("\tjava.version : " + cfg.getValue("java.version", String.class));
+ System.out.println("\tversion : " + cfg.getValue("version", String.class));
}
- private void dump(Map<String, String> properties, PrintStream stream) {
+ private void dump(Iterable<String> keys, Config config, PrintStream stream) {
stream.println("FULL DUMP:");
- for (Map.Entry<String, String> en : new TreeMap<>(properties).entrySet()) {
- stream.println("\t" + en.getKey() + " = " + en.getValue());
+ for (String key : keys) {
+ stream.println("\t" + key + " = " + config.getValue(key, String.class));
}
}
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/581c92e7/modules/functions/src/test/java/org/apache/tamaya/functions/EnrichedConfigurationTest.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/test/java/org/apache/tamaya/functions/EnrichedConfigurationTest.java b/modules/functions/src/test/java/org/apache/tamaya/functions/EnrichedConfigurationTest.java
index 6bf97ac..6134144 100644
--- a/modules/functions/src/test/java/org/apache/tamaya/functions/EnrichedConfigurationTest.java
+++ b/modules/functions/src/test/java/org/apache/tamaya/functions/EnrichedConfigurationTest.java
@@ -25,13 +25,17 @@ import org.assertj.core.api.ThrowableAssert;
import org.junit.Ignore;
import org.junit.Test;
-import java.util.HashMap;
-import java.util.Map;
+import javax.config.Config;
+import java.lang.reflect.Type;
+import java.util.*;
import static java.util.Collections.EMPTY_MAP;
import static org.apache.tamaya.functions.MethodNotMockedAnswer.NOT_MOCKED_ANSWER;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
@@ -47,13 +51,13 @@ public class EnrichedConfigurationTest {
@Test
public void getKeyIsNull() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
final EnrichedConfiguration sut = new EnrichedConfiguration(base, EMPTY_MAP, true);
assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
@Override
public void call() throws Throwable {
- sut.get(null);
+ sut.getValue(null, String.class);
}
}).isInstanceOf(NullPointerException.class)
.hasMessage("Key must be given.");
@@ -61,9 +65,9 @@ public class EnrichedConfigurationTest {
@Test
public void getKeyIsNotKownAndHasNotAnOverriderWithOverridingOn() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn("9").when(base).get(eq("b"));
- doReturn(null).when(base).get(eq("y"));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(Optional.of("9")).when(base).getOptionalValue(eq("b"), any());
+ doReturn(Optional.empty()).when(base).getOptionalValue(eq("y"), any());
Map<String, Object> additions = new HashMap<>();
additions.put("z0", "0");
@@ -71,7 +75,7 @@ public class EnrichedConfigurationTest {
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, true);
- String result = sut.get("y");
+ String result = sut.getValue("y", String.class);
assertThat(result).isNull();
@@ -79,9 +83,9 @@ public class EnrichedConfigurationTest {
@Test
public void getKeyIsNotKownAndHasNotAnOverriderWithOverridingOff() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn("9").when(base).get(eq("b"));
- doReturn(null).when(base).get(eq("y"));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(Optional.of("9")).when(base).getOptionalValue(eq("b"), any());
+ doReturn(Optional.empty()).when(base).getOptionalValue(eq("y"), eq(String.class));
Map<String, Object> additions = new HashMap<>();
additions.put("z0", "0");
@@ -89,15 +93,15 @@ public class EnrichedConfigurationTest {
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, false);
- String result = sut.get("y");
+ String result = sut.getValue("y", String.class);
assertThat(result).isNull();
}
@Test
public void getKeyIsNotKownAndHasOverriderAndConfigurationIsOverridingIsOn() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn("9").when(base).get(eq("y"));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn("9").when(base).getValue(eq("y"),any() );
Map<String, Object> additions = new HashMap<>();
additions.put("z0", "0");
@@ -105,15 +109,16 @@ public class EnrichedConfigurationTest {
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, true);
- String result = sut.get("b");
+ String result = sut.getValue("b", String.class);
assertThat(result).isNotNull().isEqualTo("1");
}
@Test
public void getKeyIsNotKownAndHasOverriderAndConfigurationIsOverridingIsOff() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn(null).when(base).get(eq("b"));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(Optional.empty()).when(base).getOptionalValue(eq("y"),any() );
+ doReturn(Optional.empty()).when(base).getOptionalValue(eq("b"),any() );
Map<String, Object> additions = new HashMap<>();
additions.put("z0", "0");
@@ -121,15 +126,15 @@ public class EnrichedConfigurationTest {
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, false);
- String result = sut.get("b");
+ String result = sut.getValue("b", String.class);
assertThat(result).isNotNull().isEqualTo("1");
}
@Test
public void getKeyIsKownAndHasOverriderAndConfigurationIsNotOverriding() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn("9").when(base).get(eq("b"));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(Optional.of("9")).when(base).getOptionalValue(eq("b"),any() );
Map<String, Object> additions = new HashMap<>();
additions.put("z0", "0");
@@ -137,15 +142,15 @@ public class EnrichedConfigurationTest {
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, false);
- String result = sut.get("b");
+ String result = sut.getValue("b", String.class);
assertThat(result).isNotNull().isEqualTo("9");
}
@Test
public void getKeyIsKownAndHasOverriderAndConfigurationIsOverriding() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn("9").when(base).get(eq("b"));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn("9").when(base).getValue(eq("b"),any() );
Map<String, Object> additions = new HashMap<>();
additions.put("z0", "0");
@@ -153,22 +158,22 @@ public class EnrichedConfigurationTest {
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, true);
- String result = sut.get("b");
+ String result = sut.getValue("b", String.class);
assertThat(result).isNotNull().isEqualTo("1");
}
@Test
public void getKeyIsKnownAndHasNoOverrider() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn("9").when(base).get(eq("b"));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(Optional.of("9")).when(base).getOptionalValue(eq("b"),any() );
Map<String, Object> additions = new HashMap<>();
additions.put("z0", "0");
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, true);
- String result = sut.get("b");
+ String result = sut.getValue("b", String.class);
assertThat(result).isNotNull().isEqualTo("9");
}
@@ -178,194 +183,156 @@ public class EnrichedConfigurationTest {
*/
@Test
- public void getOrDefaultStringStringWithKeyIsNull() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
+ public void getOptionalValueStringWithKeyIsNull() throws Exception {
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
final EnrichedConfiguration sut = new EnrichedConfiguration(base, EMPTY_MAP, true);
assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
@Override
public void call() throws Throwable {
- sut.getOrDefault(null, "v");
+ sut.getOptionalValue(null, String.class);
}
}).isInstanceOf(NullPointerException.class)
.hasMessage("Key must be given.");
}
@Test
- public void getOrDefaultStringStringWithDefaultValueIsNull() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
-
- final EnrichedConfiguration sut = new EnrichedConfiguration(base, EMPTY_MAP, true);
-
- assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- @Override
- public void call() throws Throwable {
- sut.getOrDefault("v", null);
- }
- }).isInstanceOf(NullPointerException.class)
- .hasMessage("Default value must be given.");
- }
-
- @Test
- public void getOrDefaultStringStringWithKeyIsOverriddenAndOverridingOn() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn("9").when(base).get(eq("b"));
+ public void getOptionalValueStringWithKeyIsOverriddenAndOverridingOn() throws Exception {
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(Optional.of("9")).when(base).getOptionalValue(eq("b"), eq(String.class));
Map<String, Object> additions = new HashMap<>();
additions.put("b", "0");
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, true);
- String result = sut.getOrDefault("b", "100");
-
- assertThat(result).isNotNull().isEqualTo("0");
+ Optional<String> result = sut.getOptionalValue("b", String.class);
+ assertNotNull(result);
+ assertTrue(result.isPresent());
+ assertEquals("0", result.get());
}
@Test
- public void getOrDefaultStringStringWithKeyIsOverriddenAndOverridingOff() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn("9").when(base).get(eq("b"));
+ public void getOptionalValueStringWithKeyIsOverriddenAndOverridingOff() throws Exception {
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(Optional.of("9")).when(base).getOptionalValue(eq("b"), any());
+ doReturn(Optional.of("9")).when(base).getOptionalValue(eq("b"), any());
Map<String, Object> additions = new HashMap<>();
additions.put("b", "0");
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, false);
- String result = sut.get("b");
+ String result = sut.getValue("b", String.class);
assertThat(result).isNotNull().isEqualTo("9");
}
@Test
public void getOrDefaultStringStringWithKeyIsKnownAndIsNotOverridden() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn("9").when(base).get(eq("b"));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(Optional.of("9")).when(base).getOptionalValue(eq("b"), any());
Map<String, Object> additions = new HashMap<>();
additions.put("z0", "0");
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, true);
- String result = sut.getOrDefault("b", "100");
+ String result = sut.getOptionalValue("b", String.class).orElse("100");
assertThat(result).isNotNull().isEqualTo("9");
}
@Test
public void getOrDefaultStringStringWithKeyIsNotKnownButIsOverridden() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn(null).when(base).get(eq("b"));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn("9").when(base).getValue(eq("b"), any());
Map<String, Object> additions = new HashMap<>();
additions.put("b", "0");
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, true);
- String result = sut.get("b");
+ String result = sut.getValue("b", String.class);
assertThat(result).isNotNull().isEqualTo("0");
}
@Test
public void getOrDefaultStringStringWithKeyIsUnKnownAndIsNotOverridden() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn(null).when(base).get(eq("b"));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(Optional.of("9")).when(base).getOptionalValue("b", String.class);
+ doReturn(Optional.empty()).when(base).getOptionalValue("z", String.class);
EnrichedConfiguration sut = new EnrichedConfiguration(base, EMPTY_MAP, true);
- String result = sut.getOrDefault("b", "1000");
+ String result = sut.getOptionalValue("z", String.class).orElse("1000");
assertThat(result).isNotNull().isEqualTo("1000");
}
/*
- * Tests for getOrDefault(String, Class<T>, T)
+ * Tests for getOptionalValue(String, Class<T>)
*/
- @Test
- public void getOrDefaultStringClassTThrowsNPEIfKeyIsNull() throws Exception {
- final EnrichedConfiguration sut = mock(EnrichedConfiguration.class, NOT_MOCKED_ANSWER);
- doCallRealMethod().when(sut).getOrDefault(anyString(), any(Class.class), anyString());
-
- assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- @Override
- public void call() throws Throwable {
- sut.getOrDefault("b", String.class, null);
- }
- }).isInstanceOf(NullPointerException.class)
- .hasMessage("Default value not given.");
- }
@Test
- public void getOrDefaultStringClassTThrowsNPEIfClassIsNull() throws Exception {
+ public void getOptionalValueStringClassTThrowsNPEIfClassIsNull() throws Exception {
final EnrichedConfiguration sut = mock(EnrichedConfiguration.class, NOT_MOCKED_ANSWER);
- doCallRealMethod().when(sut).getOrDefault(anyString(), any(Class.class), anyString());
+ doCallRealMethod().when(sut).getOptionalValue(anyString(), any(Class.class));
assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
@Override
public void call() throws Throwable {
- sut.getOrDefault("b", (Class<String>)null, "20");
+ sut.getOptionalValue("b", (Class<String>)null);
}
}).isInstanceOf(NullPointerException.class)
- .hasMessage("Class not given.");
+ .hasMessage("Type must be given.");
}
@Test
- public void getOrDefaultStringClassTThrowsNPEIfDefaultValueIsNull() throws Exception {
- final EnrichedConfiguration sut = mock(EnrichedConfiguration.class, NOT_MOCKED_ANSWER);
- doCallRealMethod().when(sut).getOrDefault(anyString(), any(Class.class), anyString());
-
- assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- @Override
- public void call() throws Throwable {
- sut.getOrDefault("b", String.class, null);
- }
- }).isInstanceOf(NullPointerException.class)
- .hasMessage("Default value not given.");
- }
-
- @Test
- public void getOrDefaultStringClassTKeyInBaseAndInAdditionsNotOverriding() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn("1").when(base).get(eq("b"), any(TypeLiteral.class));
+ public void getOptionalValueStringClassTKeyInBaseAndInAdditionsNotOverriding() throws Exception {
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(Optional.of("1")).when(base).getOptionalValue(eq("b"), any());
Map<String, Object> additions = new HashMap<>();
additions.put("b", "2");
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, false);
- String result = sut.getOrDefault("b", String.class, "3");
-
- assertThat(result).isEqualTo("1");
+ Optional<String> result = sut.getOptionalValue("b", String.class);
+ assertNotNull(result);
+ assertTrue(result.isPresent());
+ assertEquals("1", result.get());
}
@Test
public void getOrDefaultStringClassTKeyInBaseAndInAddtionsOverriding() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn("1").when(base).get(eq("b"), any(TypeLiteral.class));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn("1").when(base).getValue(eq("b"), any());
Map<String, Object> additions = new HashMap<>();
additions.put("b", "2");
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, true);
- String result = sut.getOrDefault("b", String.class, "3");
+ String result = sut.getOptionalValue("b", String.class).orElse("3");
assertThat(result).isEqualTo("2");
}
@Test
public void getOrDefaultStringClassTKeyNotInBaseInAdditionsNotOverriding() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn(null).when(base).get(eq("b"), any(TypeLiteral.class));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(Optional.empty()).when(base).getOptionalValue(eq("b"), any());
Map<String, Object> additions = new HashMap<>();
additions.put("b", "20");
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, false);
- String result = sut.getOrDefault("b", String.class, "B");
+ String result = sut.getOptionalValue("b", String.class).orElse("B");
assertThat(result).isEqualTo("20");
}
@@ -374,15 +341,15 @@ public class EnrichedConfigurationTest {
@Test
public void getOrDefaultStringClassTKeyNotInBaseInAddtionsOverriding() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn(null).when(base).get(eq("b"), any(TypeLiteral.class));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(null).when(base).getValue(eq("b"), any());
Map<String, Object> additions = new HashMap<>();
additions.put("b", "20");
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, true);
- String result = sut.getOrDefault("b", String.class, "B");
+ String result = sut.getOptionalValue("b", String.class).orElse("B");
assertThat(result).isEqualTo("20");
}
@@ -390,28 +357,28 @@ public class EnrichedConfigurationTest {
@Test
public void getOrDefaultStringClassTKeyNotInBaseNotInAdditionsAndNotOverrding() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn(null).when(base).get(eq("b"), any(TypeLiteral.class));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(Optional.empty()).when(base).getOptionalValue(eq("b"), any());
Map<String, Object> additions = new HashMap<>();
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, false);
- String result = sut.getOrDefault("b", String.class, "B");
+ String result = sut.getOptionalValue("b", String.class).orElse("B");
assertThat(result).isEqualTo("B");
}
@Test
public void getOrDefaultStringClassTKeyNotInBaseNotInAdditionsAndOverriding() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn(null).when(base).get(eq("b"), any(TypeLiteral.class));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(null).when(base).getOptionalValue(eq("b"), any());
Map<String, Object> additions = new HashMap<>();
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, true);
- String result = sut.getOrDefault("b", String.class, "3");
+ String result = sut.getOptionalValue("b", String.class).orElse("3");
assertThat(result).isEqualTo("3");
}
@@ -434,58 +401,43 @@ public class EnrichedConfigurationTest {
@Test
public void getOrDefaultStringTypeLiteralTThrowsNPEIfKeyIsNull() throws Exception {
final EnrichedConfiguration sut = mock(EnrichedConfiguration.class, NOT_MOCKED_ANSWER);
- doCallRealMethod().when(sut).getOrDefault(anyString(), any(TypeLiteral.class), anyString());
+ doCallRealMethod().when(sut).getOptionalValue(anyString(), any(Class.class));
assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
@Override
public void call() throws Throwable {
- sut.getOrDefault("b", TypeLiteral.<String>of(String.class), null);
+ sut.getOptionalValue(null,String.class);
}
- }).isInstanceOf(NullPointerException.class)
- .hasMessage("Default value not given.");
+ }).isInstanceOf(NullPointerException.class);
}
@Test
public void getOrDefaultStringLiteralTThrowsNPEIfClassIsNull() throws Exception {
final EnrichedConfiguration sut = mock(EnrichedConfiguration.class, NOT_MOCKED_ANSWER);
- doCallRealMethod().when(sut).getOrDefault(anyString(), any(TypeLiteral.class), anyString());
+ doCallRealMethod().when(sut).getOptionalValue(anyString(), any(Class.class));
assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
@Override
public void call() throws Throwable {
- sut.getOrDefault("b", (TypeLiteral<String>)null, "20");
+ sut.getOptionalValue("b", (Class)null).orElse("20");
}
}).isInstanceOf(NullPointerException.class)
- .hasMessage("Type not given.");
+ .hasMessage("Type must be given.");
}
@Test
- public void getOrDefaultStringTypeLiteralThrowsNPEIfDefaultValueIsNull() throws Exception {
- final EnrichedConfiguration sut = mock(EnrichedConfiguration.class, NOT_MOCKED_ANSWER);
- doCallRealMethod().when(sut).getOrDefault(anyString(), any(TypeLiteral.class), anyString());
-
- assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- @Override
- public void call() throws Throwable {
- sut.getOrDefault("b", TypeLiteral.<String>of(String.class), null);
- }
- }).isInstanceOf(NullPointerException.class)
- .hasMessage("Default value not given.");
- }
-
- @Test
public void getOrDefaultStringTypeLiteralTKeyInBaseAndInAdditionsNotOverriding() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn("1").when(base).get(eq("b"), any(TypeLiteral.class));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(Optional.of("1")).when(base).getOptionalValue(eq("b"), any(Class.class));
Map<String, Object> additions = new HashMap<>();
additions.put("b", "2");
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, false);
- String result = sut.getOrDefault("b", TypeLiteral.<String>of(String.class), "3");
+ String result = sut.getOptionalValue("b", String.class).orElse("3");
assertThat(result).isEqualTo("1");
}
@@ -493,47 +445,48 @@ public class EnrichedConfigurationTest {
@Test
public void getOrDefaultStringTypeLiteralTKeyInBaseAndInAddtionsOverriding() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn("1").when(base).get(eq("b"), any(TypeLiteral.class));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn("1").when(base).getValue(eq("b"), any(Class.class));
Map<String, Object> additions = new HashMap<>();
additions.put("b", "2");
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, true);
- String result = sut.getOrDefault("b", TypeLiteral.<String>of(String.class), "3");
+ String result = sut.getOptionalValue("b", String.class).orElse("3");
assertThat(result).isEqualTo("2");
}
@Test
public void getOrDefaultStringTypeLiteralTKeyNotInBaseInAdditionsNotOverriding() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn(null).when(base).get(eq("b"), any(TypeLiteral.class));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(Optional.empty()).when(base).getOptionalValue(eq("b"), any());
Map<String, Object> additions = new HashMap<>();
additions.put("b", "20");
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, false);
- String result = sut.getOrDefault("b", TypeLiteral.<String>of(String.class), "B");
-
- assertThat(result).isEqualTo("20");
+ Optional<String> result = sut.getOptionalValue("b", String.class);
+ assertNotNull(result);
+ assertTrue(result.isPresent());
+ assertEquals("20", result.get());
}
@Test
public void getOrDefaultStringTypeLiteralTKeyNotInBaseInAddtionsOverriding() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn(null).when(base).get(eq("b"), any(TypeLiteral.class));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(null).when(base).getValue(eq("b"), any(Class.class));
Map<String, Object> additions = new HashMap<>();
additions.put("b", "20");
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, true);
- String result = sut.getOrDefault("b", TypeLiteral.<String>of(String.class), "B");
+ String result = sut.getOptionalValue("b", String.class).orElse("B");
assertThat(result).isEqualTo("20");
}
@@ -541,28 +494,28 @@ public class EnrichedConfigurationTest {
@Test
public void getOrDefaultStringTypeLiteralTKeyNotInBaseNotInAdditionsAndNotOverrding() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn(null).when(base).get(eq("b"), any(TypeLiteral.class));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(Optional.empty()).when(base).getOptionalValue(eq("b"), any(Class.class));
Map<String, Object> additions = new HashMap<>();
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, false);
- String result = sut.getOrDefault("b", TypeLiteral.<String>of(String.class), "B");
+ String result = sut.getOptionalValue("b", String.class).orElse("B");
assertThat(result).isEqualTo("B");
}
@Test
public void getOrDefaultStringTypeLiteralTKeyNotInBaseNotInAdditionsAndOverriding() throws Exception {
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn(null).when(base).get(eq("b"), any(TypeLiteral.class));
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(null).when(base).getOptionalValue("b", String.class);
Map<String, Object> additions = new HashMap<>();
EnrichedConfiguration sut = new EnrichedConfiguration(base, additions, true);
- String result = sut.getOrDefault("b", TypeLiteral.<String>of(String.class), "3");
+ String result = sut.getOptionalValue("b", String.class).orElse("3");
assertThat(result).isEqualTo("3");
}
@@ -579,18 +532,21 @@ public class EnrichedConfigurationTest {
baseProps.put("b", "B");
baseProps.put("c", "C");
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn(baseProps).when(base).getProperties();
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(baseProps.keySet()).when(base).getPropertyNames();
+ doReturn(Optional.of("A")).when(base).getOptionalValue("a", String.class);
+ doReturn(Optional.of("B")).when(base).getOptionalValue("b", String.class);
+ doReturn(Optional.of("C")).when(base).getOptionalValue("c", String.class);
EnrichedConfiguration enrichedConfiguration = new EnrichedConfiguration(base, EMPTY_MAP, true);
- Map<String, String> result = enrichedConfiguration.getProperties();
+ Iterable<String> result = enrichedConfiguration.getPropertyNames();
assertThat(result).isNotEmpty()
- .hasSize(3)
- .containsEntry("a", "A")
- .containsEntry("b", "B")
- .containsEntry("c", "C");
+ .hasSize(3);
+ assertEquals("A", enrichedConfiguration.getValue("a", String.class));
+ assertEquals("B", enrichedConfiguration.getValue("b", String.class));
+ assertEquals("C", enrichedConfiguration.getValue("c", String.class));
}
@@ -601,21 +557,22 @@ public class EnrichedConfigurationTest {
baseProps.put("b", "B");
baseProps.put("c", "C");
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn(baseProps).when(base).getProperties();
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(baseProps.keySet()).when(base).getPropertyNames();
+ doReturn(Optional.empty()).when(base).getOptionalValue(any(), any());
Map<String, Object> additionalProps = new HashMap<>();
- additionalProps.put("b", "b");
+ additionalProps.put("b", "B");
EnrichedConfiguration enrichedConfiguration = new EnrichedConfiguration(base, additionalProps, true);
- Map<String, String> result = enrichedConfiguration.getProperties();
+ Iterable<String> result = enrichedConfiguration.getPropertyNames();
assertThat(result).isNotEmpty()
.hasSize(3)
- .containsEntry("a", "A")
- .containsEntry("b", "b")
- .containsEntry("c", "C");
+ .contains("a").contains("b").contains("c");
+ assertEquals(null, enrichedConfiguration.getValue("a", String.class));
+ assertEquals("B", enrichedConfiguration.getValue("b", String.class));
}
@Test
@@ -625,23 +582,24 @@ public class EnrichedConfigurationTest {
baseProps.put("b", "B");
baseProps.put("c", "C");
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn(baseProps).when(base).getProperties();
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(baseProps.keySet()).when(base).getPropertyNames();
+ doReturn(Optional.empty()).when(base).getOptionalValue(any(), any());
Map<String, Object> additionalProps = new HashMap<>();
additionalProps.put("e", "E");
EnrichedConfiguration enrichedConfiguration = new EnrichedConfiguration(base, additionalProps, true);
- Map<String, String> result = enrichedConfiguration.getProperties();
-
- assertThat(result).isNotEmpty()
- .hasSize(4)
- .containsEntry("a", "A")
- .containsEntry("b", "B")
- .containsEntry("c", "C")
- .containsEntry("e", "E");
+ Iterable<String> result = enrichedConfiguration.getPropertyNames();
+ assertThat(result)
+ .isNotEmpty()
+ .hasSize(4)
+ .contains("a")
+ .contains("b")
+ .contains("c")
+ .contains("e");
}
@Test
@@ -651,22 +609,26 @@ public class EnrichedConfigurationTest {
baseProps.put("b", "B");
baseProps.put("c", "C");
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn(baseProps).when(base).getProperties();
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(baseProps.keySet()).when(base).getPropertyNames();
+ doReturn(Optional.of("A")).when(base).getOptionalValue(eq("a"), any());
+ doReturn(Optional.of("B")).when(base).getOptionalValue(eq("b"), any());
+ doReturn(Optional.of("C")).when(base).getOptionalValue(eq("c"), any());
+ doReturn(Optional.empty()).when(base).getOptionalValue(eq("e"), any());
Map<String, Object> additionalProps = new HashMap<>();
additionalProps.put("e", "E");
EnrichedConfiguration enrichedConfiguration = new EnrichedConfiguration(base, additionalProps, false);
- Map<String, String> result = enrichedConfiguration.getProperties();
+ Iterable<String> result = enrichedConfiguration.getPropertyNames();
assertThat(result).isNotEmpty()
- .hasSize(4)
- .containsEntry("a", "A")
- .containsEntry("b", "B")
- .containsEntry("c", "C")
- .containsEntry("e", "E");
+ .hasSize(4);
+ assertEquals("A", enrichedConfiguration.getValue("a", String.class));
+ assertEquals("B", enrichedConfiguration.getValue("b", String.class));
+ assertEquals("C", enrichedConfiguration.getValue("c", String.class));
+ assertEquals("E", enrichedConfiguration.getValue("e", String.class));
}
@@ -677,21 +639,22 @@ public class EnrichedConfigurationTest {
baseProps.put("b", "B");
baseProps.put("c", "C");
- Configuration base = mock(Configuration.class, NOT_MOCKED_ANSWER);
- doReturn(baseProps).when(base).getProperties();
+ Config base = mock(Config.class, NOT_MOCKED_ANSWER);
+ doReturn(baseProps.keySet()).when(base).getPropertyNames();
+ doReturn(Optional.empty()).when(base).getOptionalValue(any(), any());
Map<String, Object> additionalProps = new HashMap<>();
additionalProps.put("b", "b");
EnrichedConfiguration enrichedConfiguration = new EnrichedConfiguration(base, additionalProps, false);
- Map<String, String> result = enrichedConfiguration.getProperties();
+ Iterable<String> result = enrichedConfiguration.getPropertyNames();
assertThat(result).isNotEmpty()
.hasSize(3)
- .containsEntry("a", "A")
- .containsEntry("b", "B")
- .containsEntry("c", "C");
+ .contains("a")
+ .contains("b")
+ .contains("c");
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/581c92e7/modules/functions/src/test/java/org/apache/tamaya/functions/MappedConfigurationTest.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/test/java/org/apache/tamaya/functions/MappedConfigurationTest.java b/modules/functions/src/test/java/org/apache/tamaya/functions/MappedConfigurationTest.java
index 2a470a2..2b79250 100644
--- a/modules/functions/src/test/java/org/apache/tamaya/functions/MappedConfigurationTest.java
+++ b/modules/functions/src/test/java/org/apache/tamaya/functions/MappedConfigurationTest.java
@@ -20,6 +20,7 @@ package org.apache.tamaya.functions;
import org.junit.Test;
+import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doCallRealMethod;
@@ -34,18 +35,18 @@ public class MappedConfigurationTest {
@Test(expected = NullPointerException.class)
public void getOrDefaultWithTwoStringParametersThrowsNPEIfValueIsNull() throws Exception {
MappedConfiguration mc = mock(MappedConfiguration.class);
- doReturn("z").when(mc).get(eq("a)"));
- doCallRealMethod().when(mc).getOrDefault(anyString(), anyString());
+ doReturn("z").when(mc).getValue(eq("a)"), any());
+ doCallRealMethod().when(mc).getOptionalValue(anyString(), any());
- mc.getOrDefault("a", (String)null);
+ mc.getOptionalValue("a", String.class);
}
@Test(expected = NullPointerException.class)
public void getOrDefaultWithTwoStringParametersThrowsNPEIfKeyIsNull() throws Exception {
MappedConfiguration mc = mock(MappedConfiguration.class);
- doCallRealMethod().when(mc).getOrDefault(anyString(), anyString());
+ doCallRealMethod().when(mc).getOptionalValue(anyString(), any());
- mc.getOrDefault(null, "z");
+ mc.getOptionalValue(null, String.class);
}
}
\ No newline at end of file
[07/18] incubator-tamaya-extensions git commit: Adapted to comply
with JSR API.
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/java/org/apache/tamaya/events/TestConfigView.java
----------------------------------------------------------------------
diff --git a/modules/events/src/test/java/org/apache/tamaya/events/TestConfigView.java b/modules/events/src/test/java/org/apache/tamaya/events/TestConfigView.java
index b15d966..03ce7ea 100644
--- a/modules/events/src/test/java/org/apache/tamaya/events/TestConfigView.java
+++ b/modules/events/src/test/java/org/apache/tamaya/events/TestConfigView.java
@@ -18,139 +18,61 @@
*/
package org.apache.tamaya.events;
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.ConfigOperator;
-import org.apache.tamaya.ConfigQuery;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.TypeLiteral;
-import org.apache.tamaya.spi.ConfigurationContext;
-import org.apache.tamaya.spi.ConversionContext;
-import org.apache.tamaya.spi.PropertyConverter;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.logging.Level;
-import java.util.logging.Logger;
+import javax.config.Config;
+import javax.config.spi.ConfigSource;
+import java.util.*;
+import java.util.function.UnaryOperator;
+
/**
* Created by Anatole on 24.03.2015.
*/
-public class TestConfigView implements ConfigOperator{
+public class TestConfigView implements UnaryOperator<Config>{
private static final TestConfigView INSTANCE = new TestConfigView();
private TestConfigView(){}
- public static ConfigOperator of(){
+ public static TestConfigView of(){
return INSTANCE;
}
@Override
- public Configuration operate(final Configuration config) {
- return new Configuration() {
+ public Config apply(final Config config) {
+ return new Config() {
@Override
- public Map<String, String> getProperties() {
- Map<String, String> result = new HashMap<>();
- for (Map.Entry<String, String> en : config.getProperties().entrySet()) {
- if (en.getKey().startsWith("test")) {
- result.put(en.getKey(), en.getValue());
+ public Iterable<String> getPropertyNames() {
+ Set<String> result = new HashSet<>();
+ for (String key: config.getPropertyNames()) {
+ if (key.startsWith("test")) {
+ result.add(key);
}
}
return result;
-// return config.getProperties().entrySet().stream().filter(e -> e.getKey().startsWith("test")).collect(
-// Collectors.toMap(en -> en.getKey(), en -> en.getProperty()));
- }
-
- @Override
- public Configuration with(ConfigOperator operator) {
- return null;
- }
-
- @Override
- public <T> T query(ConfigQuery<T> query) {
- return null;
- }
-
- @Override
- public ConfigurationContext getContext() {
- return config.getContext();
}
@Override
- public String get(String key) {
- return getProperties().get(key);
+ public Iterable<ConfigSource> getConfigSources() {
+ return config.getConfigSources();
}
@Override
- public String getOrDefault(String key, String defaultValue) {
- String val = get(key);
- if(val==null){
- return defaultValue;
+ public <T> T getValue(String key, Class<T> type) {
+ if (key.startsWith("test")) {
+ return config.getValue(key, type);
}
- return val;
+ throw new NoSuchElementException(key);
}
@Override
- public <T> T getOrDefault(String key, Class<T> type, T defaultValue) {
- T val = get(key, type);
- if(val==null){
- return defaultValue;
+ public <T> Optional<T> getOptionalValue(String key, Class<T> type) {
+ if (key.startsWith("test")) {
+ return config.getOptionalValue(key, type);
}
- return val;
+ return Optional.empty();
}
- @SuppressWarnings("unchecked")
- @Override
- public <T> T get(String key, Class<T> type) {
- return (T) get(key, TypeLiteral.of(type));
- }
-
- /**
- * Accesses the current String value for the given key and tries to convert it
- * using the {@link org.apache.tamaya.spi.PropertyConverter} instances provided by the current
- * {@link org.apache.tamaya.spi.ConfigurationContext}.
- *
- * @param key the property's absolute, or relative path, e.g. @code
- * a/b/c/d.myProperty}.
- * @param type The target type required, not null.
- * @param <T> the value type
- * @return the converted value, never null.
- */
- @Override
- public <T> T get(String key, TypeLiteral<T> type) {
- String value = get(key);
- if (value != null) {
- List<PropertyConverter<T>> converters = getContext()
- .getPropertyConverters(type);
- ConversionContext context = new ConversionContext.Builder(
- key,type).build();
- for (PropertyConverter<T> converter : converters) {
- try {
- T t = converter.convert(value, context);
- if (t != null) {
- return t;
- }
- } catch (Exception e) {
- Logger.getLogger(getClass().getName())
- .log(Level.FINEST, "PropertyConverter: " + converter + " failed to convert value: "
- + value, e);
- }
- }
- throw new ConfigException("Unparseable config value for type: " + type.getRawType().getName() + ": "
- + key + ", supportedFormats: " + context.getSupportedFormats());
- }
- return null;
- }
-
- @Override
- public <T> T getOrDefault(String key, TypeLiteral<T> type, T defaultValue) {
- T val = get(key, type);
- if(val==null){
- return defaultValue;
- }
- return val;
- }
};
}
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/java/org/apache/tamaya/events/folderobserver/FileChangeListener.java
----------------------------------------------------------------------
diff --git a/modules/events/src/test/java/org/apache/tamaya/events/folderobserver/FileChangeListener.java b/modules/events/src/test/java/org/apache/tamaya/events/folderobserver/FileChangeListener.java
index 9b6b93a..e0d67f5 100644
--- a/modules/events/src/test/java/org/apache/tamaya/events/folderobserver/FileChangeListener.java
+++ b/modules/events/src/test/java/org/apache/tamaya/events/folderobserver/FileChangeListener.java
@@ -18,7 +18,7 @@
*/
package org.apache.tamaya.events.folderobserver;
-import org.apache.tamaya.ConfigException;
+import org.apache.tamaya.events.ConfigSourceChange;
import java.io.IOException;
import java.nio.file.FileSystem;
@@ -35,7 +35,7 @@ import java.util.logging.Logger;
/**
* Class that has the responsibility to watch the folder and then publish the changes to a
- * {@link org.apache.tamaya.events.PropertySourceChange}.
+ * {@link ConfigSourceChange}.
* @see ObservingPropertySourceProvider
* This listener will wait to events and wait to one second to watch again.
* <p>If new file was created or modified will commit from this file.</p>
@@ -128,7 +128,7 @@ class FileChangeListener implements Runnable {
/**
* Exception if file listening fails.
*/
- static class FileChangeListenerException extends ConfigException {
+ static class FileChangeListenerException extends IllegalStateException {
/** Serialversion UID. */
private static final long serialVersionUID = -8965486770881001513L;
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/java/org/apache/tamaya/events/folderobserver/ObservingPropertySourceProvider.java
----------------------------------------------------------------------
diff --git a/modules/events/src/test/java/org/apache/tamaya/events/folderobserver/ObservingPropertySourceProvider.java b/modules/events/src/test/java/org/apache/tamaya/events/folderobserver/ObservingPropertySourceProvider.java
index c821d43..30ff4b8 100644
--- a/modules/events/src/test/java/org/apache/tamaya/events/folderobserver/ObservingPropertySourceProvider.java
+++ b/modules/events/src/test/java/org/apache/tamaya/events/folderobserver/ObservingPropertySourceProvider.java
@@ -39,21 +39,21 @@ import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertySourceProvider;
-import org.apache.tamaya.spi.PropertyValue;
-import org.apache.tamaya.spisupport.propertysource.BasePropertySource;
+import org.apache.tamaya.base.configsource.BaseConfigSource;
+import org.apache.tamaya.events.ConfigSourceChange;
+
+import javax.config.spi.ConfigSource;
+import javax.config.spi.ConfigSourceProvider;
/**
* This implementation runs in a folder taking up all files compatible with the given
* ConfigurationFormats. When a file is added, deleted or modified the PropertySourceProvider
* will adapt the changes automatically and trigger according
- * {@link org.apache.tamaya.events.PropertySourceChange} events.
+ * {@link ConfigSourceChange} events.
* The default folder is META-INF/config, but you can change it via an absolute path in the
* "-Dtamaya.configdir" parameter.
*/
-public class ObservingPropertySourceProvider implements PropertySourceProvider, FileChangeObserver {
+public class ObservingPropertySourceProvider implements ConfigSourceProvider, FileChangeObserver {
/**
* The logger.
*/
@@ -61,7 +61,7 @@ public class ObservingPropertySourceProvider implements PropertySourceProvider,
/**
* The current active property sources of this provider.
*/
- private final List<PropertySource> propertySources = Collections.synchronizedList(new LinkedList<PropertySource>());
+ private final List<ConfigSource> configSources = Collections.synchronizedList(new LinkedList<ConfigSource>());
/**
* The thread pool used.
*/
@@ -77,8 +77,8 @@ public class ObservingPropertySourceProvider implements PropertySourceProvider,
directory = getDirectory();
}
if (directory!=null){
- synchronized (this.propertySources) {
- this.propertySources.addAll(readConfiguration(directory));
+ synchronized (this.configSources) {
+ this.configSources.addAll(readConfiguration(directory));
}
final Runnable runnable = new FileChangeListener(directory, this);
executor.execute(runnable);
@@ -92,12 +92,12 @@ public class ObservingPropertySourceProvider implements PropertySourceProvider,
*
* @param directory the target directory, not null.
*/
- private List<PropertySource> readConfiguration(Path directory) {
- final List<PropertySource> result = new ArrayList<>();
+ private List<ConfigSource> readConfiguration(Path directory) {
+ final List<ConfigSource> result = new ArrayList<>();
try {
- synchronized (propertySources) {
+ synchronized (configSources) {
for (final Path path : Files.newDirectoryStream(directory, "*")) {
- result.addAll(getPropertySources(path));
+ result.addAll(getConfigSources(path));
}
return result;
}
@@ -113,12 +113,12 @@ public class ObservingPropertySourceProvider implements PropertySourceProvider,
* @param file source of the property sources.
* @return property sources from the given file.
*/
- protected Collection<PropertySource> getPropertySources(final Path file) {
- return Arrays.asList(new PropertySource[]{new BasePropertySource(file.toString()) {
- private final Map<String,PropertyValue> props = readProperties(file);
+ protected Collection<ConfigSource> getConfigSources(final Path file) {
+ return Arrays.asList(new ConfigSource[]{new BaseConfigSource(file.toString()) {
+ private final Map<String,String> props = readProperties(file);
@Override
- public Map<String, PropertyValue> getProperties() {
+ public Map<String, String> getProperties() {
return props;
}
}});
@@ -130,14 +130,14 @@ public class ObservingPropertySourceProvider implements PropertySourceProvider,
* @param file the file, not null.
* @return properties as read from the given file.
*/
- protected static Map<String,PropertyValue> readProperties(Path file) {
+ protected static Map<String,String> readProperties(Path file) {
try (InputStream is = file.toUri().toURL().openStream()){
final Properties props = new Properties();
props.load(is);
- final Map<String,PropertyValue> result = new HashMap<>();
+ final Map<String,String> result = new HashMap<>();
for(final Map.Entry<Object,Object> en:props.entrySet()){
String key = String.valueOf(en.getKey());
- result.put(key, PropertyValue.of(key, String.valueOf(en.getValue()), file.toString()));
+ result.put(key, en.getValue().toString());
}
return result;
} catch (final Exception e) {
@@ -166,7 +166,7 @@ public class ObservingPropertySourceProvider implements PropertySourceProvider,
try {
return Paths.get(resource.toURI());
} catch (final URISyntaxException e) {
- throw new ConfigException("An error to find the directory to watch", e);
+ throw new IllegalArgumentException("An error to find the directory to watch", e);
}
}
return null;
@@ -175,17 +175,17 @@ public class ObservingPropertySourceProvider implements PropertySourceProvider,
@Override
public void directoryChanged(Path directory) {
- synchronized (this.propertySources) {
- propertySources.clear();
- final Collection<PropertySource> sourcesRead = readConfiguration(directory);
- this.propertySources.addAll(sourcesRead);
+ synchronized (this.configSources) {
+ configSources.clear();
+ final Collection<ConfigSource> sourcesRead = readConfiguration(directory);
+ this.configSources.addAll(sourcesRead);
}
}
@Override
- public Collection<PropertySource> getPropertySources() {
- synchronized (propertySources) {
- return new ArrayList<>(this.propertySources);
+ public Collection<ConfigSource> getConfigSources(ClassLoader classLoader) {
+ synchronized (configSources) {
+ return new ArrayList<>(this.configSources);
}
}
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/java/org/apache/tamaya/events/internal/DefaultConfigChangeObserverTest.java
----------------------------------------------------------------------
diff --git a/modules/events/src/test/java/org/apache/tamaya/events/internal/DefaultConfigChangeObserverTest.java b/modules/events/src/test/java/org/apache/tamaya/events/internal/DefaultConfigChangeObserverTest.java
index e0fa52b..31ff765 100644
--- a/modules/events/src/test/java/org/apache/tamaya/events/internal/DefaultConfigChangeObserverTest.java
+++ b/modules/events/src/test/java/org/apache/tamaya/events/internal/DefaultConfigChangeObserverTest.java
@@ -18,7 +18,7 @@
*/
package org.apache.tamaya.events.internal;
-import org.apache.tamaya.events.FrozenConfiguration;
+import org.apache.tamaya.events.FrozenConfig;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -67,9 +67,9 @@ public class DefaultConfigChangeObserverTest {
observer.checkConfigurationUpdate();
- FrozenConfiguration config1 = observer.getLastConfig();
+ FrozenConfig config1 = observer.getLastConfig();
observer.checkConfigurationUpdate();
- FrozenConfiguration config2 = observer.getLastConfig();
+ FrozenConfig config2 = observer.getLastConfig();
assertThat(config1).describedAs("After the firt check last configuration must be set.")
.isNotEqualTo(config2);
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
----------------------------------------------------------------------
diff --git a/modules/events/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource b/modules/events/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
index 9c2b9f6..b0d532a 100644
--- a/modules/events/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
+++ b/modules/events/src/test/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
@@ -16,4 +16,4 @@
# specific language governing permissions and limitations
# under the License.
#
-org.apache.tamaya.events.RandomPropertySource
+org.apache.tamaya.events.RandomConfigSource
[17/18] incubator-tamaya-extensions git commit: Rewrite/adaptation
based on JSR API.
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/filter/src/test/java/org/apache/tamaya/filter/ProgrammableFilterTest.java
----------------------------------------------------------------------
diff --git a/modules/filter/src/test/java/org/apache/tamaya/filter/ProgrammableFilterTest.java b/modules/filter/src/test/java/org/apache/tamaya/filter/ProgrammableFilterTest.java
deleted file mode 100644
index b6e7bb7..0000000
--- a/modules/filter/src/test/java/org/apache/tamaya/filter/ProgrammableFilterTest.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.filter;
-
-import org.apache.tamaya.spi.ConfigurationContext;
-import org.apache.tamaya.spi.PropertyFilter;
-import org.apache.tamaya.spi.PropertyValue;
-import org.apache.tamaya.spisupport.DefaultConfigurationContextBuilder;
-import org.apache.tamaya.spisupport.RegexPropertyFilter;
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.junit.Assert.*;
-
-/**
- * Tests for {@link FilterContext}. Created by atsticks on 11.02.16.
- */
-public class ProgrammableFilterTest {
-
- private static ConfigurationContext context = new DefaultConfigurationContextBuilder().build();
- private static PropertyValue test1Property = PropertyValue.of("test1","test1","test");
- private static PropertyValue test2Property = PropertyValue.of("test2","test2","test");
- private static PropertyValue test3Property = PropertyValue.of("test.test3","test.test3","test");
-
- @Test
- public void testAddRemoveFilter() throws Exception {
- FilterContext filter = new FilterContext();
- Map<String,PropertyValue> map = new HashMap<>();
- assertEquals(filter.filterProperty(test1Property, new org.apache.tamaya.spi.FilterContext(test1Property, map, context)), test1Property);
- assertEquals(filter.filterProperty(test2Property, new org.apache.tamaya.spi.FilterContext(test2Property, map, context)), test2Property);
- assertEquals(filter.filterProperty(test3Property, new org.apache.tamaya.spi.FilterContext(test3Property, map, context)), test3Property);
- RegexPropertyFilter regexFilter = new RegexPropertyFilter();
- regexFilter.setIncludes("test\\..*");
- filter.addFilter(regexFilter);
- assertNull(filter.filterProperty(test1Property, new org.apache.tamaya.spi.FilterContext(test1Property, map, context)));
- assertNull(filter.filterProperty(test2Property, new org.apache.tamaya.spi.FilterContext(test2Property, map, context)));
- assertEquals(filter.filterProperty(test3Property, new org.apache.tamaya.spi.FilterContext(test3Property, map, context)), test3Property);
- filter.removeFilter(0);
- assertEquals(filter.filterProperty(test1Property, new org.apache.tamaya.spi.FilterContext(test1Property, map, context)), test1Property);
- assertEquals(filter.filterProperty(test2Property, new org.apache.tamaya.spi.FilterContext(test2Property, map, context)), test2Property);
- assertEquals(filter.filterProperty(test3Property, new org.apache.tamaya.spi.FilterContext(test3Property, map, context)), test3Property);
- filter.addFilter(0, regexFilter);
- assertNull(filter.filterProperty(test1Property, new org.apache.tamaya.spi.FilterContext(test1Property, map, context)));
- assertNull(filter.filterProperty(test2Property, new org.apache.tamaya.spi.FilterContext(test2Property, map, context)));
- assertEquals(filter.filterProperty(test3Property, new org.apache.tamaya.spi.FilterContext(test3Property, map, context)), test3Property);
- }
-
- @Test
- public void testClearFilters() throws Exception {
- FilterContext filter = new FilterContext();
- RegexPropertyFilter regexFilter = new RegexPropertyFilter();
- regexFilter.setIncludes("test1.*");
- Map<String,String> map = new HashMap<>();
- map.put("test1", "test1");
- map.put("test2", "test2");
- map.put("test.test3", "test.test3");
- assertEquals(filter.filterProperty(test1Property, new org.apache.tamaya.spi.FilterContext(test1Property, context)), test1Property);
- assertEquals(filter.filterProperty(test2Property, new org.apache.tamaya.spi.FilterContext(test2Property, context)), test2Property);
- assertEquals(filter.filterProperty(test3Property, new org.apache.tamaya.spi.FilterContext(test3Property, context)), test3Property);
- filter.addFilter(regexFilter);
- assertEquals(filter.filterProperty(test1Property, new org.apache.tamaya.spi.FilterContext(test1Property, context)), test1Property);
- assertNull(filter.filterProperty(test2Property, new org.apache.tamaya.spi.FilterContext(test2Property, context)));
- assertNull(filter.filterProperty(test3Property, new org.apache.tamaya.spi.FilterContext(test3Property, context)));
- filter.clearFilters();
- assertEquals(filter.filterProperty(test1Property, new org.apache.tamaya.spi.FilterContext(test1Property, context)), test1Property);
- assertEquals(filter.filterProperty(test2Property, new org.apache.tamaya.spi.FilterContext(test2Property, context)), test2Property);
- assertEquals(filter.filterProperty(test3Property, new org.apache.tamaya.spi.FilterContext(test3Property, context)), test3Property);
- }
-
- @Test
- public void testSetFilters() throws Exception {
- FilterContext filter = new FilterContext();
- RegexPropertyFilter regexFilter = new RegexPropertyFilter();
- regexFilter.setIncludes("test\\..*");
- Map<String,PropertyValue> map = new HashMap<>();
- map.put("test1", test1Property);
- map.put("test2", test1Property);
- map.put("test.test3", test3Property);
- assertEquals(filter.filterProperty(test1Property, new org.apache.tamaya.spi.FilterContext(test1Property, context)), test1Property);
- assertEquals(filter.filterProperty(test2Property, new org.apache.tamaya.spi.FilterContext(test2Property, map, context)), test2Property);
- assertEquals(filter.filterProperty(test3Property, new org.apache.tamaya.spi.FilterContext(test3Property, map, context)), test3Property);
- filter.setFilters(regexFilter);
- assertEquals(filter.filterProperty(test3Property, new org.apache.tamaya.spi.FilterContext(test3Property, map, context)), test3Property);
- assertNull(filter.filterProperty(test2Property, new org.apache.tamaya.spi.FilterContext(test2Property, map, context)));
- assertNull(filter.filterProperty(test1Property, new org.apache.tamaya.spi.FilterContext(test1Property, map, context)));
- }
-
- @Test
- public void testSetFilters1() throws Exception {
- FilterContext filter = new FilterContext();
- RegexPropertyFilter regexFilter = new RegexPropertyFilter();
- regexFilter.setIncludes("test1.*");
- Map<String,String> map = new HashMap<>();
- assertEquals(filter.filterProperty(test1Property, new org.apache.tamaya.spi.FilterContext(test1Property, context)), test1Property);
- assertEquals(filter.filterProperty(test2Property, new org.apache.tamaya.spi.FilterContext(test2Property, context)), test2Property);
- assertEquals(filter.filterProperty(test3Property, new org.apache.tamaya.spi.FilterContext(test3Property, context)), test3Property);
- filter.setFilters(Arrays.asList(new PropertyFilter[]{regexFilter}));
- assertEquals(filter.filterProperty(test1Property, new org.apache.tamaya.spi.FilterContext(test1Property, context)), test1Property);
- assertNull(filter.filterProperty(test2Property, new org.apache.tamaya.spi.FilterContext(test2Property, context)));
- assertNull(filter.filterProperty(test3Property, new org.apache.tamaya.spi.FilterContext(test3Property, context)));
- }
-
- @Test
- public void testGetFilters() throws Exception {
- FilterContext filter = new FilterContext();
- assertNotNull(filter.getFilters());
- assertTrue(filter.getFilters().isEmpty());
- RegexPropertyFilter regexFilter = new RegexPropertyFilter();
- regexFilter.setIncludes("test\\..*");
- filter.addFilter(regexFilter);
- assertNotNull(filter.getFilters());
- assertFalse(filter.getFilters().isEmpty());
- assertEquals(1, filter.getFilters().size());
- assertEquals(regexFilter, filter.getFilters().get(0));
- }
-
- @Test
- public void testToString() throws Exception {
- FilterContext filter = new FilterContext();
- assertFalse(filter.toString().contains("test\\..*"));
- assertTrue(filter.toString().contains("ProgrammableFilter"));
- assertFalse(filter.toString().contains("RegexPropertyFilter"));
- RegexPropertyFilter regexFilter = new RegexPropertyFilter();
- regexFilter.setIncludes("test\\..*");
- filter.addFilter(regexFilter);
- assertTrue(filter.toString().contains("test\\..*"));
- assertTrue(filter.toString().contains("ProgrammableFilter"));
- assertTrue(filter.toString().contains("RegexPropertyFilter"));
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/filter/src/test/java/org/apache/tamaya/spisupport/filter/ConfigurationFilterTest.java
----------------------------------------------------------------------
diff --git a/modules/filter/src/test/java/org/apache/tamaya/spisupport/filter/ConfigurationFilterTest.java b/modules/filter/src/test/java/org/apache/tamaya/spisupport/filter/ConfigurationFilterTest.java
new file mode 100644
index 0000000..e0f24ef
--- /dev/null
+++ b/modules/filter/src/test/java/org/apache/tamaya/spisupport/filter/ConfigurationFilterTest.java
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.spisupport.filter;
+
+import org.apache.tamaya.filter.ConfigurationFilter;
+import org.apache.tamaya.spi.ConfigValue;
+import org.apache.tamaya.spi.Filter;
+import org.junit.Test;
+
+import javax.config.Config;
+import javax.config.ConfigProvider;
+
+import static org.junit.Assert.*;
+
+/**
+ * Tests for {@link ConfigurationFilter}. Created by atsticks on 11.02.16.
+ */
+public class ConfigurationFilterTest {
+
+ @Test
+ public void testMetadataFiltered() throws Exception {
+ ConfigurationFilter.setMetadataFiltered(true);
+ assertTrue(ConfigurationFilter.isMetadataFiltered());
+ ConfigurationFilter.setMetadataFiltered(false);
+ assertFalse(ConfigurationFilter.isMetadataFiltered());
+ }
+
+ @Test
+ public void testGetFilters() throws Exception {
+ Config config = ConfigProvider.getConfig();
+ assertNotNull(ConfigurationFilter.getFilters());
+ Filter testFilter = (k,v) -> k + ":testGetSingleFilters";
+ ConfigurationFilter.addFilter(testFilter);
+ assertTrue(ConfigurationFilter.getFilters().contains(testFilter));
+ }
+
+ @Test
+ public void testFiltering() throws Exception {
+ Config config = ConfigProvider.getConfig();
+ Filter testFilter = (k,v) -> k + ":testGetMapFilters";
+ ConfigurationFilter.addFilter(testFilter);
+ assertEquals("user.home:testGetMapFilters", config.getValue("user.home", String.class));
+ ConfigurationFilter.removeFilter(testFilter);
+ assertNotSame("user.home:testGetSingleFilters", config.getValue("user.home", String.class));
+ }
+
+ @Test
+ public void testRemove() throws Exception {
+ Config config = ConfigProvider.getConfig();
+ Filter testFilter = (k,v) -> k + ":testGetMapFilters";
+ ConfigurationFilter.addFilter(testFilter);
+ assertTrue(ConfigurationFilter.getFilters().contains(testFilter));
+ ConfigurationFilter.removeFilter(testFilter);
+ assertFalse(ConfigurationFilter.getFilters().contains(testFilter));
+ }
+
+ @Test
+ public void testRemoveFilterAt0() throws Exception {
+ Config config = ConfigProvider.getConfig();
+ Filter testFilter = (k,v) -> k + ":testGetMapFilters";
+ ConfigurationFilter.addFilter(testFilter);
+ assertTrue(ConfigurationFilter.getFilters().contains(testFilter));
+ ConfigurationFilter.removeFilter(0);
+ assertFalse(ConfigurationFilter.getFilters().contains(testFilter));
+ }
+
+ @Test
+ public void testClearFilters() throws Exception {
+ Config config = ConfigProvider.getConfig();
+ Filter testFilter = (k,v) -> k + ":testGetSingleFilters";
+ ConfigurationFilter.addFilter(testFilter);
+ assertTrue(ConfigurationFilter.getFilters().contains(testFilter));
+ assertEquals("user.home:testGetSingleFilters", config.getValue("user.home", String.class));
+ ConfigurationFilter.cleanupFilterContext();
+ assertFalse(ConfigurationFilter.getFilters().contains(testFilter));
+ assertNotSame("user.home:testGetSingleFilters", config.getValue("user.home", String.class));
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/filter/src/test/java/org/apache/tamaya/spisupport/filter/ProgrammableFilterTest.java
----------------------------------------------------------------------
diff --git a/modules/filter/src/test/java/org/apache/tamaya/spisupport/filter/ProgrammableFilterTest.java b/modules/filter/src/test/java/org/apache/tamaya/spisupport/filter/ProgrammableFilterTest.java
new file mode 100644
index 0000000..15e54e6
--- /dev/null
+++ b/modules/filter/src/test/java/org/apache/tamaya/spisupport/filter/ProgrammableFilterTest.java
@@ -0,0 +1,183 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.spisupport.filter;
+
+import org.apache.tamaya.base.filter.FilterContext;
+import org.apache.tamaya.base.filter.RegexPropertyFilter;
+import org.apache.tamaya.filter.Context;
+import org.apache.tamaya.spi.Filter;
+import org.junit.Test;
+
+import javax.config.Config;
+import javax.config.ConfigProvider;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.Assert.*;
+
+/**
+ * Tests for {@link Context}. Created by atsticks on 11.02.16.
+ */
+public class ProgrammableFilterTest {
+
+ private static Config config = ConfigProvider.getConfig();
+ private static String test1Property = "test1";
+ private static String test2Property = "test2";
+ private static String test3Property = "test.test3";
+
+ @Test
+ public void testAddRemoveFilter() throws Exception {
+ Context filter = new Context();
+ Map<String,String> map = new HashMap<>();
+ FilterContext.setContext(new FilterContext(map, config));
+ assertEquals(filter.filterProperty(test1Property,test1Property), test1Property);
+ FilterContext.setContext(new FilterContext(map, config));
+ assertEquals(filter.filterProperty(test2Property, test2Property), test2Property);
+ FilterContext.setContext(new FilterContext(map, config));
+ assertEquals(filter.filterProperty(test3Property, test3Property), test3Property);
+ RegexPropertyFilter regexFilter = new RegexPropertyFilter();
+ regexFilter.setIncludes("test\\..*");
+ filter.addFilter(regexFilter);
+ FilterContext.setContext(new FilterContext(map, config));
+ assertNull(filter.filterProperty(test1Property, test1Property));
+ FilterContext.setContext(new FilterContext(map, config));
+ assertNull(filter.filterProperty(test2Property, test2Property));
+ FilterContext.setContext(new FilterContext(map, config));
+ assertEquals(filter.filterProperty(test3Property, test3Property), test3Property);
+ filter.removeFilter(0);
+ FilterContext.setContext(new FilterContext(map, config));
+ assertEquals(filter.filterProperty(test1Property, test1Property), test1Property);
+ FilterContext.setContext(new FilterContext(map, config));
+ assertEquals(filter.filterProperty(test2Property, test2Property), test2Property);
+ FilterContext.setContext(new FilterContext(map, config));
+ assertEquals(filter.filterProperty(test3Property, test3Property), test3Property);
+ filter.addFilter(0, regexFilter);
+ FilterContext.setContext(new FilterContext(map, config));
+ assertNull(filter.filterProperty(test1Property, test1Property));
+ FilterContext.setContext(new FilterContext(map, config));
+ assertNull(filter.filterProperty(test2Property, test2Property));
+ FilterContext.setContext(new FilterContext(map, config));
+ assertEquals(filter.filterProperty(test3Property, test3Property), test3Property);
+ }
+
+ @Test
+ public void testClearFilters() throws Exception {
+ Context filter = new Context();
+ RegexPropertyFilter regexFilter = new RegexPropertyFilter();
+ regexFilter.setIncludes("test1.*");
+ Map<String,String> map = new HashMap<>();
+ map.put("test1", "test1");
+ map.put("test2", "test2");
+ map.put("test.test3", "test.test3");
+ FilterContext.setContext(new FilterContext(config));
+ assertEquals(filter.filterProperty(test1Property, test1Property), test1Property);
+ FilterContext.setContext(new FilterContext(config));
+ assertEquals(filter.filterProperty(test2Property, test2Property), test2Property);
+ FilterContext.setContext(new FilterContext(config));
+ assertEquals(filter.filterProperty(test3Property, test3Property), test3Property);
+ filter.addFilter(regexFilter);
+ FilterContext.setContext(new FilterContext(config));
+ assertEquals(filter.filterProperty(test1Property, test1Property), test1Property);
+ FilterContext.setContext(new FilterContext(config));
+ assertNull(filter.filterProperty(test2Property, test2Property));
+ FilterContext.setContext(new FilterContext(config));
+ assertNull(filter.filterProperty(test3Property, test3Property));
+ filter.clearFilters();
+ FilterContext.setContext(new FilterContext(config));
+ assertEquals(filter.filterProperty(test1Property, test1Property), test1Property);
+ FilterContext.setContext(new FilterContext(config));
+ assertEquals(filter.filterProperty(test2Property, test2Property), test2Property);
+ FilterContext.setContext(new FilterContext(config));
+ assertEquals(filter.filterProperty(test3Property, test3Property), test3Property);
+ }
+
+ @Test
+ public void testSetFilters() throws Exception {
+ Context filter = new Context();
+ RegexPropertyFilter regexFilter = new RegexPropertyFilter();
+ regexFilter.setIncludes("test\\..*");
+ Map<String,String> map = new HashMap<>();
+ map.put("test1", test1Property);
+ map.put("test2", test1Property);
+ map.put("test.test3", test3Property);
+ FilterContext.setContext(new FilterContext(map, config));
+ assertEquals(filter.filterProperty(test1Property, test1Property), test1Property);
+ FilterContext.setContext(new FilterContext(map, config));
+ assertEquals(filter.filterProperty(test2Property, test2Property), test2Property);
+ FilterContext.setContext(new FilterContext(map, config));
+ assertEquals(filter.filterProperty(test3Property, test3Property), test3Property);
+ filter.setFilters(regexFilter);
+ FilterContext.setContext(new FilterContext(map, config));
+ assertEquals(filter.filterProperty(test3Property, test3Property), test3Property);
+ FilterContext.setContext(new FilterContext(map, config));
+ assertNull(filter.filterProperty(test2Property, test2Property));
+ FilterContext.setContext(new FilterContext(map, config));
+ assertNull(filter.filterProperty(test1Property, test1Property));
+ }
+
+ @Test
+ public void testSetFilters1() throws Exception {
+ Context filter = new Context();
+ RegexPropertyFilter regexFilter = new RegexPropertyFilter();
+ regexFilter.setIncludes("test1.*");
+ Map<String,String> map = new HashMap<>();
+ FilterContext.setContext(new FilterContext(map, config));
+ assertEquals(filter.filterProperty(test1Property, test1Property), test1Property);
+ FilterContext.setContext(new FilterContext(map, config));
+ assertEquals(filter.filterProperty(test2Property, test2Property), test2Property);
+ FilterContext.setContext(new FilterContext(map, config));
+ assertEquals(filter.filterProperty(test3Property, test3Property), test3Property);
+ filter.setFilters(Arrays.asList(new Filter[]{regexFilter}));
+ FilterContext.setContext(new FilterContext(config));
+ assertEquals(filter.filterProperty(test1Property, test1Property), test1Property);
+ FilterContext.setContext(new FilterContext(config));
+ assertNull(filter.filterProperty(test2Property, test2Property));
+ FilterContext.setContext(new FilterContext(config));
+ assertNull(filter.filterProperty(test3Property, test3Property));
+ }
+
+ @Test
+ public void testGetFilters() throws Exception {
+ Context filter = new Context();
+ assertNotNull(filter.getFilters());
+ assertTrue(filter.getFilters().isEmpty());
+ RegexPropertyFilter regexFilter = new RegexPropertyFilter();
+ regexFilter.setIncludes("test\\..*");
+ filter.addFilter(regexFilter);
+ assertNotNull(filter.getFilters());
+ assertFalse(filter.getFilters().isEmpty());
+ assertEquals(1, filter.getFilters().size());
+ assertEquals(regexFilter, filter.getFilters().get(0));
+ }
+
+ @Test
+ public void testToString() throws Exception {
+ Context filter = new Context();
+ assertFalse(filter.toString().contains("test\\..*"));
+ assertTrue(filter.toString().contains("ProgrammableFilter"));
+ assertFalse(filter.toString().contains("RegexPropertyFilter"));
+ RegexPropertyFilter regexFilter = new RegexPropertyFilter();
+ regexFilter.setIncludes("test\\..*");
+ filter.addFilter(regexFilter);
+ assertTrue(filter.toString().contains("test\\..*"));
+ assertTrue(filter.toString().contains("ProgrammableFilter"));
+ assertTrue(filter.toString().contains("RegexPropertyFilter"));
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/base/pom.xml
----------------------------------------------------------------------
diff --git a/modules/formats/base/pom.xml b/modules/formats/base/pom.xml
index a2007ce..20d4ab0 100644
--- a/modules/formats/base/pom.xml
+++ b/modules/formats/base/pom.xml
@@ -34,19 +34,13 @@ under the License.
<dependencies>
<dependency>
- <groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-api</artifactId>
- <version>${tamaya-apicore.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
<groupId>org.apache.tamaya.ext</groupId>
<artifactId>tamaya-resources</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-spisupport</artifactId>
+ <artifactId>tamaya-base</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/base/src/main/java/org/apache/tamaya/format/BaseFormatConfigSourceProvider.java
----------------------------------------------------------------------
diff --git a/modules/formats/base/src/main/java/org/apache/tamaya/format/BaseFormatConfigSourceProvider.java b/modules/formats/base/src/main/java/org/apache/tamaya/format/BaseFormatConfigSourceProvider.java
new file mode 100644
index 0000000..86cf909
--- /dev/null
+++ b/modules/formats/base/src/main/java/org/apache/tamaya/format/BaseFormatConfigSourceProvider.java
@@ -0,0 +1,159 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.format;
+
+import javax.config.spi.ConfigSource;
+import javax.config.spi.ConfigSourceProvider;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Objects;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Implementation of a {@link ConfigSourceProvider} that reads configuration from some given resource paths
+ * and using the given formats. The resource path are resolved as classpath resources. This can be changed by
+ * overriding {@link #getConfigSources(ConfigurationData)}.
+ * For each resource found the configuration formats passed get a chance to read the resource, if they succeed the
+ * result is taken as the providers PropertySources to be exposed.
+ */
+public abstract class BaseFormatConfigSourceProvider implements ConfigSourceProvider {
+ /**
+ * The logger used.
+ */
+ private static final Logger LOG = Logger.getLogger(BaseFormatConfigSourceProvider.class.getName());
+ /**
+ * The config formats supported for the given location/resource paths.
+ */
+ private final List<ConfigurationFormat> configFormats = new ArrayList<>();
+ /**
+ * The paths to be evaluated.
+ */
+ private final Collection<URL> paths = new ArrayList<>();
+
+ /**
+ * Creates a new instance.
+ *
+ * @param formats the formats to be used, not null, not empty.
+ * @param paths the paths to be resolved, not null, not empty.
+ */
+ public BaseFormatConfigSourceProvider(
+ List<ConfigurationFormat> formats,
+ URL... paths) {
+ this.configFormats.addAll(Objects.requireNonNull(formats));
+ this.paths.addAll(Arrays.asList(Objects.requireNonNull(paths)));
+ }
+
+ /**
+ * Creates a new instance, hereby using the current thread context classloader, or if not available the classloader
+ * that loaded this class.
+ * @param formats the formats to be used, not null, not empty.
+ * @param paths the paths to be resolved, not null, not empty.
+ */
+ public BaseFormatConfigSourceProvider(
+ List<ConfigurationFormat> formats, String... paths) {
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ if(cl==null){
+ cl = getClass().getClassLoader();
+ }
+ this.configFormats.addAll(Objects.requireNonNull(formats));
+ for(String path:paths) {
+ Enumeration<URL> urls;
+ try {
+ urls = cl.getResources(path);
+ } catch (IOException e) {
+ LOG.log(Level.WARNING, "Failed to read resource: " + path, e);
+ continue;
+ }
+ while(urls.hasMoreElements()) {
+ this.paths.add(urls.nextElement());
+ }
+ }
+ }
+
+ /**
+ * Creates a new instance.
+ *
+ * @param classLoader the ClassLoader to be used, not null, not empty.
+ * @param formats the formats to be used, not null, not empty.
+ * @param paths the paths to be resolved, not null, not empty.
+ */
+ public BaseFormatConfigSourceProvider(
+ List<ConfigurationFormat> formats,
+ ClassLoader classLoader, String... paths) {
+ this.configFormats.addAll(Objects.requireNonNull(formats));
+ for(String path:paths) {
+ Enumeration<URL> urls;
+ try {
+ urls = classLoader.getResources(path);
+ } catch (IOException e) {
+ LOG.log(Level.WARNING, "Failed to read resource: " + path, e);
+ continue;
+ }
+ while(urls.hasMoreElements()) {
+ this.paths.add(urls.nextElement());
+ }
+ }
+ }
+
+
+ /**
+ * Method to create a {@link ConfigSource} based on the given entries read.
+ *
+ * @param data the configuration data, not null.
+ * @return the {@link ConfigSource} instance ready to be registered.
+ */
+ protected abstract Collection<ConfigSource> getConfigSources(ConfigurationData data);
+
+ /**
+ * This method does dynamically resolve the paths using the current ClassLoader set. If no ClassLoader was
+ * explcitly set during creation the current Thread context ClassLoader is used. If none of the supported
+ * formats is able to parse a resource a WARNING log is written.
+ *
+ * @return the PropertySources successfully read
+ */
+ @Override
+ public Iterable<ConfigSource> getConfigSources(ClassLoader classLoader) {
+ List<ConfigSource> propertySources = new ArrayList<>();
+ for (URL res : this.paths) {
+ try{
+ for (ConfigurationFormat format : configFormats) {
+ try (InputStream inputStream = res.openStream()){
+ if (format.accepts(res)) {
+ ConfigurationData data = format.readConfiguration(res.toString(), inputStream);
+ propertySources.addAll(getConfigSources(data));
+ }
+ } catch (Exception e) {
+ LOG.log(Level.WARNING, "Failed to put resource based config: " + res, e);
+ }
+ }
+ } catch (Exception e) {
+ LOG.log(Level.WARNING, "Failed to put resource based config: " + res, e);
+ }
+ }
+ return propertySources;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/base/src/main/java/org/apache/tamaya/format/BaseFormatPropertySourceProvider.java
----------------------------------------------------------------------
diff --git a/modules/formats/base/src/main/java/org/apache/tamaya/format/BaseFormatPropertySourceProvider.java b/modules/formats/base/src/main/java/org/apache/tamaya/format/BaseFormatPropertySourceProvider.java
deleted file mode 100644
index a0f1fdd..0000000
--- a/modules/formats/base/src/main/java/org/apache/tamaya/format/BaseFormatPropertySourceProvider.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.format;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertySourceProvider;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.Objects;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * Implementation of a {@link PropertySourceProvider} that reads configuration from some given resource paths
- * and using the given formats. The resource path are resolved as classpath resources. This can be changed by
- * overriding {@link #getPropertySources()}.
- * For each resource found the configuration formats passed get a chance to read the resource, if they succeed the
- * result is taken as the providers PropertySources to be exposed.
- */
-public abstract class BaseFormatPropertySourceProvider implements PropertySourceProvider {
- /**
- * The logger used.
- */
- private static final Logger LOG = Logger.getLogger(BaseFormatPropertySourceProvider.class.getName());
- /**
- * The config formats supported for the given location/resource paths.
- */
- private final List<ConfigurationFormat> configFormats = new ArrayList<>();
- /**
- * The paths to be evaluated.
- */
- private final Collection<URL> paths = new ArrayList<>();
-
- /**
- * Creates a new instance.
- *
- * @param formats the formats to be used, not null, not empty.
- * @param paths the paths to be resolved, not null, not empty.
- */
- public BaseFormatPropertySourceProvider(
- List<ConfigurationFormat> formats,
- URL... paths) {
- this.configFormats.addAll(Objects.requireNonNull(formats));
- this.paths.addAll(Arrays.asList(Objects.requireNonNull(paths)));
- }
-
- /**
- * Creates a new instance, hereby using the current thread context classloader, or if not available the classloader
- * that loaded this class.
- * @param formats the formats to be used, not null, not empty.
- * @param paths the paths to be resolved, not null, not empty.
- */
- public BaseFormatPropertySourceProvider(
- List<ConfigurationFormat> formats, String... paths) {
- ClassLoader cl = Thread.currentThread().getContextClassLoader();
- if(cl==null){
- cl = getClass().getClassLoader();
- }
- this.configFormats.addAll(Objects.requireNonNull(formats));
- for(String path:paths) {
- Enumeration<URL> urls;
- try {
- urls = cl.getResources(path);
- } catch (IOException e) {
- LOG.log(Level.WARNING, "Failed to read resource: " + path, e);
- continue;
- }
- while(urls.hasMoreElements()) {
- this.paths.add(urls.nextElement());
- }
- }
- }
-
- /**
- * Creates a new instance.
- *
- * @param classLoader the ClassLoader to be used, not null, not empty.
- * @param formats the formats to be used, not null, not empty.
- * @param paths the paths to be resolved, not null, not empty.
- */
- public BaseFormatPropertySourceProvider(
- List<ConfigurationFormat> formats,
- ClassLoader classLoader, String... paths) {
- this.configFormats.addAll(Objects.requireNonNull(formats));
- for(String path:paths) {
- Enumeration<URL> urls;
- try {
- urls = classLoader.getResources(path);
- } catch (IOException e) {
- LOG.log(Level.WARNING, "Failed to read resource: " + path, e);
- continue;
- }
- while(urls.hasMoreElements()) {
- this.paths.add(urls.nextElement());
- }
- }
- }
-
-
- /**
- * Method to create a {@link org.apache.tamaya.spi.PropertySource} based on the given entries read.
- *
- * @param data the configuration data, not null.
- * @return the {@link org.apache.tamaya.spi.PropertySource} instance ready to be registered.
- */
- protected abstract Collection<PropertySource> getPropertySources(ConfigurationData data);
-
- /**
- * This method does dynamically resolve the paths using the current ClassLoader set. If no ClassLoader was
- * explcitly set during creation the current Thread context ClassLoader is used. If none of the supported
- * formats is able to parse a resource a WARNING log is written.
- *
- * @return the PropertySources successfully read
- */
- @Override
- public Collection<PropertySource> getPropertySources() {
- List<PropertySource> propertySources = new ArrayList<>();
- for (URL res : this.paths) {
- try{
- for (ConfigurationFormat format : configFormats) {
- try (InputStream inputStream = res.openStream()){
- if (format.accepts(res)) {
- ConfigurationData data = format.readConfiguration(res.toString(), inputStream);
- propertySources.addAll(getPropertySources(data));
- }
- } catch (Exception e) {
- LOG.log(Level.WARNING, "Failed to put resource based config: " + res, e);
- }
- }
- } catch (Exception e) {
- LOG.log(Level.WARNING, "Failed to put resource based config: " + res, e);
- }
- }
- return propertySources;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/base/src/main/java/org/apache/tamaya/format/ConfigurationFormats.java
----------------------------------------------------------------------
diff --git a/modules/formats/base/src/main/java/org/apache/tamaya/format/ConfigurationFormats.java b/modules/formats/base/src/main/java/org/apache/tamaya/format/ConfigurationFormats.java
index f08e967..804147e 100644
--- a/modules/formats/base/src/main/java/org/apache/tamaya/format/ConfigurationFormats.java
+++ b/modules/formats/base/src/main/java/org/apache/tamaya/format/ConfigurationFormats.java
@@ -31,10 +31,10 @@ import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.spi.PropertySource;
import org.apache.tamaya.spi.ServiceContextManager;
+import javax.config.spi.ConfigSource;
+
/**
* Small accessor and management class dealing with {@link org.apache.tamaya.format.ConfigurationFormat}
* instances.
@@ -199,7 +199,7 @@ public final class ConfigurationFormats {
* @param inputStream the inputStream from where to read, not null.
* @param formats the formats to try.
* @return the ConfigurationData read, or null.
- * @throws ConfigException if the resource cannot be read.
+ * @throws IllegalArgumentException if the resource cannot be read.
*/
public static ConfigurationData readConfigurationData(String resource, InputStream inputStream,
Collection<ConfigurationFormat> formats) throws IOException {
@@ -222,64 +222,64 @@ public final class ConfigurationFormats {
/**
* Tries to read configuration data from a given URL, hereby explicitly trying all given formats
- * in order and transforms it into a {@link PropertySource} using a default mapping.
+ * in order and transforms it into a {@link javax.config.spi.ConfigSource} using a default mapping.
*
* @param url the URL to read, not null.
* @param formats the formats to try. If not formats are passed explicitly, all known formats
* are tried.
* @return a corresponding property source, or null.
- * @throws ConfigException if the resource cannot be read.
+ * @throws IllegalArgumentException if the resource cannot be read.
* @throws IOException if the URL's stream can not be opened.
*/
- public static PropertySource createPropertySource(URL url, ConfigurationFormat... formats)throws IOException{
- return createPropertySource(url.toString(), url.openStream(), formats);
+ public static ConfigSource createConfigSource(URL url, ConfigurationFormat... formats)throws IOException{
+ return createConfigSource(url.toString(), url.openStream(), formats);
}
/**
* Tries to read configuration data from a given URL, hereby explicitly trying all given formats
- * in order and transforms it into a {@link PropertySource} using a default mapping.
+ * in order and transforms it into a {@link ConfigSource} using a default mapping.
*
* @param url the URL to read, not null.
* @param formats the formats to try. If not formats are passed explicitly, all known formats
* are tried.
* @return a corresponding property source, or null.
- * @throws ConfigException if the resource cannot be read.
+ * @throws IllegalArgumentException if the resource cannot be read.
* @throws IOException if the URL's stream can not be opened.
*/
- public static PropertySource createPropertySource(URL url, Collection<ConfigurationFormat> formats)throws IOException{
- return createPropertySource(url.toString(), url.openStream(), formats);
+ public static ConfigSource createConfigSource(URL url, Collection<ConfigurationFormat> formats)throws IOException{
+ return createConfigSource(url.toString(), url.openStream(), formats);
}
/**
* Tries to read configuration data from a given URL, hereby explicitly trying all given formats
- * in order and transforms it into a {@link PropertySource} using a default mapping.
+ * in order and transforms it into a {@link ConfigSource} using a default mapping.
*
* @param resource a descriptive name for the resource, since an InputStream does not have any
* @param inputStream the inputStream from where to read, not null.
* @param formats the formats to try. If not formats are passed explicitly, all known formats
* are tried.
* @return a corresponding property source, or null.
- * @throws ConfigException if the resource cannot be read.
+ * @throws IllegalArgumentException if the resource cannot be read.
*/
- public static PropertySource createPropertySource(String resource, InputStream inputStream,
- ConfigurationFormat... formats){
- return createPropertySource(resource, inputStream, Arrays.asList(formats));
+ public static ConfigSource createConfigSource(String resource, InputStream inputStream,
+ ConfigurationFormat... formats){
+ return createConfigSource(resource, inputStream, Arrays.asList(formats));
}
/**
* Tries to read configuration data from a given URL, hereby explicitly trying all given formats
- * in order and transforms it into a {@link PropertySource} using a default mapping.
+ * in order and transforms it into a {@link ConfigSource} using a default mapping.
*
* @param resource a descriptive name for the resource, since an InputStream does not have any
* @param inputStream the inputStream from where to read, not null.
* @param formats the formats to try. If not formats are passed explicitly, all known formats
* are tried.
* @return a corresponding property source, or null.
- * @throws ConfigException if the resource cannot be read.
+ * @throws IllegalArgumentException if the resource cannot be read.
*/
- public static PropertySource createPropertySource(String resource, InputStream inputStream,
- Collection<ConfigurationFormat> formats) {
+ public static ConfigSource createConfigSource(String resource, InputStream inputStream,
+ Collection<ConfigurationFormat> formats) {
Objects.requireNonNull(resource, "Config resource required for traceability.");
try(InputStreamFactory isFactory = new InputStreamFactory(Objects.requireNonNull(inputStream))) {
if(formats.isEmpty()){
@@ -289,7 +289,7 @@ public final class ConfigurationFormats {
try (InputStream is = isFactory.createInputStream()) {
final ConfigurationData data = format.readConfiguration(resource, is);
if (data != null) {
- return new MappedConfigurationDataPropertySource(data);
+ return new MappedConfigurationDataConfigSource(data);
}
} catch (final Exception e) {
LOG.log(Level.INFO,
@@ -297,9 +297,9 @@ public final class ConfigurationFormats {
}
}
}catch(IOException ioe){
- throw new ConfigException("Failed to read from input stream for "+resource, ioe);
+ throw new IllegalArgumentException("Failed to read from input stream for "+resource, ioe);
}
- throw new ConfigException("No matching format found for "+resource+", tried: "+ formats);
+ throw new IllegalArgumentException("No matching format found for "+resource+", tried: "+ formats);
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/base/src/main/java/org/apache/tamaya/format/MappedConfigurationDataConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/formats/base/src/main/java/org/apache/tamaya/format/MappedConfigurationDataConfigSource.java b/modules/formats/base/src/main/java/org/apache/tamaya/format/MappedConfigurationDataConfigSource.java
new file mode 100644
index 0000000..3c45747
--- /dev/null
+++ b/modules/formats/base/src/main/java/org/apache/tamaya/format/MappedConfigurationDataConfigSource.java
@@ -0,0 +1,152 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.format;
+
+import org.apache.tamaya.base.configsource.BaseConfigSource;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.function.Supplier;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Mapped PropertySource that uses the flattened config data read from an URL by a
+ * {@link org.apache.tamaya.format.ConfigurationFormat}. Use of a {@link Supplier}
+ * allows deferring the load until a resource is available.
+ */
+public class MappedConfigurationDataConfigSource extends BaseConfigSource {
+ private static final Logger LOG = Logger.getLogger(MappedConfigurationDataConfigSource.class.getName());
+ private Map<String, String> properties;
+ private final Supplier<ConfigurationData> dataSupplier;
+
+ /*
+ * Constructor, uses hereby the flattened config data read from an URL by a
+ * ${@link org.apache.tamaya.format.ConfigurationFormat}.
+ * Hereby it reads the <i>default</i> properties as is and adds properties
+ * contained in a section as {@code Entry<section.propertyName,value>}.
+ * @see ConfigurationData#getCombinedProperties()
+ */
+ public MappedConfigurationDataConfigSource(String name, final Supplier<ConfigurationData> dataSupplier) {
+ this(name, 0, dataSupplier);
+ }
+
+ /*
+ * Constructor, uses hereby the flattened config data read from an URL by a
+ * ${@link org.apache.tamaya.format.ConfigurationFormat}.
+ * Hereby it reads the <i>default</i> properties as is and adds properties
+ * contained in a section as {@code Entry<section.propertyName,value>}.
+ * @see ConfigurationData#getCombinedProperties()
+ */
+ public MappedConfigurationDataConfigSource(final ConfigurationData data) {
+ this(data.getResource(), 0, new Supplier<ConfigurationData>(){
+ @Override
+ public ConfigurationData get() {
+ return data;
+ }
+ });
+ }
+
+ /*
+ * Constructor, uses hereby the flattened config data read from an URL by a
+ * ${@link org.apache.tamaya.format.ConfigurationFormat}.
+ * Hereby it reads the <i>default</i> properties as is and adds properties
+ * contained in a section as {@code Entry<section.propertyName,value>}.
+ * @see ConfigurationData#getCombinedProperties()
+ */
+ public MappedConfigurationDataConfigSource(int defaultOrdinal, final ConfigurationData data) {
+ this(data.getResource(), defaultOrdinal, new Supplier<ConfigurationData>() {
+ @Override
+ public ConfigurationData get() {
+ return data;
+ }
+ });
+ }
+
+ /*
+ * Constructor, uses hereby the flattened config data read from an URL by a
+ * ${@link org.apache.tamaya.format.ConfigurationFormat}.
+ * Hereby it reads the <i>default</i> properties as is and adds properties
+ * contained in a section as {@code Entry<section.propertyName,value>}.
+ * @see ConfigurationData#getCombinedProperties()
+ */
+ public MappedConfigurationDataConfigSource(String name, int defaultOrdinal, Supplier<ConfigurationData> dataSupplier) {
+ super(defaultOrdinal);
+ setName(name);
+ this.dataSupplier = dataSupplier;
+ load();
+ }
+
+ public void load(){
+ try{
+ this.properties = populateData(dataSupplier.get());
+ }catch(Exception e){
+ LOG.log(Level.INFO, "Failed to load property source: " + getName(), e);
+ if(this.properties==null) {
+ this.properties = new HashMap<>();
+ }
+ this.properties.put("_exception", e.getLocalizedMessage());
+ this.properties.put("_state", "ERROR");
+ }finally{
+ this.properties.put("_timestamp", String.valueOf(System.currentTimeMillis()));
+ }
+ }
+
+ /**
+ * Method that copies and converts the properties read from the data instance
+ * provided.
+ * @param data the data returned from the format, not null.
+ * @return the final properties to be included.
+ */
+ protected Map<String, String> populateData(ConfigurationData data) {
+ Map<String, String> result = new HashMap<>();
+ if(data!=null) {
+ for (String section : data.getSectionNames()) {
+ for (Map.Entry<String, String> en : data.getSection(section).entrySet()) {
+ if ("default".equals(section)) {
+ result.put(en.getKey(), en.getValue());
+ } else {
+ result.put(section + '.' + en.getKey(), en.getValue());
+ }
+ }
+ }
+ result.put("_propertySource", getName());
+ result.put("_source", data.getResource());
+ }
+ return result;
+ }
+
+ @Override
+ public String getValue(String key) {
+ return properties.get(key);
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ return Collections.unmodifiableMap(this.properties);
+ }
+
+ @Override
+ protected String toStringValues() {
+ return super.toStringValues() +
+ " dataSupplier=" + dataSupplier + '\n';
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/base/src/main/java/org/apache/tamaya/format/MappedConfigurationDataPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/formats/base/src/main/java/org/apache/tamaya/format/MappedConfigurationDataPropertySource.java b/modules/formats/base/src/main/java/org/apache/tamaya/format/MappedConfigurationDataPropertySource.java
deleted file mode 100644
index 5bd6444..0000000
--- a/modules/formats/base/src/main/java/org/apache/tamaya/format/MappedConfigurationDataPropertySource.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.format;
-
-import org.apache.tamaya.functions.Supplier;
-import org.apache.tamaya.spi.PropertyValue;
-import org.apache.tamaya.spisupport.propertysource.BasePropertySource;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * Mapped PropertySource that uses the flattened config data read from an URL by a
- * {@link org.apache.tamaya.format.ConfigurationFormat}. Use of a {@link Supplier}
- * allows deferring the load until a resource is available.
- */
-public class MappedConfigurationDataPropertySource extends BasePropertySource {
- private static final Logger LOG = Logger.getLogger(MappedConfigurationDataPropertySource.class.getName());
- private Map<String, String> properties;
- private final Supplier<ConfigurationData> dataSupplier;
-
- /*
- * Constructor, uses hereby the flattened config data read from an URL by a
- * ${@link org.apache.tamaya.format.ConfigurationFormat}.
- * Hereby it reads the <i>default</i> properties as is and adds properties
- * contained in a section as {@code Entry<section.propertyName,value>}.
- * @see ConfigurationData#getCombinedProperties()
- */
- public MappedConfigurationDataPropertySource(String name, final Supplier<ConfigurationData> dataSupplier) {
- this(name, 0, dataSupplier);
- }
-
- /*
- * Constructor, uses hereby the flattened config data read from an URL by a
- * ${@link org.apache.tamaya.format.ConfigurationFormat}.
- * Hereby it reads the <i>default</i> properties as is and adds properties
- * contained in a section as {@code Entry<section.propertyName,value>}.
- * @see ConfigurationData#getCombinedProperties()
- */
- public MappedConfigurationDataPropertySource(final ConfigurationData data) {
- this(data.getResource(), 0, new Supplier<ConfigurationData>(){
- @Override
- public ConfigurationData get() {
- return data;
- }
- });
- }
-
- /*
- * Constructor, uses hereby the flattened config data read from an URL by a
- * ${@link org.apache.tamaya.format.ConfigurationFormat}.
- * Hereby it reads the <i>default</i> properties as is and adds properties
- * contained in a section as {@code Entry<section.propertyName,value>}.
- * @see ConfigurationData#getCombinedProperties()
- */
- public MappedConfigurationDataPropertySource(int defaultOrdinal, final ConfigurationData data) {
- this(data.getResource(), defaultOrdinal, new Supplier<ConfigurationData>() {
- @Override
- public ConfigurationData get() {
- return data;
- }
- });
- }
-
- /*
- * Constructor, uses hereby the flattened config data read from an URL by a
- * ${@link org.apache.tamaya.format.ConfigurationFormat}.
- * Hereby it reads the <i>default</i> properties as is and adds properties
- * contained in a section as {@code Entry<section.propertyName,value>}.
- * @see ConfigurationData#getCombinedProperties()
- */
- public MappedConfigurationDataPropertySource(String name, int defaultOrdinal, Supplier<ConfigurationData> dataSupplier) {
- super(defaultOrdinal);
- setName(name);
- this.dataSupplier = dataSupplier;
- load();
- }
-
- public void load(){
- try{
- this.properties = populateData(dataSupplier.get());
- }catch(Exception e){
- LOG.log(Level.INFO, "Failed to load property source: " + getName(), e);
- if(this.properties==null) {
- this.properties = new HashMap<>();
- }
- this.properties.put("_exception", e.getLocalizedMessage());
- this.properties.put("_state", "ERROR");
- }finally{
- this.properties.put("_timestamp", String.valueOf(System.currentTimeMillis()));
- }
- }
-
- /**
- * Method that copies and converts the properties read from the data instance
- * provided.
- * @param data the data returned from the format, not null.
- * @return the final properties to be included.
- */
- protected Map<String, String> populateData(ConfigurationData data) {
- Map<String, String> result = new HashMap<>();
- if(data!=null) {
- for (String section : data.getSectionNames()) {
- for (Map.Entry<String, String> en : data.getSection(section).entrySet()) {
- if ("default".equals(section)) {
- result.put(en.getKey(), en.getValue());
- } else {
- result.put(section + '.' + en.getKey(), en.getValue());
- }
- }
- }
- result.put("_propertySource", getName());
- result.put("_source", data.getResource());
- }
- return result;
- }
-
- @Override
- public PropertyValue get(String key) {
- String val = properties.get(key);
- return PropertyValue.of(key, val, getName());
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
- Map<String, PropertyValue> result = new HashMap<>();
- for(Map.Entry<String,String> en:this.properties.entrySet()) {
- result.put(en.getKey(), PropertyValue.of(en.getKey(), en.getValue(), getName()));
- }
- return result;
- }
-
- @Override
- protected String toStringValues() {
- return super.toStringValues() +
- " dataSupplier=" + dataSupplier + '\n';
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/base/src/main/java/org/apache/tamaya/format/formats/IniConfigurationFormat.java
----------------------------------------------------------------------
diff --git a/modules/formats/base/src/main/java/org/apache/tamaya/format/formats/IniConfigurationFormat.java b/modules/formats/base/src/main/java/org/apache/tamaya/format/formats/IniConfigurationFormat.java
index 6fe82c6..b1f2267 100644
--- a/modules/formats/base/src/main/java/org/apache/tamaya/format/formats/IniConfigurationFormat.java
+++ b/modules/formats/base/src/main/java/org/apache/tamaya/format/formats/IniConfigurationFormat.java
@@ -18,7 +18,6 @@
*/
package org.apache.tamaya.format.formats;
-import org.apache.tamaya.ConfigException;
import org.apache.tamaya.format.ConfigurationData;
import org.apache.tamaya.format.ConfigurationDataBuilder;
import org.apache.tamaya.format.ConfigurationFormat;
@@ -65,7 +64,7 @@ public class IniConfigurationFormat implements ConfigurationFormat {
if (line.startsWith("[")) {
int end = line.indexOf(']');
if (end < 0) {
- throw new ConfigException(
+ throw new IllegalArgumentException(
"Invalid INI-Format, ']' expected, at " + lineNum + " in " + resource);
}
section = line.substring(1, end);
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/base/src/test/java/org/apache/tamaya/format/FormatConfigSourceProviderTest.java
----------------------------------------------------------------------
diff --git a/modules/formats/base/src/test/java/org/apache/tamaya/format/FormatConfigSourceProviderTest.java b/modules/formats/base/src/test/java/org/apache/tamaya/format/FormatConfigSourceProviderTest.java
new file mode 100644
index 0000000..881a817
--- /dev/null
+++ b/modules/formats/base/src/test/java/org/apache/tamaya/format/FormatConfigSourceProviderTest.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.format;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+
+import org.junit.Test;
+
+import javax.config.spi.ConfigSource;
+import javax.config.spi.ConfigSourceProvider;
+
+import static org.junit.Assert.*;
+
+public class FormatConfigSourceProviderTest
+ extends BaseFormatConfigSourceProvider {
+ public FormatConfigSourceProviderTest() {
+ super(ConfigurationFormats.getFormats(), "Test.ini", "Test.properties");
+ }
+
+ @Test
+ public void getConfigSourcesTest() {
+ ConfigSourceProvider provider = new FormatConfigSourceProviderTest();
+ Iterable<ConfigSource> sources = provider.getConfigSources(null);
+
+ Iterator iter = sources.iterator();
+ assertTrue(iter.hasNext());
+ iter.next();
+ assertTrue(iter.hasNext());
+ iter.next();
+ assertFalse(iter.hasNext());
+ }
+
+ @Override
+ protected Collection<ConfigSource> getConfigSources(ConfigurationData data) {
+ ConfigSource ps = new MappedConfigurationDataConfigSource(data);
+ ArrayList<ConfigSource> result = new ArrayList<ConfigSource>();
+ result.add(ps);
+ return result;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/base/src/test/java/org/apache/tamaya/format/FormatPropertySourceProviderTest.java
----------------------------------------------------------------------
diff --git a/modules/formats/base/src/test/java/org/apache/tamaya/format/FormatPropertySourceProviderTest.java b/modules/formats/base/src/test/java/org/apache/tamaya/format/FormatPropertySourceProviderTest.java
deleted file mode 100644
index 3a4ec16..0000000
--- a/modules/formats/base/src/test/java/org/apache/tamaya/format/FormatPropertySourceProviderTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.format;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertySourceProvider;
-import org.junit.Test;
-import static org.junit.Assert.*;
-
-public class FormatPropertySourceProviderTest
- extends BaseFormatPropertySourceProvider {
- public FormatPropertySourceProviderTest() {
- super(ConfigurationFormats.getFormats(), "Test.ini", "Test.properties");
- }
-
- @Test
- public void getPropertySourcesTest() {
- PropertySourceProvider provider = new FormatPropertySourceProviderTest();
- Collection<PropertySource> sources = provider.getPropertySources();
-
- assertEquals(2, sources.size());
- }
-
- @Override
- protected Collection<PropertySource> getPropertySources(ConfigurationData data) {
- PropertySource ps = new MappedConfigurationDataPropertySource(data);
- ArrayList<PropertySource> result = new ArrayList<PropertySource>();
- result.add(ps);
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/base/src/test/java/org/apache/tamaya/format/MappedConfigurationDataPropertySourceTest.java
----------------------------------------------------------------------
diff --git a/modules/formats/base/src/test/java/org/apache/tamaya/format/MappedConfigurationDataPropertySourceTest.java b/modules/formats/base/src/test/java/org/apache/tamaya/format/MappedConfigurationDataPropertySourceTest.java
index 1d26d3a..619240f 100644
--- a/modules/formats/base/src/test/java/org/apache/tamaya/format/MappedConfigurationDataPropertySourceTest.java
+++ b/modules/formats/base/src/test/java/org/apache/tamaya/format/MappedConfigurationDataPropertySourceTest.java
@@ -19,21 +19,22 @@
package org.apache.tamaya.format;
import org.apache.tamaya.format.formats.PropertiesFormat;
-import org.apache.tamaya.spi.PropertySource;
import org.junit.Test;
+import javax.config.spi.ConfigSource;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/**
- * Tests for {@link MappedConfigurationDataPropertySource}.
+ * Tests for {@link MappedConfigurationDataConfigSource}.
*/
public class MappedConfigurationDataPropertySourceTest {
@Test
public void testGetName() throws Exception {
- MappedConfigurationDataPropertySource ps = new MappedConfigurationDataPropertySource(createConfigurationData("test1"));
+ MappedConfigurationDataConfigSource ps = new MappedConfigurationDataConfigSource(createConfigurationData("test1"));
assertEquals("test1", ps.getName());
}
@@ -47,7 +48,7 @@ public class MappedConfigurationDataPropertySourceTest {
private ConfigurationData createConfigurationData(String sourceName, int ordinal) {
return ConfigurationDataBuilder.of(sourceName, new PropertiesFormat())
.addDefaultProperty("a", "aValue").addSectionProperty("section1", "sectionKey1", "sectionValue11")
- .addSections("section1", "section12").addDefaultProperty(PropertySource.TAMAYA_ORDINAL, String.valueOf(ordinal))
+ .addSections("section1", "section12").addDefaultProperty(ConfigSource.CONFIG_ORDINAL, String.valueOf(ordinal))
.addSectionProperty("section2", "sectionKey1", "sectionValue21").build();
}
@@ -60,39 +61,39 @@ public class MappedConfigurationDataPropertySourceTest {
@Test
public void testGetOrdinal() throws Exception {
- MappedConfigurationDataPropertySource ps = new MappedConfigurationDataPropertySource(createConfigurationData("test1", 11));
+ MappedConfigurationDataConfigSource ps = new MappedConfigurationDataConfigSource(createConfigurationData("test1", 11));
assertEquals(11, ps.getOrdinal());
}
@Test
public void testGet() throws Exception {
- MappedConfigurationDataPropertySource ps = new MappedConfigurationDataPropertySource(createConfigurationData("test2"));
- assertEquals("aValue", ps.get("a").getValue());
- assertNotNull(ps.get("section1.sectionKey1").getValue());
- assertNotNull(ps.get("section2.sectionKey1").getValue());
- assertNull(ps.get("sectionKey1"));
- ps = new MappedConfigurationDataPropertySource(createConfigurationDataNoDefault("test2"));
- assertEquals("sectionValue11", ps.get("section1.sectionKey1").getValue());
- assertEquals("sectionValue21", ps.get("section2.sectionKey1").getValue());
- assertNull(ps.get("a"));
- assertNull(ps.get("section1"));
+ MappedConfigurationDataConfigSource ps = new MappedConfigurationDataConfigSource(createConfigurationData("test2"));
+ assertEquals("aValue", ps.getValue("a"));
+ assertNotNull(ps.getValue("section1.sectionKey1"));
+ assertNotNull(ps.getValue("section2.sectionKey1"));
+ assertNull(ps.getValue("sectionKey1"));
+ ps = new MappedConfigurationDataConfigSource(createConfigurationDataNoDefault("test2"));
+ assertEquals("sectionValue11", ps.getValue("section1.sectionKey1"));
+ assertEquals("sectionValue21", ps.getValue("section2.sectionKey1"));
+ assertNull(ps.getValue("a"));
+ assertNull(ps.getValue("section1"));
}
@Test
public void testGetProperties() throws Exception {
- MappedConfigurationDataPropertySource ps = new MappedConfigurationDataPropertySource(createConfigurationData("test3"));
+ MappedConfigurationDataConfigSource ps = new MappedConfigurationDataConfigSource(createConfigurationData("test3"));
assertNotNull(ps.getProperties());
- assertEquals("aValue", ps.getProperties().get("a").getValue());
+ assertEquals("aValue", ps.getProperties().get("a"));
assertNotNull(ps.getProperties().get("section1.sectionKey1"));
assertNotNull(ps.getProperties().get("section2.sectionKey1"));
assertNull(ps.getProperties().get("section1.sectionKey2"));
assertNull(ps.getProperties().get("section2.sectionKey2"));
assertNull(ps.getProperties().get("sectionKey1"));
assertNull(ps.getProperties().get("sectionKey2"));
- ps = new MappedConfigurationDataPropertySource(createConfigurationDataNoDefault("test3"));
+ ps = new MappedConfigurationDataConfigSource(createConfigurationDataNoDefault("test3"));
assertNotNull(ps.getProperties());
- assertEquals("sectionValue11", ps.getProperties().get("section1.sectionKey1").getValue());
- assertEquals("sectionValue21", ps.getProperties().get("section2.sectionKey1").getValue());
- assertNull(ps.get("section1"));
+ assertEquals("sectionValue11", ps.getProperties().get("section1.sectionKey1"));
+ assertEquals("sectionValue21", ps.getProperties().get("section2.sectionKey1"));
+ assertNull(ps.getValue("section1"));
}
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/json/pom.xml
----------------------------------------------------------------------
diff --git a/modules/formats/json/pom.xml b/modules/formats/json/pom.xml
index 49360ca..75a27f7 100644
--- a/modules/formats/json/pom.xml
+++ b/modules/formats/json/pom.xml
@@ -37,16 +37,9 @@ under the License.
<dependencies>
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-api</artifactId>
- <version>${tamaya-apicore.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.tamaya</groupId>
<artifactId>tamaya-core</artifactId>
<version>${tamaya-apicore.version}</version>
- <scope>provided</scope>
+ <scope>test</scope>
</dependency>
<dependency>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/json/src/main/java/org/apache/tamaya/json/JSONConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/formats/json/src/main/java/org/apache/tamaya/json/JSONConfigSource.java b/modules/formats/json/src/main/java/org/apache/tamaya/json/JSONConfigSource.java
new file mode 100644
index 0000000..2f73fb0
--- /dev/null
+++ b/modules/formats/json/src/main/java/org/apache/tamaya/json/JSONConfigSource.java
@@ -0,0 +1,148 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.json;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.nio.charset.Charset;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.config.spi.ConfigSource;
+import javax.json.Json;
+import javax.json.JsonObject;
+import javax.json.JsonReaderFactory;
+import javax.json.JsonStructure;
+
+import static java.lang.String.format;
+
+/**
+ * Property source based on a JSON file.
+ */
+public class JSONConfigSource implements ConfigSource {
+ /** Constant for enabling comments in Johnzon. */
+ public static final String JOHNZON_SUPPORTS_COMMENTS_PROP = "org.apache.johnzon.supports-comments";
+
+ /** The underlying resource. */
+ private final URL urlResource;
+ /** The values read. */
+ private final Map<String, String> values;
+ /** The evaluated ordinal. */
+ private int ordinal;
+ /** The JSON reader factory used. */
+ private JsonReaderFactory readerFactory = initReaderFactory();
+
+ /** Initializes the factory to be used for creating readers. */
+ private JsonReaderFactory initReaderFactory() {
+ Map<String, Object> config = new HashMap<>();
+ config.put(JOHNZON_SUPPORTS_COMMENTS_PROP, true);
+ return Json.createReaderFactory(config);
+ }
+
+ /**
+ * Constructor, hereby using 0 as the default ordinal.
+ * @param resource the resource modelled as URL, not null.
+ */
+ public JSONConfigSource(URL resource)throws IOException {
+ this(resource, 0);
+ }
+
+ /**
+ * Constructor.
+ * @param resource the resource modelled as URL, not null.
+ * @param defaultOrdinal the defaultOrdinal to be used.
+ */
+ public JSONConfigSource(URL resource, int defaultOrdinal)throws IOException {
+ urlResource = Objects.requireNonNull(resource);
+ this.ordinal = defaultOrdinal; // may be overriden by read...
+ this.values = readConfig(urlResource);
+ if (this.values.containsKey(CONFIG_ORDINAL)) {
+ this.ordinal = Integer.parseInt(this.values.get(CONFIG_ORDINAL));
+ }
+ Map<String, Object> config = new HashMap<>();
+ config.put(JOHNZON_SUPPORTS_COMMENTS_PROP, true);
+ this.readerFactory = Json.createReaderFactory(config);
+ }
+
+
+ public int getOrdinal() {
+ String configuredOrdinal = getValue(CONFIG_ORDINAL);
+ if(configuredOrdinal!=null){
+ try{
+ return Integer.parseInt(configuredOrdinal);
+ } catch(Exception e){
+ Logger.getLogger(getClass().getName()).log(Level.WARNING,
+ "Configured Ordinal is not an int number: " + configuredOrdinal, e);
+ }
+ }
+ return ordinal;
+ }
+
+ @Override
+ public String getName() {
+ return urlResource.toExternalForm();
+ }
+
+ @Override
+ public String getValue(String key) {
+ return getProperties().get(key);
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+
+ return Collections.unmodifiableMap(values);
+ }
+
+ /**
+ * Reads the configuration.
+ * @param urlResource soure of the configuration.
+ * @return the configuration read from the given resource URL.
+ * @throws IllegalArgumentException if resource URL cannot be read.
+ */
+ protected Map<String, String> readConfig(URL urlResource) throws IOException{
+ try (InputStream is = urlResource.openStream()) {
+ JsonStructure root = this.readerFactory.createReader(is, Charset.forName("UTF-8")).read();
+
+ // Test added. H. Saly, 15. Aug. 2015
+ if (!(root instanceof JsonObject)) {
+ throw new IllegalArgumentException("Currently only JSON objects are supported");
+ }
+
+ Map<String, String> values = new HashMap<>();
+ JSONVisitor visitor = new JSONVisitor((JsonObject)root, values);
+ visitor.run();
+ Map<String, String> result = new HashMap<>();
+ for(Map.Entry<String,String> en:values.entrySet()){
+ result.put(en.getKey(), en.getValue());
+ }
+ return result;
+ }catch(IOException ioe){
+ throw ioe;
+ }catch (Exception t) {
+ throw new IOException(format("Failed to read properties from %s", urlResource.toExternalForm()), t);
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/json/src/main/java/org/apache/tamaya/json/JSONPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/formats/json/src/main/java/org/apache/tamaya/json/JSONPropertySource.java b/modules/formats/json/src/main/java/org/apache/tamaya/json/JSONPropertySource.java
deleted file mode 100644
index 5934210..0000000
--- a/modules/formats/json/src/main/java/org/apache/tamaya/json/JSONPropertySource.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.json;
-
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.nio.charset.Charset;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.json.Json;
-import javax.json.JsonObject;
-import javax.json.JsonReaderFactory;
-import javax.json.JsonStructure;
-
-import static java.lang.String.format;
-
-/**
- * Property source based on a JSON file.
- */
-public class JSONPropertySource implements PropertySource {
- /** Constant for enabling comments in Johnzon. */
- public static final String JOHNZON_SUPPORTS_COMMENTS_PROP = "org.apache.johnzon.supports-comments";
-
- /** The underlying resource. */
- private final URL urlResource;
- /** The values read. */
- private final Map<String, PropertyValue> values;
- /** The evaluated ordinal. */
- private int ordinal;
- /** The JSON reader factory used. */
- private JsonReaderFactory readerFactory = initReaderFactory();
-
- /** Initializes the factory to be used for creating readers. */
- private JsonReaderFactory initReaderFactory() {
- Map<String, Object> config = new HashMap<>();
- config.put(JOHNZON_SUPPORTS_COMMENTS_PROP, true);
- return Json.createReaderFactory(config);
- }
-
- /**
- * Constructor, hereby using 0 as the default ordinal.
- * @param resource the resource modelled as URL, not null.
- */
- public JSONPropertySource(URL resource)throws IOException {
- this(resource, 0);
- }
-
- /**
- * Constructor.
- * @param resource the resource modelled as URL, not null.
- * @param defaultOrdinal the defaultOrdinal to be used.
- */
- public JSONPropertySource(URL resource, int defaultOrdinal)throws IOException {
- urlResource = Objects.requireNonNull(resource);
- this.ordinal = defaultOrdinal; // may be overriden by read...
- this.values = readConfig(urlResource);
- if (this.values.containsKey(TAMAYA_ORDINAL)) {
- this.ordinal = Integer.parseInt(this.values.get(TAMAYA_ORDINAL).getValue());
- }
- Map<String, Object> config = new HashMap<>();
- config.put(JOHNZON_SUPPORTS_COMMENTS_PROP, true);
- this.readerFactory = Json.createReaderFactory(config);
- }
-
-
- public int getOrdinal() {
- PropertyValue configuredOrdinal = get(TAMAYA_ORDINAL);
- if(configuredOrdinal!=null){
- try{
- return Integer.parseInt(configuredOrdinal.getValue());
- } catch(Exception e){
- Logger.getLogger(getClass().getName()).log(Level.WARNING,
- "Configured Ordinal is not an int number: " + configuredOrdinal, e);
- }
- }
- return ordinal;
- }
-
- @Override
- public String getName() {
- return urlResource.toExternalForm();
- }
-
- @Override
- public PropertyValue get(String key) {
- return getProperties().get(key);
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
-
- return Collections.unmodifiableMap(values);
- }
-
- /**
- * Reads the configuration.
- * @param urlResource soure of the configuration.
- * @return the configuration read from the given resource URL.
- * @throws ConfigException if resource URL cannot be read.
- */
- protected Map<String, PropertyValue> readConfig(URL urlResource) throws IOException{
- try (InputStream is = urlResource.openStream()) {
- JsonStructure root = this.readerFactory.createReader(is, Charset.forName("UTF-8")).read();
-
- // Test added. H. Saly, 15. Aug. 2015
- if (!(root instanceof JsonObject)) {
- throw new ConfigException("Currently only JSON objects are supported");
- }
-
- Map<String, String> values = new HashMap<>();
- JSONVisitor visitor = new JSONVisitor((JsonObject)root, values);
- visitor.run();
- Map<String, PropertyValue> result = new HashMap<>();
- for(Map.Entry<String,String> en:values.entrySet()){
- result.put(en.getKey(), PropertyValue.of(en.getKey(), en.getValue(), getName()));
- }
- return result;
- }catch(IOException ioe){
- throw ioe;
- }catch (Exception t) {
- throw new IOException(format("Failed to read properties from %s", urlResource.toExternalForm()), t);
- }
- }
-
- @Override
- public boolean isScannable() {
- return true;
- }
-}
[15/18] incubator-tamaya-extensions git commit: Rewrite/adaptation
based on JSR API.
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/NotFoundNoDefault.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/NotFoundNoDefault.java b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/NotFoundNoDefault.java
index 6e4e50e..46f6c2a 100644
--- a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/NotFoundNoDefault.java
+++ b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/NotFoundNoDefault.java
@@ -16,8 +16,7 @@
*/
package org.apache.tamaya.cdi;
-import org.apache.tamaya.inject.api.Config;
-
+import javax.config.inject.ConfigProperty;
import javax.enterprise.inject.Alternative;
import javax.inject.Inject;
import java.io.File;
@@ -28,23 +27,23 @@ import java.time.Duration;
public class NotFoundNoDefault {
@Inject
- @Config("string.bla")
+ @ConfigProperty(name="string.bla")
private String string;
@Inject
- @Config("file.bla")
+ @ConfigProperty(name="file.bla")
private File file;
@Inject
- @Config("duration.bla")
+ @ConfigProperty(name="duration.bla")
private Duration duration;
@Inject
- @Config("boolean.bla")
+ @ConfigProperty(name="boolean.bla")
private Boolean aBoolean;
@Inject
- @Config("integer.bla")
+ @ConfigProperty(name="integer.bla")
private Integer integer;
public String getString() {
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/cfg/ProvidedConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/cfg/ProvidedConfigSource.java b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/cfg/ProvidedConfigSource.java
new file mode 100644
index 0000000..b9333d1
--- /dev/null
+++ b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/cfg/ProvidedConfigSource.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 current the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.tamaya.cdi.cfg;
+
+import javax.config.spi.ConfigSource;
+import javax.enterprise.inject.Vetoed;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Created by Anatole on 17.09.2015.
+ */
+@Vetoed
+class ProvidedConfigSource implements ConfigSource{
+
+ final Map<String,String> config = new HashMap<>();
+
+ public ProvidedConfigSource(){
+ config.put("a.b.c.key3", "keys current a.b.c.key3");
+ config.put("a.b.c.key4", "keys current a.b.c.key4");
+ }
+
+ @Override
+ public int getOrdinal() {
+ return 10;
+ }
+
+ @Override
+ public String getName() {
+ return getClass().getName();
+ }
+
+ @Override
+ public String getValue(String key) {
+ return config.get(key);
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ return config;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/cfg/ProvidedPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/cfg/ProvidedPropertySource.java b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/cfg/ProvidedPropertySource.java
deleted file mode 100644
index 8ed0588..0000000
--- a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/cfg/ProvidedPropertySource.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 current the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.tamaya.cdi.cfg;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-
-import javax.enterprise.inject.Vetoed;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Created by Anatole on 17.09.2015.
- */
-@Vetoed
-class ProvidedPropertySource implements PropertySource{
-
- final Map<String,PropertyValue> config = new HashMap<>();
-
- public ProvidedPropertySource(){
- config.put("a.b.c.key3", PropertyValue.of("a.b.c.key3","keys current a.b.c.key3",getName()));
- config.put("a.b.c.key4", PropertyValue.of("a.b.c.key4","keys current a.b.c.key4", getName()));
- }
-
- @Override
- public int getOrdinal() {
- return 10;
- }
-
- @Override
- public String getName() {
- return getClass().getName();
- }
-
- @Override
- public PropertyValue get(String key) {
- return config.get(key);
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
- return config;
- }
-
- @Override
- public boolean isScannable() {
- return true;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/cfg/TestConfigProvider.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/cfg/TestConfigProvider.java b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/cfg/TestConfigProvider.java
index 036b9da..31bf136 100644
--- a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/cfg/TestConfigProvider.java
+++ b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/cfg/TestConfigProvider.java
@@ -18,9 +18,8 @@
*/
package org.apache.tamaya.cdi.cfg;
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertySourceProvider;
-
+import javax.config.spi.ConfigSource;
+import javax.config.spi.ConfigSourceProvider;
import javax.enterprise.context.ApplicationScoped;
import java.util.ArrayList;
import java.util.Collection;
@@ -30,16 +29,16 @@ import java.util.List;
* Created by Anatole on 29.09.2014.
*/
@ApplicationScoped
-public class TestConfigProvider implements PropertySourceProvider {
+public class TestConfigProvider implements ConfigSourceProvider {
- private List<PropertySource> configs = new ArrayList<>();
+ private List<ConfigSource> configs = new ArrayList<>();
public TestConfigProvider(){
- configs.add(new ProvidedPropertySource());
+ configs.add(new ProvidedConfigSource());
}
@Override
- public Collection<PropertySource> getPropertySources() {
+ public Collection<ConfigSource> getConfigSources(ClassLoader cl) {
return configs;
}
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/cfg/TestPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/cfg/TestPropertySource.java b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/cfg/TestPropertySource.java
index e31070a..0ecfd9b 100644
--- a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/cfg/TestPropertySource.java
+++ b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/cfg/TestPropertySource.java
@@ -19,9 +19,7 @@
*/
package org.apache.tamaya.cdi.cfg;
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-
+import javax.config.spi.ConfigSource;
import javax.inject.Singleton;
import java.util.HashMap;
import java.util.Map;
@@ -30,7 +28,7 @@ import java.util.Map;
* Created by Anatole on 17.09.2015.
*/
@Singleton
-public class TestPropertySource implements PropertySource{
+public class TestPropertySource implements ConfigSource{
final Map<String,String> config = new HashMap<>();
@@ -62,21 +60,13 @@ public class TestPropertySource implements PropertySource{
}
@Override
- public PropertyValue get(String key) {
- String val = this.config.get(key);
- if(val!=null) {
- return PropertyValue.of(key, val, getName());
- }
- return null;
+ public String getValue(String key) {
+ return this.config.get(key);
}
@Override
- public Map<String, PropertyValue> getProperties() {
- return PropertyValue.map(config ,getName());
+ public Map<String, String> getProperties() {
+ return config;
}
- @Override
- public boolean isScannable() {
- return true;
- }
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/extra/ConfiguredVetoExtensionTest.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/extra/ConfiguredVetoExtensionTest.java b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/extra/ConfiguredVetoExtensionTest.java
index 11f7dfd..15b4d47 100644
--- a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/extra/ConfiguredVetoExtensionTest.java
+++ b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/extra/ConfiguredVetoExtensionTest.java
@@ -18,12 +18,11 @@
*/
package org.apache.tamaya.cdi.extra;
-import org.apache.tamaya.ConfigurationProvider;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.spi.ConfigurationContext;
import org.junit.Test;
+import javax.config.Config;
+import javax.config.spi.ConfigProviderResolver;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.ProcessAnnotatedType;
@@ -34,13 +33,12 @@ public class ConfiguredVetoExtensionTest {
@Test
public void willBeVetoedIfTypeHasBeenConfiguredAsConcreteClassName() {
- ConfigurationContext context = mock(ConfigurationContext.class);
- Configuration configuration = mock(Configuration.class);
+ Config configuration = mock(Config.class);
- when(configuration.getContext()).thenReturn(context);
- when(configuration.get("javax.enterprise.inject.vetoed")).thenReturn("org.apache.tamaya.cdi.extra.TestKlazz");
+ when(configuration.getValue("javax.enterprise.inject.vetoed", String.class))
+ .thenReturn("org.apache.tamaya.cdi.extra.TestKlazz");
- ConfigurationProvider.setConfiguration(configuration);
+ ConfigProviderResolver.instance().registerConfig(configuration, getClass().getClassLoader());
AnnotatedType<TestKlazz> annotatedType = mock(AnnotatedType.class);
when(annotatedType.getJavaClass()).thenReturn(TestKlazz.class);
@@ -55,13 +53,12 @@ public class ConfiguredVetoExtensionTest {
@Test
public void willNotBeVetoedIfTypeHasNotBeenConfigured() {
- ConfigurationContext context = mock(ConfigurationContext.class);
- Configuration configuration = mock(Configuration.class);
+ Config configuration = mock(Config.class);
- when(configuration.getContext()).thenReturn(context);
- when(configuration.get("javax.enterprise.inject.vetoed")).thenReturn("org.apache.tamaya.cdi.extra.O");
+ when(configuration.getValue("javax.enterprise.inject.vetoed", String.class))
+ .thenReturn("org.apache.tamaya.cdi.extra.O");
- ConfigurationProvider.setConfiguration(configuration);
+ ConfigProviderResolver.instance().registerConfig(configuration, getClass().getClassLoader());
AnnotatedType<TestKlazz> annotatedType = mock(AnnotatedType.class);
when(annotatedType.getJavaClass()).thenReturn(TestKlazz.class);
@@ -79,13 +76,11 @@ public class ConfiguredVetoExtensionTest {
String configuredValue = " " + TestKlazz.class.getName() +
",\t" + TestKlazz2.class.getName();
- ConfigurationContext context = mock(ConfigurationContext.class);
- Configuration configuration = mock(Configuration.class);
+ Config configuration = mock(Config.class);
- when(configuration.getContext()).thenReturn(context);
- when(configuration.get("javax.enterprise.inject.vetoed")).thenReturn(configuredValue);
+ when(configuration.getValue("javax.enterprise.inject.vetoed", String.class)).thenReturn(configuredValue);
- ConfigurationProvider.setConfiguration(configuration);
+ ConfigProviderResolver.instance().registerConfig(configuration, getClass().getClassLoader());
AnnotatedType<TestKlazz> annotatedType = mock(AnnotatedType.class);
when(annotatedType.getJavaClass()).thenReturn(TestKlazz.class);
@@ -103,13 +98,12 @@ public class ConfiguredVetoExtensionTest {
String configuredValue = " " + TestKlazz.class.getPackage().getName() +
"\\..+";
- ConfigurationContext context = mock(ConfigurationContext.class);
- Configuration configuration = mock(Configuration.class);
+ Config configuration = mock(Config.class);
- when(configuration.getContext()).thenReturn(context);
- when(configuration.get("javax.enterprise.inject.vetoed")).thenReturn(configuredValue);
+ when(configuration.getValue("javax.enterprise.inject.vetoed", String.class))
+ .thenReturn(configuredValue);
- ConfigurationProvider.setConfiguration(configuration);
+ ConfigProviderResolver.instance().registerConfig(configuration, getClass().getClassLoader());
AnnotatedType<TestKlazz> annotatedType = mock(AnnotatedType.class);
when(annotatedType.getJavaClass()).thenReturn(TestKlazz.class);
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/test/resources/META-INF/javaconfig.properties
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/test/resources/META-INF/javaconfig.properties b/modules/injection/cdi/src/test/resources/META-INF/javaconfig.properties
new file mode 100644
index 0000000..c72446e
--- /dev/null
+++ b/modules/injection/cdi/src/test/resources/META-INF/javaconfig.properties
@@ -0,0 +1,35 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+#
+double1=1234.5678
+int2=13
+booleanT=y
+remote.wsdl.location = classpath:/service-wsdl.xml
+remote.port=1443
+remote.address=${remote.host}:${remote.port}
+remote.target.url = https://${remote.address}/remote/service/url
+remote.username = joecool
+
+# ciphered using built in StaticDESPasswordCipher
+remote.password = NjAq6q2agYVnvSMz+eYUZg==
+cipher=org.apache.openejb.cipher.StaticDESPasswordCipher
+
+string.value = hello
+file.value = ./conf
+duration.value = 10 minutes and 57 seconds
+boolean.value = true
+integer.value = 123
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/test/resources/META-INF/javaconfiguration.properties
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/test/resources/META-INF/javaconfiguration.properties b/modules/injection/cdi/src/test/resources/META-INF/javaconfiguration.properties
deleted file mode 100644
index c72446e..0000000
--- a/modules/injection/cdi/src/test/resources/META-INF/javaconfiguration.properties
+++ /dev/null
@@ -1,35 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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.
-#
-double1=1234.5678
-int2=13
-booleanT=y
-remote.wsdl.location = classpath:/service-wsdl.xml
-remote.port=1443
-remote.address=${remote.host}:${remote.port}
-remote.target.url = https://${remote.address}/remote/service/url
-remote.username = joecool
-
-# ciphered using built in StaticDESPasswordCipher
-remote.password = NjAq6q2agYVnvSMz+eYUZg==
-cipher=org.apache.openejb.cipher.StaticDESPasswordCipher
-
-string.value = hello
-file.value = ./conf
-duration.value = 10 minutes and 57 seconds
-boolean.value = true
-integer.value = 123
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/pom.xml
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/pom.xml b/modules/injection/injection-api/pom.xml
index 82c89c3..4bd3ece 100644
--- a/modules/injection/injection-api/pom.xml
+++ b/modules/injection/injection-api/pom.xml
@@ -40,13 +40,7 @@ under the License.
<dependencies>
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-api</artifactId>
- <version>${tamaya-apicore.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-core</artifactId>
+ <artifactId>tamaya-base</artifactId>
<version>${tamaya-apicore.version}</version>
<scope>test</scope>
</dependency>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/Config.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/Config.java b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/Config.java
deleted file mode 100644
index 10ba0c8..0000000
--- a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/Config.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.inject.api;
-
-
-import javax.enterprise.util.Nonbinding;
-import javax.inject.Qualifier;
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotation to define injection of a configured property or define the configuration data
- * backing a configuration template method. Hereby this annotation can be used in multiple
- * ways and combined with other annotations such as {@link WithConfigOperator}, {@link WithPropertyConverter}.
- *
- * <h3>Simplest variant</h3>
- * Below the most simple variant of a configured class is given:
- * <pre>
- * package a.b;
- *
- * public class ConfiguredItem {
- * &Config
- * private String aValue;
- * }
- * </pre>
- * Configuration resolution is implemented as follows:
- * <ul>
- * <li>The current valid Configuration is evaluated by calling {@code Configuration cfg = ConfigurationProvider.getConfiguration();}</li>
- * <li>The current possible property keys are evaluated by calling {@code cfg.get("a.b.ConfigureItem.aValue");},
- * {@code cfg.get("ConfigureItem.aValue");}, {@code cfg.get("aValue");}</li>
- * <li>if not successful, and since no @ConfigDefault annotation is present, the configured default value is used.
- * <li>If no value could be evaluated a ({@link org.apache.tamaya.ConfigException} is thrown.</li>
- * <li>On success, since no type conversion is involved, the value is injected.</li>
- * </ul>
- *
- * <h3>Explicit annotations</h3>
- * In the next example we explicitly define the configuration keys to be used:
- * <pre>
- * &ConfigDefaultSections("section1")
- * public class ConfiguredItem {
- *
- * &Config(value = {"b", "[a.b.deprecated.keys]", "a"}, defaultValue = "myDefaultValue")
- * private String aValue;
- * }
- * </pre>
- *
- * Within this example we evaluate multiple possible keys: {@code section1.b, a.b.deprecated.keys, section1.a}.
- * Evaluation is aborted if a key is resolved successfully. Hereby the ordering of the annotation values
- * define the ordering of resolution. If no value can be found, the configured default {@code myDefaultValue} is
- * injected.
- *
- * <h3>Using explicit field annotation only</h3>
- * In the last example we explicitly define the configuration keys but omit the section part, letting the default
- * section names to be taken:
- * <pre>
- * package a.b;
- *
- * public class ConfiguredItem {
- *
- * &Config(value = {"b", "[a.b.deprecated.keys]", "a"}, defaultValue = "myDefaultValue")
- * private String aValue;
- * }
- * </pre>
- *
- * Key resolution is similar to above, but now the default package names are used, resulting in
- * {@code a.b.ConfiguredItem.b, ConfiguredItem.b, a.b.deprecated.keys, a.b.ConfiguredItem.a, ConfiguredItem.a}
- * being evaluated.
- */
-@Qualifier
-@Retention(RetentionPolicy.RUNTIME)
-@Target(value = { ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER })
-public @interface Config {
-
- /** Value that is set by default as default, so it is possible to use empty Strings as default values. */
- String UNCONFIGURED_VALUE = "org.apache.tamaya.config.configproperty.unconfigureddvalue";
-
- /**
- * Defines the configuration property keys to be used. Hereby the first non null value evaluated is injected as
- * property value.
- *
- * @return the property keys, not null. If empty, the field or property name (of a setter method) being injected
- * is used by default.
- */
- @Nonbinding
- String[] value() default {};
-
- /**
- * The default value to be injected, if none of the configuration keys could be resolved. If no key has been
- * resolved and no default value is defined, it is, by default, handled as a deployment error. Depending on the
- * extension loaded default values can be fixed Strings or even themselves resolvable. For typed configuration of
- * type T entries that are not Strings the default value must be a valid input to a corresponding
- * {@link org.apache.tamaya.spi.PropertyConverter}.
- *
- * @return default value used in case resolution fails.
- */
- @Nonbinding
- String defaultValue() default UNCONFIGURED_VALUE;
-
- /**
- * Flag that defines if a configuration property is required. If a required
- * property is missing, a {@link org.apache.tamaya.ConfigException} is raised.
- * Default is {@code true}.
- * @return the flag value.
- */
- @Nonbinding
- boolean required() default true;
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/ConfigAutoDetect.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/ConfigAutoDetect.java b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/ConfigAutoDetect.java
new file mode 100644
index 0000000..f3dee88
--- /dev/null
+++ b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/ConfigAutoDetect.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.inject.api;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Adding this annotation tells the Tamaya injection system to inject all
+ * fields found, also including fields not annotated with {@code @Config}.
+ * The configuration keys to be used for resolution are basically determined
+ * by the {@link Config} annotation(s). If missing the keys are evaluated in the
+ * following order:
+ * <ul>
+ * <li>packagename.simpleClassname.fieldName</li>
+ * <li>simpleClassname.fieldName</li>
+ * <li>fieldName</li>
+ * </ul>
+ * Fields not to be injected can be annotated with {@code @NoConfig} to exclude
+ * them being elected for injection.
+ * @see Config
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target(value = { ElementType.TYPE })
+public @interface ConfigAutoDetect {
+
+ /**
+ * Flag that tells the injection system if a {@link IllegalStateException} should
+ * be thrown when a property cannot be resolved. Default is {@code false}.
+ * @return {@code false} if no exception is thrown on unresolvable properties, {@code true} otherwise.
+ */
+ boolean failIfMissing() default false;
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/ConfigAutoInject.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/ConfigAutoInject.java b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/ConfigAutoInject.java
deleted file mode 100644
index 251caf9..0000000
--- a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/ConfigAutoInject.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.inject.api;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Adding this annotation tells the Tamaya injection system to inject all
- * fields found, also including fields not annotated with {@code @Config}.
- * The configuration keys to be used for resolution are basically determined
- * by the {@link Config} annotation(s). If missing the keys are evaluated in the
- * following order:
- * <ul>
- * <li>packagename.simpleClassname.fieldName</li>
- * <li>simpleClassname.fieldName</li>
- * <li>fieldName</li>
- * </ul>
- * Fields not to be injected can be annotated with {@code @NoConfig} to exclude
- * them being elected for injection.
- * @see Config
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(value = { ElementType.TYPE })
-public @interface ConfigAutoInject {
-
- /**
- * Flag that tells the injection system if a {@link org.apache.tamaya.ConfigException} should
- * be thrown when a property cannot be resolved. Default is {@code false}.
- * @return {@code false} if no exception is thrown on unresolvable properties, {@code true} otherwise.
- */
- boolean failIfMissing() default false;
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/ConfigDefaultSections.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/ConfigDefaultSections.java b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/ConfigDefaultSections.java
index a9025f6..9071c4e 100644
--- a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/ConfigDefaultSections.java
+++ b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/ConfigDefaultSections.java
@@ -30,7 +30,7 @@ import java.lang.annotation.Target;
* annotation(s). This annotation allows
* to define the configuration section that is prefixed to all <b>relative</b> configuration keys.
* @see Config
- * @see ConfigAutoInject
+ * @see ConfigAutoDetect
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE })
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/ConfigFallbackKeys.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/ConfigFallbackKeys.java b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/ConfigFallbackKeys.java
new file mode 100644
index 0000000..8d0aa4a
--- /dev/null
+++ b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/ConfigFallbackKeys.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.inject.api;
+
+
+import javax.enterprise.util.Nonbinding;
+import javax.inject.Qualifier;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Annotation to define additional keys to be used as fallback keys to evaluate a configuration entry.
+ */
+@Qualifier
+@Retention(RetentionPolicy.RUNTIME)
+@Target(value = { ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER })
+public @interface ConfigFallbackKeys {
+
+ /**
+ * Defines the configuration property keys to be used as fallback keys.
+ *
+ * @return the property keys, not null. If empty, the field or property name (of a setter method) being injected
+ * is used by default.
+ */
+ @Nonbinding
+ String[] value() default {};
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/DynamicValue.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/DynamicValue.java b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/DynamicValue.java
index ef249ac..1efcb11 100644
--- a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/DynamicValue.java
+++ b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/DynamicValue.java
@@ -18,6 +18,7 @@
*/
package org.apache.tamaya.inject.api;
+import javax.inject.Provider;
import java.beans.PropertyChangeListener;
import java.util.function.Supplier;
@@ -40,13 +41,13 @@ import java.util.function.Supplier;
*
* @param <T> The type of the value.
*/
-public interface DynamicValue<T> {
+public interface DynamicValue<T>{
/**
* Performs a commit, if necessary, and returns the current value.
*
* @return the non-null value held by this {@code DynamicValue}
- * @throws org.apache.tamaya.ConfigException if there is no value present
+ * @throws java.util.NoSuchElementException if there is no value present
*
* @see DynamicValue#isPresent()
*/
@@ -89,7 +90,7 @@ public interface DynamicValue<T> {
* otherwise throws {@code ConfigException}.
*
* @return the non-null value held by this {@code Optional}
- * @throws org.apache.tamaya.ConfigException if there is no value present
+ * @throws java.util.NoSuchElementException if there is no value present
*
* @see DynamicValue#isPresent()
*/
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/LoadPolicy.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/LoadPolicy.java b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/LoadPolicy.java
index b445e14..985252a 100644
--- a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/LoadPolicy.java
+++ b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/LoadPolicy.java
@@ -23,9 +23,7 @@ package org.apache.tamaya.inject.api;
* for a {@link DynamicValue}.
* The policy also affects the cases were any configured listeners/listener methods are called for
* propagation current configuration changes.
- * @deprecated Currently only used internally. Future usage unclear.
*/
-@Deprecated
public enum LoadPolicy {
/**
* The configuration keys is evaluated once, when the owning component is loaded/configured, but never updated later.
@@ -38,7 +36,7 @@ public enum LoadPolicy {
*/
LAZY,
/**
- * The configuration value is evaluated every time it is accessed.
+ * The configuration value is (re)evaluated every time it is accessed.
*/
ALWAYS
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/OptionalConfig.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/OptionalConfig.java b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/OptionalConfig.java
new file mode 100644
index 0000000..8ab2e98
--- /dev/null
+++ b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/OptionalConfig.java
@@ -0,0 +1,37 @@
+///*
+// * Licensed to the Apache Software Foundation (ASF) under one
+// * or more contributor license agreements. See the NOTICE file
+// * distributed with this work for additional information
+// * regarding copyright ownership. The ASF licenses this file
+// * to you under the Apache License, Version 2.0 (the
+// * "License"); you may not use this file except in compliance
+// * with the License. You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing,
+// * software distributed under the License is distributed on an
+// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// * KIND, either express or implied. See the License for the
+// * specific language governing permissions and limitations
+// * under the License.
+// */
+//package org.apache.tamaya.inject.api;
+//
+//
+//import javax.enterprise.util.Nonbinding;
+//import javax.inject.Qualifier;
+//import java.lang.annotation.ElementType;
+//import java.lang.annotation.Retention;
+//import java.lang.annotation.RetentionPolicy;
+//import java.lang.annotation.Target;
+//
+///**
+// * Annotation to mark a configuration entry as optional, thus not throwing any exceptions if not satisfied.
+// */
+//@Qualifier
+//@Retention(RetentionPolicy.RUNTIME)
+//@Target(value = { ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER })
+//public @interface OptionalConfig {
+//
+//}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/UpdatePolicy.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/UpdatePolicy.java b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/UpdatePolicy.java
index ddee4e0..3183938 100644
--- a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/UpdatePolicy.java
+++ b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/UpdatePolicy.java
@@ -22,11 +22,6 @@ package org.apache.tamaya.inject.api;
* Policy to control how new values are applied to a {@link DynamicValue}.
*/
public enum UpdatePolicy {
- /**
- * @deprecated Use {@link #IMMEDIATE} instead of.
- */
- @Deprecated
- IMMEDEATE,
/** New values are applied immediately and registered listeners are informed about the change. */
IMMEDIATE,
/** New values or not applied, but stored in the newValue property. Explicit call to DynamicValue#commit
@@ -35,11 +30,6 @@ public enum UpdatePolicy {
*/
EXPLICIT,
/**
- * @deprecated Use {@link #EXPLICIT} instead of.
- */
- @Deprecated
- EXPLCIT,
- /**
* New values are always immediately discarded, listeners are not triggered.
*/
NEVER,
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/WithConfigOperator.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/WithConfigOperator.java b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/WithConfigOperator.java
deleted file mode 100644
index 6630e53..0000000
--- a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/WithConfigOperator.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.inject.api;
-
-import org.apache.tamaya.ConfigOperator;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotation to define an configuration operator to be used before accessing a configured key.
- * This allows filtering the current configuration, e.g. to realize views or ensure security
- * constraints.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(value = {ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})
-public @interface WithConfigOperator {
-
- /**
- * Define a custom adapter that should be used to adapt the configuration entry injected. This overrides any
- * general org.apache.tamaya.core.internal registered. If no adapter is defined (default) and no corresponding adapter is
- * registered, it is handled as a deployment error.
- * @return adapter used to transform the configuration entry.
- */
- Class<? extends ConfigOperator> value();
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/WithConverter.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/WithConverter.java b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/WithConverter.java
new file mode 100644
index 0000000..b831afc
--- /dev/null
+++ b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/WithConverter.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.inject.api;
+
+
+import javax.config.spi.Converter;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Annotation to define a type adapter to be used before injecting a configured key, or for applying changes.
+ * This will override any other adapter for performing the type conversion before
+ * injecting the field keys.
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target(value = {ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
+public @interface WithConverter {
+
+ /**
+ * Define a custom adapter or codec that should be used to adapt the configuration entry injected. This overrides any
+ * general org.apache.tamaya.core.internal registered. If no adapter is defined (default) and no corresponding adapter is
+ * registered, it is handled as a deployment error.
+ * @return adapter used to change the configuration entry.
+ */
+ Class<? extends Converter<?>> value();
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/WithPropertyConverter.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/WithPropertyConverter.java b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/WithPropertyConverter.java
deleted file mode 100644
index 499360c..0000000
--- a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/WithPropertyConverter.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.inject.api;
-
-
-import org.apache.tamaya.spi.PropertyConverter;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotation to define a type adapter to be used before injecting a configured key, or for applying changes.
- * This will override any other adapter for performing the type conversion before
- * injecting the field keys.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(value = {ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
-public @interface WithPropertyConverter {
-
- /**
- * Define a custom adapter or codec that should be used to adapt the configuration entry injected. This overrides any
- * general org.apache.tamaya.core.internal registered. If no adapter is defined (default) and no corresponding adapter is
- * registered, it is handled as a deployment error.
- * @return adapter used to change the configuration entry.
- */
- Class<? extends PropertyConverter<?>> value();
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/package-info.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/package-info.java b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/package-info.java
index b5d8bc3..b0cac4e 100644
--- a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/package-info.java
+++ b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/api/package-info.java
@@ -17,6 +17,6 @@
* under the License.
*/
/**
- * Common njection API.
+ * Common injection API.
*/
package org.apache.tamaya.inject.api;
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/BaseDynamicValue.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/BaseDynamicValue.java b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/BaseDynamicValue.java
index e8a081a..87da886 100644
--- a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/BaseDynamicValue.java
+++ b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/BaseDynamicValue.java
@@ -18,18 +18,15 @@
*/
package org.apache.tamaya.inject.spi;
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.TypeLiteral;
+import javax.config.Config;
import org.apache.tamaya.inject.api.DynamicValue;
import org.apache.tamaya.inject.api.UpdatePolicy;
-import org.apache.tamaya.spi.ConversionContext;
-import org.apache.tamaya.spi.PropertyConverter;
+import javax.config.spi.Converter;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
-import java.io.Serializable;
import java.lang.ref.WeakReference;
+import java.lang.reflect.Type;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Supplier;
@@ -72,7 +69,7 @@ public abstract class BaseDynamicValue<T> implements DynamicValue<T> {
*/
private UpdatePolicy updatePolicy = UpdatePolicy.NEVER;
/** The targe type. */
- private TypeLiteral<T> targetType;
+ private Type targetType;
/**
* The current value, never null.
*/
@@ -95,9 +92,9 @@ public abstract class BaseDynamicValue<T> implements DynamicValue<T> {
* @param targetType the target type.
* @param keys the candidate keys.
*/
- public BaseDynamicValue(Object owner, String propertyName, TypeLiteral targetType, List<String> keys){
+ public BaseDynamicValue(Object owner, String propertyName, Type targetType, List<String> keys){
if(keys == null || keys.isEmpty()){
- throw new ConfigException("At least one key is required.");
+ throw new IllegalArgumentException("At least one key is required.");
}
this.owner = owner;
this.propertyName = Objects.requireNonNull(propertyName);
@@ -125,7 +122,7 @@ public abstract class BaseDynamicValue<T> implements DynamicValue<T> {
* Get the configuration to evaluate.
* @return the configuration, never null.
*/
- protected abstract Configuration getConfiguration();
+ protected abstract Config getConfiguration();
/**
* Get the corresponding property name.
@@ -155,7 +152,7 @@ public abstract class BaseDynamicValue<T> implements DynamicValue<T> {
* Get the target type.
* @return the target type, not null.
*/
- public TypeLiteral<T> getTargetType(){
+ public Type getTargetType(){
return targetType;
}
@@ -207,7 +204,7 @@ public abstract class BaseDynamicValue<T> implements DynamicValue<T> {
@Override
public boolean updateValue() {
- Configuration config = getConfiguration();
+ Config config = getConfiguration();
T val = evaluateValue();
if(value == null){
value = val;
@@ -262,48 +259,21 @@ public abstract class BaseDynamicValue<T> implements DynamicValue<T> {
* Allows to customize type conversion if needed, e.g. based on some annotations defined.
* @return the custom converter, which replaces the default converters, ot null.
*/
- protected PropertyConverter<T> getCustomConverter(){
+ protected Converter<T> getCustomConverter(){
return null;
}
@Override
public T evaluateValue() {
T value = null;
- List<PropertyConverter<T>> converters = new ArrayList<>();
- if (this.getCustomConverter() != null) {
- converters.add(this.getCustomConverter());
- }
- converters.addAll(getConfiguration().getContext().getPropertyConverters(targetType));
-
+ Converter<T> customConverter = getCustomConverter();
for (String key : keys) {
- ConversionContext ctx = new ConversionContext.Builder(key, targetType).build();
- String stringVal = getConfiguration().getOrDefault(key, String.class, null);
- if(stringVal!=null) {
- if(String.class.equals(targetType.getType())){
- value = (T)stringVal;
- }
- for(PropertyConverter<T> conv:converters){
- try{
- value = conv.convert(stringVal, ctx);
- if(value!=null){
- break;
- }
- }catch(Exception e){
- LOG.warning("failed to convert: " + ctx);
- }
- }
- }
- }
- if(value == null && defaultValue!=null){
- ConversionContext ctx = new ConversionContext.Builder("<defaultValue>", targetType).build();
- for(PropertyConverter<T> conv:converters){
- try{
- value = conv.convert(defaultValue, ctx);
- if(value!=null){
- break;
- }
- }catch(Exception e){
- LOG.warning("failed to convert: " + ctx);
+ Optional<String> stringVal = getConfiguration().getOptionalValue(key, String.class);
+ if(stringVal.isPresent()) {
+ if(customConverter!=null){
+ return customConverter.convert(stringVal.get());
+ }else{
+ return (T)getConfiguration().getValue(key, (Class)getTargetType());
}
}
}
@@ -324,7 +294,7 @@ public abstract class BaseDynamicValue<T> implements DynamicValue<T> {
* Performs a commit, if necessary, and returns the current value.
*
* @return the non-null value held by this {@code DynamicValue}
- * @throws org.apache.tamaya.ConfigException if there is no value present
+ * @throws IllegalArgumentException if there is no value present
* @see DynamicValue#isPresent()
*/
@Override
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/ConfiguredField.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/ConfiguredField.java b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/ConfiguredField.java
index 94c0091..30740c6 100644
--- a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/ConfiguredField.java
+++ b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/ConfiguredField.java
@@ -18,8 +18,7 @@
*/
package org.apache.tamaya.inject.spi;
-import org.apache.tamaya.Configuration;
-
+import javax.config.Config;
import java.lang.reflect.Field;
import java.util.Collection;
@@ -64,5 +63,5 @@ public interface ConfiguredField {
* @param instance the instance, not null.
* @param config the configuration, not null.
*/
- void configure(Object instance, Configuration config);
+ void configure(Object instance, Config config);
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/ConfiguredMethod.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/ConfiguredMethod.java b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/ConfiguredMethod.java
index d8b0d09..00775c5 100644
--- a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/ConfiguredMethod.java
+++ b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/ConfiguredMethod.java
@@ -18,8 +18,7 @@
*/
package org.apache.tamaya.inject.spi;
-import org.apache.tamaya.Configuration;
-
+import javax.config.Config;
import java.lang.reflect.Method;
import java.util.Collection;
@@ -64,7 +63,7 @@ public interface ConfiguredMethod {
*
* @param instance the target instance, not null.
* @param config the configuration, not null.
- * @throws org.apache.tamaya.ConfigException if evaluation or conversion failed.
+ * @throws IllegalArgumentException if evaluation or conversion failed.
*/
- void configure(Object instance, Configuration config);
+ void configure(Object instance, Config config);
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/ConfiguredType.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/ConfiguredType.java b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/ConfiguredType.java
index 0f81dc7..f7a10ad 100644
--- a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/ConfiguredType.java
+++ b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/ConfiguredType.java
@@ -18,8 +18,7 @@
*/
package org.apache.tamaya.inject.spi;
-import org.apache.tamaya.Configuration;
-
+import javax.config.Config;
import java.util.Collection;
/**
@@ -57,7 +56,7 @@ public interface ConfiguredType{
* @param instance The instance to be configured, not null.
* @param config the target config, not null.
*/
- void configure(Object instance, Configuration config);
+ void configure(Object instance, Config config);
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/InjectionEvaluator.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/InjectionEvaluator.java b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/InjectionEvaluator.java
new file mode 100644
index 0000000..4374819
--- /dev/null
+++ b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/InjectionEvaluator.java
@@ -0,0 +1,159 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.inject.spi;
+
+import org.apache.tamaya.inject.api.ConfigDefaultSections;
+import org.apache.tamaya.inject.api.ConfigFallbackKeys;
+
+import javax.config.inject.ConfigProperty;
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.Field;
+import java.lang.reflect.Member;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Utility class with several commonly used functions.
+ */
+public final class InjectionEvaluator {
+
+ private InjectionEvaluator(){}
+
+
+ /**
+ * Collects all keys to be be accessed as defined by any annotations of type
+ * {@link ConfigDefaultSections}, {@link javax.config.inject.ConfigProperty}.
+ * @param member the (optionally) annotated member instance
+ * @return the regarding key list to be accessed fomr the {@link javax.config.Config}.
+ */
+ public static List<String> getKeys(AccessibleObject member) {
+ if(member instanceof Field){
+ Field f = (Field)member;
+ return getKeys(f, f.getDeclaringClass().getAnnotation(ConfigDefaultSections.class));
+ } else if(member instanceof Method){
+ Method m = (Method)member;
+ return getKeys(m, m.getDeclaringClass().getAnnotation(ConfigDefaultSections.class));
+ }
+ return Collections.emptyList();
+ }
+
+ /**
+ * Evaluates all absolute configuration keys based on the annotations found in a field/class.
+ *
+ * @param method method to analyze.
+ * @return the list current keys in order how they should be processed/looked up.
+ */
+ private static List<String> getKeys(Method method, ConfigDefaultSections sectionAnnot) {
+ return getKeys(method,
+ sectionAnnot,
+ method.getAnnotation(ConfigProperty.class),
+ method.getAnnotation(ConfigFallbackKeys.class));
+ }
+
+ /**
+ * Evaluates all absolute configuration keys based on the annotations found in a field/class.
+ *
+ * @param field field to analyze.
+ * @return the list current keys in order how they should be processed/looked up.
+ */
+ private static List<String> getKeys(Field field, ConfigDefaultSections sectionAnnot) {
+ return getKeys(field,
+ sectionAnnot,
+ field.getAnnotation(ConfigProperty.class),
+ field.getAnnotation(ConfigFallbackKeys.class));
+ }
+
+ /**
+ * Evaluates all absolute configuration keys based on the annotations found in a class.
+ *
+ * @param member member to analyze.
+ * @param sectionsAnnot the (optional) annotation definining sections to be looked up.
+ * @param propertyAnnotation the annotation on field/method level that may defined one or
+ * several keys to be looked up (in absolute or relative form).
+ * @return the list current keys in order how they should be processed/looked up.
+ */
+ private static List<String> getKeys(Member member,
+ ConfigDefaultSections sectionsAnnot,
+ ConfigProperty propertyAnnotation,
+ ConfigFallbackKeys configFallbackKeys) {
+ List<String> result = new ArrayList<>();
+ List<String> memberKeys = new ArrayList<>();
+ if(propertyAnnotation!=null && !propertyAnnotation.name().isEmpty()){
+ memberKeys.add(propertyAnnotation.name());
+ }
+ if(configFallbackKeys !=null){
+ memberKeys.addAll(Arrays.asList(configFallbackKeys.value()));
+ }
+ if (memberKeys.isEmpty()) {
+ memberKeys.add(member.getName());
+ }
+ List<String> areaKeys = getSectionKeys(member, sectionsAnnot);
+ for(String memberKey:memberKeys){
+ if (memberKey.startsWith("[") && memberKey.endsWith("]")) {
+ // absolute key, strip away brackets, take key as is
+ result.add(memberKey.substring(1, memberKey.length()-1));
+ }else{
+ for(String areaKey:areaKeys) {
+ result.add(areaKey + '.' + memberKey);
+ }
+ result.add(memberKey);
+ }
+ }
+ return result;
+ }
+
+ private static List<String> getSectionKeys(Member member, ConfigDefaultSections sectionsAnnot) {
+ if(member instanceof Field){
+ Field f = (Field)member;
+ return getSectionKeys(f,sectionsAnnot);
+ } else if(member instanceof Method){
+ Method m = (Method)member;
+ return getSectionKeys(m,sectionsAnnot);
+ }
+ return Collections.emptyList();
+ }
+
+ private static List<String> getSectionKeys(Method method, ConfigDefaultSections sectionAnnot) {
+ List<String> areaKeys = new ArrayList<>();
+ if (sectionAnnot != null && sectionAnnot.value().length>0) {
+ // Remove original entry, since it will be replaced with prefixed entries
+ areaKeys.addAll(Arrays.asList(sectionAnnot.value()));
+ }else{
+ areaKeys.add(method.getDeclaringClass().getName());
+ areaKeys.add(method.getDeclaringClass().getSimpleName());
+ }
+ return areaKeys;
+ }
+
+ private static List<String> getSectionKeys(Field field, ConfigDefaultSections sectionAnnot) {
+ List<String> areaKeys = new ArrayList<>();
+ if (sectionAnnot != null && sectionAnnot.value().length>0) {
+ // Remove original entry, since it will be replaced with prefixed entries
+ areaKeys.addAll(Arrays.asList(sectionAnnot.value()));
+ }else{
+ areaKeys.add(field.getDeclaringClass().getName());
+ areaKeys.add(field.getDeclaringClass().getSimpleName());
+ }
+ return areaKeys;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/InjectionUtils.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/InjectionUtils.java b/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/InjectionUtils.java
deleted file mode 100644
index d5ab2ef..0000000
--- a/modules/injection/injection-api/src/main/java/org/apache/tamaya/inject/spi/InjectionUtils.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.inject.spi;
-
-import org.apache.tamaya.inject.api.Config;
-import org.apache.tamaya.inject.api.ConfigDefaultSections;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Member;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * Utility class with several commonly used functions.
- */
-public final class InjectionUtils {
-
- private InjectionUtils(){}
-
-
- /**
- * Collects all keys to be be accessed as defined by any annotations of type
- * {@link ConfigDefaultSections}, {@link Config}.
- * @param field the (optionally) annotated field instance
- * @return the regarding key list to be accessed fomr the {@link org.apache.tamaya.Configuration}.
- */
- public static List<String> getKeys(Field field) {
- ConfigDefaultSections areasAnnot = field.getDeclaringClass().getAnnotation(ConfigDefaultSections.class);
- return InjectionUtils.evaluateKeys(field, areasAnnot, field.getAnnotation(Config.class));
- }
-
- /**
- * Collects all keys to be be accessed as defined by any annotations of type
- * {@link ConfigDefaultSections}, {@link Config}.
- * @param method the (optionally) annotated method instance
- * @return the regarding key list to be accessed fomr the {@link org.apache.tamaya.Configuration}.
- */
- public static List<String> getKeys(Method method) {
- ConfigDefaultSections areasAnnot = method.getDeclaringClass().getAnnotation(ConfigDefaultSections.class);
- return InjectionUtils.evaluateKeys(method, areasAnnot, method.getAnnotation(Config.class));
- }
-
- /**
- * Evaluates all absolute configuration keys based on the member name found.
- *
- * @param member member to analyze.
- * @param sectionAnnot the (optional) annotation defining areas to be looked up.
- * @return the list of current keys in order how they should be processed/looked up.
- */
- public static List<String> evaluateKeys(Member member, ConfigDefaultSections sectionAnnot) {
- List<String> keys = new ArrayList<>();
- List<String> areaKeys = evaluateSectionKeys(member, sectionAnnot);
- String key = null;
- String name = member.getName();
- if (name.startsWith("get") || name.startsWith("set")) {
- key = Character.toLowerCase(name.charAt(3)) + name.substring(4);
- } else {
- key = Character.toLowerCase(name.charAt(0)) + name.substring(1);
- }
- for(String areaKey:areaKeys) {
- keys.add(areaKey + '.' + key);
- }
- keys.add(key);
- return keys;
- }
-
- /**
- * Evaluates all absolute configuration keys based on the annotations found in a class.
- *
- * @param member member to analyze.
- * @param areasAnnot the (optional) annotation definining areas to be looked up.
- * @param propertyAnnotation the annotation on field/method level that may defined one or
- * several keys to be looked up (in absolute or relative form).
- * @return the list current keys in order how they should be processed/looked up.
- */
- public static List<String> evaluateKeys(Member member, ConfigDefaultSections areasAnnot, Config propertyAnnotation) {
- if(propertyAnnotation==null){
- return evaluateKeys(member, areasAnnot);
- }
- List<String> result = new ArrayList<>();
- List<String> memberKeys = new ArrayList<>(Arrays.asList(propertyAnnotation.value()));
- if (memberKeys.isEmpty()) {
- memberKeys.add(member.getName());
- }
- List<String> areaKeys = evaluateSectionKeys(member, areasAnnot);
- for(String memberKey:memberKeys){
- if (memberKey.startsWith("[") && memberKey.endsWith("]")) {
- // absolute key, strip away brackets, take key as is
- result.add(memberKey.substring(1, memberKey.length()-1));
- }else{
- for(String areaKey:areaKeys) {
- result.add(areaKey + '.' + memberKey);
- }
- result.add(memberKey);
- }
- }
- return result;
- }
-
- private static List<String> evaluateSectionKeys(Member member, ConfigDefaultSections sectionAnnot) {
- List<String> areaKeys = new ArrayList<>();
- if (sectionAnnot != null && sectionAnnot.value().length>0) {
- // Remove original entry, since it will be replaced with prefixed entries
- areaKeys.addAll(Arrays.asList(sectionAnnot.value()));
- }else{
- areaKeys.add(member.getDeclaringClass().getName());
- areaKeys.add(member.getDeclaringClass().getSimpleName());
- }
- return areaKeys;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/test/java/org/apache/tamaya/inject/spi/BaseDynamicValueTest.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/test/java/org/apache/tamaya/inject/spi/BaseDynamicValueTest.java b/modules/injection/injection-api/src/test/java/org/apache/tamaya/inject/spi/BaseDynamicValueTest.java
index bb568a5..6f2a88b 100644
--- a/modules/injection/injection-api/src/test/java/org/apache/tamaya/inject/spi/BaseDynamicValueTest.java
+++ b/modules/injection/injection-api/src/test/java/org/apache/tamaya/inject/spi/BaseDynamicValueTest.java
@@ -18,13 +18,11 @@
*/
package org.apache.tamaya.inject.spi;
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
-import org.apache.tamaya.TypeLiteral;
import org.apache.tamaya.inject.api.UpdatePolicy;
import org.junit.Test;
+import javax.config.Config;
+import javax.config.ConfigProvider;
import java.util.Arrays;
import static org.junit.Assert.*;
@@ -36,7 +34,7 @@ public class BaseDynamicValueTest {
new MyDynamicValue("a", "b");
}
- @Test(expected = ConfigException.class)
+ @Test(expected = IllegalArgumentException.class)
public void create_nokeys(){
new MyDynamicValue();
}
@@ -79,12 +77,12 @@ public class BaseDynamicValueTest {
private static final class MyDynamicValue extends BaseDynamicValue{
public MyDynamicValue(String... keys){
- super(null, "test", TypeLiteral.of(String.class), Arrays.asList(keys));
+ super(null, "test", String.class, Arrays.asList(keys));
}
@Override
- protected Configuration getConfiguration() {
- return ConfigurationProvider.getConfiguration();
+ protected Config getConfiguration() {
+ return ConfigProvider.getConfig();
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/injection-api/src/test/java/org/apache/tamaya/inject/spi/InjectionUtilsTest.java
----------------------------------------------------------------------
diff --git a/modules/injection/injection-api/src/test/java/org/apache/tamaya/inject/spi/InjectionUtilsTest.java b/modules/injection/injection-api/src/test/java/org/apache/tamaya/inject/spi/InjectionUtilsTest.java
index fee1a58..4b76d36 100644
--- a/modules/injection/injection-api/src/test/java/org/apache/tamaya/inject/spi/InjectionUtilsTest.java
+++ b/modules/injection/injection-api/src/test/java/org/apache/tamaya/inject/spi/InjectionUtilsTest.java
@@ -18,10 +18,11 @@
*/
package org.apache.tamaya.inject.spi;
-import org.apache.tamaya.inject.api.Config;
import org.apache.tamaya.inject.api.ConfigDefaultSections;
+import org.apache.tamaya.inject.api.ConfigFallbackKeys;
import org.junit.Test;
+import javax.config.inject.ConfigProperty;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
@@ -33,13 +34,14 @@ public class InjectionUtilsTest {
@Test
public void getKeysMethod() {
class Klazz {
- @Config({"val", "val2", "[vvv]"})
+ @ConfigProperty(name="val")
+ @ConfigFallbackKeys({"val2", "[vvv]"})
public void setValue(String field){}
}
Method method = Klazz.class.getMethods()[0];
- List<String> foundKeys = InjectionUtils.getKeys(method);
+ List<String> foundKeys = InjectionEvaluator.getKeys(method);
assertThat(foundKeys).isNotNull()
.contains("org.apache.tamaya.inject.spi.InjectionUtilsTest$1Klazz.val",
@@ -61,7 +63,7 @@ public class InjectionUtilsTest {
Field field = Klazz.class.getFields()[0];
- List<String> foundKeys = InjectionUtils.getKeys(field);
+ List<String> foundKeys = InjectionEvaluator.getKeys(field);
assertThat(foundKeys).isNotNull()
.contains("org.apache.tamaya.inject.spi.InjectionUtilsTest$2Klazz.field",
@@ -80,7 +82,7 @@ public class InjectionUtilsTest {
Field field = Klazz.class.getFields()[0];
- List<String> foundKeys = InjectionUtils.evaluateKeys(field, Klazz.class.getAnnotation(ConfigDefaultSections.class));
+ List<String> foundKeys = InjectionEvaluator.getKeys(field);
assertThat(foundKeys).isNotNull()
.contains("basic.field",
"field");
@@ -90,7 +92,8 @@ public class InjectionUtilsTest {
public void evaluateKeysWithSectionAndMemberAnnotation() {
@ConfigDefaultSections("basic")
class Klazz {
- @Config({"val", "[absoluteVal]"})
+ @ConfigProperty(name="val")
+ @ConfigFallbackKeys({"absoluteVal"})
public String field;
protected String protectedField;
private String privateField;
@@ -98,8 +101,7 @@ public class InjectionUtilsTest {
Field field = Klazz.class.getFields()[0];
- List<String> foundKeys = InjectionUtils.evaluateKeys(field, Klazz.class.getAnnotation(ConfigDefaultSections.class),
- field.getAnnotation(Config.class));
+ List<String> foundKeys = InjectionEvaluator.getKeys(field);
assertThat(foundKeys).isNotNull()
.contains("basic.val", "val",
"absoluteVal");
@@ -108,7 +110,8 @@ public class InjectionUtilsTest {
@Test
public void evaluateKeysWithMemberAnnotation() {
class Klazz {
- @Config({"val", "[absoluteVal]"})
+ @ConfigProperty(name="val")
+ @ConfigFallbackKeys("[absoluteVal]")
public String field;
protected String protectedField;
private String privateField;
@@ -116,8 +119,7 @@ public class InjectionUtilsTest {
Field field = Klazz.class.getFields()[0];
- List<String> foundKeys = InjectionUtils.evaluateKeys(field, null,
- field.getAnnotation(Config.class));
+ List<String> foundKeys = InjectionEvaluator.getKeys(field);
assertThat(foundKeys).isNotNull()
.contains("Klazz.val", "val",
"absoluteVal");
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/pom.xml
----------------------------------------------------------------------
diff --git a/modules/injection/pom.xml b/modules/injection/pom.xml
index d811715..c7da6e0 100644
--- a/modules/injection/pom.xml
+++ b/modules/injection/pom.xml
@@ -35,4 +35,13 @@
<module>cdi</module>
</modules>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.tamaya</groupId>
+ <artifactId>tamaya-core</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
</project>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/pom.xml
----------------------------------------------------------------------
diff --git a/modules/injection/standalone/pom.xml b/modules/injection/standalone/pom.xml
index e3f646e..f677ca2 100644
--- a/modules/injection/standalone/pom.xml
+++ b/modules/injection/standalone/pom.xml
@@ -35,7 +35,7 @@ under the License.
<dependencies>
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-api</artifactId>
+ <artifactId>tamaya-base</artifactId>
<version>${tamaya-apicore.version}</version>
<scope>provided</scope>
</dependency>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/ConfigurationInjector.java
----------------------------------------------------------------------
diff --git a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/ConfigurationInjector.java b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/ConfigurationInjector.java
index 898e937..042efc0 100644
--- a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/ConfigurationInjector.java
+++ b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/ConfigurationInjector.java
@@ -19,8 +19,7 @@
package org.apache.tamaya.inject;
-import org.apache.tamaya.Configuration;
-
+import javax.config.Config;
import java.util.function.Supplier;
/**
@@ -51,7 +50,7 @@ public interface ConfigurationInjector {
* @param config the configuration to be used for injection.
* @return the configured instance (allows chaining of operations).
*/
- <T> T configure(T instance, Configuration config);
+ <T> T configure(T instance, Config config);
/**
* Creates a template implementing the annotated methods based on current configuration data.
@@ -70,7 +69,7 @@ public interface ConfigurationInjector {
* @param templateType the type of the template to be created.
* @return the configured template.
*/
- <T> T createTemplate(Class<T> templateType, Configuration config);
+ <T> T createTemplate(Class<T> templateType, Config config);
/**
@@ -90,6 +89,13 @@ public interface ConfigurationInjector {
* @param <T> the target type.
* @return a supplier creating configured instances of {@code T}.
*/
- <T> Supplier<T> getConfiguredSupplier(Supplier<T> supplier, Configuration config);
+ <T> Supplier<T> getConfiguredSupplier(Supplier<T> supplier, Config config);
+ /**
+ * Method checks if the given instance is annotated for being configured using {@link javax.config.inject.ConfigProperty}
+ * annotations.
+ * @param o the instance, not null.
+ * @return true, if the instance has any fields or setter methods annotated with {@link javax.config.inject.ConfigProperty}.
+ */
+ boolean isConfigured(Object o);
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfigTemplateInvocationHandler.java
----------------------------------------------------------------------
diff --git a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfigTemplateInvocationHandler.java b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfigTemplateInvocationHandler.java
index fd9f7be..bee17a0 100644
--- a/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfigTemplateInvocationHandler.java
+++ b/modules/injection/standalone/src/main/java/org/apache/tamaya/inject/internal/ConfigTemplateInvocationHandler.java
@@ -18,12 +18,10 @@
*/
package org.apache.tamaya.inject.internal;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
-import org.apache.tamaya.TypeLiteral;
import org.apache.tamaya.inject.api.DynamicValue;
import org.apache.tamaya.inject.spi.ConfiguredType;
+import javax.config.ConfigProvider;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Objects;
@@ -53,7 +51,7 @@ public final class ConfigTemplateInvocationHandler implements InvocationHandler
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- Configuration config = ConfigurationProvider.getConfiguration();
+ javax.config.Config config = ConfigProvider.getConfig();
if ("toString".equals(method.getName())) {
return "Configured Proxy -> " + this.type.getType().getName();
} else if ("hashCode".equals(method.getName())) {
@@ -66,8 +64,6 @@ public final class ConfigTemplateInvocationHandler implements InvocationHandler
if (method.getReturnType() == DynamicValue.class) {
return DefaultDynamicValue.of(proxy, method, config);
}
- String[] retKey = new String[1];
- String configValue = InjectionHelper.getConfigValue(method, retKey, config);
- return InjectionHelper.adaptValue(method, TypeLiteral.of(method.getReturnType()), retKey[0], configValue);
+ return InjectionHelper.getConfigValue(method, method.getReturnType(), config);
}
}
[16/18] incubator-tamaya-extensions git commit: Rewrite/adaptation
based on JSR API.
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/json/src/main/java/org/apache/tamaya/json/JSONVisitor.java
----------------------------------------------------------------------
diff --git a/modules/formats/json/src/main/java/org/apache/tamaya/json/JSONVisitor.java b/modules/formats/json/src/main/java/org/apache/tamaya/json/JSONVisitor.java
index 92c81fe..07208d9 100644
--- a/modules/formats/json/src/main/java/org/apache/tamaya/json/JSONVisitor.java
+++ b/modules/formats/json/src/main/java/org/apache/tamaya/json/JSONVisitor.java
@@ -18,10 +18,7 @@
*/
package org.apache.tamaya.json;
-import java.util.ArrayDeque;
-import java.util.Deque;
-import java.util.Iterator;
-import java.util.Map;
+import java.util.*;
import javax.json.JsonArray;
import javax.json.JsonObject;
@@ -29,7 +26,6 @@ import javax.json.JsonString;
import javax.json.JsonStructure;
import javax.json.JsonValue;
-import org.apache.tamaya.ConfigException;
/**
* Visitor implementation to read a JSON formatted input source.
@@ -64,7 +60,7 @@ class JSONVisitor {
case NUMBER: value = jsonValue.toString(); break;
case STRING: value = ((JsonString) jsonValue).getString(); break;
default:
- throw new ConfigException("Internal failure while processing JSON document.");
+ throw new IllegalStateException("Internal failure while processing JSON document.");
}
targetStore.put(key, value);
@@ -73,9 +69,11 @@ class JSONVisitor {
JsonObject node = (JsonObject) current.getValue();
stack.push(new VisitingContext(node, key));
} else if (current.getValue() instanceof JsonArray) {
- throw new ConfigException("Arrays are not supported at the moment.");
+ String key = stack.peek().getNSPrefix() + current.getKey();
+ JsonArray array = (JsonArray) current.getValue();
+ stack.push(new VisitingContext(array, key));
} else {
- throw new ConfigException("Internal failure while processing JSON document.");
+ throw new IllegalStateException("Internal failure while processing JSON document.");
}
goOn = stack.peek().hasNext();
@@ -94,6 +92,7 @@ class JSONVisitor {
private static class VisitingContext {
private final String namespace;
private final JsonObject node;
+ private final JsonArray array;
private final Iterator<Map.Entry<String, JsonValue>> elements;
public VisitingContext(JsonObject node) {
@@ -103,9 +102,45 @@ class JSONVisitor {
public VisitingContext(JsonObject rootNode, String currentNamespace) {
namespace = currentNamespace;
node = rootNode;
+ array = null;
elements = node.entrySet().iterator();
}
+ public VisitingContext(JsonArray array, String currentNamespace) {
+ namespace = currentNamespace;
+ this.array = array;
+ this.node = null;
+ Map<String,JsonValue> arrayMap = new HashMap<>();
+ arrayMap.put("[array]", formatArray(array.iterator()));
+ elements = arrayMap.entrySet().iterator();
+ }
+
+ private JsonValue formatArray(Iterator<JsonValue> iterator) {
+ StringBuilder b = new StringBuilder();
+ iterator.forEachRemaining(r -> {b.append(r.toString().replace(",", "\\,")).append(',');});
+ if(b.length()>0){
+ b.setLength(b.length()-1);
+ }
+ String elemsAsString = b.toString();
+ return new JsonString(){
+
+ @Override
+ public ValueType getValueType() {
+ return ValueType.STRING;
+ }
+
+ @Override
+ public String getString() {
+ return elemsAsString;
+ }
+
+ @Override
+ public CharSequence getChars() {
+ return elemsAsString;
+ }
+ };
+ }
+
public Map.Entry<String, JsonValue> nextElement() {
return elements.next();
}
@@ -116,6 +151,9 @@ class JSONVisitor {
}
public String getNSPrefix() {
+ if(array!=null){
+ return namespace;
+ }
return namespace.isEmpty() ? namespace : namespace + ".";
}
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/json/src/test/java/org/apache/tamaya/json/JSONVisitorTest.java
----------------------------------------------------------------------
diff --git a/modules/formats/json/src/test/java/org/apache/tamaya/json/JSONVisitorTest.java b/modules/formats/json/src/test/java/org/apache/tamaya/json/JSONVisitorTest.java
index 209b438..73e20ed 100644
--- a/modules/formats/json/src/test/java/org/apache/tamaya/json/JSONVisitorTest.java
+++ b/modules/formats/json/src/test/java/org/apache/tamaya/json/JSONVisitorTest.java
@@ -26,7 +26,6 @@ import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonValue;
-import org.apache.tamaya.ConfigException;
import org.junit.Test;
public class JSONVisitorTest {
@@ -67,7 +66,7 @@ public class JSONVisitorTest {
assertThat(targetStore).isEmpty();
}
- @Test(expected = ConfigException.class)
+ @Test
public void arraysAreNotSupported() {
JsonObject startNode = Json.createObjectBuilder().//
add("arrayKey", Json.createArrayBuilder().build()).//
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/json/src/test/java/org/apache/tamaya/yaml/CommonJSONTestCaseCollection.java
----------------------------------------------------------------------
diff --git a/modules/formats/json/src/test/java/org/apache/tamaya/yaml/CommonJSONTestCaseCollection.java b/modules/formats/json/src/test/java/org/apache/tamaya/yaml/CommonJSONTestCaseCollection.java
index e1f94cf..9636471 100644
--- a/modules/formats/json/src/test/java/org/apache/tamaya/yaml/CommonJSONTestCaseCollection.java
+++ b/modules/formats/json/src/test/java/org/apache/tamaya/yaml/CommonJSONTestCaseCollection.java
@@ -27,20 +27,20 @@ import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.URL;
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-import org.apache.tamaya.spisupport.PropertySourceComparator;
+import org.apache.tamaya.base.configsource.ConfigSourceComparator;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matchers;
import org.junit.Test;
+import javax.config.spi.ConfigSource;
+
/**
* Class with a collection of common test cases each JSON processing
* class must be able to pass.
*/
public abstract class CommonJSONTestCaseCollection {
- abstract PropertySource getPropertiesFrom(URL source) throws Exception;
+ abstract ConfigSource getPropertiesFrom(URL source) throws Exception;
@Test
public void canReadNonLatinCharacters() throws Exception {
@@ -49,12 +49,12 @@ public abstract class CommonJSONTestCaseCollection {
assertThat(configURL, Matchers.notNullValue());
- PropertySource propertySource = getPropertiesFrom(configURL);
+ ConfigSource propertySource = getPropertiesFrom(configURL);
- assertThat(propertySource.get("name"), Matchers.notNullValue());
- assertThat(propertySource.get("name").getValue(), equalTo("\u041e\u043b\u0438\u0432\u0435\u0440"));
- assertThat(propertySource.get("\u0444\u0430\u043c\u0438\u043b\u0438\u044f"), Matchers.notNullValue());
- assertThat(propertySource.get("\u0444\u0430\u043c\u0438\u043b\u0438\u044f").getValue(), Matchers.equalTo("Fischer"));
+ assertThat(propertySource.getValue("name"), Matchers.notNullValue());
+ assertThat(propertySource.getValue("name"), equalTo("\u041e\u043b\u0438\u0432\u0435\u0440"));
+ assertThat(propertySource.getValue("\u0444\u0430\u043c\u0438\u043b\u0438\u044f"), Matchers.notNullValue());
+ assertThat(propertySource.getValue("\u0444\u0430\u043c\u0438\u043b\u0438\u044f"), Matchers.equalTo("Fischer"));
}
@Test
@@ -64,11 +64,11 @@ public abstract class CommonJSONTestCaseCollection {
assertThat(configURL, Matchers.notNullValue());
- PropertySource propertySource = getPropertiesFrom(configURL);
+ ConfigSource propertySource = getPropertiesFrom(configURL);
- assertThat(propertySource.get("onamae"), Matchers.notNullValue());
+ assertThat(propertySource.getValue("onamae"), Matchers.notNullValue());
// 霊屋 = Tamaya
- assertThat(propertySource.get("onamae").getValue(), equalTo("\u970a\u5c4b"));
+ assertThat(propertySource.getValue("onamae"), equalTo("\u970a\u5c4b"));
}
@Test
@@ -78,20 +78,20 @@ public abstract class CommonJSONTestCaseCollection {
assertThat(configURL, CoreMatchers.notNullValue());
- PropertySource properties = getPropertiesFrom(configURL);
+ ConfigSource properties = getPropertiesFrom(configURL);
assertTrue(properties.getProperties().keySet().size()>=5);
- PropertyValue keyB = properties.get("b");
- PropertyValue keyDO = properties.get("d.o");
- PropertyValue keyDP = properties.get("d.p");
+ String keyB = properties.getValue("b");
+ String keyDO = properties.getValue("d.o");
+ String keyDP = properties.getValue("d.p");
assertThat(keyB, notNullValue());
- assertThat(keyB.getValue(), equalTo("B"));
+ assertThat(keyB, equalTo("B"));
assertThat(keyDO, notNullValue());
- assertThat(keyDO.getValue(), equalTo("O"));
+ assertThat(keyDO, equalTo("O"));
assertThat(keyDP, Matchers.notNullValue());
- assertThat(keyDP.getValue(), is("P"));
+ assertThat(keyDP, is("P"));
}
@Test
@@ -102,28 +102,28 @@ public abstract class CommonJSONTestCaseCollection {
assertThat(configURL, CoreMatchers.notNullValue());
- PropertySource properties = getPropertiesFrom(configURL);
+ ConfigSource properties = getPropertiesFrom(configURL);
assertTrue(properties.getProperties().keySet().size()>=4);
- PropertyValue keyA = properties.get("a");
- PropertyValue keyDO = properties.get("b.o");
- PropertyValue keyDP = properties.get("b.p");
- PropertyValue keyC = properties.get("c");
+ String keyA = properties.getValue("a");
+ String keyDO = properties.getValue("b.o");
+ String keyDP = properties.getValue("b.p");
+ String keyC = properties.getValue("c");
assertThat(keyA, notNullValue());
- assertThat(keyA.getValue(), is("A"));
+ assertThat(keyA, is("A"));
assertThat(keyC, notNullValue());
- assertThat(keyC.getValue(), equalTo("C"));
+ assertThat(keyC, equalTo("C"));
assertThat(keyDO, notNullValue());
- assertThat(keyDO.getValue(), equalTo("O"));
+ assertThat(keyDO, equalTo("O"));
assertThat(keyDP, notNullValue());
- assertThat(keyDP.getValue(), is("P"));
+ assertThat(keyDP, is("P"));
}
- @Test(expected = IOException.class)
- public void canHandleIllegalJSONFileWhichContainsAnArray() throws Exception {
- URL configURL = CommonJSONTestCaseCollection.class.getResource("/configs/invalid/with-array.json");
+ @Test
+ public void canHandleJSONFileWhichContainsAnArray() throws Exception {
+ URL configURL = CommonJSONTestCaseCollection.class.getResource("/configs/valid/with-array.json");
assertThat(configURL, CoreMatchers.notNullValue());
@@ -154,9 +154,9 @@ public abstract class CommonJSONTestCaseCollection {
assertThat(configURL, CoreMatchers.notNullValue());
- PropertySource properties = getPropertiesFrom(configURL);
+ ConfigSource properties = getPropertiesFrom(configURL);
- assertThat(PropertySourceComparator.getOrdinal(properties), is(16784));
+ assertThat(ConfigSourceComparator.getOrdinal(properties), is(16784));
}
@Test
@@ -165,20 +165,20 @@ public abstract class CommonJSONTestCaseCollection {
assertThat(configURL, CoreMatchers.notNullValue());
- PropertySource properties = getPropertiesFrom(configURL);
+ ConfigSource properties = getPropertiesFrom(configURL);
assertTrue(properties.getProperties().keySet().size()>=3);
- PropertyValue keyA = properties.get("a");
- PropertyValue keyB = properties.get("b");
- PropertyValue keyC = properties.get("c");
+ String keyA = properties.getValue("a");
+ String keyB = properties.getValue("b");
+ String keyC = properties.getValue("c");
assertThat(keyA, notNullValue());
- assertThat(keyA.getValue(), equalTo("A"));
+ assertThat(keyA, equalTo("A"));
assertThat(keyB, notNullValue());
- assertThat(keyB.getValue(), is("B"));
+ assertThat(keyB, is("B"));
assertThat(keyC, notNullValue());
- assertThat(keyC.getValue(), is("C"));
+ assertThat(keyC, is("C"));
}
@Test(expected = IOException.class)
@@ -187,7 +187,7 @@ public abstract class CommonJSONTestCaseCollection {
assertThat(configURL, CoreMatchers.notNullValue());
- PropertySource properties = getPropertiesFrom(configURL);
+ ConfigSource properties = getPropertiesFrom(configURL);
properties.getProperties();
}
@@ -198,7 +198,7 @@ public abstract class CommonJSONTestCaseCollection {
assertThat(configURL, CoreMatchers.notNullValue());
- PropertySource properties = getPropertiesFrom(configURL);
+ ConfigSource properties = getPropertiesFrom(configURL);
assertTrue(properties.getProperties().keySet().size()>=0);
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/json/src/test/java/org/apache/tamaya/yaml/JSONFormatTest.java
----------------------------------------------------------------------
diff --git a/modules/formats/json/src/test/java/org/apache/tamaya/yaml/JSONFormatTest.java b/modules/formats/json/src/test/java/org/apache/tamaya/yaml/JSONFormatTest.java
index 216573e..ae1e6d2 100644
--- a/modules/formats/json/src/test/java/org/apache/tamaya/yaml/JSONFormatTest.java
+++ b/modules/formats/json/src/test/java/org/apache/tamaya/yaml/JSONFormatTest.java
@@ -20,11 +20,11 @@ package org.apache.tamaya.yaml;
import org.apache.tamaya.format.ConfigurationData;
-import org.apache.tamaya.format.MappedConfigurationDataPropertySource;
+import org.apache.tamaya.format.MappedConfigurationDataConfigSource;
import org.apache.tamaya.json.JSONFormat;
-import org.apache.tamaya.spi.PropertySource;
import org.junit.Test;
+import javax.config.spi.ConfigSource;
import java.io.InputStream;
import java.net.URL;
@@ -67,10 +67,10 @@ public class JSONFormatTest extends CommonJSONTestCaseCollection {
}
@Override
- PropertySource getPropertiesFrom(URL source) throws Exception {
+ ConfigSource getPropertiesFrom(URL source) throws Exception {
try (InputStream is = source.openStream()) {
ConfigurationData data = format.readConfiguration(source.toString(), is);
- return new MappedConfigurationDataPropertySource(data);
+ return new MappedConfigurationDataConfigSource(data);
}
}
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/json/src/test/java/org/apache/tamaya/yaml/JSONPropertySourceTest.java
----------------------------------------------------------------------
diff --git a/modules/formats/json/src/test/java/org/apache/tamaya/yaml/JSONPropertySourceTest.java b/modules/formats/json/src/test/java/org/apache/tamaya/yaml/JSONPropertySourceTest.java
index 0555bb8..3e9126a 100644
--- a/modules/formats/json/src/test/java/org/apache/tamaya/yaml/JSONPropertySourceTest.java
+++ b/modules/formats/json/src/test/java/org/apache/tamaya/yaml/JSONPropertySourceTest.java
@@ -24,11 +24,12 @@ import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.URL;
-import org.apache.tamaya.json.JSONPropertySource;
-import org.apache.tamaya.spi.PropertySource;
+import org.apache.tamaya.json.JSONConfigSource;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
+import javax.config.spi.ConfigSource;
+
public class JSONPropertySourceTest extends CommonJSONTestCaseCollection {
@Test
@@ -37,7 +38,7 @@ public class JSONPropertySourceTest extends CommonJSONTestCaseCollection {
assertThat(configURL, CoreMatchers.notNullValue());
- JSONPropertySource source = new JSONPropertySource(configURL, 4);
+ JSONConfigSource source = new JSONConfigSource(configURL, 4);
assertEquals(source.getOrdinal(), 16784);
}
@@ -47,11 +48,11 @@ public class JSONPropertySourceTest extends CommonJSONTestCaseCollection {
assertThat(configURL, CoreMatchers.notNullValue());
- new JSONPropertySource(configURL);
+ new JSONConfigSource(configURL);
}
@Override
- PropertySource getPropertiesFrom(URL source) throws Exception {
- return new JSONPropertySource(source);
+ ConfigSource getPropertiesFrom(URL source) throws Exception {
+ return new JSONConfigSource(source);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/json/src/test/resources/configs/invalid/with-array.json
----------------------------------------------------------------------
diff --git a/modules/formats/json/src/test/resources/configs/invalid/with-array.json b/modules/formats/json/src/test/resources/configs/invalid/with-array.json
deleted file mode 100644
index e623e49..0000000
--- a/modules/formats/json/src/test/resources/configs/invalid/with-array.json
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one
-or more contributor license agreements. See the NOTICE file
-distributed with this work for additional information
-regarding copyright ownership. The ASF licenses this file
-to you 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.
-*/
-{
- "a" : "A",
- "b" : {
- "c" : "C",
- "d" : [
- "1", "2"
- ]
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/json/src/test/resources/configs/valid/with-array.json
----------------------------------------------------------------------
diff --git a/modules/formats/json/src/test/resources/configs/valid/with-array.json b/modules/formats/json/src/test/resources/configs/valid/with-array.json
new file mode 100644
index 0000000..e623e49
--- /dev/null
+++ b/modules/formats/json/src/test/resources/configs/valid/with-array.json
@@ -0,0 +1,27 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you 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.
+*/
+{
+ "a" : "A",
+ "b" : {
+ "c" : "C",
+ "d" : [
+ "1", "2"
+ ]
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/formats/json/src/test/resources/configs/valid/with-explicit-priority.json
----------------------------------------------------------------------
diff --git a/modules/formats/json/src/test/resources/configs/valid/with-explicit-priority.json b/modules/formats/json/src/test/resources/configs/valid/with-explicit-priority.json
index ed7acc2..fe9b61b 100644
--- a/modules/formats/json/src/test/resources/configs/valid/with-explicit-priority.json
+++ b/modules/formats/json/src/test/resources/configs/valid/with-explicit-priority.json
@@ -20,6 +20,6 @@ under the License.
/*
some useful comment here
*/
- "tamaya.ordinal" : 16784,
+ "config_ordinal" : 16784,
"a" : "A" // another comment
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/pom.xml
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/pom.xml b/modules/injection/cdi/pom.xml
index e1e59a5..f033574 100644
--- a/modules/injection/cdi/pom.xml
+++ b/modules/injection/cdi/pom.xml
@@ -100,13 +100,7 @@ under the License.
</dependency>
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-api</artifactId>
- <version>${tamaya-apicore.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-spisupport</artifactId>
+ <artifactId>tamaya-base</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIAwareServiceContext.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIAwareServiceContext.java b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIAwareServiceContext.java
index 20c3bbd..ffb3236 100644
--- a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIAwareServiceContext.java
+++ b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIAwareServiceContext.java
@@ -18,7 +18,6 @@
*/
package org.apache.tamaya.cdi;
-import org.apache.tamaya.ConfigException;
import org.apache.tamaya.spi.ServiceContext;
import javax.annotation.Priority;
@@ -57,13 +56,17 @@ public class CDIAwareServiceContext implements ServiceContext {
private ServiceContext defaultServiceContext = new ServiceLoaderServiceContext();
-
@Override
public <T> T getService(Class<T> serviceType) {
+ return getService(serviceType, ServiceContext.defaultClassLoader());
+ }
+
+ @Override
+ public <T> T getService(Class<T> serviceType, ClassLoader classLoader) {
Object cached = singletons.get(serviceType);
if (cached == null) {
- Collection<T> services = getServices(serviceType);
+ Collection<T> services = getServices(serviceType, classLoader);
if (services.isEmpty()) {
cached = null;
} else {
@@ -78,7 +81,12 @@ public class CDIAwareServiceContext implements ServiceContext {
@Override
public <T> T create(Class<T> serviceType) {
- T serv = getService(serviceType);
+ return create(serviceType, ServiceContext.defaultClassLoader());
+ }
+
+ @Override
+ public <T> T create(Class<T> serviceType, ClassLoader classLoader) {
+ T serv = getService(serviceType, classLoader);
if(serv!=null){
try {
return (T)serv.getClass().newInstance();
@@ -99,7 +107,19 @@ public class CDIAwareServiceContext implements ServiceContext {
*/
@Override
public <T> List<T> getServices(final Class<T> serviceType) {
- List<T> found = defaultServiceContext.getServices(serviceType);
+ return getServices(serviceType, ServiceContext.defaultClassLoader());
+ }
+
+ /**
+ * Loads and registers services.
+ *
+ * @param <T> the concrete type.
+ * @param serviceType The service type.
+ * @return the items found, never {@code null}.
+ */
+ @Override
+ public <T> List<T> getServices(final Class<T> serviceType, ClassLoader classLoader) {
+ List<T> found = defaultServiceContext.getServices(serviceType, classLoader);
BeanManager beanManager = TamayaCDIAccessor.getBeanManager();
Instance<T> cdiInstances = null;
if(beanManager!=null){
@@ -159,7 +179,7 @@ public class CDIAwareServiceContext implements ServiceContext {
*
* @return the service with the highest {@link Priority#value()}
*
- * @throws ConfigException if there are multiple service implementations with the maximum priority
+ * @throws IllegalStateException if there are multiple service implementations with the maximum priority
*/
private <T> T getServiceWithHighestPriority(Collection<T> services, Class<T> serviceType) {
@@ -184,7 +204,7 @@ public class CDIAwareServiceContext implements ServiceContext {
}
if (highestPriorityServiceCount > 1) {
- throw new ConfigException(MessageFormat.format("Found {0} implementations for Service {1} with Priority {2}: {3}",
+ throw new IllegalStateException(MessageFormat.format("Found {0} implementations for Service {1} with Priority {2}: {3}",
highestPriorityServiceCount,
serviceType.getName(),
highestPriority,
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIConfiguredField.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIConfiguredField.java b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIConfiguredField.java
index 3331d9a..5ed58c5 100644
--- a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIConfiguredField.java
+++ b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIConfiguredField.java
@@ -16,9 +16,9 @@
*/
package org.apache.tamaya.cdi;
-import org.apache.tamaya.Configuration;
import org.apache.tamaya.inject.spi.ConfiguredField;
+import javax.config.Config;
import javax.enterprise.inject.spi.InjectionPoint;
import java.lang.reflect.Field;
import java.util.ArrayList;
@@ -66,7 +66,7 @@ class CDIConfiguredField implements ConfiguredField{
}
@Override
- public void configure(Object instance, Configuration config) {
+ public void configure(Object instance, Config config) {
throw new UnsupportedOperationException("Use CDI annotations for configuration injection.");
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIConfiguredMethod.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIConfiguredMethod.java b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIConfiguredMethod.java
index c38fc23..8424f00 100644
--- a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIConfiguredMethod.java
+++ b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIConfiguredMethod.java
@@ -16,9 +16,9 @@
*/
package org.apache.tamaya.cdi;
-import org.apache.tamaya.Configuration;
import org.apache.tamaya.inject.spi.ConfiguredMethod;
+import javax.config.Config;
import javax.enterprise.inject.spi.InjectionPoint;
import java.lang.reflect.Method;
import java.util.ArrayList;
@@ -79,7 +79,7 @@ public class CDIConfiguredMethod implements ConfiguredMethod{
}
@Override
- public void configure(Object instance, Configuration config) {
+ public void configure(Object instance, Config config) {
throw new UnsupportedOperationException("Use CDI annotations for configuration injection.");
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIConfiguredType.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIConfiguredType.java b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIConfiguredType.java
index 0c7e34a..c5fae2f 100644
--- a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIConfiguredType.java
+++ b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/CDIConfiguredType.java
@@ -16,11 +16,11 @@
*/
package org.apache.tamaya.cdi;
-import org.apache.tamaya.Configuration;
import org.apache.tamaya.inject.spi.ConfiguredField;
import org.apache.tamaya.inject.spi.ConfiguredMethod;
import org.apache.tamaya.inject.spi.ConfiguredType;
+import javax.config.Config;
import javax.enterprise.inject.spi.InjectionPoint;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
@@ -65,7 +65,7 @@ class CDIConfiguredType implements ConfiguredType{
}
@Override
- public void configure(Object instance, Configuration config) {
+ public void configure(Object instance, Config config) {
throw new UnsupportedOperationException("Use CDI annotations for configuration injection.");
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/ConfigProducer.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/ConfigProducer.java b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/ConfigProducer.java
new file mode 100644
index 0000000..10e92dc
--- /dev/null
+++ b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/ConfigProducer.java
@@ -0,0 +1,200 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tamaya.cdi;
+
+import org.apache.tamaya.base.convert.ConversionContext;
+import org.apache.tamaya.base.convert.ConverterManager;
+import org.apache.tamaya.functions.Supplier;
+import org.apache.tamaya.inject.api.ConfigDefaultSections;
+import org.apache.tamaya.inject.api.DynamicValue;
+import org.apache.tamaya.inject.api.WithConverter;
+import org.apache.tamaya.spi.ConfigContextSupplier;
+import org.apache.tamaya.spi.TypeLiteral;
+
+import javax.config.Config;
+import javax.config.ConfigProvider;
+import javax.config.inject.ConfigProperty;
+import javax.config.spi.ConfigBuilder;
+import javax.config.spi.ConfigProviderResolver;
+import javax.config.spi.Converter;
+import javax.enterprise.context.ApplicationScoped;
+import javax.enterprise.inject.Instance;
+import javax.enterprise.inject.Produces;
+import javax.enterprise.inject.spi.InjectionPoint;
+import javax.inject.Provider;
+import java.lang.reflect.*;
+import java.util.List;
+import java.util.Optional;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Producer bean for configuration properties.
+ */
+@ApplicationScoped
+public class ConfigProducer {
+
+ private static final Logger LOGGER = Logger.getLogger(ConfigProducer.class.getName());
+
+ private DynamicValue createDynamicValue(final InjectionPoint injectionPoint) {
+ Member member = injectionPoint.getMember();
+ if (member instanceof Field) {
+ return DefaultDynamicValue.of(injectionPoint.getBean(), (Field) member, ConfigProvider.getConfig());
+ } else if (member instanceof Method) {
+ return DefaultDynamicValue.of(injectionPoint.getBean(), (Method) member, ConfigProvider.getConfig());
+ }
+ return null;
+ }
+
+ @Produces
+ @ConfigProperty
+ public Object resolveAndConvert(final InjectionPoint injectionPoint) {
+ if (DynamicValue.class.equals(injectionPoint.getAnnotated().getBaseType())) {
+ return createDynamicValue(injectionPoint);
+ }
+ final ConfigProperty annotation = injectionPoint.getAnnotated().getAnnotation(ConfigProperty.class);
+ final ConfigDefaultSections typeAnnot = injectionPoint.getMember().getDeclaringClass().getAnnotation(ConfigDefaultSections.class);
+ final List<String> keys = TamayaCDIInjectionExtension.evaluateKeys(injectionPoint.getMember().getName(),
+ annotation != null ? new String[]{annotation.name()} : null,
+ typeAnnot != null ? typeAnnot.value() : null);
+
+ Converter customConverter = null;
+ final WithConverter withConverterAnnot = injectionPoint.getAnnotated().getAnnotation(WithConverter.class);
+ if (withConverterAnnot != null) {
+ customConverter = TamayaCDIInjectionExtension.CUSTOM_CONVERTERS.get(withConverterAnnot.value());
+ }
+ String defaultTextValue = null;
+ if(annotation!=null && !annotation.defaultValue().equals(ConfigProperty.UNCONFIGURED_VALUE)){
+ defaultTextValue = annotation.defaultValue();
+ }
+ Config config = ConfigProvider.getConfig();
+// final WithConfigOperator withOperatorAnnot = injectionPoint.getAnnotated().getAnnotation(WithConfigOperator.class);
+// ConfigOperator operator = null;
+// if (withOperatorAnnot != null) {
+// operator = TamayaCDIInjectionExtension.CUSTOM_OPERATORS.get(withOperatorAnnot.value());
+// }
+// config = Objects.requireNonNull(operator.apply(config));
+
+ Optional<String> textValue = Optional.empty();
+ // Try to esolve using type, non present is possible, conversion issues are errors.
+ String keyFound = null;
+ for(String key:keys) {
+ textValue = config.getOptionalValue(key, String.class);
+ if(textValue.isPresent()) {
+ keyFound = key;
+ break;
+ }
+ }
+ LOGGER.info("Converting config value found for " + injectionPoint );
+ ConversionContext conversionContext = createConversionContext(keyFound, keys, config, injectionPoint);
+
+ Object value = convertValue(textValue.orElse(defaultTextValue), conversionContext, customConverter);
+ if (value == null) {
+ throw new IllegalArgumentException(String.format(
+ "Can't resolve any of the possible config keys: %s to the required target type: %s, supported formats: %s",
+ keys, conversionContext.getTargetType(), conversionContext.getSupportedFormats().toString()));
+ }
+ LOGGER.finest(String.format("Injecting %s for key %s in class %s", keyFound, value.toString(), injectionPoint.toString()));
+ if(TypeLiteral.of(injectionPoint.getAnnotated().getBaseType()).getRawType().equals(Optional.class)){
+ return Optional.ofNullable(value);
+ }
+ return value;
+ }
+
+// private Class getClass(Type baseType) {
+// if(baseType instanceof Class){
+// return Class.class.cast(baseType);
+// }else if(baseType instanceof ParameterizedType){
+// return getClass(((ParameterizedType)baseType).getRawType());
+// }else{
+// try {
+// return Class.forName(baseType.getTypeName());
+// } catch (ClassNotFoundException e) {
+// throw new IllegalArgumentException("Not a class tape: " + baseType.getTypeName());
+// }
+// }
+// }
+
+ static ConversionContext createConversionContext(String key, List<String> keys, Config config, InjectionPoint injectionPoint) {
+ final Type targetType = resolveTargetType(injectionPoint.getAnnotated().getBaseType());
+ ConversionContext.Builder builder = new ConversionContext.Builder(config, key, targetType);
+ if (injectionPoint.getMember() instanceof Field) {
+ Field annotated = (Field)injectionPoint.getMember();
+ if(annotated.isAnnotationPresent(ConfigProperty.class)) {
+ builder.setAnnotatedElement(annotated);
+ }
+ }else if(injectionPoint.getMember() instanceof Method){
+ Method method = (Method)injectionPoint.getMember();
+ for(Type type:method.getParameterTypes()){
+ if(type instanceof AnnotatedElement){
+ AnnotatedElement annotated = (AnnotatedElement)type;
+ if(annotated.isAnnotationPresent(ConfigProperty.class)) {
+ builder.setAnnotatedElement(annotated);
+ }
+ }
+ }
+ }
+ return builder.build();
+ }
+
+ private static <T> T convertValue(String textValue, ConversionContext conversionContext,
+ Converter<T> customConverter) {
+ try {
+ ConversionContext.setContext(conversionContext);
+ if(customConverter!=null) {
+ return customConverter.convert(textValue);
+ }
+
+ if(conversionContext.getConfiguration() instanceof ConfigContextSupplier){
+ try {
+ return ConverterManager.defaultInstance().convertValue(textValue, conversionContext.getTargetType(),
+ ((ConfigContextSupplier) conversionContext.getConfiguration()).getConfigContext()
+ .getConverters(conversionContext.getTargetType()));
+ }catch(IllegalArgumentException e){
+ return null;
+ }
+ }
+ return ConverterManager.defaultInstance().convertValue(textValue, conversionContext.getTargetType());
+ }finally{
+ ConversionContext.reset();
+ }
+ }
+
+ private static Type resolveTargetType(Type targetType) {
+ if(targetType instanceof ParameterizedType){
+ ParameterizedType pt = (ParameterizedType)targetType;
+ if(Provider.class.equals(pt.getRawType()) || Supplier.class.equals(pt.getRawType())
+ || Instance.class.equals(pt.getRawType())
+ || Optional.class.equals(pt.getRawType())){
+ return pt.getActualTypeArguments()[0];
+ }
+ }
+ return targetType;
+ }
+
+
+ @Produces
+ public Config getConfig(){
+ return ConfigProvider.getConfig();
+ }
+
+ @Produces
+ public ConfigBuilder getConfigBuilder(){
+ return ConfigProviderResolver.instance().getBuilder();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/ConfigurationProducer.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/ConfigurationProducer.java b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/ConfigurationProducer.java
deleted file mode 100644
index fdcf995..0000000
--- a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/ConfigurationProducer.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.tamaya.cdi;
-
-import org.apache.tamaya.*;
-import org.apache.tamaya.inject.api.*;
-import org.apache.tamaya.spi.*;
-
-import javax.enterprise.context.ApplicationScoped;
-import javax.enterprise.inject.Instance;
-import javax.enterprise.inject.Produces;
-import javax.enterprise.inject.spi.InjectionPoint;
-import javax.inject.Provider;
-import java.lang.reflect.*;
-import java.util.List;
-import java.util.Optional;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * Producer bean for configuration properties.
- */
-@ApplicationScoped
-public class ConfigurationProducer {
-
- private static final Logger LOGGER = Logger.getLogger(ConfigurationProducer.class.getName());
-
- private DynamicValue createDynamicValue(final InjectionPoint injectionPoint) {
- Member member = injectionPoint.getMember();
- if (member instanceof Field) {
- return DefaultDynamicValue.of(injectionPoint.getBean(), (Field) member, ConfigurationProvider.getConfiguration());
- } else if (member instanceof Method) {
- return DefaultDynamicValue.of(injectionPoint.getBean(), (Method) member, ConfigurationProvider.getConfiguration());
- }
- return null;
- }
-
- @Produces
- @Config
- public Object resolveAndConvert(final InjectionPoint injectionPoint) {
- if (DynamicValue.class.equals(injectionPoint.getAnnotated().getBaseType())) {
- return createDynamicValue(injectionPoint);
- }
- final Config annotation = injectionPoint.getAnnotated().getAnnotation(Config.class);
- final ConfigDefaultSections typeAnnot = injectionPoint.getMember().getDeclaringClass().getAnnotation(ConfigDefaultSections.class);
- final List<String> keys = TamayaCDIInjectionExtension.evaluateKeys(injectionPoint.getMember().getName(),
- annotation != null ? annotation.value() : null,
- typeAnnot != null ? typeAnnot.value() : null);
-
- final WithConfigOperator withOperatorAnnot = injectionPoint.getAnnotated().getAnnotation(WithConfigOperator.class);
- ConfigOperator operator = null;
- if (withOperatorAnnot != null) {
- operator = TamayaCDIInjectionExtension.CUSTOM_OPERATORS.get(withOperatorAnnot.value());
- }
- PropertyConverter customConverter = null;
- final WithPropertyConverter withConverterAnnot = injectionPoint.getAnnotated().getAnnotation(WithPropertyConverter.class);
- if (withConverterAnnot != null) {
- customConverter = TamayaCDIInjectionExtension.CUSTOM_CONVERTERS.get(withConverterAnnot.value());
- }
-
- // unless the extension is not installed, this should never happen because the extension
- // enforces the resolvability of the config
-
- String defaultTextValue = annotation.defaultValue().equals(Config.UNCONFIGURED_VALUE) ? null : annotation.defaultValue();
- String textValue = null;
- Configuration config = ConfigurationProvider.getConfiguration();
- if(operator!=null) {
- config = config.with(operator);
- }
- String keyFound = null;
- for(String key:keys) {
- textValue = config.get(key);
- if(textValue!=null) {
- keyFound = key;
- break;
- }
- }
- if(textValue==null) {
- LOGGER.info("Using default value: '" + defaultTextValue + "' for IP: " + injectionPoint );
- textValue = defaultTextValue;
- }
- ConversionContext conversionContext = createConversionContext(keyFound, keys, injectionPoint);
- Object value = convertValue(textValue, conversionContext, injectionPoint, customConverter);
- if (value == null) {
- throw new ConfigException(String.format(
- "Can't resolve any of the possible config keys: %s to the required target type: %s, supported formats: %s",
- keys, conversionContext.getTargetType(), conversionContext.getSupportedFormats().toString()));
- }
- LOGGER.finest(String.format("Injecting %s for key %s in class %s", keyFound, value.toString(), injectionPoint.toString()));
- return value;
- }
-
- static ConversionContext createConversionContext(String key, List<String> keys, InjectionPoint injectionPoint) {
- final Type targetType = injectionPoint.getAnnotated().getBaseType();
- Configuration config = ConfigurationProvider.getConfiguration();
- ConversionContext.Builder builder = new ConversionContext.Builder(config,
- ConfigurationProvider.getConfiguration().getContext(), key, TypeLiteral.of(targetType));
- // builder.setKeys(keys);
- if(targetType instanceof ParameterizedType){
- ParameterizedType pt = (ParameterizedType)targetType;
- if(pt.getRawType().equals(Provider.class)) {
- builder.setTargetType(
- TypeLiteral.of(pt.getActualTypeArguments()[0]));
- }
- }
- if (injectionPoint.getMember() instanceof Field) {
- Field annotated = (Field)injectionPoint.getMember();
- if(annotated.isAnnotationPresent(Config.class)) {
- builder.setAnnotatedElement(annotated);
- }
- }else if(injectionPoint.getMember() instanceof Method){
- Method method = (Method)injectionPoint.getMember();
- for(Type type:method.getParameterTypes()){
- if(type instanceof AnnotatedElement){
- AnnotatedElement annotated = (AnnotatedElement)type;
- if(annotated.isAnnotationPresent(Config.class)) {
- builder.setAnnotatedElement(annotated);
- }
- }
- }
- }
- return builder.build();
- }
-
- static Object convertValue(String textValue, ConversionContext conversionContext, InjectionPoint injectionPoint,
- PropertyConverter customConverter) {
- if (customConverter != null) {
- return customConverter.convert(textValue, conversionContext);
- }
- if(String.class.equals(conversionContext.getTargetType().getRawType())){
- return textValue;
- }
- Object value = null;
- ParameterizedType pt = null;
- Type toType = injectionPoint.getAnnotated().getBaseType();
- if(toType instanceof ParameterizedType){
- pt = (ParameterizedType)toType;
- if(Provider.class.equals(pt.getRawType()) || Instance.class.equals(pt.getRawType())
- || Optional.class.equals(pt.getRawType())){
- toType = pt.getActualTypeArguments()[0];
- }
- if(toType.equals(String.class)){
- value = textValue;
- }
- }
- List<PropertyConverter<Object>> converters = ConfigurationProvider.getConfiguration().getContext()
- .getPropertyConverters(TypeLiteral.of(toType));
- for (PropertyConverter<Object> converter : converters) {
- try {
- value = converter.convert(textValue, conversionContext);
- if (value != null) {
- LOGGER.log(Level.INFO, "Parsed value from '" + textValue + "' into " +
- injectionPoint);
- break;
- }
- } catch (Exception e) {
- LOGGER.log(Level.INFO, "Failed to convert value '" + textValue + "' for " +
- injectionPoint, e);
- }
- }
- if(pt != null && Optional.class.equals(pt.getRawType())){
- return Optional.ofNullable(value);
- }
- return value;
- }
-
- @Produces
- public Configuration getConfiguration(){
- return ConfigurationProvider.getConfiguration();
- }
-
- @Produces
- public ConfigurationContext getConfigurationContext(){
- return ConfigurationProvider.getConfiguration().getContext();
- }
-
- @Deprecated
- @Produces
- public ConfigurationContextBuilder getConfigurationContextBuilder(){
- return ConfigurationProvider.getConfigurationContextBuilder();
- }
-
- @Produces
- public ConfigurationBuilder getConfigurationBuilder(){
- return ConfigurationProvider.getConfigurationBuilder();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/DefaultDynamicValue.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/DefaultDynamicValue.java b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/DefaultDynamicValue.java
index 8c6dfee..6b31196 100644
--- a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/DefaultDynamicValue.java
+++ b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/DefaultDynamicValue.java
@@ -18,17 +18,15 @@
*/
package org.apache.tamaya.cdi;
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.TypeLiteral;
import org.apache.tamaya.inject.api.DynamicValue;
import org.apache.tamaya.inject.api.LoadPolicy;
import org.apache.tamaya.inject.api.UpdatePolicy;
-import org.apache.tamaya.inject.api.WithPropertyConverter;
+import org.apache.tamaya.inject.api.WithConverter;
import org.apache.tamaya.inject.spi.BaseDynamicValue;
-import org.apache.tamaya.inject.spi.InjectionUtils;
-import org.apache.tamaya.spi.PropertyConverter;
+import org.apache.tamaya.inject.spi.InjectionEvaluator;
+import javax.config.Config;
+import javax.config.spi.Converter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
@@ -55,12 +53,12 @@ final class DefaultDynamicValue<T> extends BaseDynamicValue<T> {
* Back reference to the base configuration instance. This reference is used reevalaute the given property and
* compare the result with the previous value after a configuration change was triggered.
*/
- private final Configuration configuration;
+ private final Config configuration;
/**
* The property converter to be applied, may be null. In the ladder case targetType is not null.
*/
- private final PropertyConverter<T> customConverter;
+ private final Converter<T> customConverter;
/**
* Load policy.
*/
@@ -75,8 +73,8 @@ final class DefaultDynamicValue<T> extends BaseDynamicValue<T> {
* @param targetType the target type, not null.
* @param customConverter the optional converter to be used.
*/
- private DefaultDynamicValue(Object owner, String propertyName, Configuration configuration, TypeLiteral<T> targetType,
- PropertyConverter<T> customConverter, List<String> keys, LoadPolicy loadPolicy,
+ private DefaultDynamicValue(Object owner, String propertyName, Config configuration, Type targetType,
+ Converter<T> customConverter, List<String> keys, LoadPolicy loadPolicy,
UpdatePolicy updatePolicy) {
super(owner, propertyName, targetType, keys);
this.configuration = Objects.requireNonNull(configuration);
@@ -88,103 +86,104 @@ final class DefaultDynamicValue<T> extends BaseDynamicValue<T> {
}
}
- public static DynamicValue of(Object owner, Field annotatedField, Configuration configuration) {
+ public static DynamicValue of(Object owner, Field annotatedField, Config configuration) {
return of(owner, annotatedField, configuration, LoadPolicy.ALWAYS, UpdatePolicy.IMMEDIATE);
}
- public static DynamicValue of(Object owner, Field annotatedField, Configuration configuration, LoadPolicy loadPolicy) {
+ public static DynamicValue of(Object owner, Field annotatedField, Config configuration, LoadPolicy loadPolicy) {
return of(owner, annotatedField, configuration, loadPolicy, UpdatePolicy.IMMEDIATE);
}
- public static DynamicValue of(Object owner, Field annotatedField, Configuration configuration, UpdatePolicy updatePolicy) {
+ public static DynamicValue of(Object owner, Field annotatedField, Config configuration, UpdatePolicy updatePolicy) {
return of(owner, annotatedField, configuration, LoadPolicy.ALWAYS, updatePolicy);
}
- public static DynamicValue of(Object owner, Field annotatedField, Configuration configuration, LoadPolicy loadPolicy, UpdatePolicy updatePolicy) {
+ public static DynamicValue of(Object owner, Field annotatedField, Config configuration, LoadPolicy loadPolicy,
+ UpdatePolicy updatePolicy) {
// Check for adapter/filter
Type targetType = annotatedField.getGenericType();
if (targetType == null) {
- throw new ConfigException("Failed to evaluate target type for " + annotatedField.getDeclaringClass().getName()
+ throw new IllegalArgumentException("Failed to evaluate target type for " + annotatedField.getDeclaringClass().getName()
+ '.' + annotatedField.getName());
}
if (targetType instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) targetType;
Type[] types = pt.getActualTypeArguments();
if (types.length != 1) {
- throw new ConfigException("Failed to evaluate target type for " + annotatedField.getDeclaringClass().getName()
+ throw new IllegalArgumentException("Failed to evaluate target type for " + annotatedField.getDeclaringClass().getName()
+ '.' + annotatedField.getName());
}
targetType = types[0];
}
- PropertyConverter<?> propertyConverter = null;
- WithPropertyConverter annot = annotatedField.getAnnotation(WithPropertyConverter.class);
+ Converter<?> propertyConverter = null;
+ WithConverter annot = annotatedField.getAnnotation(WithConverter.class);
if (annot != null) {
try {
propertyConverter = annot.value().newInstance();
} catch (Exception e) {
- throw new ConfigException("Failed to instantiate annotated PropertyConverter on " +
+ throw new IllegalArgumentException("Failed to instantiate annotated Converter on " +
annotatedField.getDeclaringClass().getName()
+ '.' + annotatedField.getName(), e);
}
}
- List<String> keys = InjectionUtils.getKeys(annotatedField);
+ List<String> keys = InjectionEvaluator.getKeys(annotatedField);
return new DefaultDynamicValue(owner, annotatedField.getName(), configuration,
- TypeLiteral.of(targetType), propertyConverter, keys, loadPolicy, updatePolicy);
+ targetType, propertyConverter, keys, loadPolicy, updatePolicy);
}
- public static DynamicValue of(Object owner, Method method, Configuration configuration) {
+ public static DynamicValue of(Object owner, Method method, Config configuration) {
return of(owner, method, configuration, LoadPolicy.ALWAYS, UpdatePolicy.IMMEDIATE);
}
- public static DynamicValue of(Object owner, Method method, Configuration configuration, UpdatePolicy updatePolicy) {
+ public static DynamicValue of(Object owner, Method method, Config configuration, UpdatePolicy updatePolicy) {
return of(owner, method, configuration, LoadPolicy.ALWAYS, updatePolicy);
}
- public static DynamicValue of(Object owner, Method method, Configuration configuration, LoadPolicy loadPolicy) {
+ public static DynamicValue of(Object owner, Method method, Config configuration, LoadPolicy loadPolicy) {
return of(owner, method, configuration, loadPolicy, UpdatePolicy.IMMEDIATE);
}
- public static DynamicValue of(Object owner, Method method, Configuration configuration, LoadPolicy loadPolicy, UpdatePolicy updatePolicy) {
+ public static DynamicValue of(Object owner, Method method, Config configuration, LoadPolicy loadPolicy, UpdatePolicy updatePolicy) {
// Check for adapter/filter
Type targetType = method.getGenericReturnType();
if (targetType == null) {
- throw new ConfigException("Failed to evaluate target type for " + method.getDeclaringClass()
+ throw new IllegalArgumentException("Failed to evaluate target type for " + method.getDeclaringClass()
.getName() + '.' + method.getName());
}
if (targetType instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) targetType;
Type[] types = pt.getActualTypeArguments();
if (types.length != 1) {
- throw new ConfigException("Failed to evaluate target type for " + method.getDeclaringClass()
+ throw new IllegalArgumentException("Failed to evaluate target type for " + method.getDeclaringClass()
.getName() + '.' + method.getName());
}
targetType = types[0];
}
- PropertyConverter<Object> propertyConverter = null;
- WithPropertyConverter annot = method.getAnnotation(WithPropertyConverter.class);
+ Converter<Object> propertyConverter = null;
+ WithConverter annot = method.getAnnotation(WithConverter.class);
if (annot != null) {
try {
- propertyConverter = (PropertyConverter<Object>) annot.value().newInstance();
+ propertyConverter = (Converter<Object>) annot.value().newInstance();
} catch (Exception e) {
- throw new ConfigException("Failed to instantiate annotated PropertyConverter on " +
+ throw new IllegalArgumentException("Failed to instantiate annotated Converter on " +
method.getDeclaringClass().getName()
+ '.' + method.getName(), e);
}
}
return new DefaultDynamicValue<>(owner, method.getName(),
- configuration, TypeLiteral.of(targetType), propertyConverter, InjectionUtils.getKeys(method),
+ configuration, targetType, propertyConverter, InjectionEvaluator.getKeys(method),
loadPolicy, updatePolicy);
}
@Override
- protected Configuration getConfiguration() {
+ protected Config getConfiguration() {
return configuration;
}
@Override
- protected PropertyConverter<T> getCustomConverter() {
+ protected Converter<T> getCustomConverter() {
return customConverter;
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/ServiceLoaderServiceContext.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/ServiceLoaderServiceContext.java b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/ServiceLoaderServiceContext.java
index f5a5f6c..f56c199 100644
--- a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/ServiceLoaderServiceContext.java
+++ b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/ServiceLoaderServiceContext.java
@@ -18,9 +18,8 @@
*/
package org.apache.tamaya.cdi;
-import org.apache.tamaya.ConfigException;
+import org.apache.tamaya.base.PriorityServiceComparator;
import org.apache.tamaya.spi.ServiceContext;
-import org.apache.tamaya.spisupport.PriorityServiceComparator;
import javax.annotation.Priority;
import java.io.IOException;
@@ -49,6 +48,11 @@ final class ServiceLoaderServiceContext implements ServiceContext {
@Override
public <T> T getService(Class<T> serviceType) {
+ return getService(serviceType, ServiceContext.defaultClassLoader());
+ }
+
+ @Override
+ public <T> T getService(Class<T> serviceType, ClassLoader classLoader) {
Object cached = singletons.get(serviceType);
if (cached == null) {
cached = create(serviceType);
@@ -61,9 +65,15 @@ final class ServiceLoaderServiceContext implements ServiceContext {
@Override
public <T> T create(Class<T> serviceType) {
+ return create(serviceType, ServiceContext.defaultClassLoader());
+ }
+
+ @Override
+ public <T> T create(Class<T> serviceType, ClassLoader classLoader) {
+ @SuppressWarnings("unchecked")
Class<? extends T> implType = factoryTypes.get(serviceType);
if(implType==null) {
- Collection<T> services = getServices(serviceType);
+ Collection<T> services = getServices(serviceType, classLoader);
if (services.isEmpty()) {
return null;
} else {
@@ -87,13 +97,25 @@ final class ServiceLoaderServiceContext implements ServiceContext {
*/
@Override
public <T> List<T> getServices(final Class<T> serviceType) {
+ return getServices(serviceType, ServiceContext.defaultClassLoader());
+ }
+
+ /**
+ * Loads and registers services.
+ *
+ * @param <T> the concrete type.
+ * @param serviceType The service type.
+ * @return the items found, never {@code null}.
+ */
+ @Override
+ public <T> List<T> getServices(final Class<T> serviceType, ClassLoader classLoader) {
List<T> found = (List<T>) servicesLoaded.get(serviceType);
if (found != null) {
return found;
}
List<T> services = new ArrayList<>();
try {
- for (T t : ServiceLoader.load(serviceType)) {
+ for (T t : ServiceLoader.load(serviceType, classLoader)) {
services.add(t);
}
Collections.sort(services, PriorityServiceComparator.getInstance());
@@ -130,7 +152,7 @@ final class ServiceLoaderServiceContext implements ServiceContext {
*
* @return the service with the highest {@link Priority#value()}
*
- * @throws ConfigException if there are multiple service implementations with the maximum priority
+ * @throws IllegalStateException if there are multiple service implementations with the maximum priority
*/
private <T> T getServiceWithHighestPriority(Collection<T> services, Class<T> serviceType) {
T highestService = null;
@@ -156,7 +178,7 @@ final class ServiceLoaderServiceContext implements ServiceContext {
}
if (highestPriorityServiceCount > 1) {
- throw new ConfigException(MessageFormat.format("Found {0} implementations for Service {1} with Priority {2}: {3}",
+ throw new IllegalStateException(MessageFormat.format("Found {0} implementations for Service {1} with Priority {2}: {3}",
highestPriorityServiceCount,
serviceType.getName(),
highestPriority,
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/TamayaCDIInjectionExtension.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/TamayaCDIInjectionExtension.java b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/TamayaCDIInjectionExtension.java
index 2485f05..2d95401 100644
--- a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/TamayaCDIInjectionExtension.java
+++ b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/TamayaCDIInjectionExtension.java
@@ -16,14 +16,11 @@
*/
package org.apache.tamaya.cdi;
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.ConfigOperator;
-import org.apache.tamaya.inject.api.Config;
import org.apache.tamaya.inject.api.ConfigDefaultSections;
-import org.apache.tamaya.inject.api.WithConfigOperator;
-import org.apache.tamaya.inject.api.WithPropertyConverter;
-import org.apache.tamaya.spi.PropertyConverter;
+import org.apache.tamaya.inject.api.WithConverter;
+import javax.config.inject.ConfigProperty;
+import javax.config.spi.Converter;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.Instance;
@@ -39,16 +36,15 @@ import java.util.logging.Logger;
/**
* CDI Extension module that adds injection mechanism for configuration.
*
- * @see Config
+ * @see javax.config.inject.ConfigProperty
* @see ConfigDefaultSections
- * @see ConfigException
*/
public class TamayaCDIInjectionExtension implements Extension {
private static final Logger LOG = Logger.getLogger(TamayaCDIInjectionExtension.class.getName());
- static final Map<Class, ConfigOperator> CUSTOM_OPERATORS = new ConcurrentHashMap<>();
- static final Map<Class, PropertyConverter> CUSTOM_CONVERTERS = new ConcurrentHashMap<>();
+// static final Map<Class, ConfigOperator> CUSTOM_OPERATORS = new ConcurrentHashMap<>();
+ static final Map<Class, Converter> CUSTOM_CONVERTERS = new ConcurrentHashMap<>();
private final Set<Type> types = new HashSet<>();
private Bean<?> tamayaProducerBean;
@@ -72,18 +68,18 @@ public class TamayaCDIInjectionExtension implements Extension {
boolean configured = false;
for (InjectionPoint injectionPoint : ips) {
- if (injectionPoint.getAnnotated().isAnnotationPresent(Config.class)) {
+ if (injectionPoint.getAnnotated().isAnnotationPresent(ConfigProperty.class)) {
LOG.fine("Configuring: " + injectionPoint);
- final Config annotation = injectionPoint.getAnnotated().getAnnotation(Config.class);
+ final ConfigProperty annotation = injectionPoint.getAnnotated().getAnnotation(ConfigProperty.class);
final ConfigDefaultSections typeAnnot = injectionPoint.getMember().getDeclaringClass().getAnnotation(ConfigDefaultSections.class);
final List<String> keys = evaluateKeys(injectionPoint.getMember().getName(),
- annotation!=null?annotation.value():null,
+ (annotation!=null && !annotation.name().isEmpty())?new String[]{annotation.name()}:null,
typeAnnot!=null?typeAnnot.value():null);
- final WithConfigOperator withOperatorAnnot = injectionPoint.getAnnotated().getAnnotation(WithConfigOperator.class);
- if(withOperatorAnnot!=null){
- tryLoadOpererator(withOperatorAnnot.value());
- }
- final WithPropertyConverter withConverterAnnot = injectionPoint.getAnnotated().getAnnotation(WithPropertyConverter.class);
+// final WithConfigOperator withOperatorAnnot = injectionPoint.getAnnotated().getAnnotation(WithConfigOperator.class);
+// if(withOperatorAnnot!=null){
+// tryLoadOpererator(withOperatorAnnot.value());
+// }
+ final WithConverter withConverterAnnot = injectionPoint.getAnnotated().getAnnotation(WithConverter.class);
if(withConverterAnnot!=null){
tryLoadConverter(withConverterAnnot.value());
}
@@ -102,7 +98,7 @@ public class TamayaCDIInjectionExtension implements Extension {
public void captureConvertBean(@Observes final ProcessProducerMethod<?, ?> ppm) {
- if (ppm.getAnnotated().isAnnotationPresent(Config.class)) {
+ if (ppm.getAnnotated().isAnnotationPresent(ConfigProperty.class)) {
tamayaProducerBean = ppm.getBean();
}
}
@@ -123,23 +119,23 @@ public class TamayaCDIInjectionExtension implements Extension {
return type;
}
- private void tryLoadOpererator(Class<? extends ConfigOperator> operatorClass) {
- Objects.requireNonNull(operatorClass);
- if(ConfigOperator.class == operatorClass){
- return;
- }
- try{
- if(!CUSTOM_OPERATORS.containsKey(operatorClass)) {
- CUSTOM_OPERATORS.put(operatorClass, operatorClass.newInstance());
- }
- } catch(Exception e){
- throw new ConfigException("Custom ConfigOperator could not be loaded: " + operatorClass.getName(), e);
- }
- }
-
- private void tryLoadConverter(Class<? extends PropertyConverter> converterClass) {
+// private void tryLoadOpererator(Class<? extends ConfigOperator> operatorClass) {
+// Objects.requireNonNull(operatorClass);
+// if(ConfigOperator.class == operatorClass){
+// return;
+// }
+// try{
+// if(!CUSTOM_OPERATORS.containsKey(operatorClass)) {
+// CUSTOM_OPERATORS.put(operatorClass, operatorClass.newInstance());
+// }
+// } catch(Exception e){
+// throw new ConfigException("Custom ConfigOperator could not be loaded: " + operatorClass.getName(), e);
+// }
+// }
+
+ private void tryLoadConverter(Class<? extends Converter> converterClass) {
Objects.requireNonNull(converterClass);
- if(PropertyConverter.class == converterClass){
+ if(Converter.class == converterClass){
return;
}
try{
@@ -147,7 +143,7 @@ public class TamayaCDIInjectionExtension implements Extension {
CUSTOM_CONVERTERS.put(converterClass, converterClass.newInstance());
}
} catch(Exception e){
- throw new ConfigException("Custom PropertyConverter could not be loaded: " + converterClass.getName(), e);
+ throw new IllegalArgumentException("Custom PropertyConverter could not be loaded: " + converterClass.getName(), e);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/TamayaSEInjectionExtension.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/TamayaSEInjectionExtension.java b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/TamayaSEInjectionExtension.java
index 024b895..6ab73b0 100644
--- a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/TamayaSEInjectionExtension.java
+++ b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/TamayaSEInjectionExtension.java
@@ -20,9 +20,9 @@ package org.apache.tamaya.cdi;
import org.apache.tamaya.inject.ConfigurationInjection;
-import org.apache.tamaya.inject.api.Config;
import org.apache.tamaya.inject.api.ConfigDefaultSections;
+import javax.config.inject.ConfigProperty;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.Vetoed;
@@ -92,13 +92,13 @@ public final class TamayaSEInjectionExtension implements Extension {
}
// if no class level annotation is there we might have field level annotations only
for (Field field : type.getDeclaredFields()) {
- if (field.isAnnotationPresent(Config.class) && !field.isAnnotationPresent(Inject.class)) {
+ if (field.isAnnotationPresent(ConfigProperty.class) && !field.isAnnotationPresent(Inject.class)) {
return true;
}
}
// if no class level annotation is there we might have method level annotations only
for (Method method : type.getDeclaredMethods()) {
- if(method.isAnnotationPresent(Config.class)) {
+ if(method.isAnnotationPresent(ConfigProperty.class)) {
return true;
}
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/extra/ConfiguredVetoExtension.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/extra/ConfiguredVetoExtension.java b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/extra/ConfiguredVetoExtension.java
index e86ee89..93fbdd2 100644
--- a/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/extra/ConfiguredVetoExtension.java
+++ b/modules/injection/cdi/src/main/java/org/apache/tamaya/cdi/extra/ConfiguredVetoExtension.java
@@ -18,8 +18,7 @@
*/
package org.apache.tamaya.cdi.extra;
-import org.apache.tamaya.ConfigurationProvider;
-
+import javax.config.ConfigProvider;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.ProcessAnnotatedType;
@@ -31,7 +30,7 @@ import javax.enterprise.inject.spi.ProcessAnnotatedType;
public class ConfiguredVetoExtension implements Extension {
public void observesBean(@Observes ProcessAnnotatedType<?> type) {
- String vetoedTypesVal = ConfigurationProvider.getConfiguration().get("javax.enterprise.inject.vetoed");
+ String vetoedTypesVal = ConfigProvider.getConfig().getValue("javax.enterprise.inject.vetoed", String.class);
String[] vetoedTypes = vetoedTypesVal.split(",");
for (String typeExpr : vetoedTypes) {
String typeExprTrimmed = typeExpr.trim();
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/BaseTestConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/BaseTestConfiguration.java b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/BaseTestConfiguration.java
index ad762a7..0365195 100644
--- a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/BaseTestConfiguration.java
+++ b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/BaseTestConfiguration.java
@@ -34,10 +34,10 @@ abstract class BaseTestConfiguration {
return ShrinkWrap.create(WebArchive.class)
.addClasses(ConfiguredTest.class, ConfiguredClass.class, InjectedClass.class,
AdditionalMatchers.class, NotFoundNoDefault.class,
- ConfigurationProducer.class)
+ ConfigProducer.class)
.addAsServiceProvider(Extension.class, TamayaCDIInjectionExtension.class)
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
- .addAsWebInfResource("META-INF/javaconfiguration.properties", "META-INF/javaconfiguration.properties");
+ .addAsWebInfResource("META-INF/javaconfig.properties", "META-INF/javaconfig.properties");
}
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/ConfigurationProducerTest.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/ConfigurationProducerTest.java b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/ConfigurationProducerTest.java
index b3459b7..bf7e55a 100644
--- a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/ConfigurationProducerTest.java
+++ b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/ConfigurationProducerTest.java
@@ -23,11 +23,11 @@ import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.Optional;
+import javax.config.inject.ConfigProperty;
import javax.enterprise.inject.spi.Extension;
import javax.inject.Inject;
import javax.inject.Provider;
-import org.apache.tamaya.inject.api.Config;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
@@ -45,10 +45,10 @@ public class ConfigurationProducerTest {
return ShrinkWrap.create(WebArchive.class)
.addClasses(ConfiguredClass.class, InjectedClass.class,
TamayaCDIInjectionExtension.class, TamayaCDIAccessor.class,
- org.apache.tamaya.cdi.ConfigurationProducer.class)
+ org.apache.tamaya.cdi.ConfigProducer.class)
.addAsServiceProvider(Extension.class, TamayaCDIInjectionExtension.class)
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
- .addAsWebInfResource("META-INF/javaconfiguration.properties", "META-INF/javaconfiguration.properties");
+ .addAsWebInfResource("META-INF/javaconfig.properties", "META-INF/javaconfig.properties");
}
@Inject
@@ -116,51 +116,51 @@ public class ConfigurationProducerTest {
private Provider<Integer> providerIntegerAsMethodParam;
@Inject
- @Config(value = "string.value", defaultValue = "defaultString")
+ @ConfigProperty(name = "string.value", defaultValue = "defaultString")
private String string;
@Inject
- @Config(value = "string.value", defaultValue = "defaultString")
+ @ConfigProperty(name = "string.value", defaultValue = "defaultString")
private Optional<String> optionalString;
@Inject
- @Config(value = "string.value", defaultValue = "defaultString")
+ @ConfigProperty(name = "string.value", defaultValue = "defaultString")
private Provider<String> providerString;
@Inject
- @Config(value = "defaultString.value", defaultValue = "defaultString")
+ @ConfigProperty(name = "defaultString.value", defaultValue = "defaultString")
private String defaultString;
@Inject
- @Config(value = "file.value", defaultValue = "./")
+ @ConfigProperty(name = "file.value", defaultValue = "./")
private File file;
@Inject
- @Config(value = "defaultFile.value", defaultValue = "./")
+ @ConfigProperty(name = "defaultFile.value", defaultValue = "./")
private File defaultFile;
@Inject
- @Config(value = "boolean.value", defaultValue = "true")
+ @ConfigProperty(name = "boolean.value", defaultValue = "true")
private Boolean aBoolean;
@Inject
- @Config(value = "defaultBoolean.value", defaultValue = "true")
+ @ConfigProperty(name = "defaultBoolean.value", defaultValue = "true")
private Boolean defaultBoolean;
@Inject
- @Config(value = "integer.value", defaultValue = "45")
+ @ConfigProperty(name = "integer.value", defaultValue = "45")
private Integer integer;
@Inject
- @Config(value = "defaultInteger.value", defaultValue = "45")
+ @ConfigProperty(name = "defaultInteger.value", defaultValue = "45")
private Integer defaultInteger;
@Inject
- @Config(value = "integer.value", defaultValue = "45")
+ @ConfigProperty(name = "integer.value", defaultValue = "45")
private Optional<Integer> optionalInteger;
@Inject
- @Config(value = "integer.value", defaultValue = "45")
+ @ConfigProperty(name = "integer.value", defaultValue = "45")
private Provider<Integer> providerInteger;
public String getString() {
@@ -197,32 +197,32 @@ public class ConfigurationProducerTest {
@Inject
- public void setStringAsMethodParam(@Config(value = "string.value", defaultValue = "defaultString") String stringAsMethodParam) {
+ public void setStringAsMethodParam(@ConfigProperty(name = "string.value", defaultValue = "defaultString") String stringAsMethodParam) {
this.stringAsMethodParam = stringAsMethodParam;
}
@Inject
- public void setIntegerAsMethodParam(@Config(value = "integer.value", defaultValue = "45")Integer integerAsMethodParam) {
+ public void setIntegerAsMethodParam(@ConfigProperty(name = "integer.value", defaultValue = "45")Integer integerAsMethodParam) {
this.integerAsMethodParam = integerAsMethodParam;
}
@Inject
- public void setOptionalStringAsMethodParam(@Config(value = "string.value", defaultValue = "defaultString") Optional<String> optionalStringAsMethodParam) {
+ public void setOptionalStringAsMethodParam(@ConfigProperty(name = "string.value", defaultValue = "defaultString") Optional<String> optionalStringAsMethodParam) {
this.optionalStringAsMethodParam = optionalStringAsMethodParam;
}
@Inject
- public void setOptionalIntegerAsMethodParam(@Config(value = "integer.value", defaultValue = "45") Optional<Integer> optionalIntegerAsMethodParam) {
+ public void setOptionalIntegerAsMethodParam(@ConfigProperty(name = "integer.value", defaultValue = "45") Optional<Integer> optionalIntegerAsMethodParam) {
this.optionalIntegerAsMethodParam = optionalIntegerAsMethodParam;
}
@Inject
- public void setProviderStringAsMethodParam(@Config(value = "string.value", defaultValue = "defaultString") Provider<String> providerStringAsMethodParam) {
+ public void setProviderStringAsMethodParam(@ConfigProperty(name = "string.value", defaultValue = "defaultString") Provider<String> providerStringAsMethodParam) {
this.providerStringAsMethodParam = providerStringAsMethodParam;
}
@Inject
- public void setProviderIntegerAsMethodParam(@Config(value = "integer.value", defaultValue = "45") Provider<Integer> providerIntegerAsMethodParam) {
+ public void setProviderIntegerAsMethodParam(@ConfigProperty(name = "integer.value", defaultValue = "45") Provider<Integer> providerIntegerAsMethodParam) {
this.providerIntegerAsMethodParam = providerIntegerAsMethodParam;
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/ConfiguredClass.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/ConfiguredClass.java b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/ConfiguredClass.java
index 5d71d5d..29c20c0 100644
--- a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/ConfiguredClass.java
+++ b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/ConfiguredClass.java
@@ -20,8 +20,9 @@
*/
package org.apache.tamaya.cdi;
-import org.apache.tamaya.inject.api.Config;
+import org.apache.tamaya.inject.api.ConfigFallbackKeys;
+import javax.config.inject.ConfigProperty;
import javax.inject.Singleton;
import java.math.BigDecimal;
@@ -31,34 +32,36 @@ import java.math.BigDecimal;
@Singleton
public class ConfiguredClass{
- @Config
+ @ConfigProperty
private String testProperty;
- @Config(value = {"a.b.c.key1","a.b.c.key2","a.b.c.key3"}, defaultValue = "The current \\${JAVA_HOME} env property is ${env:JAVA_HOME}.")
+ @ConfigProperty(name = "a.b.c.key1", defaultValue = "The current \\${JAVA_HOME} env property is ${env:JAVA_HOME}.")
+ @ConfigFallbackKeys({"a.b.c.key2","a.b.c.key3"})
String value1;
- @Config({"foo","a.b.c.key2"})
+ @ConfigProperty(name="foo")
+ @ConfigFallbackKeys({"a.b.c.key2"})
private String value2;
- @Config(defaultValue = "N/A")
+ @ConfigProperty(defaultValue = "N/A")
private String runtimeVersion;
- @Config(defaultValue = "${sys:java.version}")
+ @ConfigProperty(defaultValue = "${sys:java.version}")
private String javaVersion2;
- @Config(defaultValue = "5")
+ @ConfigProperty(defaultValue = "5")
private Integer int1;
- @Config
+ @ConfigProperty
private int int2;
- @Config
+ @ConfigProperty
private boolean booleanT;
- @Config("BD")
+ @ConfigProperty(name="BD")
private BigDecimal bigNumber;
- @Config("double1")
+ @ConfigProperty(name="double1")
private double doubleValue;
public String getTestProperty() {
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/ConfiguredTest.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/ConfiguredTest.java b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/ConfiguredTest.java
index 8143d95..95435e7 100644
--- a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/ConfiguredTest.java
+++ b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/ConfiguredTest.java
@@ -52,7 +52,7 @@ public class ConfiguredTest extends BaseTestConfiguration {
assertNotNull(injectedClass.builder1);
assertNotNull(injectedClass.builder2);
assertNotNull(injectedClass.config);
- assertNotNull(injectedClass.configContext);
+ assertNotNull(injectedClass.config2);
}
@Test
@@ -67,12 +67,6 @@ public class ConfiguredTest extends BaseTestConfiguration {
assertTrue(injectedClass.config == injectedClass.config2);
}
- @Test
- public void test_Injected_configContexts_are_same(){
- InjectedClass injectedClass = CDI.current().select(InjectedClass.class).get();
- assertTrue(injectedClass.configContext == injectedClass.configContext2);
- }
-
@Test(expected=Exception.class)
public void test_error_Injection() {
NotFoundNoDefault injectedClass = CDI.current().select(NotFoundNoDefault.class).get();
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/InjectedClass.java
----------------------------------------------------------------------
diff --git a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/InjectedClass.java b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/InjectedClass.java
index 3c6ca51..e3d6fa2 100644
--- a/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/InjectedClass.java
+++ b/modules/injection/cdi/src/test/java/org/apache/tamaya/cdi/InjectedClass.java
@@ -19,10 +19,8 @@
*/
package org.apache.tamaya.cdi;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.spi.ConfigurationContext;
-import org.apache.tamaya.spi.ConfigurationBuilder;
-
+import javax.config.Config;
+import javax.config.spi.ConfigBuilder;
import javax.inject.Inject;
import javax.inject.Singleton;
@@ -33,28 +31,21 @@ import javax.inject.Singleton;
public class InjectedClass {
@Inject
- Configuration config;
-
- @Inject
- Configuration config2;
-
- @Inject
- ConfigurationContext configContext;
+ Config config;
@Inject
- ConfigurationContext configContext2;
+ Config config2;
@Inject
- ConfigurationBuilder builder1;
+ ConfigBuilder builder1;
@Inject
- ConfigurationBuilder builder2;
+ ConfigBuilder builder2;
@Override
public String toString() {
return "InjectedClass{" +
"config=" + config +
- ", configContext=" + configContext +
", builder1=" + builder1 +
", builder2=" + builder2 +
'}';
[02/18] incubator-tamaya-extensions git commit: Added full JSR
support.
Posted by an...@apache.org.
Added full JSR support.
Signed-off-by: Anatole Tresch <an...@apache.org>
Project: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/commit/06f29e1a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/tree/06f29e1a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/diff/06f29e1a
Branch: refs/heads/configjsr
Commit: 06f29e1a51a4b11d8eb7e2dcdaae3611951bcba6
Parents: 4af5f5f
Author: Anatole Tresch <an...@apache.org>
Authored: Wed Dec 13 22:44:40 2017 +0100
Committer: Anatole Tresch <an...@apache.org>
Committed: Wed Dec 13 22:44:40 2017 +0100
----------------------------------------------------------------------
modules/resources/pom.xml | 2 +-
.../AbstractPathConfigSourceProvider.java | 206 +++++++++++++++++++
.../AbstractPathPropertySourceProvider.java | 205 ------------------
.../apache/tamaya/resource/ConfigResources.java | 7 +-
.../AbstractPathPropertySourceProviderTest.java | 31 ++-
.../internal/PathBasedConfigSourceProvider.java | 87 ++++++++
.../PathBasedPropertySourceProvider.java | 94 ---------
7 files changed, 310 insertions(+), 322 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/06f29e1a/modules/resources/pom.xml
----------------------------------------------------------------------
diff --git a/modules/resources/pom.xml b/modules/resources/pom.xml
index e482618..f0aa1c2 100644
--- a/modules/resources/pom.xml
+++ b/modules/resources/pom.xml
@@ -34,7 +34,7 @@ under the License.
<dependencies>
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-api</artifactId>
+ <artifactId>tamaya-base</artifactId>
<version>${tamaya-apicore.version}</version>
</dependency>
<dependency>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/06f29e1a/modules/resources/src/main/java/org/apache/tamaya/resource/AbstractPathConfigSourceProvider.java
----------------------------------------------------------------------
diff --git a/modules/resources/src/main/java/org/apache/tamaya/resource/AbstractPathConfigSourceProvider.java b/modules/resources/src/main/java/org/apache/tamaya/resource/AbstractPathConfigSourceProvider.java
new file mode 100644
index 0000000..a536be9
--- /dev/null
+++ b/modules/resources/src/main/java/org/apache/tamaya/resource/AbstractPathConfigSourceProvider.java
@@ -0,0 +1,206 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.resource;
+
+import org.apache.tamaya.spi.ServiceContext;
+
+import java.io.InputStream;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Objects;
+import java.util.Properties;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+
+import javax.config.spi.ConfigSource;
+import javax.config.spi.ConfigSourceProvider;
+
+/**
+ * Abstract base class that uses a descriptive resource path to define the locations of configuration files to be
+ * included into the configuration. This is especially useful, when the current configuration policy in place
+ * does not define the exact file names, but the file locations, where configuration can be provided.
+ */
+public abstract class AbstractPathConfigSourceProvider implements ConfigSourceProvider{
+ /** The log used. */
+ private static final Logger LOG = Logger.getLogger(AbstractPathConfigSourceProvider.class.getName());
+ /** The resource paths. */
+ private String[] resourcePaths;
+
+
+ /**
+ * Creates a new instance using the given resource paths.
+ * @param resourcePaths the resource paths, not null, not empty.
+ */
+ public AbstractPathConfigSourceProvider(String... resourcePaths){
+ if(resourcePaths.length==0){
+ throw new IllegalArgumentException("At least one resource path should be configured.");
+ }
+
+ setResourcePaths(resourcePaths);
+ }
+
+ @Override
+ public Collection<ConfigSource> getConfigSources(ClassLoader classLoader) {
+ List<ConfigSource> propertySources = new ArrayList<>();
+ if(classLoader == null){
+ classLoader = ServiceContext.defaultClassLoader();
+ }
+ for (String resource : getResourcePaths()) {
+ try {
+ // TODO Get a resource resolver for a certain classloader
+ Collection<URL> resources = ConfigResources.getResourceResolver().getResources(resource);
+ for (URL url : resources) {
+ try {
+ Collection<ConfigSource> propertySourcesToInclude = getConfigSources(url);
+ if(propertySourcesToInclude!=null){
+ propertySources.addAll(propertySourcesToInclude);
+ }
+ } catch (Exception e) {
+ LOG.log(Level.WARNING, "Failed to read configuration from " + url, e);
+ }
+ }
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "Invalid resource path: " + resource, e);
+ }
+ }
+ return propertySources;
+ }
+
+ protected String[] getResourcePaths() {
+ return resourcePaths;
+ }
+
+ protected void setResourcePaths(String[] paths) {
+ resourcePaths = paths.clone();
+ }
+
+ /**
+ * Factory method that creates a {@link ConfigSource} based on the URL found by
+ * the resource locator.
+ * @param url the URL, not null.
+ * @return the {@link ConfigSource}s to be included into the current provider's sources
+ * list. It is safe to return {@code null} here, in case the content of the URL has shown to be not relevant
+ * as configuration input. In case the input is not valid or accessible an exception can be thrown or logged.
+ */
+ protected abstract Collection<ConfigSource> getConfigSources(URL url);
+
+ /**
+ * Utility method that reads a .properties file from the given url and creates a corresponding
+ * {@link ConfigSource}.
+ * @param url the url to read, not null.
+ * @return the corresponding PropertySource, or null.
+ */
+ public static ConfigSource createConfigSource(URL url) {
+ Properties props = new Properties();
+ try (InputStream is = url.openStream()){
+ props.load(is);
+ return new PropertiesBasedConfigSource(url.toString(), props);
+ }
+ catch (Exception e){
+ LOG.log(Level.WARNING, "Failed to read properties from " + url, e);
+ return null;
+ }
+ }
+
+ /**
+ * Minimal {@link ConfigSource} implementation based on {@link Properties} or
+ * {@link Map}.
+ */
+ private final static class PropertiesBasedConfigSource implements ConfigSource{
+ /** The property source's name. */
+ private final String name;
+ /** The properties. */
+ private final Map<String,String> properties = new HashMap<>();
+
+ /**
+ * Constructor for a simple properties configuration.
+ * @param name the source's name, not null
+ * @param props the properties, not null
+ */
+ public PropertiesBasedConfigSource(String name, Properties props) {
+ this.name = Objects.requireNonNull(name);
+ for (Entry<Object, Object> en : props.entrySet()) {
+ this.properties.put(en.getKey().toString(),
+ String.valueOf(en.getValue()));
+ }
+ }
+
+ /**
+ * Constructor for a simple properties configuration.
+ * @param name the source's name, not null
+ * @param props the properties, not null
+ */
+ public PropertiesBasedConfigSource(String name, Map<String,String> props) {
+ this.name = Objects.requireNonNull(name);
+ for (Entry<String, String> en : props.entrySet()) {
+ this.properties.put(en.getKey(),
+ en.getValue());
+ }
+ }
+
+ public int getOrdinal() {
+ String configuredOrdinal = getValue(CONFIG_ORDINAL);
+ if (configuredOrdinal != null) {
+ try {
+ return Integer.parseInt(configuredOrdinal);
+ } catch (Exception e) {
+ Logger.getLogger(getClass().getName()).log(Level.WARNING,
+ "Configured Ordinal is not an int number: " + configuredOrdinal, e);
+ }
+ }
+ return getDefaultOrdinal();
+ }
+
+ /**
+ * Returns the default ordinal used, when no ordinal is set, or the ordinal was not parseable to an int value.
+ *
+ * @return the default ordinal used, by default 0.
+ */
+ public int getDefaultOrdinal() {
+ return 0;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public String getValue(String key) {
+ return this.properties.get(key);
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ return properties;
+ }
+
+ @Override
+ public String toString(){
+ return "PropertiesBasedConfigSource["+name+']';
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/06f29e1a/modules/resources/src/main/java/org/apache/tamaya/resource/AbstractPathPropertySourceProvider.java
----------------------------------------------------------------------
diff --git a/modules/resources/src/main/java/org/apache/tamaya/resource/AbstractPathPropertySourceProvider.java b/modules/resources/src/main/java/org/apache/tamaya/resource/AbstractPathPropertySourceProvider.java
deleted file mode 100644
index 760e688..0000000
--- a/modules/resources/src/main/java/org/apache/tamaya/resource/AbstractPathPropertySourceProvider.java
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.resource;
-
-import java.io.InputStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Objects;
-import java.util.Properties;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertySourceProvider;
-import org.apache.tamaya.spi.PropertyValue;
-
-/**
- * Abstract base class that uses a descriptive resource path to define the locations of configuration files to be
- * included into the configuration. This is especially useful, when the current configuration policy in place
- * does not define the exact file names, but the file locations, where configuration can be provided.
- */
-public abstract class AbstractPathPropertySourceProvider implements PropertySourceProvider{
- /** The log used. */
- private static final Logger LOG = Logger.getLogger(AbstractPathPropertySourceProvider.class.getName());
- /** The resource paths. */
- private String[] resourcePaths;
-
-
- /**
- * Creates a new instance using the given resource paths.
- * @param resourcePaths the resource paths, not null, not empty.
- */
- public AbstractPathPropertySourceProvider(String... resourcePaths){
- if(resourcePaths.length==0){
- throw new IllegalArgumentException("At least one resource path should be configured.");
- }
-
- setResourcePaths(resourcePaths);
- }
-
- @Override
- public Collection<PropertySource> getPropertySources() {
- List<PropertySource> propertySources = new ArrayList<>();
- for (String resource : getResourcePaths()) {
- try {
- Collection<URL> resources = ConfigResources.getResourceResolver().getResources(resource);
- for (URL url : resources) {
- try {
- Collection<PropertySource> propertySourcesToInclude = getPropertySources(url);
- if(propertySourcesToInclude!=null){
- propertySources.addAll(propertySourcesToInclude);
- }
- } catch (Exception e) {
- LOG.log(Level.WARNING, "Failed to read configuration from " + url, e);
- }
- }
- } catch (Exception e) {
- LOG.log(Level.SEVERE, "Invalid resource path: " + resource, e);
- }
- }
- return propertySources;
- }
-
- protected String[] getResourcePaths() {
- return resourcePaths;
- }
-
- protected void setResourcePaths(String[] paths) {
- resourcePaths = paths.clone();
- }
-
- /**
- * Factory method that creates a {@link org.apache.tamaya.spi.PropertySource} based on the URL found by
- * the resource locator.
- * @param url the URL, not null.
- * @return the {@link org.apache.tamaya.spi.PropertySource}s to be included into the current provider's sources
- * list. It is safe to return {@code null} here, in case the content of the URL has shown to be not relevant
- * as configuration input. In case the input is not valid or accessible an exception can be thrown or logged.
- */
- protected abstract Collection<PropertySource> getPropertySources(URL url);
-
- /**
- * Utility method that reads a .properties file from the given url and creates a corresponding
- * {@link org.apache.tamaya.spi.PropertySource}.
- * @param url the url to read, not null.
- * @return the corresponding PropertySource, or null.
- */
- public static PropertySource createPropertiesPropertySource(URL url) {
- Properties props = new Properties();
- try (InputStream is = url.openStream()){
- props.load(is);
- return new PropertiesBasedPropertySource(url.toString(), props);
- }
- catch (Exception e){
- LOG.log(Level.WARNING, "Failed to read properties from " + url, e);
- return null;
- }
- }
-
- /**
- * Minimal {@link PropertySource} implementation based on {@link Properties} or
- * {@link Map}.
- */
- private final static class PropertiesBasedPropertySource implements PropertySource{
- /** The property source's name. */
- private final String name;
- /** The properties. */
- private final Map<String,PropertyValue> properties = new HashMap<>();
-
- /**
- * Constructor for a simple properties configuration.
- * @param name the source's name, not null
- * @param props the properties, not null
- */
- public PropertiesBasedPropertySource(String name, Properties props) {
- this.name = Objects.requireNonNull(name);
- for (Entry<Object, Object> en : props.entrySet()) {
- this.properties.put(en.getKey().toString(),
- PropertyValue.of(en.getKey().toString(), String.valueOf(en.getValue()), name));
- }
- }
-
- /**
- * Constructor for a simple properties configuration.
- * @param name the source's name, not null
- * @param props the properties, not null
- */
- public PropertiesBasedPropertySource(String name, Map<String,String> props) {
- this.name = Objects.requireNonNull(name);
- for (Entry<String, String> en : props.entrySet()) {
- this.properties.put(en.getKey(),
- PropertyValue.of(en.getKey(), en.getValue(), name));
- }
- }
-
- public int getOrdinal() {
- PropertyValue configuredOrdinal = get(TAMAYA_ORDINAL);
- if (configuredOrdinal != null) {
- try {
- return Integer.parseInt(configuredOrdinal.getValue());
- } catch (Exception e) {
- Logger.getLogger(getClass().getName()).log(Level.WARNING,
- "Configured Ordinal is not an int number: " + configuredOrdinal, e);
- }
- }
- return getDefaultOrdinal();
- }
-
- /**
- * Returns the default ordinal used, when no ordinal is set, or the ordinal was not parseable to an int value.
- *
- * @return the default ordinal used, by default 0.
- */
- public int getDefaultOrdinal() {
- return 0;
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public PropertyValue get(String key) {
- return this.properties.get(key);
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
- return properties;
- }
-
- @Override
- public boolean isScannable() {
- return false;
- }
-
- @Override
- public String toString(){
- return "PropertiesBasedPropertySource["+name+']';
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/06f29e1a/modules/resources/src/main/java/org/apache/tamaya/resource/ConfigResources.java
----------------------------------------------------------------------
diff --git a/modules/resources/src/main/java/org/apache/tamaya/resource/ConfigResources.java b/modules/resources/src/main/java/org/apache/tamaya/resource/ConfigResources.java
index ae08148..fc40260 100644
--- a/modules/resources/src/main/java/org/apache/tamaya/resource/ConfigResources.java
+++ b/modules/resources/src/main/java/org/apache/tamaya/resource/ConfigResources.java
@@ -18,7 +18,6 @@
*/
package org.apache.tamaya.resource;
-import org.apache.tamaya.ConfigException;
import org.apache.tamaya.spi.ServiceContextManager;
@@ -35,14 +34,14 @@ public final class ConfigResources {
/**
* <p>Access the current ResourceResolver.</p>
*
- * @throws ConfigException if no ResourceResolver is available (should not happen).
+ * @throws IllegalStateException if no ResourceResolver is available (should not happen).
*
* @return the current ResourceResolver instance, never null.
*/
- public static ResourceResolver getResourceResolver() throws ConfigException {
+ public static ResourceResolver getResourceResolver() {
ResourceResolver resolver = ServiceContextManager.getServiceContext().getService(ResourceResolver.class);
if (resolver == null) {
- throw new ConfigException("ResourceResolver not available.");
+ throw new IllegalStateException("ResourceResolver not available.");
}
return resolver;
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/06f29e1a/modules/resources/src/test/java/org/apache/tamaya/resource/AbstractPathPropertySourceProviderTest.java
----------------------------------------------------------------------
diff --git a/modules/resources/src/test/java/org/apache/tamaya/resource/AbstractPathPropertySourceProviderTest.java b/modules/resources/src/test/java/org/apache/tamaya/resource/AbstractPathPropertySourceProviderTest.java
index 0dc6c91..3ad3e93 100644
--- a/modules/resources/src/test/java/org/apache/tamaya/resource/AbstractPathPropertySourceProviderTest.java
+++ b/modules/resources/src/test/java/org/apache/tamaya/resource/AbstractPathPropertySourceProviderTest.java
@@ -18,10 +18,9 @@
*/
package org.apache.tamaya.resource;
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
import org.junit.Test;
+import javax.config.spi.ConfigSource;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
@@ -36,30 +35,30 @@ import static org.junit.Assert.assertTrue;
public class AbstractPathPropertySourceProviderTest {
- private final AbstractPathPropertySourceProvider myProvider = new AbstractPathPropertySourceProvider("*.properties") {
+ private final AbstractPathConfigSourceProvider myProvider = new AbstractPathConfigSourceProvider("*.properties") {
@Override
- protected Collection<PropertySource> getPropertySources(URL url) {
- List<PropertySource> result = new ArrayList<>();
- result.add(new EmptyPropertySource());
+ protected Collection<ConfigSource> getConfigSources(URL url) {
+ List<ConfigSource> result = new ArrayList<>();
+ result.add(new EmptyConfigSource());
return result;
}
};
@Test
- public void testGetPropertySources() throws Exception {
- assertNotNull(myProvider.getPropertySources());
+ public void testGetConfigSources() throws Exception {
+ assertNotNull(myProvider.getConfigSources((ClassLoader)null));
}
@Test
public void testCreatePropertiesPropertySource() throws Exception {
- PropertySource ps = AbstractPathPropertySourceProvider.createPropertiesPropertySource(
+ ConfigSource ps = AbstractPathConfigSourceProvider.createConfigSource(
ClassLoader.getSystemClassLoader().getResource("test.properties")
);
assertNotNull(ps);
assertTrue(ps.getProperties().isEmpty());
}
- private static final class EmptyPropertySource implements PropertySource {
+ private static final class EmptyConfigSource implements ConfigSource {
/**
* Lookup order:
* TODO rethink whole default PropertySources and ordering:
@@ -88,10 +87,10 @@ public class AbstractPathPropertySourceProviderTest {
* @return the 'importance' aka ordinal of the configured values. The higher, the more important.
*/
public int getOrdinal() {
- PropertyValue configuredOrdinal = get(TAMAYA_ORDINAL);
+ String configuredOrdinal = getValue(CONFIG_ORDINAL);
if (configuredOrdinal != null) {
try {
- return Integer.parseInt(configuredOrdinal.getValue());
+ return Integer.parseInt(configuredOrdinal);
} catch (Exception e) {
Logger.getLogger(getClass().getName()).log(Level.WARNING,
"Configured Ordinal is not an int number: " + configuredOrdinal, e);
@@ -115,18 +114,14 @@ public class AbstractPathPropertySourceProviderTest {
}
@Override
- public PropertyValue get(String key) {
+ public String getValue(String key) {
return null;
}
@Override
- public Map<String, PropertyValue> getProperties() {
+ public Map<String, String> getProperties() {
return Collections.emptyMap();
}
- @Override
- public boolean isScannable() {
- return true;
- }
}
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/06f29e1a/modules/resources/src/test/java/org/apache/tamaya/resource/internal/PathBasedConfigSourceProvider.java
----------------------------------------------------------------------
diff --git a/modules/resources/src/test/java/org/apache/tamaya/resource/internal/PathBasedConfigSourceProvider.java b/modules/resources/src/test/java/org/apache/tamaya/resource/internal/PathBasedConfigSourceProvider.java
new file mode 100644
index 0000000..db1c72a
--- /dev/null
+++ b/modules/resources/src/test/java/org/apache/tamaya/resource/internal/PathBasedConfigSourceProvider.java
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.resource.internal;
+
+import org.apache.tamaya.resource.AbstractPathConfigSourceProvider;
+
+import javax.config.spi.ConfigSource;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.*;
+
+/**
+ * Created by Anatole on 03.03.2015.
+ */
+public class PathBasedConfigSourceProvider extends AbstractPathConfigSourceProvider {
+
+ public PathBasedConfigSourceProvider() {
+ super("META-INF/cfg/**/*.properties");
+ }
+
+ @Override
+ protected Collection<ConfigSource> getConfigSources(URL url) {
+ List<ConfigSource> list = new ArrayList<>();
+ Properties props = new Properties();
+ try(InputStream is = url.openStream()){
+ props.load(is);
+ list.add(new PropertiesBasedConfigSource(url.toString(), props));
+ }
+ catch(Exception e){
+ e.printStackTrace();
+ return null;
+ }
+ return list;
+ }
+
+
+ private final static class PropertiesBasedConfigSource implements ConfigSource{
+
+ private final String name;
+ private final Map<String,String> properties = new HashMap<>();
+
+ public PropertiesBasedConfigSource(String name, Properties props) {
+ this.name = Objects.requireNonNull(name);
+ for (Map.Entry en : props.entrySet()) {
+ this.properties.put(en.getKey().toString(),
+ String.valueOf(en.getValue()));
+ }
+ }
+
+ @Override
+ public int getOrdinal() {
+ return 0;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public String getValue(String key) {
+ return properties.get(key);
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ return properties;
+ }
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/06f29e1a/modules/resources/src/test/java/org/apache/tamaya/resource/internal/PathBasedPropertySourceProvider.java
----------------------------------------------------------------------
diff --git a/modules/resources/src/test/java/org/apache/tamaya/resource/internal/PathBasedPropertySourceProvider.java b/modules/resources/src/test/java/org/apache/tamaya/resource/internal/PathBasedPropertySourceProvider.java
deleted file mode 100644
index 7e2f622..0000000
--- a/modules/resources/src/test/java/org/apache/tamaya/resource/internal/PathBasedPropertySourceProvider.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.resource.internal;
-
-import org.apache.tamaya.resource.AbstractPathPropertySourceProvider;
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-
-import java.io.InputStream;
-import java.net.URL;
-import java.util.*;
-
-/**
- * Created by Anatole on 03.03.2015.
- */
-public class PathBasedPropertySourceProvider extends AbstractPathPropertySourceProvider{
-
- public PathBasedPropertySourceProvider() {
- super("META-INF/cfg/**/*.properties");
- }
-
- @Override
- protected Collection<PropertySource> getPropertySources(URL url) {
- List<PropertySource> list = new ArrayList<>();
- Properties props = new Properties();
- try(InputStream is = url.openStream()){
- props.load(is);
- list.add(new PropertiesBasedPropertySource(url.toString(), props));
- }
- catch(Exception e){
- e.printStackTrace();
- return null;
- }
- return list;
- }
-
-
- private final static class PropertiesBasedPropertySource implements PropertySource{
-
- private final String name;
- private final Map<String,PropertyValue> properties = new HashMap<>();
-
- public PropertiesBasedPropertySource(String name, Properties props) {
- this.name = Objects.requireNonNull(name);
- for (Map.Entry en : props.entrySet()) {
- this.properties.put(en.getKey().toString(),
- PropertyValue.of(en.getKey().toString(),
- String.valueOf(en.getValue()),
- name));
- }
- }
-
- @Override
- public int getOrdinal() {
- return 0;
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public PropertyValue get(String key) {
- return properties.get(key);
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
- return properties;
- }
-
- @Override
- public boolean isScannable() {
- return false;
- }
- }
-}
[09/18] incubator-tamaya-extensions git commit: Adapted to comply
with JSR API.
Posted by an...@apache.org.
Adapted to comply with JSR API.
Signed-off-by: Anatole Tresch <an...@apache.org>
Project: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/commit/4869d946
Tree: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/tree/4869d946
Diff: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/diff/4869d946
Branch: refs/heads/configjsr
Commit: 4869d946cb8a5730feb74c8dea379d9462427b5e
Parents: 36b4466
Author: Anatole Tresch <an...@apache.org>
Authored: Thu Dec 28 02:27:43 2017 +0100
Committer: Anatole Tresch <an...@apache.org>
Committed: Thu Dec 28 02:27:43 2017 +0100
----------------------------------------------------------------------
modules/events/pom.xml | 15 +-
.../org/apache/tamaya/events/ConfigChange.java | 229 +++++++++++++++
.../tamaya/events/ConfigChangeBuilder.java | 274 ++++++++++++++++++
.../tamaya/events/ConfigEventManager.java | 9 +-
.../tamaya/events/ConfigSourceChange.java | 211 ++++++++++++++
.../events/ConfigSourceChangeBuilder.java | 250 +++++++++++++++++
.../tamaya/events/ConfigurationChange.java | 230 ---------------
.../events/ConfigurationChangeBuilder.java | 278 -------------------
.../org/apache/tamaya/events/FrozenConfig.java | 197 +++++++++++++
.../tamaya/events/FrozenConfigSource.java | 129 +++++++++
.../tamaya/events/FrozenConfiguration.java | 227 ---------------
.../tamaya/events/FrozenPropertySource.java | 135 ---------
.../tamaya/events/PropertySourceChange.java | 212 --------------
.../events/PropertySourceChangeBuilder.java | 252 -----------------
.../internal/DefaultConfigChangeObserver.java | 20 +-
.../events/internal/LoggingConfigListener.java | 4 +-
.../events/spi/ConfigEventManagerSpi.java | 3 +-
.../events/ChangeableGlobalConfigSource.java | 62 +++++
.../events/ChangeableGlobalPropertySource.java | 62 -----
.../ChangeableThreadLocalPropertySource.java | 7 +-
.../tamaya/events/ConfigChangeBuilderTest.java | 134 +++++++++
.../apache/tamaya/events/ConfigChangeTest.java | 161 +++++++++++
.../tamaya/events/ConfigSourceChangeTest.java | 180 ++++++++++++
.../events/ConfigurationChangeBuilderTest.java | 131 ---------
.../tamaya/events/ConfigurationChangeTest.java | 162 -----------
.../tamaya/events/FrozenConfigSourceTest.java | 108 +++++++
.../tamaya/events/FrozenConfigurationTest.java | 23 +-
.../tamaya/events/FrozenPropertySourceTest.java | 109 --------
.../tamaya/events/ObservedConfigTest.java | 4 +-
.../tamaya/events/PropertySourceChangeTest.java | 180 ------------
.../tamaya/events/RandomConfigSource.java | 59 ++++
.../tamaya/events/RandomPropertySource.java | 65 -----
.../apache/tamaya/events/TestConfigView.java | 126 ++-------
.../folderobserver/FileChangeListener.java | 6 +-
.../ObservingPropertySourceProvider.java | 58 ++--
.../DefaultConfigChangeObserverTest.java | 6 +-
.../org.apache.tamaya.spi.PropertySource | 2 +-
37 files changed, 2094 insertions(+), 2226 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/pom.xml
----------------------------------------------------------------------
diff --git a/modules/events/pom.xml b/modules/events/pom.xml
index aaa650f..33904d0 100644
--- a/modules/events/pom.xml
+++ b/modules/events/pom.xml
@@ -34,25 +34,20 @@ under the License.
<dependencies>
<dependency>
- <groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-api</artifactId>
- <version>${tamaya-apicore.version}</version>
- </dependency>
- <dependency>
<groupId>org.apache.tamaya.ext</groupId>
<artifactId>tamaya-functions</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-spisupport</artifactId>
- <version>${project.version}</version>
+ <artifactId>tamaya-core</artifactId>
+ <version>${tamaya-apicore.version}</version>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-core</artifactId>
- <version>${tamaya-apicore.version}</version>
- <scope>runtime</scope>
+ <artifactId>tamaya-base</artifactId>
+ <version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/main/java/org/apache/tamaya/events/ConfigChange.java
----------------------------------------------------------------------
diff --git a/modules/events/src/main/java/org/apache/tamaya/events/ConfigChange.java b/modules/events/src/main/java/org/apache/tamaya/events/ConfigChange.java
new file mode 100644
index 0000000..01074b5
--- /dev/null
+++ b/modules/events/src/main/java/org/apache/tamaya/events/ConfigChange.java
@@ -0,0 +1,229 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.events;
+
+import javax.config.Config;
+import java.beans.PropertyChangeEvent;
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+/**
+ * Event that contains a set current changes that were applied or could be applied.
+ * This class is immutable and thread-safe. To create instances use
+ * {@link ConfigSourceChangeBuilder}.
+ *
+ * Created by Anatole on 22.10.2014.
+ */
+public final class ConfigChange implements ConfigEvent<Config>, Serializable{
+
+ private static final long serialVersionUID = 1L;
+ /** The base property provider/configuration. */
+ private final FrozenConfig configuration;
+ /** The base version, usable for optimistic locking. */
+ private String version = UUID.randomUUID().toString();
+ /** The timestamp of the change set in millis from the epoch. */
+ private long timestamp = System.currentTimeMillis();
+ /** The recorded changes. */
+ private final Map<String,PropertyChangeEvent> changes = new HashMap<>();
+
+ /**
+ * Get an empty change set for the given provider.
+ * @param configuration The configuration changed, not null.
+ * @return an empty ConfigurationChangeSet instance.
+ */
+ public static ConfigChange emptyChangeSet(Config configuration){
+ return ConfigChangeBuilder.of(configuration).build();
+ }
+
+ /**
+ * Constructor used by {@link ConfigSourceChangeBuilder}.
+ * @param builder The builder used, not null.
+ */
+ ConfigChange(ConfigChangeBuilder builder) {
+ this.configuration = FrozenConfig.of(builder.source);
+ for(PropertyChangeEvent ev:builder.delta.values()){
+ this.changes.put(ev.getPropertyName(), ev);
+ }
+ if(builder.version!=null){
+ this.version = builder.version;
+ }
+ if(builder.timestamp!=null){
+ this.timestamp = builder.timestamp;
+ }
+ }
+
+ @Override
+ public Class<Config> getResourceType() {
+ return Config.class;
+ }
+
+ /**
+ * Get the underlying property provider/configuration.
+ * @return the underlying property provider/configuration, never null.
+ */
+ @Override
+ public Config getResource(){
+ return this.configuration;
+ }
+
+ /**
+ * Get the base version, usable for optimistic locking.
+ * @return the base version.
+ */
+ @Override
+ public String getVersion(){
+ return version;
+ }
+
+ /**
+ * Get the timestamp in millis from the current epoch. it is expected that the timestamp and the version are unique to
+ * identify a changeset.
+ * @return the timestamp, when this changeset was created.
+ */
+ @Override
+ public long getTimestamp(){
+ return timestamp;
+ }
+
+ /**
+ * Get the changes recorded.
+ * @return the recorded changes, never null.
+ */
+ public Collection<PropertyChangeEvent> getChanges(){
+ return Collections.unmodifiableCollection(this.changes.values());
+ }
+
+ /**
+ * Access the number current removed entries.
+ * @return the number current removed entries.
+ */
+ public int getRemovedSize() {
+ int removedCount = 0;
+ for(PropertyChangeEvent ev:this.changes.values()){
+ if(ev.getPropertyName().startsWith("_")){
+ continue;
+ }
+ if(ev.getNewValue() == null){
+ removedCount++;
+ }
+ }
+ return removedCount;
+ }
+
+ /**
+ * Access the number current added entries.
+ * @return the number current added entries.
+ */
+ public int getAddedSize() {
+ int addedCount = 0;
+ for(PropertyChangeEvent ev:this.changes.values()){
+ if(ev.getPropertyName().startsWith("_")){
+ continue;
+ }
+ if(ev.getOldValue() == null &&
+ ev.getNewValue() != null){
+ addedCount++;
+ }
+ }
+ return addedCount;
+ }
+
+ /**
+ * Access the number current updated entries.
+ * @return the number current updated entries.
+ */
+ public int getUpdatedSize() {
+ int updatedCount = 0;
+ for(PropertyChangeEvent ev:this.changes.values()){
+ if(ev.getPropertyName().startsWith("_")){
+ continue;
+ }
+ if( ev.getOldValue()!=null && ev.getNewValue()!=null){
+ updatedCount++;
+ }
+ }
+ return updatedCount;
+ }
+
+
+ /**
+ * Checks if the given key was removed.
+ * @param key the target key, not null.
+ * @return true, if the given key was removed.
+ */
+ public boolean isRemoved(String key) {
+ PropertyChangeEvent change = this.changes.get(key);
+ return change != null && change.getNewValue() == null;
+ }
+
+ /**
+ * Checks if the given key was added.
+ * @param key the target key, not null.
+ * @return true, if the given key was added.
+ */
+ public boolean isAdded(String key) {
+ PropertyChangeEvent change = this.changes.get(key);
+ return change != null && change.getOldValue() == null;
+ }
+
+ /**
+ * Checks if the given key was updated.
+ * @param key the target key, not null.
+ * @return true, if the given key was updated.
+ */
+ public boolean isUpdated(String key) {
+ PropertyChangeEvent change = this.changes.get(key);
+ return change != null && change.getOldValue() != null && change.getNewValue() != null;
+ }
+
+ /**
+ * Checks if the given key is added, or updated AND NOT removed.
+ * @param key the target key, not null.
+ * @return true, if the given key was added, or updated BUT NOT removed.
+ */
+ public boolean isKeyAffected(String key) {
+ PropertyChangeEvent change = this.changes.get(key);
+ return change != null && change.getNewValue() != null;
+ }
+
+ /**
+ * CHecks if the current change set does not contain any changes.
+ * @return tru, if the change set is empty.
+ */
+ public boolean isEmpty(){
+ return this.changes.isEmpty();
+ }
+
+
+ @Override
+ public String toString() {
+ return "ConfigurationChange{" +
+ "\n config-id = " + configuration.getOptionalValue("_id",String.class).orElse("-") +
+ "\n change-id = " + version +
+ "\n timestamp = " + timestamp +
+ "\n added = " + this.getAddedSize() +
+ "\n updated = " + this.getUpdatedSize() +
+ "\n removed = " + this.getRemovedSize() + '\n' +
+ '}';
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/main/java/org/apache/tamaya/events/ConfigChangeBuilder.java
----------------------------------------------------------------------
diff --git a/modules/events/src/main/java/org/apache/tamaya/events/ConfigChangeBuilder.java b/modules/events/src/main/java/org/apache/tamaya/events/ConfigChangeBuilder.java
new file mode 100644
index 0000000..a170ab4
--- /dev/null
+++ b/modules/events/src/main/java/org/apache/tamaya/events/ConfigChangeBuilder.java
@@ -0,0 +1,274 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.events;
+
+import javax.config.Config;
+import javax.config.ConfigProvider;
+import java.beans.PropertyChangeEvent;
+import java.util.*;
+
+/**
+ * Models a set current changes applied to a {@link org.apache.tamaya.spi.PropertySource}. Consumers of these events
+ * can observe changes to property sources and
+ * <ol>
+ * <li>Check if their current configuration instance ({@link org.apache.tamaya.spi.ConfigurationContext}
+ * contains the changed {@link org.apache.tamaya.spi.PropertySource} (Note: the reference to a property source is never affected by a
+ * change, its only the data of the property source).</li>
+ * <li>If so corresponding actions might be taken, such as reevaluating the configuration values (depending on
+ * the update policy) or reevaluating the complete {@link org.apache.tamaya.Configuration} to create a change
+ * event on configuration level.
+ * </ol>
+ */
+public final class ConfigChangeBuilder {
+ /**
+ * The recorded changes.
+ */
+ final SortedMap<String, PropertyChangeEvent> delta = new TreeMap<>();
+ /**
+ * The underlying configuration/provider.
+ */
+ final Config source;
+ /**
+ * The version configured, or null, for generating a default.
+ */
+ String version;
+ /**
+ * The optional timestamp in millis of this epoch.
+ */
+ Long timestamp;
+
+ /**
+ * Constructor.
+ *
+ * @param configuration the underlying configuration, not null.
+ */
+ private ConfigChangeBuilder(Config configuration) {
+ this.source = Objects.requireNonNull(configuration);
+ }
+
+ /**
+ * Creates a new instance current this builder using the current COnfiguration as root resource.
+ *
+ * @return the builder for chaining.
+ */
+ public static ConfigChangeBuilder of() {
+ return new ConfigChangeBuilder(ConfigProvider.getConfig());
+ }
+
+ /**
+ * Creates a new instance current this builder.
+ *
+ * @param configuration the configuration changed, not null.
+ * @return the builder for chaining.
+ */
+ public static ConfigChangeBuilder of(Config configuration) {
+ return new ConfigChangeBuilder(configuration);
+ }
+
+ /**
+ * Compares the two property config/configurations and creates a collection with all changes
+ * that must be applied to render {@code previous} into {@code target}.
+ *
+ * @param previous the previous map, not null.
+ * @param current the target map, not null.
+ * @return a collection current change events, never {@code null}.
+ */
+ public static Collection<PropertyChangeEvent> compare(Config previous, Config current) {
+ TreeMap<String, PropertyChangeEvent> events = new TreeMap<>();
+
+ for (String key : previous.getPropertyNames()) {
+ String previousValue = previous.getValue(key, String.class);
+ Optional<String> currentValue = current.getOptionalValue(key, String.class);
+ if(Objects.equals(currentValue.orElse(null), previousValue)){
+ continue;
+ }else {
+ PropertyChangeEvent event = new PropertyChangeEvent(previous, key, previousValue, currentValue.orElse(null));
+ events.put(key, event);
+ }
+ }
+
+ for (String key : current.getPropertyNames()){
+ Optional<String> previousValue = previous.getOptionalValue(key, String.class);
+ String currentValue = current.getOptionalValue(key, String.class).orElse(null);
+ if(Objects.equals(currentValue, previousValue.orElse(null))){
+ continue;
+ }else{
+ if (!previousValue.isPresent()) {
+ PropertyChangeEvent event = new PropertyChangeEvent(current, key, null, currentValue);
+ events.put(key, event);
+ }
+ // the other cases were already covered by the previous loop.
+ }
+ }
+ return events.values();
+ }
+
+ /*
+ * Apply a version/UUID to the set being built.
+ * @param version the version to apply, or null, to let the system generate a version for you.
+ * @return the builder for chaining.
+ */
+ public ConfigChangeBuilder setVersion(String version) {
+ this.version = version;
+ return this;
+ }
+
+ /*
+ * Apply given timestamp to the set being built.
+ * @param version the version to apply, or null, to let the system generate a version for you.
+ * @return the builder for chaining.
+ */
+ public ConfigChangeBuilder setTimestamp(long timestamp) {
+ this.timestamp = timestamp;
+ return this;
+ }
+
+ /**
+ * This method records all changes to be applied to the base property provider/configuration to
+ * achieve the given target state.
+ *
+ * @param newState the new target state, not null.
+ * @return the builder for chaining.
+ */
+ public ConfigChangeBuilder addChanges(Config newState) {
+ for (PropertyChangeEvent c : compare(this.source, newState)) {
+ this.delta.put(c.getPropertyName(), c);
+ }
+ return this;
+ }
+
+ /**
+ * Applies a single key/value change.
+ *
+ * @param key the changed key
+ * @param value the new value.
+ * @return this instance for chaining.
+ */
+ public ConfigChangeBuilder addChange(String key, String value) {
+ this.delta.put(key, new PropertyChangeEvent(this.source, key,
+ this.source.getOptionalValue(key, String.class).orElse(null),
+ value));
+ return this;
+ }
+
+ /**
+ * Get the current values, also considering any changes recorded within this change set.
+ *
+ * @param key the key current the entry, not null.
+ * @return the keys, or null.
+ */
+ public String get(String key) {
+ PropertyChangeEvent change = this.delta.get(key);
+ if (change != null && !(change.getNewValue() == null)) {
+ return (String) change.getNewValue();
+ }
+ return null;
+ }
+
+ /**
+ * Marks the given key(s) fromMap the configuration/properties to be removed.
+ *
+ * @param key the key current the entry, not null.
+ * @param otherKeys additional keys to be removed (convenience), not null.
+ * @return the builder for chaining.
+ */
+ public ConfigChangeBuilder removeKey(String key, String... otherKeys) {
+ Optional<String> oldValue = this.source.getOptionalValue(key, String.class);
+ if (!oldValue.isPresent()) {
+ this.delta.remove(key);
+ }
+ this.delta.put(key, new PropertyChangeEvent(this.source, key, oldValue, null));
+ for (String addKey : otherKeys) {
+ oldValue = this.source.getOptionalValue(key, String.class);
+ if (!oldValue.isPresent()) {
+ this.delta.remove(addKey);
+ }
+ this.delta.put(addKey, new PropertyChangeEvent(this.source, addKey, oldValue, null));
+ }
+ return this;
+ }
+
+ /**
+ * Apply all the given values to the base configuration/properties.
+ * Note that all values passed must be convertible to String, either
+ * <ul>
+ * <li>the registered codecs provider provides codecs for the corresponding keys, or </li>
+ * <li>default codecs are present for the given type, or</li>
+ * <li>the value is an instanceof String</li>
+ * </ul>
+ *
+ * @param changes the changes to be applied, not null.
+ * @return the builder for chaining.
+ */
+ public ConfigChangeBuilder putAll(Map<String, String> changes) {
+ for (Map.Entry<String, String> en : changes.entrySet()) {
+ this.delta.put(en.getKey(), new PropertyChangeEvent(this.source, en.getKey(), null, en.getValue()));
+ }
+ return this;
+ }
+
+ /**
+ * This method will create a change set that clears all entries fromMap the given base configuration/properties.
+ *
+ * @return the builder for chaining.
+ */
+ public ConfigChangeBuilder removeAllKeys() {
+ this.delta.clear();
+ for (String key : this.source.getPropertyNames()) {
+ this.delta.put(key, new PropertyChangeEvent(this.source, key, this.source.getValue(key, String.class),
+ null));
+ }
+// this.source.getProperties().forEach((k, v) ->
+// this.delta.put(k, new PropertyChangeEvent(this.source, k, v, null)));
+ return this;
+ }
+
+ /**
+ * Checks if the change set is empty, i.e. does not contain any changes.
+ *
+ * @return true, if the set is empty.
+ */
+ public boolean isEmpty() {
+ return this.delta.isEmpty();
+ }
+
+ /**
+ * Resets this change set instance. This will clear all changes done to this builder, so the
+ * set will be empty.
+ */
+ public void reset() {
+ this.delta.clear();
+ }
+
+ /**
+ * Builds the corresponding change set.
+ *
+ * @return the new change set, never null.
+ */
+ public ConfigChange build() {
+ return new ConfigChange(this);
+ }
+
+ @Override
+ public String toString() {
+ return "ConfigurationChangeSetBuilder [config=" + source + ", " +
+ ", delta=" + delta + "]";
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/main/java/org/apache/tamaya/events/ConfigEventManager.java
----------------------------------------------------------------------
diff --git a/modules/events/src/main/java/org/apache/tamaya/events/ConfigEventManager.java b/modules/events/src/main/java/org/apache/tamaya/events/ConfigEventManager.java
index 96dc9a5..29426a1 100644
--- a/modules/events/src/main/java/org/apache/tamaya/events/ConfigEventManager.java
+++ b/modules/events/src/main/java/org/apache/tamaya/events/ConfigEventManager.java
@@ -18,7 +18,6 @@
*/
package org.apache.tamaya.events;
-import org.apache.tamaya.ConfigException;
import org.apache.tamaya.events.spi.ConfigEventManagerSpi;
import org.apache.tamaya.spi.ServiceContextManager;
@@ -37,7 +36,7 @@ public final class ConfigEventManager {
ConfigEventManagerSpi spi = ServiceContextManager.getServiceContext()
.getService(ConfigEventManagerSpi.class);
if(spi==null){
- throw new ConfigException("No SPI registered for " +
+ throw new IllegalStateException("No SPI registered for " +
ConfigEventManager.class.getName());
}
return spi;
@@ -110,7 +109,7 @@ public final class ConfigEventManager {
}
/**
- * Publishes a {@link ConfigurationChange} synchronously to all interested listeners.
+ * Publishes a {@link ConfigChange} synchronously to all interested listeners.
*
* @param <T> the type of the event.
* @param event the event, not null.
@@ -120,7 +119,7 @@ public final class ConfigEventManager {
}
/**
- * Publishes a {@link ConfigurationChange} asynchronously/multithreaded to all interested listeners.
+ * Publishes a {@link ConfigChange} asynchronously/multithreaded to all interested listeners.
*
* @param <T> the type of the event.
* @param event the event, not null.
@@ -134,7 +133,7 @@ public final class ConfigEventManager {
* and trigger ConfigurationChange events if something changed. This is quite handy for publishing
* configuration changes to whatever systems are interested in. Hereby the origin of a configuration change
* can be on this machine, or also remotely. For handling corresponding {@link ConfigEventListener} have
- * to be registered, e.g. listening on {@link org.apache.tamaya.events.ConfigurationChange} events.
+ * to be registered, e.g. listening on {@link ConfigChange} events.
*
* @param enable whether to enable or disable the change monitoring.
*
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/main/java/org/apache/tamaya/events/ConfigSourceChange.java
----------------------------------------------------------------------
diff --git a/modules/events/src/main/java/org/apache/tamaya/events/ConfigSourceChange.java b/modules/events/src/main/java/org/apache/tamaya/events/ConfigSourceChange.java
new file mode 100644
index 0000000..7bb5395
--- /dev/null
+++ b/modules/events/src/main/java/org/apache/tamaya/events/ConfigSourceChange.java
@@ -0,0 +1,211 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.events;
+
+import javax.config.spi.ConfigSource;
+import java.beans.PropertyChangeEvent;
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+/**
+ * Event that contains a set current changes that were applied or could be applied.
+ * This class is immutable and thread-safe. To create instances use
+ * {@link ConfigSourceChangeBuilder}.
+ *
+ * Created by Anatole on 22.10.2014.
+ */
+public final class ConfigSourceChange implements ConfigEvent<ConfigSource>, Serializable{
+
+ private static final long serialVersionUID = 1L;
+ /** The base property provider/configuration. */
+ private final FrozenConfigSource configSource;
+ /** The base version, usable for optimistic locking. */
+ private String version = UUID.randomUUID().toString();
+ /** The timestamp of the change set in millis from the epoch. */
+ private long timestamp = System.currentTimeMillis();
+ /** The recorded changes. */
+ private final Map<String,PropertyChangeEvent> changes = new HashMap<>();
+
+ /**
+ * Constructor used by {@link ConfigSourceChangeBuilder}.
+ * @param builder The builder used, not null.
+ */
+ ConfigSourceChange(ConfigSourceChangeBuilder builder) {
+ this.configSource = FrozenConfigSource.of(builder.source);
+ for (PropertyChangeEvent c : builder.delta.values()) {
+ this.changes.put(c.getPropertyName(), c);
+ }
+ if(builder.version!=null){
+ this.version = builder.version;
+ }
+ if(builder.timestamp!=null){
+ this.timestamp = builder.timestamp;
+ }
+ }
+
+ @Override
+ public Class<ConfigSource> getResourceType() {
+ return ConfigSource.class;
+ }
+
+ /**
+ * Get the underlying property provider/configuration.
+ * @return the underlying property provider/configuration, or null, if the change instance was deserialized.
+ */
+ @Override
+ public ConfigSource getResource(){
+ return this.configSource;
+ }
+
+ /**
+ * Get the base version, usable for optimistic locking.
+ * @return the base version.
+ */
+ @Override
+ public String getVersion(){
+ return version;
+ }
+
+ /**
+ * Get the timestamp in millis from the current epoch. it is expected that the timestamp and the version are unique to
+ * identify a changeset.
+ * @return the timestamp, when this changeset was created.
+ */
+ @Override
+ public long getTimestamp(){
+ return timestamp;
+ }
+
+ /**
+ * Get the changes recorded.
+ * @return the recorded changes, never null.
+ */
+ public Collection<PropertyChangeEvent> getChanges(){
+ return Collections.unmodifiableCollection(this.changes.values());
+ }
+
+ /**
+ * Access the number current removed entries.
+ * @return the number current removed entries.
+ */
+ public int getRemovedSize() {
+ int removedCount = 0;
+ for (PropertyChangeEvent ev : this.changes.values()) {
+ if (ev.getNewValue() == null) {
+ removedCount++;
+ }
+ }
+ return removedCount;
+// return (int) this.changes.values().stream().filter((e) -> e.getNewValue() == null).count();
+ }
+
+ /**
+ * Access the number current added entries.
+ * @return the number current added entries.
+ */
+ public int getAddedSize() {
+ int addedCount = 0;
+ for (PropertyChangeEvent ev : this.changes.values()) {
+ if (ev.getOldValue() == null &&
+ ev.getNewValue() != null) {
+ addedCount++;
+ }
+ }
+ return addedCount;
+// return (int) this.changes.values().stream().filter((e) -> e.getOldValue() == null).count();
+ }
+
+ /**
+ * Access the number current updated entries.
+ * @return the number current updated entries.
+ */
+ public int getUpdatedSize() {
+ int updatedCount = 0;
+ for (PropertyChangeEvent ev : this.changes.values()) {
+ if (ev.getOldValue() != null && ev.getNewValue() != null) {
+ updatedCount++;
+ }
+ }
+ return updatedCount;
+// return (int) this.changes.values().stream().filter((e) -> e.getOldValue()!=null && e.getNewValue()!=null).count();
+ }
+
+
+ /**
+ * Checks if the given key was removed.
+ * @param key the target key, not null.
+ * @return true, if the given key was removed.
+ */
+ public boolean isRemoved(String key) {
+ PropertyChangeEvent change = this.changes.get(key);
+ return change != null && change.getNewValue() == null;
+ }
+
+ /**
+ * Checks if the given key was added.
+ * @param key the target key, not null.
+ * @return true, if the given key was added.
+ */
+ public boolean isAdded(String key) {
+ PropertyChangeEvent change = this.changes.get(key);
+ return change != null && change.getOldValue() == null;
+ }
+
+ /**
+ * Checks if the given key was updated.
+ * @param key the target key, not null.
+ * @return true, if the given key was updated.
+ */
+ public boolean isUpdated(String key) {
+ PropertyChangeEvent change = this.changes.get(key);
+ return change != null && change.getOldValue() != null && change.getNewValue() != null;
+ }
+
+ /**
+ * Checks if the given key is added, or updated AND NOT removed.
+ * @param key the target key, not null.
+ * @return true, if the given key was added, or updated BUT NOT removed.
+ */
+ public boolean isKeyAffected(String key) {
+ PropertyChangeEvent change = this.changes.get(key);
+ return change != null && change.getNewValue() != null;
+ }
+
+ /**
+ * CHecks if the current change set does not contain any changes.
+ * @return tru, if the change set is empty.
+ */
+ public boolean isEmpty(){
+ return this.changes.isEmpty();
+ }
+
+
+ @Override
+ public String toString() {
+ return "ConfigSourceChange{" +
+ ", configSource=" + configSource +
+ ", version='" + version + '\'' +
+ ", timestamp=" + timestamp +
+ '}';
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/main/java/org/apache/tamaya/events/ConfigSourceChangeBuilder.java
----------------------------------------------------------------------
diff --git a/modules/events/src/main/java/org/apache/tamaya/events/ConfigSourceChangeBuilder.java b/modules/events/src/main/java/org/apache/tamaya/events/ConfigSourceChangeBuilder.java
new file mode 100644
index 0000000..684bcf1
--- /dev/null
+++ b/modules/events/src/main/java/org/apache/tamaya/events/ConfigSourceChangeBuilder.java
@@ -0,0 +1,250 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.events;
+
+import javax.config.spi.ConfigSource;
+import java.beans.PropertyChangeEvent;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+/**
+ * Models a set current changes applied to a {@link ConfigSource}. Consumers of these events
+ * can observing changes to property sources and
+ * <ol>
+ * <li>Check if their current configuration instance ({@link javax.config.Config}
+ * contains the changed {@link ConfigSource} (Note: the reference tova property source is never affected by a
+ * change, its only the data of the property source).</li>
+ * <li>If so corresponding action may be taken, such as reevaluating the configuration values (depending on
+ * the update policy) or reevaluating the complete {@link javax.config.Config} to create a change
+ * event on configuration level.
+ * </ol>
+ */
+public final class ConfigSourceChangeBuilder {
+ /**
+ * The recorded changes.
+ */
+ final SortedMap<String, PropertyChangeEvent> delta = new TreeMap<>();
+ /**
+ * The underlying configuration/provider.
+ */
+ final ConfigSource source;
+ /**
+ * The version configured, or null, for generating a default.
+ */
+ String version;
+ /**
+ * The optional timestamp in millis of this epoch.
+ */
+ Long timestamp;
+
+ /**
+ * Constructor.
+ *
+ * @param source the underlying configuration/provider, not null.
+ */
+ private ConfigSourceChangeBuilder(ConfigSource source) {
+ this.source = Objects.requireNonNull(source);
+ }
+
+ /**
+ * Creates a new instance of this builder.
+ *
+ * @param source the underlying property provider/configuration, not null.
+ * @return the builder for chaining.
+ */
+ public static ConfigSourceChangeBuilder of(ConfigSource source) {
+ return new ConfigSourceChangeBuilder(source);
+ }
+
+ /**
+ * Compares the two property config/configurations and creates a collection current all changes
+ * that must be applied to render {@code map1} into {@code map2}.
+ *
+ * @param map1 the source map, not null.
+ * @param map2 the target map, not null.
+ * @return a collection current change events, never null.
+ */
+ public static Collection<PropertyChangeEvent> compare(ConfigSource map1, ConfigSource map2) {
+ List<PropertyChangeEvent> changes = new ArrayList<>();
+ for (Map.Entry<String, String> en : map1.getProperties().entrySet()) {
+ String val = map2.getValue(en.getKey());
+ if (val == null) {
+ changes.add(new PropertyChangeEvent(map1, en.getKey(), null, en.getValue()));
+ } else if (!val.equals(en.getValue())) {
+ changes.add(new PropertyChangeEvent(map1, en.getKey(), val, en.getValue()));
+ }
+ }
+ for (Map.Entry<String, String> en : map2.getProperties().entrySet()) {
+ String val = map1.getValue(en.getKey());
+ if (val == null) {
+ changes.add(new PropertyChangeEvent(map1, en.getKey(), en.getValue(), null));
+ } else if (!val.equals(en.getValue())) {
+ changes.add(new PropertyChangeEvent(map1, en.getKey(), en.getValue(), val));
+ }
+ }
+ return changes;
+ }
+
+ /*
+ * Apply a version/UUID to the set being built.
+ * @param version the version to apply, or null, to let the system generate a version for you.
+ * @return the builder for chaining.
+ */
+ public ConfigSourceChangeBuilder setVersion(String version) {
+ this.version = version;
+ return this;
+ }
+
+ /*
+ * Apply given timestamp to the set being built.
+ * @param version the version to apply, or null, to let the system generate a version for you.
+ * @return the builder for chaining.
+ */
+ public ConfigSourceChangeBuilder setTimestamp(long timestamp) {
+ this.timestamp = timestamp;
+ return this;
+ }
+
+ /**
+ * This method records all changes to be applied to the base property provider/configuration to
+ * achieve the given target state.
+ *
+ * @param newState the new target state, not null.
+ * @return the builder for chaining.
+ */
+ public ConfigSourceChangeBuilder addChanges(ConfigSource newState) {
+ Collection<PropertyChangeEvent> events = ConfigSourceChangeBuilder.compare(newState, this.source);
+ for (PropertyChangeEvent c : events) {
+ this.delta.put(c.getPropertyName(), c);
+ }
+ return this;
+ }
+
+ /**
+ * Get the current values, also considering any changes recorded within this change set.
+ *
+ * @param key the key current the entry, not null.
+ * @return the keys, or null.
+ */
+ public String get(String key) {
+ PropertyChangeEvent change = this.delta.get(key);
+ if (change != null && !(change.getNewValue() == null)) {
+ return (String) change.getNewValue();
+ }
+ return null;
+ }
+
+ /**
+ * Marks the given key(s) fromMap the configuration/properties to be removed.
+ *
+ * @param key the key current the entry, not null.
+ * @param otherKeys additional keys to be removed (convenience), not null.
+ * @return the builder for chaining.
+ */
+ public ConfigSourceChangeBuilder remove(String key, String... otherKeys) {
+ String oldValue = this.source.getValue(key);
+ if (oldValue == null) {
+ this.delta.remove(key);
+ }
+ this.delta.put(key, new PropertyChangeEvent(this.source, key, oldValue, null));
+ for (String addKey : otherKeys) {
+ oldValue = this.source.getValue(addKey);
+ if (oldValue == null) {
+ this.delta.remove(addKey);
+ }
+ this.delta.put(addKey, new PropertyChangeEvent(this.source, addKey, oldValue, null));
+ }
+ return this;
+ }
+
+ /**
+ * Apply all the given values to the base configuration/properties.
+ * Note that all values passed must be convertible to String, either
+ * <ul>
+ * <li>the registered codecs provider provides codecs for the corresponding keys, or </li>
+ * <li>default codecs are present for the given type, or</li>
+ * <li>the value is an instanceof String</li>
+ * </ul>
+ *
+ * @param changes the changes to be applied, not null.
+ * @return the builder for chaining.
+ */
+ public ConfigSourceChangeBuilder putAll(Map<String, String> changes) {
+ for (Map.Entry<String, String> en : this.source.getProperties().entrySet()) {
+ this.delta.put(en.getKey(), new PropertyChangeEvent(this.source, en.getKey(), null, en.getValue()));
+ }
+ return this;
+ }
+
+ /**
+ * This method will create a change set that clears all entries fromMap the given base configuration/properties.
+ *
+ * @return the builder for chaining.
+ */
+ public ConfigSourceChangeBuilder deleteAll() {
+ this.delta.clear();
+ for (Map.Entry<String, String> en : this.source.getProperties().entrySet()) {
+ this.delta.put(en.getKey(), new PropertyChangeEvent(this.source, en.getKey(), en.getValue(), null));
+ }
+ return this;
+ }
+
+ /**
+ * Checks if the change set is empty, i.e. does not contain any changes.
+ *
+ * @return true, if the set is empty.
+ */
+ public boolean isEmpty() {
+ return this.delta.isEmpty();
+ }
+
+ /**
+ * Resets this change set instance. This will clear all changes done to this builder, so the
+ * set will be empty.
+ */
+ public void reset() {
+ this.delta.clear();
+ }
+
+
+ /**
+ * Builds the corresponding change set.
+ *
+ * @return the new change set, never null.
+ */
+ public ConfigSourceChange build() {
+ return new ConfigSourceChange(this);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ return "ConfigSourceChangeBuilder [source=" + source + ", " +
+ ", delta=" + delta + "]";
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/main/java/org/apache/tamaya/events/ConfigurationChange.java
----------------------------------------------------------------------
diff --git a/modules/events/src/main/java/org/apache/tamaya/events/ConfigurationChange.java b/modules/events/src/main/java/org/apache/tamaya/events/ConfigurationChange.java
deleted file mode 100644
index 9cdd4fc..0000000
--- a/modules/events/src/main/java/org/apache/tamaya/events/ConfigurationChange.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.events;
-
-import org.apache.tamaya.Configuration;
-
-import java.beans.PropertyChangeEvent;
-import java.io.Serializable;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-
-/**
- * Event that contains a set current changes that were applied or could be applied.
- * This class is immutable and thread-safe. To create instances use
- * {@link PropertySourceChangeBuilder}.
- *
- * Created by Anatole on 22.10.2014.
- */
-public final class ConfigurationChange implements ConfigEvent<Configuration>, Serializable{
-
- private static final long serialVersionUID = 1L;
- /** The base property provider/configuration. */
- private final FrozenConfiguration configuration;
- /** The base version, usable for optimistic locking. */
- private String version = UUID.randomUUID().toString();
- /** The timestamp of the change set in millis from the epoch. */
- private long timestamp = System.currentTimeMillis();
- /** The recorded changes. */
- private final Map<String,PropertyChangeEvent> changes = new HashMap<>();
-
- /**
- * Get an empty change set for the given provider.
- * @param configuration The configuration changed, not null.
- * @return an empty ConfigurationChangeSet instance.
- */
- public static ConfigurationChange emptyChangeSet(Configuration configuration){
- return ConfigurationChangeBuilder.of(configuration).build();
- }
-
- /**
- * Constructor used by {@link PropertySourceChangeBuilder}.
- * @param builder The builder used, not null.
- */
- ConfigurationChange(ConfigurationChangeBuilder builder) {
- this.configuration = FrozenConfiguration.of(builder.source);
- for(PropertyChangeEvent ev:builder.delta.values()){
- this.changes.put(ev.getPropertyName(), ev);
- }
- if(builder.version!=null){
- this.version = builder.version;
- }
- if(builder.timestamp!=null){
- this.timestamp = builder.timestamp;
- }
- }
-
- @Override
- public Class<Configuration> getResourceType() {
- return Configuration.class;
- }
-
- /**
- * Get the underlying property provider/configuration.
- * @return the underlying property provider/configuration, never null.
- */
- @Override
- public Configuration getResource(){
- return this.configuration;
- }
-
- /**
- * Get the base version, usable for optimistic locking.
- * @return the base version.
- */
- @Override
- public String getVersion(){
- return version;
- }
-
- /**
- * Get the timestamp in millis from the current epoch. it is expected that the timestamp and the version are unique to
- * identify a changeset.
- * @return the timestamp, when this changeset was created.
- */
- @Override
- public long getTimestamp(){
- return timestamp;
- }
-
- /**
- * Get the changes recorded.
- * @return the recorded changes, never null.
- */
- public Collection<PropertyChangeEvent> getChanges(){
- return Collections.unmodifiableCollection(this.changes.values());
- }
-
- /**
- * Access the number current removed entries.
- * @return the number current removed entries.
- */
- public int getRemovedSize() {
- int removedCount = 0;
- for(PropertyChangeEvent ev:this.changes.values()){
- if(ev.getPropertyName().startsWith("_")){
- continue;
- }
- if(ev.getNewValue() == null){
- removedCount++;
- }
- }
- return removedCount;
- }
-
- /**
- * Access the number current added entries.
- * @return the number current added entries.
- */
- public int getAddedSize() {
- int addedCount = 0;
- for(PropertyChangeEvent ev:this.changes.values()){
- if(ev.getPropertyName().startsWith("_")){
- continue;
- }
- if(ev.getOldValue() == null &&
- ev.getNewValue() != null){
- addedCount++;
- }
- }
- return addedCount;
- }
-
- /**
- * Access the number current updated entries.
- * @return the number current updated entries.
- */
- public int getUpdatedSize() {
- int updatedCount = 0;
- for(PropertyChangeEvent ev:this.changes.values()){
- if(ev.getPropertyName().startsWith("_")){
- continue;
- }
- if( ev.getOldValue()!=null && ev.getNewValue()!=null){
- updatedCount++;
- }
- }
- return updatedCount;
- }
-
-
- /**
- * Checks if the given key was removed.
- * @param key the target key, not null.
- * @return true, if the given key was removed.
- */
- public boolean isRemoved(String key) {
- PropertyChangeEvent change = this.changes.get(key);
- return change != null && change.getNewValue() == null;
- }
-
- /**
- * Checks if the given key was added.
- * @param key the target key, not null.
- * @return true, if the given key was added.
- */
- public boolean isAdded(String key) {
- PropertyChangeEvent change = this.changes.get(key);
- return change != null && change.getOldValue() == null;
- }
-
- /**
- * Checks if the given key was updated.
- * @param key the target key, not null.
- * @return true, if the given key was updated.
- */
- public boolean isUpdated(String key) {
- PropertyChangeEvent change = this.changes.get(key);
- return change != null && change.getOldValue() != null && change.getNewValue() != null;
- }
-
- /**
- * Checks if the given key is added, or updated AND NOT removed.
- * @param key the target key, not null.
- * @return true, if the given key was added, or updated BUT NOT removed.
- */
- public boolean isKeyAffected(String key) {
- PropertyChangeEvent change = this.changes.get(key);
- return change != null && change.getNewValue() != null;
- }
-
- /**
- * CHecks if the current change set does not contain any changes.
- * @return tru, if the change set is empty.
- */
- public boolean isEmpty(){
- return this.changes.isEmpty();
- }
-
-
- @Override
- public String toString() {
- return "ConfigurationChange{" +
- "\n configuration-id = " + configuration.getOrDefault("_id", "-") +
- "\n change-id = " + version +
- "\n timestamp = " + timestamp +
- "\n added = " + this.getAddedSize() +
- "\n updated = " + this.getUpdatedSize() +
- "\n removed = " + this.getRemovedSize() + '\n' +
- '}';
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/main/java/org/apache/tamaya/events/ConfigurationChangeBuilder.java
----------------------------------------------------------------------
diff --git a/modules/events/src/main/java/org/apache/tamaya/events/ConfigurationChangeBuilder.java b/modules/events/src/main/java/org/apache/tamaya/events/ConfigurationChangeBuilder.java
deleted file mode 100644
index 8becb11..0000000
--- a/modules/events/src/main/java/org/apache/tamaya/events/ConfigurationChangeBuilder.java
+++ /dev/null
@@ -1,278 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.events;
-
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
-
-import java.beans.PropertyChangeEvent;
-import java.util.Collection;
-import java.util.Map;
-import java.util.Objects;
-import java.util.SortedMap;
-import java.util.TreeMap;
-
-/**
- * Models a set current changes applied to a {@link org.apache.tamaya.spi.PropertySource}. Consumers of these events
- * can observe changes to property sources and
- * <ol>
- * <li>Check if their current configuration instance ({@link org.apache.tamaya.spi.ConfigurationContext}
- * contains the changed {@link org.apache.tamaya.spi.PropertySource} (Note: the reference to a property source is never affected by a
- * change, its only the data of the property source).</li>
- * <li>If so corresponding actions might be taken, such as reevaluating the configuration values (depending on
- * the update policy) or reevaluating the complete {@link org.apache.tamaya.Configuration} to create a change
- * event on configuration level.
- * </ol>
- */
-public final class ConfigurationChangeBuilder {
- /**
- * The recorded changes.
- */
- final SortedMap<String, PropertyChangeEvent> delta = new TreeMap<>();
- /**
- * The underlying configuration/provider.
- */
- final Configuration source;
- /**
- * The version configured, or null, for generating a default.
- */
- String version;
- /**
- * The optional timestamp in millis of this epoch.
- */
- Long timestamp;
-
- /**
- * Constructor.
- *
- * @param configuration the underlying configuration, not null.
- */
- private ConfigurationChangeBuilder(Configuration configuration) {
- this.source = Objects.requireNonNull(configuration);
- }
-
- /**
- * Creates a new instance current this builder using the current COnfiguration as root resource.
- *
- * @return the builder for chaining.
- */
- public static ConfigurationChangeBuilder of() {
- return new ConfigurationChangeBuilder(ConfigurationProvider.getConfiguration());
- }
-
- /**
- * Creates a new instance current this builder.
- *
- * @param configuration the configuration changed, not null.
- * @return the builder for chaining.
- */
- public static ConfigurationChangeBuilder of(Configuration configuration) {
- return new ConfigurationChangeBuilder(configuration);
- }
-
- /**
- * Compares the two property config/configurations and creates a collection with all changes
- * that must be applied to render {@code previous} into {@code target}.
- *
- * @param previous the previous map, not null.
- * @param current the target map, not null.
- * @return a collection current change events, never {@code null}.
- */
- public static Collection<PropertyChangeEvent> compare(Configuration previous, Configuration current) {
- TreeMap<String, PropertyChangeEvent> events = new TreeMap<>();
-
- for (Map.Entry<String, String> en : previous.getProperties().entrySet()) {
- String key = en.getKey();
- String previousValue = en.getValue();
- String currentValue = current.get(en.getKey());
- if(Objects.equals(currentValue, previousValue)){
- continue;
- }else {
- PropertyChangeEvent event = new PropertyChangeEvent(previous, key, previousValue, currentValue);
- events.put(key, event);
- }
- }
-
- for (Map.Entry<String, String> en : current.getProperties().entrySet()) {
- String key = en.getKey();
- String previousValue = previous.get(en.getKey());
- String currentValue = en.getValue();
- if(Objects.equals(currentValue, previousValue)){
- continue;
- }else{
- if (previousValue == null) {
- PropertyChangeEvent event = new PropertyChangeEvent(current, key, null, currentValue);
- events.put(key, event);
- }
- // the other cases were already covered by the previous loop.
- }
- }
- return events.values();
- }
-
- /*
- * Apply a version/UUID to the set being built.
- * @param version the version to apply, or null, to let the system generate a version for you.
- * @return the builder for chaining.
- */
- public ConfigurationChangeBuilder setVersion(String version) {
- this.version = version;
- return this;
- }
-
- /*
- * Apply given timestamp to the set being built.
- * @param version the version to apply, or null, to let the system generate a version for you.
- * @return the builder for chaining.
- */
- public ConfigurationChangeBuilder setTimestamp(long timestamp) {
- this.timestamp = timestamp;
- return this;
- }
-
- /**
- * This method records all changes to be applied to the base property provider/configuration to
- * achieve the given target state.
- *
- * @param newState the new target state, not null.
- * @return the builder for chaining.
- */
- public ConfigurationChangeBuilder addChanges(Configuration newState) {
- for (PropertyChangeEvent c : compare(this.source, newState)) {
- this.delta.put(c.getPropertyName(), c);
- }
- return this;
- }
-
- /**
- * Applies a single key/value change.
- *
- * @param key the changed key
- * @param value the new value.
- * @return this instance for chaining.
- */
- public ConfigurationChangeBuilder addChange(String key, String value) {
- this.delta.put(key, new PropertyChangeEvent(this.source, key, this.source.get(key), value));
- return this;
- }
-
- /**
- * Get the current values, also considering any changes recorded within this change set.
- *
- * @param key the key current the entry, not null.
- * @return the keys, or null.
- */
- public String get(String key) {
- PropertyChangeEvent change = this.delta.get(key);
- if (change != null && !(change.getNewValue() == null)) {
- return (String) change.getNewValue();
- }
- return null;
- }
-
- /**
- * Marks the given key(s) fromMap the configuration/properties to be removed.
- *
- * @param key the key current the entry, not null.
- * @param otherKeys additional keys to be removed (convenience), not null.
- * @return the builder for chaining.
- */
- public ConfigurationChangeBuilder removeKey(String key, String... otherKeys) {
- String oldValue = this.source.get(key);
- if (oldValue == null) {
- this.delta.remove(key);
- }
- this.delta.put(key, new PropertyChangeEvent(this.source, key, oldValue, null));
- for (String addKey : otherKeys) {
- oldValue = this.source.get(addKey);
- if (oldValue == null) {
- this.delta.remove(addKey);
- }
- this.delta.put(addKey, new PropertyChangeEvent(this.source, addKey, oldValue, null));
- }
- return this;
- }
-
- /**
- * Apply all the given values to the base configuration/properties.
- * Note that all values passed must be convertible to String, either
- * <ul>
- * <li>the registered codecs provider provides codecs for the corresponding keys, or </li>
- * <li>default codecs are present for the given type, or</li>
- * <li>the value is an instanceof String</li>
- * </ul>
- *
- * @param changes the changes to be applied, not null.
- * @return the builder for chaining.
- */
- public ConfigurationChangeBuilder putAll(Map<String, String> changes) {
- for (Map.Entry<String, String> en : changes.entrySet()) {
- this.delta.put(en.getKey(), new PropertyChangeEvent(this.source, en.getKey(), null, en.getValue()));
- }
- return this;
- }
-
- /**
- * This method will create a change set that clears all entries fromMap the given base configuration/properties.
- *
- * @return the builder for chaining.
- */
- public ConfigurationChangeBuilder removeAllKeys() {
- this.delta.clear();
- for (Map.Entry<String, String> en : this.source.getProperties().entrySet()) {
- this.delta.put(en.getKey(), new PropertyChangeEvent(this.source, en.getKey(), en.getValue(), null));
- }
-// this.source.getProperties().forEach((k, v) ->
-// this.delta.put(k, new PropertyChangeEvent(this.source, k, v, null)));
- return this;
- }
-
- /**
- * Checks if the change set is empty, i.e. does not contain any changes.
- *
- * @return true, if the set is empty.
- */
- public boolean isEmpty() {
- return this.delta.isEmpty();
- }
-
- /**
- * Resets this change set instance. This will clear all changes done to this builder, so the
- * set will be empty.
- */
- public void reset() {
- this.delta.clear();
- }
-
- /**
- * Builds the corresponding change set.
- *
- * @return the new change set, never null.
- */
- public ConfigurationChange build() {
- return new ConfigurationChange(this);
- }
-
- @Override
- public String toString() {
- return "ConfigurationChangeSetBuilder [config=" + source + ", " +
- ", delta=" + delta + "]";
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/main/java/org/apache/tamaya/events/FrozenConfig.java
----------------------------------------------------------------------
diff --git a/modules/events/src/main/java/org/apache/tamaya/events/FrozenConfig.java b/modules/events/src/main/java/org/apache/tamaya/events/FrozenConfig.java
new file mode 100644
index 0000000..dca2204
--- /dev/null
+++ b/modules/events/src/main/java/org/apache/tamaya/events/FrozenConfig.java
@@ -0,0 +1,197 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.events;
+
+import org.apache.tamaya.base.convert.ConversionContext;
+import org.apache.tamaya.base.convert.ConverterManager;
+import org.apache.tamaya.spi.ConfigContext;
+import org.apache.tamaya.spi.ConfigContextSupplier;
+
+import javax.config.Config;
+import javax.config.spi.ConfigSource;
+import javax.config.spi.Converter;
+import java.io.Serializable;
+import java.lang.reflect.Type;
+import java.util.*;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * /**
+ * Configuration implementation that stores all current values of a given (possibly dynamic, contextual and non server
+ * capable instance) and is fully serializable. Note that hereby only the scannable key/value pairs are considered.
+ */
+public final class FrozenConfig implements Config, Serializable {
+ private static final long serialVersionUID = -6373137316556444171L;
+
+ /**
+ * The properties frozen.
+ */
+ private Map<String, String> properties = new HashMap<>();
+ private long frozenAt = System.nanoTime();
+ private UUID id = UUID.randomUUID();
+ private ConverterManager converterManager = new ConverterManager();
+
+ /**
+ * Constructor.
+ *
+ * @param config The base configuration.
+ */
+ private FrozenConfig(Config config) {
+ for(String key:config.getPropertyNames()) {
+ this.properties.put(key, config.getValue(key, String.class));
+ }
+ this.properties = Collections.unmodifiableMap(this.properties);
+ if(config instanceof ConfigContextSupplier){
+ ConfigContext ctx = ((ConfigContextSupplier)config).getConfigContext();
+ for(Map.Entry<Type, List<Converter>> en:ctx.getConverters().entrySet()) {
+ this.converterManager.addConverter(en.getKey(), en.getValue());
+ }
+ }
+ }
+
+ /**
+ * Creates a new FrozenConfiguration instance based on a Configuration given.
+ *
+ * @param config the configuration to be frozen, not null.
+ * @return the frozen Configuration.
+ */
+ public static FrozenConfig of(Config config) {
+ if (config instanceof FrozenConfig) {
+ return (FrozenConfig) config;
+ }
+ return new FrozenConfig(config);
+ }
+
+ public String getValue(String key) {
+ String val = this.properties.get(key);
+ if(val==null){
+ throw new NoSuchElementException("No such config found: " + key);
+ }
+ return val;
+ }
+
+ @Override
+ public <T> Optional<T> getOptionalValue(String key, Class<T> type) {
+ String value = this.properties.get(key);
+ if (value != null) {
+ List<Converter> converters = converterManager.getConverters(type);
+ ConversionContext context = new ConversionContext.Builder(this, key,type).build();
+ ConversionContext.setContext(context);
+ try {
+ for (Converter<T> converter : converters) {
+ try {
+ T t = converter.convert(value);
+ if (t != null) {
+ return Optional.of((T) t);
+ }
+ } catch (Exception e) {
+ Logger.getLogger(getClass().getName())
+ .log(Level.FINEST, "PropertyConverter: " + converter + " failed to convert value: " + value,
+ e);
+ }
+ }
+ }finally{
+ ConversionContext.reset();
+ }
+ if(String.class==type){
+ return Optional.of((T)value);
+ }
+ throw new IllegalArgumentException("Unparseable config value for type: " + type.getName() + ": " + key
+ + ", supported formats: " + context.getSupportedFormats());
+ }
+ return Optional.empty();
+ }
+
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public <T> T getValue(String key, Class<T> type) {
+ return getOptionalValue(key, type)
+ .orElseThrow(() -> new NoSuchElementException("No such config found: " + key));
+ }
+
+ @Override
+ public Iterable<String> getPropertyNames() {
+ return properties.keySet();
+ }
+
+ @Override
+ public List<ConfigSource> getConfigSources() {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ FrozenConfig that = (FrozenConfig) o;
+
+ if (frozenAt != that.frozenAt) {
+ return false;
+ }
+ if (properties != null ? !properties.equals(that.properties) : that.properties != null) {
+ return false;
+ }
+ return id != null ? id.equals(that.id) : that.id == null;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = properties != null ? properties.hashCode() : 0;
+ result = 31 * result + (int) (frozenAt ^ (frozenAt >>> 32));
+ result = 31 * result + (id != null ? id.hashCode() : 0);
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return "FrozenConfiguration{" +
+ "id=" + getId() + "," +
+ "frozenAt=" + getFrozenAt() + "," +
+ "properties=" + properties +
+ '}';
+ }
+
+ /**
+ * <p>Returns the moment in time when this frozen configuration has been created.</p>
+ *
+ * <p>The time is taken from {@linkplain System#currentTimeMillis()}</p>
+ *
+ * @see System#currentTimeMillis()
+ * @return the moment in time when this configuration has been created
+ */
+ public long getFrozenAt() {
+ return frozenAt;
+ }
+
+ /**
+ * <p>Returns the unique id of this frozen configuration.</p>
+ *
+ * @return the unique id of this frozen configuration, never {@code null}
+ */
+ public UUID getId() {
+ return id;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/main/java/org/apache/tamaya/events/FrozenConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/events/src/main/java/org/apache/tamaya/events/FrozenConfigSource.java b/modules/events/src/main/java/org/apache/tamaya/events/FrozenConfigSource.java
new file mode 100644
index 0000000..4bdd2a7
--- /dev/null
+++ b/modules/events/src/main/java/org/apache/tamaya/events/FrozenConfigSource.java
@@ -0,0 +1,129 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.events;
+
+import org.apache.tamaya.base.configsource.ConfigSourceComparator;
+
+import javax.config.spi.ConfigSource;
+import java.io.Serializable;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * PropertySource implementation that stores all current values of a given (possibly dynamic, contextual and non server
+ * capable instance) and is fully serializable. Note that hereby only the scannable key/value pairs are considered.
+ */
+public final class FrozenConfigSource implements ConfigSource, Serializable {
+ private static final long serialVersionUID = -6373137316556444171L;
+ /**
+ * The ordinal.
+ */
+ private final int ordinal;
+ /**
+ * The properties read.
+ */
+ private Map<String, String> properties = new HashMap<>();
+ /**
+ * The PropertySource's name.
+ */
+ private final String name;
+
+ private long frozenAt = System.currentTimeMillis();
+
+ /**
+ * Constructor.
+ *
+ * @param configSource The base ConfigSource.
+ */
+ private FrozenConfigSource(ConfigSource configSource) {
+ this.properties.putAll(configSource.getProperties());
+ this.properties = Collections.unmodifiableMap(this.properties);
+ this.ordinal = ConfigSourceComparator.getOrdinal(configSource);
+ this.name = configSource.getName();
+ }
+
+ /**
+ * Creates a new FrozenPropertySource instance based on a PropertySource given.
+ *
+ * @param configSource the config source to be frozen, not null.
+ * @return the frozen property source.
+ */
+ public static FrozenConfigSource of(ConfigSource configSource) {
+ if (configSource instanceof FrozenConfigSource) {
+ return (FrozenConfigSource) configSource;
+ }
+ return new FrozenConfigSource(configSource);
+ }
+
+ @Override
+ public String getName() {
+ return this.name;
+ }
+
+ public int getOrdinal() {
+ return this.ordinal;
+ }
+
+ /**
+ * Get the creation timestamp of this instance.
+ * @return the creation timestamp
+ */
+ public long getFrozenAt(){
+ return frozenAt;
+ }
+
+ @Override
+ public String getValue(String key) {
+ return this.properties.get(key);
+ }
+
+ @Override
+ public Map<String,String> getProperties() {
+ return Collections.unmodifiableMap(properties);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (!(o instanceof FrozenConfigSource)) {
+ return false;
+ }
+ FrozenConfigSource that = (FrozenConfigSource) o;
+ return ordinal == that.ordinal && properties.equals(that.properties);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = ordinal;
+ result = 31 * result + properties.hashCode();
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return "FrozenPropertySource{" +
+ "name=" + name +
+ ", ordinal=" + ordinal +
+ ", properties=" + properties +
+ '}';
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/main/java/org/apache/tamaya/events/FrozenConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/events/src/main/java/org/apache/tamaya/events/FrozenConfiguration.java b/modules/events/src/main/java/org/apache/tamaya/events/FrozenConfiguration.java
deleted file mode 100644
index 21ef873..0000000
--- a/modules/events/src/main/java/org/apache/tamaya/events/FrozenConfiguration.java
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.events;
-
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.ConfigOperator;
-import org.apache.tamaya.ConfigQuery;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.TypeLiteral;
-import org.apache.tamaya.functions.ConfigurationFunctions;
-import org.apache.tamaya.spi.ConfigurationContext;
-import org.apache.tamaya.spi.ConversionContext;
-import org.apache.tamaya.spi.PropertyConverter;
-
-import java.io.Serializable;
-import java.util.*;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * /**
- * Configuration implementation that stores all current values of a given (possibly dynamic, contextual and non server
- * capable instance) and is fully serializable. Note that hereby only the scannable key/value pairs are considered.
- */
-public final class FrozenConfiguration implements Configuration, Serializable {
- private static final long serialVersionUID = -6373137316556444171L;
-
- /**
- * The properties frozen.
- */
- private Map<String, String> properties = new HashMap<>();
- private long frozenAt = System.nanoTime();
- private UUID id = UUID.randomUUID();
-
- /**
- * Constructor.
- *
- * @param config The base configuration.
- */
- private FrozenConfiguration(Configuration config) {
- this.properties.putAll(config.getProperties());
- this.properties = Collections.unmodifiableMap(this.properties);
- }
-
- /**
- * Creates a new FrozenConfiguration instance based on a Configuration given.
- *
- * @param config the configuration to be frozen, not null.
- * @return the frozen Configuration.
- */
- public static FrozenConfiguration of(Configuration config) {
- if (config instanceof FrozenConfiguration) {
- return (FrozenConfiguration) config;
- }
- return new FrozenConfiguration(config);
- }
-
- @Override
- public String get(String key) {
- return this.properties.get(key);
- }
-
- @Override
- public String getOrDefault(String key, String defaultValue) {
- String val = get(key);
- if(val==null){
- return defaultValue;
- }
- return val;
- }
-
- @Override
- public <T> T getOrDefault(String key, Class<T> type, T defaultValue) {
- T val = get(key, type);
- if(val==null){
- return defaultValue;
- }
- return val;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T> T get(String key, Class<T> type) {
- return (T) get(key, TypeLiteral.of(type));
- }
-
- /**
- * Accesses the current String value for the given key and tries to convert it
- * using the {@link org.apache.tamaya.spi.PropertyConverter} instances provided by the current
- * {@link org.apache.tamaya.spi.ConfigurationContext}.
- *
- * @param key the property's absolute, or relative path, e.g. @code
- * a/b/c/d.myProperty}.
- * @param type The target type required, not null.
- * @param <T> the value type
- * @return the converted value, never null.
- */
- @Override
- public <T> T get(String key, TypeLiteral<T> type) {
- String value = get(key);
- if (value != null) {
- List<PropertyConverter<T>> converters = getContext()
- .getPropertyConverters(type);
- ConversionContext context = new ConversionContext.Builder(this,
- getContext(), key,type).build();
- for (PropertyConverter<T> converter : converters) {
- try {
- T t = converter.convert(value, context);
- if (t != null) {
- return t;
- }
- } catch (Exception e) {
- Logger.getLogger(getClass().getName())
- .log(Level.FINEST, "PropertyConverter: " + converter + " failed to convert value: " + value,
- e);
- }
- }
- throw new ConfigException("Unparseable config value for type: " + type.getRawType().getName() + ": " + key
- + ", supported formats: " + context.getSupportedFormats());
- }
-
- return null;
- }
-
- @Override
- public <T> T getOrDefault(String key, TypeLiteral<T> type, T defaultValue) {
- T val = get(key, type);
- if(val==null){
- return defaultValue;
- }
- return val;
- }
-
- @Override
- public Map<String, String> getProperties() {
- return properties;
- }
-
- @Override
- public Configuration with(ConfigOperator operator) {
- return operator.operate(this);
- }
-
- @Override
- public <T> T query(ConfigQuery<T> query) {
- return query.query(this);
- }
-
- @Override
- public ConfigurationContext getContext() {
- return ConfigurationFunctions.emptyConfigurationContext();
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
-
- FrozenConfiguration that = (FrozenConfiguration) o;
-
- if (frozenAt != that.frozenAt) {
- return false;
- }
- if (properties != null ? !properties.equals(that.properties) : that.properties != null) {
- return false;
- }
- return id != null ? id.equals(that.id) : that.id == null;
- }
-
- @Override
- public int hashCode() {
- int result = properties != null ? properties.hashCode() : 0;
- result = 31 * result + (int) (frozenAt ^ (frozenAt >>> 32));
- result = 31 * result + (id != null ? id.hashCode() : 0);
- return result;
- }
-
- @Override
- public String toString() {
- return "FrozenConfiguration{" +
- "id=" + getId() + "," +
- "frozenAt=" + getFrozenAt() + "," +
- "properties=" + properties +
- '}';
- }
-
- /**
- * <p>Returns the moment in time when this frozen configuration has been created.</p>
- *
- * <p>The time is taken from {@linkplain System#currentTimeMillis()}</p>
- *
- * @see System#currentTimeMillis()
- * @return the moment in time when this configuration has been created
- */
- public long getFrozenAt() {
- return frozenAt;
- }
-
- /**
- * <p>Returns the unique id of this frozen configuration.</p>
- *
- * @return the unique id of this frozen configuration, never {@code null}
- */
- public UUID getId() {
- return id;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/main/java/org/apache/tamaya/events/FrozenPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/events/src/main/java/org/apache/tamaya/events/FrozenPropertySource.java b/modules/events/src/main/java/org/apache/tamaya/events/FrozenPropertySource.java
deleted file mode 100644
index 0bc71ce..0000000
--- a/modules/events/src/main/java/org/apache/tamaya/events/FrozenPropertySource.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.events;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-import org.apache.tamaya.spisupport.PropertySourceComparator;
-
-import java.io.Serializable;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * PropertySource implementation that stores all current values of a given (possibly dynamic, contextual and non server
- * capable instance) and is fully serializable. Note that hereby only the scannable key/value pairs are considered.
- */
-public final class FrozenPropertySource implements PropertySource, Serializable {
- private static final long serialVersionUID = -6373137316556444171L;
- /**
- * The ordinal.
- */
- private final int ordinal;
- /**
- * The properties read.
- */
- private Map<String, PropertyValue> properties = new HashMap<>();
- /**
- * The PropertySource's name.
- */
- private final String name;
-
- private long frozenAt = System.currentTimeMillis();
-
- /**
- * Constructor.
- *
- * @param propertySource The base PropertySource.
- */
- private FrozenPropertySource(PropertySource propertySource) {
- this.properties.putAll(propertySource.getProperties());
- this.properties = Collections.unmodifiableMap(this.properties);
- this.ordinal = PropertySourceComparator.getOrdinal(propertySource);
- this.name = propertySource.getName();
- }
-
- /**
- * Creates a new FrozenPropertySource instance based on a PropertySource given.
- *
- * @param propertySource the property source to be frozen, not null.
- * @return the frozen property source.
- */
- public static FrozenPropertySource of(PropertySource propertySource) {
- if (propertySource instanceof FrozenPropertySource) {
- return (FrozenPropertySource) propertySource;
- }
- return new FrozenPropertySource(propertySource);
- }
-
- @Override
- public String getName() {
- return this.name;
- }
-
- public int getOrdinal() {
- return this.ordinal;
- }
-
- /**
- * Get the creation timestamp of this instance.
- * @return the creation timestamp
- */
- public long getFrozenAt(){
- return frozenAt;
- }
-
- @Override
- public PropertyValue get(String key) {
- return this.properties.get(key);
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
- return properties;
- }
-
- @Override
- public boolean isScannable() {
- return true;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (!(o instanceof FrozenPropertySource)) {
- return false;
- }
- FrozenPropertySource that = (FrozenPropertySource) o;
- return ordinal == that.ordinal && properties.equals(that.properties);
- }
-
- @Override
- public int hashCode() {
- int result = ordinal;
- result = 31 * result + properties.hashCode();
- return result;
- }
-
- @Override
- public String toString() {
- return "FrozenPropertySource{" +
- "name=" + name +
- ", ordinal=" + ordinal +
- ", properties=" + properties +
- '}';
- }
-}
[13/18] incubator-tamaya-extensions git commit: Rewrite/adaptation
based on JSR API.
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/jndi/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
----------------------------------------------------------------------
diff --git a/modules/jndi/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertySource b/modules/jndi/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
index b587cf7..1b036f1 100644
--- a/modules/jndi/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
+++ b/modules/jndi/src/main/resources/META-INF/services/org.apache.tamaya.spi.PropertySource
@@ -16,4 +16,4 @@
# specific language governing permissions and limitations
# under the License.
#
-org.apache.tamaya.jndi.JNDIPropertySource
\ No newline at end of file
+org.apache.tamaya.jndi.JNDIConfigSource
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/jndi/src/test/java/org/apache/tamaya/jndi/JNDIConfigSourceTest.java
----------------------------------------------------------------------
diff --git a/modules/jndi/src/test/java/org/apache/tamaya/jndi/JNDIConfigSourceTest.java b/modules/jndi/src/test/java/org/apache/tamaya/jndi/JNDIConfigSourceTest.java
new file mode 100644
index 0000000..bb00dd5
--- /dev/null
+++ b/modules/jndi/src/test/java/org/apache/tamaya/jndi/JNDIConfigSourceTest.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.jndi;
+
+import org.junit.Test;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+import java.io.File;
+import java.net.MalformedURLException;
+import java.util.Hashtable;
+import java.util.Map;
+
+import static junit.framework.TestCase.assertNotNull;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class JNDIConfigSourceTest {
+
+ private InitialContext createFSContext() throws NamingException, MalformedURLException {
+ Hashtable<String, String> env = new Hashtable<String, String>();
+ env.put (Context.INITIAL_CONTEXT_FACTORY,
+ "com.sun.jndi.fscontext.RefFSContextFactory");
+ return new InitialContext(env);
+ }
+
+ private Context getTestDirContext(InitialContext ctx) throws NamingException {
+ return (Context)ctx.lookup(new File("./src/test/jndi-dir").getAbsolutePath());
+ }
+
+ @Test
+ public void testCreateWithContext() throws NamingException, MalformedURLException {
+ new JNDIConfigSource("jndi-test", createFSContext());
+ }
+
+ @Test
+ public void testScanContext() throws NamingException, MalformedURLException {
+ JNDIConfigSource ps = new JNDIConfigSource("jndi-test", getTestDirContext(createFSContext()));
+ Map<String,String> props = ps.getProperties();
+ assertNotNull(props);
+ assertTrue(props.isEmpty());
+ ps.setScannable(true);
+ props = ps.getProperties();
+ assertNotNull(props);
+ assertFalse(props.isEmpty());
+ assertEquals(props.size(), 5);
+ assertNotNull(props.get("c.c1.test5"));
+ assertNotNull(props.get("c.test3"));
+ assertNotNull(props.get("c.test4"));
+ assertNotNull(props.get("b.test2"));
+ assertNotNull(props.get("a.test1"));
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/jndi/src/test/java/org/apache/tamaya/jndi/JNDIPropertySourceTest.java
----------------------------------------------------------------------
diff --git a/modules/jndi/src/test/java/org/apache/tamaya/jndi/JNDIPropertySourceTest.java b/modules/jndi/src/test/java/org/apache/tamaya/jndi/JNDIPropertySourceTest.java
deleted file mode 100644
index 1f06855..0000000
--- a/modules/jndi/src/test/java/org/apache/tamaya/jndi/JNDIPropertySourceTest.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.jndi;
-
-import org.apache.tamaya.spi.PropertyValue;
-import org.junit.Test;
-
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import java.io.File;
-import java.net.MalformedURLException;
-import java.util.Hashtable;
-import java.util.Map;
-
-import static junit.framework.TestCase.assertNotNull;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-public class JNDIPropertySourceTest{
-
- private InitialContext createFSContext() throws NamingException, MalformedURLException {
- Hashtable<String, String> env = new Hashtable<String, String>();
- env.put (Context.INITIAL_CONTEXT_FACTORY,
- "com.sun.jndi.fscontext.RefFSContextFactory");
- return new InitialContext(env);
- }
-
- private Context getTestDirContext(InitialContext ctx) throws NamingException {
- return (Context)ctx.lookup(new File("./src/test/jndi-dir").getAbsolutePath());
- }
-
- @Test
- public void testCreateWithContext() throws NamingException, MalformedURLException {
- new JNDIPropertySource("jndi-test", createFSContext());
- }
-
- @Test
- public void testScanContext() throws NamingException, MalformedURLException {
- JNDIPropertySource ps = new JNDIPropertySource("jndi-test", getTestDirContext(createFSContext()));
- assertFalse(ps.isScannable());
- Map<String,PropertyValue> props = ps.getProperties();
- assertNotNull(props);
- assertTrue(props.isEmpty());
- ps.setScannable(true);
- assertTrue(ps.isScannable());
- props = ps.getProperties();
- assertNotNull(props);
- assertFalse(props.isEmpty());
- assertEquals(props.size(), 5);
- assertNotNull(props.get("c.c1.test5"));
- assertNotNull(props.get("c.test3"));
- assertNotNull(props.get("c.test4"));
- assertNotNull(props.get("b.test2"));
- assertNotNull(props.get("a.test1"));
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/bnd.bnd
----------------------------------------------------------------------
diff --git a/modules/microprofile/bnd.bnd b/modules/microprofile/bnd.bnd
deleted file mode 100644
index da67308..0000000
--- a/modules/microprofile/bnd.bnd
+++ /dev/null
@@ -1,34 +0,0 @@
--buildpath: \
- osgi.annotation; version=6.0.0,\
- osgi.core; version=6.0,\
- osgi.cmpn; version=6.0
-
--testpath: \
- ${junit}
-
-javac.source: 1.8
-javac.target: 1.8
-
-Bundle-Version: ${version}.${tstamp}
-Bundle-Name: Apache Tamaya - Microprofile
-Bundle-SymbolicName: org.apache.tamaya.microprofile
-Bundle-Description: Apacha Tamaya Config - Microprofile Implementation
-Bundle-Category: Implementation
-Bundle-Copyright: (C) Apache Foundation
-Bundle-License: Apache Licence version 2
-Bundle-Vendor: Apache Software Foundation
-Bundle-ContactAddress: dev-tamaya@incubator.apache.org
-Bundle-DocURL: http://tamaya.apache.org
-Export-Package: \
- org.apache.tamaya.microprofile,\
- org.apache.tamaya.microprofile.cdi,\
- org.apache.tamaya.microprofile.converter
-Import-Package: \
- org.apache.tamaya,\
- org.apache.tamaya.spi,\
- org.eclipse.microprofile.config
-Export-Service: \
- org.apache.tamaya.spi.PropertyConverter,\
- org.apache.tamaya.spi.ProperySource,\
- org.eclipse.microprofile.config.spi.ConfigProviderResolver,\
- javax.enterprise.inject.spi.Extension
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/pom.xml
----------------------------------------------------------------------
diff --git a/modules/microprofile/pom.xml b/modules/microprofile/pom.xml
deleted file mode 100644
index 86b6889..0000000
--- a/modules/microprofile/pom.xml
+++ /dev/null
@@ -1,166 +0,0 @@
-<!--
-Licensed to the Apache Software Foundation (ASF) under one
-or more contributor license agreements. See the NOTICE file
-distributed with this work for additional information
-regarding copyright ownership. The ASF licenses this file
-to you 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 current 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.
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.apache.tamaya.ext</groupId>
- <artifactId>tamaya-extensions</artifactId>
- <version>0.4-incubating-SNAPSHOT</version>
- </parent>
-
- <artifactId>tamaya-microprofile</artifactId>
- <name>Apache Tamaya Modules - Microprofile API</name>
- <packaging>jar</packaging>
-
- <properties>
- <maven.compile.sourceLevel>1.8</maven.compile.sourceLevel>
- <maven.compile.targetLevel>1.8</maven.compile.targetLevel>
- <microprofile.config.version>1.1</microprofile.config.version>
- <geronimo-atinject-1.0-spec.version>1.0</geronimo-atinject-1.0-spec.version>
- <geronimo-jcdi-1.1-spec.version>1.0</geronimo-jcdi-1.1-spec.version>
- <version.shrinkwrap.resolvers>2.2.6</version.shrinkwrap.resolvers>
- <tamaya-version>0.4-incubating-SNAPSHOT</tamaya-version>
- <arquillian.version>1.1.13.Final</arquillian.version>
- <arquillian-weld-embedded.version>2.0.0.Beta5</arquillian-weld-embedded.version>
- <cdi-api.version>2.0</cdi-api.version>
- <weld.version>3.0.1.Final</weld.version>
- <deltaspike.version>1.1.0</deltaspike.version>
- <openejb.version>4.7.1</openejb.version>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.hamcrest</groupId>
- <artifactId>java-hamcrest</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-core</artifactId>
- <version>${tamaya-version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-api</artifactId>
- <version>${tamaya-version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.tamaya.ext</groupId>
- <artifactId>tamaya-functions</artifactId>
- <version>${tamaya-version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.tamaya.ext</groupId>
- <artifactId>tamaya-events</artifactId>
- <version>${tamaya-version}</version>
- </dependency>
- <dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.eclipse.microprofile.config</groupId>
- <artifactId>microprofile-config-api</artifactId>
- <version>${microprofile.config.version}</version>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- </dependency>
- <dependency>
- <groupId>javax.enterprise</groupId>
- <artifactId>cdi-api</artifactId>
- <version>${cdi-api.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.weld.se</groupId>
- <artifactId>weld-se-shaded</artifactId>
- <version>${weld.version}</version>
- <scope>test</scope>
- </dependency>
- <!-- Microprofile TCK support only -->
- <dependency>
- <groupId>org.jboss.arquillian.testng</groupId>
- <artifactId>arquillian-testng-container</artifactId>
- <version>${arquillian.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.testng</groupId>
- <artifactId>testng</artifactId>
- <version>6.9.9</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.shrinkwrap.resolver</groupId>
- <artifactId>shrinkwrap-resolver-depchain</artifactId>
- <version>${version.shrinkwrap.resolvers}</version>
- <scope>test</scope>
- <type>pom</type>
- </dependency>
- </dependencies>
-
- <profiles>
- <profile>
- <id>TCK</id>
- <activation>
- <activeByDefault>false</activeByDefault>
- </activation>
- <dependencies>
- <dependency>
- <groupId>org.eclipse.microprofile.config</groupId>
- <artifactId>microprofile-config-tck</artifactId>
- <version>${microprofile.config.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.arquillian.container</groupId>
- <artifactId>arquillian-weld-embedded</artifactId>
- <version>${arquillian-weld-embedded.version}</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <version>2.20.1</version>
- <configuration>
- <suiteXmlFiles>
- <suiteXmlFile>src/test/tck-suite.xml</suiteXmlFile>
- </suiteXmlFiles>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </profile>
- </profiles>
-
-</project>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileAdapter.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileAdapter.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileAdapter.java
deleted file mode 100644
index 8f5002c..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileAdapter.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-
-import org.apache.tamaya.*;
-import org.apache.tamaya.spi.ConfigurationContextBuilder;
-import org.apache.tamaya.spi.PropertyConverter;
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-import org.eclipse.microprofile.config.Config;
-import org.eclipse.microprofile.config.spi.ConfigBuilder;
-import org.eclipse.microprofile.config.spi.ConfigSource;
-import org.eclipse.microprofile.config.spi.Converter;
-
-import java.util.*;
-
-/**
- * Utility class for adapting microprofile artifacts into Tamaya artifacts and vice versa.
- */
-public final class MicroprofileAdapter{
-
- /**
- * Singleton constructor.
- */
- private MicroprofileAdapter(){}
-
- /**
- * Converts a Tamaya {@link Configuration} into a Microprofile.io {@link Config}.
- * @param config the Tamaya {@link Configuration} instance, not null.
- * @return the corresponding Microprofile.io {@link Config} instance, never null.
- */
- public static Config toConfig(Configuration config){
- if(config instanceof TamayaConfiguration){
- return ((TamayaConfiguration)config).getConfig();
- }
- return new MicroprofileConfig(config);
- }
-
- /**
- * Converts a Microprofile {@link Config}s into Tamaya {@link Configuration}s.
- * @param config the Microprofile {@link Config} instance, not null.
- * @return the corresponding Tamaya {@link Configuration} instance, never null.
- */
- public static Configuration toConfiguration(Config config){
- if(config instanceof MicroprofileConfig){
- return ((MicroprofileConfig)config).getConfiguration();
- }
- return new TamayaConfiguration(config);
- }
-
- /**
- * Converts a Tamaya {@link PropertySource}s into a Microprofile.io {@link ConfigSource}.
- * @param propertySources the Tamaya {@link PropertySource} instances, not null.
- * @return the corresponding Microprofile.io {@link ConfigSource} instance, never null.
- */
- public static List<ConfigSource> toConfigSources(Iterable<PropertySource> propertySources) {
- List<ConfigSource> configSources = new ArrayList<>();
- for(PropertySource ps:propertySources){
- configSources.add(toConfigSource(ps));
- }
- Collections.reverse(configSources);
- return configSources;
- }
-
- /**
- * Converts a Microprofile {@link ConfigSource}s into Tamaya {@link PropertySource}s.
- * @param configSources the Microprofile {@link ConfigSource} instances, not null.
- * @return the corresponding Tamaya {@link PropertySource} instances, never null.
- */
- public static List<PropertySource> toPropertySources(Iterable<ConfigSource> configSources) {
- List<PropertySource> propertySources = new ArrayList<>();
- for(ConfigSource cs:configSources){
- propertySources.add(toPropertySource(cs));
- }
- return propertySources;
- }
-
- /**
- * Converts a Tamaya {@link PropertySource} into a Microprofile.io {@link ConfigSource}.
- * @param propertySource the Tamaya {@link PropertySource} instance, not null.
- * @return the corresponding Microprofile.io {@link ConfigSource} instance, never null.
- */
- public static ConfigSource toConfigSource(PropertySource propertySource) {
- if(propertySource instanceof TamayaPropertySource){
- return ((TamayaPropertySource)propertySource).getConfigSource();
- }
- return new MicroprofileConfigSource(propertySource);
- }
-
- /**
- * Converts a Microprofile {@link ConfigSource} into a Tamaya {@link PropertySource}.
- * @param configSource the Microprofile {@link ConfigSource} instance, not null.
- * @return the corresponding Tamaya {@link PropertySource} instance, never null.
- */
- public static PropertySource toPropertySource(ConfigSource configSource) {
- if(configSource instanceof MicroprofileConfigSource){
- return ((MicroprofileConfigSource)configSource).getPropertySource();
- }
- return new TamayaPropertySource(configSource);
- }
-
- /**
- * Converts a Microprofile {@link Converter} into a Tamaya {@link PropertyConverter}.
- * @param converter the Microprofile {@link Converter} instance, not null.
- * @param <T> the target type
- * @return the corresponding Tamaya {@link PropertyConverter} instance, never null.
- */
- public static <T> PropertyConverter<T> toPropertyConverter(Converter<T> converter) {
- if(converter instanceof MicroprofileConverter){
- return ((MicroprofileConverter)converter).getPropertyConverter();
- }
- return new TamayaPropertyConverter(converter);
- }
-
- /**
- * Converts a Tamaya {@link PropertyConverter} into a Microprofile.io {@link Converter}.
- * @param converter the Tamaya {@link PropertyConverter} instance, not null.
- * @param <T> the target type
- * @return the corresponding Microprofile.io {@link Converter} instance, never null.
- */
- public static <T> Converter<T> toConverter(PropertyConverter<T> converter) {
- if(converter instanceof TamayaPropertyConverter){
- return ((TamayaPropertyConverter)converter).getConverter();
- }
- return new MicroprofileConverter(converter);
- }
-
- /**
- * Converts a Tamaya {@link ConfigurationContextBuilder} into a Microprofile.io {@link ConfigBuilder}.
- * @param builder the Tamaya {@link ConfigurationContextBuilder} instance, not null.
- * @return the corresponding Microprofile.io {@link ConfigBuilder} instance, never null.
- */
- public static ConfigBuilder toConfigBuilder(ConfigurationContextBuilder builder) {
- return new MicroprofileConfigBuilder(builder);
- }
-
- /**
- * Converts the given Tamaya key, value map into a corresponding String based map, hereby
- * omitting all meta-entries.
- * @param properties the Tamaya key, value map, not null.
- * @return the corresponding String based map, never null.
- */
- public static Map<String, String> toStringMap(Map<String, PropertyValue> properties) {
- Map<String, String> valueMap = new HashMap<>(properties.size());
- for(Map.Entry<String,PropertyValue> en:properties.entrySet()){
- if(en.getValue().getValue()!=null) {
- valueMap.put(en.getKey(), en.getValue().getValue());
- }
- }
- return valueMap;
- }
-
- /**
- * Converts the given String based key, value map into a corresponding String,PropertyValue
- * based map.
- * @param properties the String based key, value map, not null.
- * @param source the source of the entries, not null.
- * @return the corresponding String,PropertyValue based map, never null.
- */
- public static Map<String, PropertyValue> toPropertyValueMap(Map<String, String> properties, String source) {
- Map<String, PropertyValue> valueMap = new HashMap<>(properties.size());
- for(Map.Entry<String,String> en:properties.entrySet()){
- valueMap.put(en.getKey(), PropertyValue.of(en.getKey(), en.getValue(), source));
- }
- return valueMap;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfig.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfig.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfig.java
deleted file mode 100644
index 61c3cdc..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfig.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.events.FrozenConfiguration;
-import org.apache.tamaya.spi.PropertySource;
-import org.eclipse.microprofile.config.Config;
-import org.eclipse.microprofile.config.spi.ConfigSource;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.*;
-
-/**
- * Microprofile {@link ConfigSource} implementation that wraps a {@link PropertySource} instance.
- */
-public class MicroprofileConfig implements Config, Serializable {
-
- private Configuration delegate;
-
- public MicroprofileConfig(Configuration delegate){
- this.delegate = Objects.requireNonNull(delegate);
- }
-
- public Configuration getConfiguration(){
- return this.delegate;
- }
-
-
- @Override
- public <T> T getValue(String propertyName, Class<T> propertyType) {
- T value = null;
- try{
- value = delegate.get(propertyName, propertyType);
- }catch(ConfigException e){
- if(e.toString().contains("Unparseable")){
- throw new IllegalArgumentException("Invalid type: " + propertyType.getName());
- }
- }
- if(value == null){
- throw new NoSuchElementException("No such config property: " + propertyName);
- }
- return value;
- }
-
- @Override
- public <T> Optional<T> getOptionalValue(String propertyName, Class<T> propertyType) {
- return Optional.ofNullable(delegate.get(propertyName, propertyType));
- }
-
- @Override
- public Iterable<String> getPropertyNames() {
- return delegate.getProperties().keySet();
- }
-
- @Override
- public Iterable<ConfigSource> getConfigSources() {
- return MicroprofileAdapter.toConfigSources(delegate.getContext().getPropertySources());
- }
-
- @Override
- public String toString() {
- return "MicroprofileConfig{" +
- "delegate=" + delegate +
- '}';
- }
-
- private void writeObject(ObjectOutputStream out) throws IOException{
- if(!(this.delegate instanceof Serializable)){
- out.writeObject(FrozenConfiguration.of(this.delegate));
- }else {
- out.writeObject(this.delegate);
- }
- }
-
- private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{
- this.delegate = (Configuration)in.readObject();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfigBuilder.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfigBuilder.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfigBuilder.java
deleted file mode 100644
index 82209c3..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfigBuilder.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.apache.tamaya.ConfigurationProvider;
-import org.apache.tamaya.TypeLiteral;
-import org.apache.tamaya.spi.ConfigurationContextBuilder;
-import org.apache.tamaya.spi.ServiceContextManager;
-import org.apache.tamaya.spisupport.propertysource.EnvironmentPropertySource;
-import org.apache.tamaya.spisupport.PropertySourceComparator;
-import org.apache.tamaya.spisupport.propertysource.SystemPropertySource;
-import org.eclipse.microprofile.config.Config;
-import org.eclipse.microprofile.config.spi.ConfigBuilder;
-import org.eclipse.microprofile.config.spi.ConfigSource;
-import org.eclipse.microprofile.config.spi.ConfigSourceProvider;
-import org.eclipse.microprofile.config.spi.Converter;
-
-import java.util.Objects;
-
-/**
- * Created by atsticks on 23.03.17.
- */
-final class MicroprofileConfigBuilder implements ConfigBuilder{
-
- private ConfigurationContextBuilder contextBuilder;
- private ClassLoader classLoader;
-
- MicroprofileConfigBuilder(ConfigurationContextBuilder contextBuilder){
- this.contextBuilder = Objects.requireNonNull(contextBuilder);
- contextBuilder.addDefaultPropertyConverters();
- }
-
- public ConfigurationContextBuilder getConfigurationContextBuilder(){
- return contextBuilder;
- }
-
- /**
- * Add the default config sources appearing on the builder's classpath
- * including:
- * <ol>
- * <li>System properties</li>
- * <li>Environment properties</li>
- * <li>/META-INF/microprofile-config.properties</li>
- * </ol>
- *
- * @return the ConfigBuilder with the default config sources
- */
- @Override
- public ConfigBuilder addDefaultSources() {
- contextBuilder.addPropertySources(
- new SystemPropertySource(400),
- new EnvironmentPropertySource(300),
- new MicroprofileDefaultProperties());
- contextBuilder.sortPropertySources(PropertySourceComparator.getInstance());
- return this;
- }
-
- /**
- * Add ConfigSources registered using the ServiceLoader.
- * @return the ConfigBuilder with the added config sources
- */
- @Override
- public ConfigBuilder addDiscoveredSources() {
- for(ConfigSource configSource: ServiceContextManager.getServiceContext().getServices(ConfigSource.class)){
- contextBuilder.addPropertySources(MicroprofileAdapter.toPropertySource(configSource));
- }
- for(ConfigSourceProvider configSourceProvider: ServiceContextManager.getServiceContext().getServices(ConfigSourceProvider.class)){
- contextBuilder.addPropertySources(MicroprofileAdapter.toPropertySources(configSourceProvider.getConfigSources(
- Thread.currentThread().getContextClassLoader()
- )));
- }
- contextBuilder.sortPropertySources(PropertySourceComparator.getInstance());
- return this;
- }
-
- /**
- * Add Converters registered using the ServiceLoader.
- * @return the ConfigBuilder with the added config converters
- */
- @Override
- public ConfigBuilder addDiscoveredConverters() {
- for(Converter<?> converter: ServiceContextManager.getServiceContext().getServices(Converter.class)){
- TypeLiteral targetType = TypeLiteral.of(
- TypeLiteral.getGenericInterfaceTypeParameters(converter.getClass(),Converter.class)[0]);
- contextBuilder.addPropertyConverters(targetType,
- MicroprofileAdapter.toPropertyConverter(converter));
- }
- return this;
- }
-
- @Override
- public ConfigBuilder forClassLoader(ClassLoader loader) {
- this.classLoader = loader;
- return this;
- }
-
- @Override
- public ConfigBuilder withSources(ConfigSource... sources) {
- for(ConfigSource source:sources){
- contextBuilder.addPropertySources(MicroprofileAdapter.toPropertySource(source));
- }
- return this;
- }
-
- @Override
- public ConfigBuilder withConverters(Converter<?>... converters) {
- for(Converter<?> converter:converters){
- TypeLiteral lit = TypeLiteral.of(converter.getClass());
- TypeLiteral target = TypeLiteral.of(lit.getType());
- contextBuilder.removePropertyConverters(target);
- contextBuilder.addPropertyConverters(
- target,
- MicroprofileAdapter.toPropertyConverter(converter));
- }
- return this;
- }
-
- @Override
- public Config build() {
- return MicroprofileAdapter.toConfig(ConfigurationProvider.createConfiguration(
- contextBuilder.build()
- ));
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfigProviderResolver.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfigProviderResolver.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfigProviderResolver.java
deleted file mode 100644
index 92a928a..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfigProviderResolver.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.apache.tamaya.ConfigurationProvider;
-import org.apache.tamaya.spi.ConfigurationContextBuilder;
-import org.eclipse.microprofile.config.Config;
-import org.eclipse.microprofile.config.spi.ConfigBuilder;
-import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.logging.Logger;
-
-/**
- * Created by atsticks on 23.03.17.
- */
-public class MicroprofileConfigProviderResolver extends ConfigProviderResolver {
-
- private Map<ClassLoader, Config> configs = new ConcurrentHashMap<>();
-
- @Override
- public Config getConfig() {
- return getConfig(Thread.currentThread().getContextClassLoader());
- }
-
- @Override
- public Config getConfig(ClassLoader loader) {
- Config config = this.configs.get(loader);
- if(config==null){
- ConfigurationContextBuilder builder = ConfigurationProvider.getConfigurationContextBuilder();
- builder.addDefaultPropertyConverters();
- MicroprofileConfigBuilder microConfigBuilder = new MicroprofileConfigBuilder(builder);
- microConfigBuilder.addDefaultSources();
- microConfigBuilder.addDiscoveredSources();
- config = microConfigBuilder.build();
- this.configs.put(loader, config);
- }
- return config;
- }
-
- @Override
- public ConfigBuilder getBuilder() {
- return new MicroprofileConfigBuilder(ConfigurationProvider.getConfigurationContextBuilder());
- }
-
- @Override
- public void registerConfig(Config config, ClassLoader classLoader) {
- if(configs.containsKey(classLoader)){
- Logger.getLogger(getClass().getName())
- .warning("Replacing existing config for classloader: " + classLoader);
-// throw new IllegalArgumentException("Already a config registered with classloader: " + classLoader);
- }
- this.configs.put(classLoader, config);
- }
-
- @Override
- public void releaseConfig(Config config) {
- for(Map.Entry<ClassLoader, Config> en: this.configs.entrySet()){
- if(en.getValue().equals(config)){
- this.configs.remove(en.getKey());
- return;
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfigSource.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfigSource.java
deleted file mode 100644
index 39ca119..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfigSource.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-import org.eclipse.microprofile.config.spi.ConfigSource;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-
-/**
- * Microprofile {@link ConfigSource} implementation that wraps a {@link PropertySource} instance.
- */
-public class MicroprofileConfigSource implements ConfigSource{
-
- private PropertySource delegate;
-
- public MicroprofileConfigSource(PropertySource propertySource){
- this.delegate = Objects.requireNonNull(propertySource);
- }
-
- public PropertySource getPropertySource(){
- return this.delegate;
- }
-
- @Override
- public int getOrdinal() {
- return delegate.getOrdinal();
- }
-
- @Override
- public String getName() {
- return delegate.getName();
- }
-
- @Override
- public String getValue(String key) {
- PropertyValue value = delegate.get(key);
- if(value!=null){
- return value.getValue();
- }
- return null;
- }
-
- @Override
- public Map<String, String> getProperties() {
- return toMap(delegate.getProperties());
- }
-
- private Map<String, String> toMap(Map<String, PropertyValue> properties) {
- Map<String, String> valueMap = new HashMap<>(properties.size());
- for(Map.Entry<String,PropertyValue> en:properties.entrySet()){
- if(en.getValue().getValue()!=null) {
- valueMap.put(en.getKey(), en.getValue().getValue());
- }
- }
- return valueMap;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfigSourceProvider.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfigSourceProvider.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfigSourceProvider.java
deleted file mode 100644
index 5176940..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConfigSourceProvider.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertySourceProvider;
-import org.apache.tamaya.spi.PropertyValue;
-import org.eclipse.microprofile.config.spi.ConfigSource;
-import org.eclipse.microprofile.config.spi.ConfigSourceProvider;
-
-import java.util.*;
-
-/**
- * Microprofile {@link ConfigSource} implementation that wraps a {@link PropertySource} instance.
- */
-public class MicroprofileConfigSourceProvider implements ConfigSourceProvider{
-
- private PropertySourceProvider delegate;
-
- public MicroprofileConfigSourceProvider(PropertySourceProvider propertySourceProvider){
- this.delegate = Objects.requireNonNull(propertySourceProvider);
- }
-
- public PropertySourceProvider getPropertySourceProvider(){
- return this.delegate;
- }
-
-
- private Map<String, String> toMap(Map<String, PropertyValue> properties) {
- Map<String, String> valueMap = new HashMap<>(properties.size());
- for(Map.Entry<String,PropertyValue> en:properties.entrySet()){
- if(en.getValue().getValue()!=null) {
- valueMap.put(en.getKey(), en.getValue().getValue());
- }
- }
- return valueMap;
- }
-
- @Override
- public Iterable<ConfigSource> getConfigSources(ClassLoader forClassLoader) {
- if(delegate instanceof TamayaPropertySourceProvider){
- return ((TamayaPropertySourceProvider)delegate).getConfigSourceProvider()
- .getConfigSources(forClassLoader);
- }else {
- return MicroprofileAdapter.toConfigSources(delegate.getPropertySources());
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConverter.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConverter.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConverter.java
deleted file mode 100644
index cb6aab2..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileConverter.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-
-import org.apache.tamaya.TypeLiteral;
-import org.apache.tamaya.spi.ConversionContext;
-import org.apache.tamaya.spi.PropertyConverter;
-import org.eclipse.microprofile.config.spi.ConfigSource;
-import org.eclipse.microprofile.config.spi.Converter;
-
-import java.util.Objects;
-
-/**
- * Property source implementation that wraps a Microprofile {@link ConfigSource} instance.
- */
-public class MicroprofileConverter<T> implements Converter<T> {
-
- private PropertyConverter<T> delegate;
-
- public MicroprofileConverter(PropertyConverter<T> delegate){
- this.delegate = Objects.requireNonNull(delegate);
- }
-
- public PropertyConverter<T> getPropertyConverter(){
- return this.delegate;
- }
-
- @Override
- public T convert(String value) {
- return delegate.convert(value, new ConversionContext.Builder("microprofile:no-key", TypeLiteral.of(
- TypeLiteral.of(getClass()).getType())).build());
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileDefaultProperties.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileDefaultProperties.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileDefaultProperties.java
deleted file mode 100644
index b20dc8f..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/MicroprofileDefaultProperties.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.apache.tamaya.spisupport.propertysource.PropertiesResourcePropertySource;
-
-
-/**
- * Default property source for config properties in the classpath.
- */
-public class MicroprofileDefaultProperties extends PropertiesResourcePropertySource{
-
- public MicroprofileDefaultProperties() {
- super("META-INF/microprofile-config.properties", null);
- setDefaultOrdinal(100);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/TamayaConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/TamayaConfiguration.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/TamayaConfiguration.java
deleted file mode 100644
index 0f27821..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/TamayaConfiguration.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.apache.tamaya.*;
-import org.apache.tamaya.spi.ConfigurationContext;
-import org.eclipse.microprofile.config.Config;
-
-import java.util.*;
-
-/**
- * Created by atsticks on 23.03.17.
- */
-public class TamayaConfiguration implements Configuration{
-
- private Config delegate;
-
- public TamayaConfiguration(Config config){
- this.delegate = Objects.requireNonNull(config);
- }
-
- public Config getConfig(){
- return delegate;
- }
-
- @Override
- public String get(String key) {
- return this.delegate.getOptionalValue(key, String.class).orElse(null);
- }
-
- @Override
- public String getOrDefault(String key, String defaultValue) {
- return this.delegate.getOptionalValue(key, String.class).orElse(defaultValue);
- }
-
- @Override
- public <T> T getOrDefault(String key, Class<T> type, T defaultValue) {
- return this.delegate.getOptionalValue(key, type).orElse(defaultValue);
- }
-
- @Override
- public <T> T get(String key, Class<T> type) {
- return this.delegate.getOptionalValue(key, type).orElseThrow(
- () -> new NoSuchElementException("Missing key: " + key));
- }
-
- @Override
- public <T> T get(String key, TypeLiteral<T> type) {
- return this.delegate.getOptionalValue(key, type.getRawType()).orElseThrow(
- () -> new NoSuchElementException("Missing key: " + key));
- }
-
- @Override
- public <T> T getOrDefault(String key, TypeLiteral<T> type, T defaultValue) {
- return null;
- }
-
- @Override
- public Map<String, String> getProperties() {
- return null;
- }
-
- @Override
- public Configuration with(ConfigOperator operator) {
- return operator.operate(this);
- }
-
- @Override
- public <T> T query(ConfigQuery<T> query) {
- return query.query(this);
- }
-
- @Override
- public ConfigurationContext getContext() {
- return null;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/TamayaPropertyConverter.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/TamayaPropertyConverter.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/TamayaPropertyConverter.java
deleted file mode 100644
index a83008a..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/TamayaPropertyConverter.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-
-import org.apache.tamaya.spi.ConversionContext;
-import org.apache.tamaya.spi.PropertyConverter;
-import org.eclipse.microprofile.config.spi.ConfigSource;
-import org.eclipse.microprofile.config.spi.Converter;
-
-import java.util.Objects;
-
-/**
- * Property source implementation that wraps a Microprofile {@link ConfigSource} instance.
- */
-public class TamayaPropertyConverter<T> implements PropertyConverter<T> {
-
- private Converter<T> delegate;
-
- public TamayaPropertyConverter(Converter<T> delegate){
- this.delegate = Objects.requireNonNull(delegate);
- }
-
- public Converter<T> getConverter(){
- return this.delegate;
- }
-
- @Override
- public T convert(String value, ConversionContext context) {
- return delegate.convert(value);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/TamayaPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/TamayaPropertySource.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/TamayaPropertySource.java
deleted file mode 100644
index 0511e32..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/TamayaPropertySource.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-import org.eclipse.microprofile.config.spi.ConfigSource;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-
-/**
- * Property source implementation that wraps a Microprofile {@link ConfigSource} instance.
- */
-public class TamayaPropertySource implements PropertySource {
-
- private ConfigSource delegate;
-
- public TamayaPropertySource(ConfigSource configSource){
- this.delegate = Objects.requireNonNull(configSource);
- }
-
- public ConfigSource getConfigSource(){
- return this.delegate;
- }
-
- @Override
- public int getOrdinal() {
- return delegate.getOrdinal();
- }
-
- @Override
- public String getName() {
- return Optional.ofNullable(delegate.getName())
- .orElse(delegate.toString());
- }
-
- @Override
- public PropertyValue get(String key) {
- return PropertyValue.of(key, delegate.getValue(key),getName());
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
- return toValueMap(delegate.getProperties());
- }
-
- private Map<String, PropertyValue> toValueMap(Map<String, String> properties) {
- Map<String, PropertyValue> valueMap = new HashMap<>(properties.size());
- for(Map.Entry<String,String> en:properties.entrySet()){
- valueMap.put(en.getKey(), PropertyValue.of(en.getKey(), en.getValue(), getName()));
- }
- return valueMap;
- }
-
- @Override
- public boolean isScannable() {
- return true;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/TamayaPropertySourceProvider.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/TamayaPropertySourceProvider.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/TamayaPropertySourceProvider.java
deleted file mode 100644
index 5b0bcf7..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/TamayaPropertySourceProvider.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.microprofile;
-
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertySourceProvider;
-import org.eclipse.microprofile.config.spi.ConfigSource;
-import org.eclipse.microprofile.config.spi.ConfigSourceProvider;
-
-import java.util.*;
-
-/**
- * Microprofile {@link ConfigSource} implementation that wraps a {@link PropertySource} instance.
- */
-public class TamayaPropertySourceProvider implements PropertySourceProvider{
-
- private ConfigSourceProvider delegate;
-
- public TamayaPropertySourceProvider(ConfigSourceProvider configSourceProvider){
- this.delegate = Objects.requireNonNull(configSourceProvider);
- }
-
- public ConfigSourceProvider getConfigSourceProvider(){
- return this.delegate;
- }
-
-
- @Override
- public Collection<PropertySource> getPropertySources() {
- if(delegate instanceof MicroprofileConfigSourceProvider){
- return ((MicroprofileConfigSourceProvider)delegate).getPropertySourceProvider()
- .getPropertySources();
- }else {
- return MicroprofileAdapter.toPropertySources(
- delegate.getConfigSources(Thread.currentThread().getContextClassLoader()));
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/BridgingConfigBean.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/BridgingConfigBean.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/BridgingConfigBean.java
deleted file mode 100644
index a08f76f..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/BridgingConfigBean.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.tamaya.microprofile.cdi;
-
-import javax.enterprise.context.spi.CreationalContext;
-import javax.enterprise.inject.spi.Bean;
-import javax.enterprise.inject.spi.InjectionPoint;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Type;
-import java.util.Objects;
-import java.util.Set;
-
-/**
- * Internally used conversion bean.
- */
-final class BridgingConfigBean implements Bean<Object> {
-
- private final Bean<Object> delegate;
- private final Set<Type> types;
-
- public BridgingConfigBean(final Bean delegate, final Set<Type> types) {
- this.types = types;
- this.delegate = Objects.requireNonNull(delegate);
- }
-
- @Override
- public Set<Type> getTypes() {
- return types;
- }
-
- @Override
- public Class<?> getBeanClass() {
- return delegate.getBeanClass();
- }
-
- @Override
- public Set<InjectionPoint> getInjectionPoints() {
- return delegate.getInjectionPoints();
- }
-
- @Override
- public String getName() {
- return delegate.getName();
- }
-
- @Override
- public Set<Annotation> getQualifiers() {
- return delegate.getQualifiers();
- }
-
- @Override
- public Class<? extends Annotation> getScope() {
- return delegate.getScope();
- }
-
- @Override
- public Set<Class<? extends Annotation>> getStereotypes() {
- return delegate.getStereotypes();
- }
-
- @Override
- public boolean isAlternative() {
- return delegate.isAlternative();
- }
-
- @Override
- public boolean isNullable() {
- return false;
- // delegate.isNullable();
- }
-
- @Override
- public Object create(CreationalContext<Object> creationalContext) {
- return this.delegate.create(creationalContext);
- }
-
- @Override
- public void destroy(Object instance, CreationalContext<Object> creationalContext) {
- delegate.destroy(instance, creationalContext);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/ConfiguredField.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/ConfiguredField.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/ConfiguredField.java
deleted file mode 100644
index 29d7122..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/ConfiguredField.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.tamaya.microprofile.cdi;
-
-import org.apache.tamaya.Configuration;
-
-import javax.enterprise.inject.spi.InjectionPoint;
-import java.lang.reflect.Field;
-
-/**
- * CDI implementation for event publishing of configured instances.
- */
-public final class ConfiguredField {
-
- private final Field field;
- private String key;
-
- ConfiguredField(InjectionPoint injectionPoint, String key){
- this.field = (Field)injectionPoint.getMember();
- this.key = key;
- }
-
- public Class<?> getType() {
- return field.getType();
- }
-
- public String getKey() {
- return key;
- }
-
- public Field getAnnotatedField() {
- return field;
- }
-
- public String getName() {
- return field.getName();
- }
-
- public String getSignature() {
- return getName()+':'+field.getType().getName();
- }
-
- public void configure(Object instance, Configuration config) {
- throw new UnsupportedOperationException("Use CDI annotations for configuration injection.");
- }
-
- @Override
- public String toString() {
- return "CDIConfiguredField["+getSignature()+']';
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/ConfiguredMethod.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/ConfiguredMethod.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/ConfiguredMethod.java
deleted file mode 100644
index 90204fe..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/ConfiguredMethod.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.tamaya.microprofile.cdi;
-
-import org.apache.tamaya.Configuration;
-
-import javax.enterprise.inject.spi.InjectionPoint;
-import java.lang.reflect.Method;
-
-/**
- * Implementation of a configured methods for CDI module.
- */
-public final class ConfiguredMethod {
-
- private final Method method;
- private String key;
-
- ConfiguredMethod(InjectionPoint injectionPoint, String key){
- this.method = (Method)injectionPoint.getMember();
- this.key = key;
- }
-
- public String getKey() {
- return key;
- }
-
- public Class<?>[] getParameterTypes() {
- return method.getParameterTypes();
- }
-
- public Method getAnnotatedMethod() {
- return method;
- }
-
- public String getName() {
- return method.getName();
- }
-
- public String getSignature() {
- return null;
- }
-
- public void configure(Object instance, Configuration config) {
- throw new UnsupportedOperationException("Use CDI annotations for configuration injection.");
- }
-
- @Override
- public String toString() {
- return "CDIConfiguredMethod["+getSignature()+']';
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/ConfiguredType.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/ConfiguredType.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/ConfiguredType.java
deleted file mode 100644
index 535a556..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/ConfiguredType.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.tamaya.microprofile.cdi;
-
-import org.apache.tamaya.Configuration;
-
-import javax.enterprise.inject.spi.InjectionPoint;
-import java.lang.reflect.Field;
-import java.lang.reflect.Member;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * Event published for items configured by CDI extensions. This is for example used by the documentation module
- * to automatically track the configuration endpoints for documentation.
- */
-public final class ConfiguredType {
-
- private final Class<?> type;
- private final List<ConfiguredMethod> methods = new ArrayList<>();
- private final List<ConfiguredField> fields = new ArrayList<>();
-
- public ConfiguredType(Class<?> type){
- this.type = Objects.requireNonNull(type);
- }
-
- public Class getType() {
- return type;
- }
-
- public String getName() {
- return type.getName();
- }
-
- public Collection<ConfiguredField> getConfiguredFields() {
- return null;
- }
-
- public Collection<ConfiguredMethod> getConfiguredMethods() {
- return null;
- }
-
- public void configure(Object instance, Configuration config) {
- throw new UnsupportedOperationException("Use CDI annotations for configuration injection.");
- }
-
- /**
- * Used to build up during injection point processing.
- * @param injectionPoint the CDI injection point, not null.
- * @param key the possible config key, not null.
- */
- void addConfiguredMember(InjectionPoint injectionPoint, String key) {
- Member member = injectionPoint.getMember();
- if(member instanceof Field){
- this.fields.add(new ConfiguredField(injectionPoint, key));
- } else if(member instanceof Method){
- this.methods.add(new ConfiguredMethod(injectionPoint, key));
- }
- }
-
- @Override
- public String toString() {
- return "CDIConfiguredType{" +
- "type=" + type +
- ", methods=" + methods +
- ", fields=" + fields +
- '}';
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/MicroprofileCDIExtension.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/MicroprofileCDIExtension.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/MicroprofileCDIExtension.java
deleted file mode 100644
index 0be929b..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/MicroprofileCDIExtension.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.tamaya.microprofile.cdi;
-
-import org.eclipse.microprofile.config.inject.ConfigProperty;
-
-import javax.enterprise.event.Observes;
-import javax.enterprise.inject.Instance;
-import javax.enterprise.inject.spi.AfterBeanDiscovery;
-import javax.enterprise.inject.spi.Bean;
-import javax.enterprise.inject.spi.BeanManager;
-import javax.enterprise.inject.spi.Extension;
-import javax.enterprise.inject.spi.InjectionPoint;
-import javax.enterprise.inject.spi.ProcessBean;
-import javax.enterprise.inject.spi.ProcessProducerMethod;
-import javax.inject.Provider;
-import java.lang.reflect.AnnotatedType;
-import java.lang.reflect.Method;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.logging.Logger;
-
-
-/**
- * CDI Extension module that adds injection mechanism for configuration.
- *
- * @see org.eclipse.microprofile.config.Config
- * @see org.eclipse.microprofile.config.inject.ConfigProperty
- */
-public class MicroprofileCDIExtension implements Extension {
-
- private static final Logger LOG = Logger.getLogger(MicroprofileCDIExtension.class.getName());
-
- private final Set<Type> types = new HashSet<>();
- private Bean<?> convBean;
-
- /**
- * Constructor for loading logging its load.
- */
- public MicroprofileCDIExtension(){
- LOG.finest("Loading Tamaya Microprofile Support...");
- }
-
- /**
- * Method that checks the configuration injection points during deployment for available configuration.
- * @param pb the bean to process.
- * @param beanManager the bean manager to notify about new injections.
- */
- public void retrieveTypes(@Observes final ProcessBean<?> pb, BeanManager beanManager) {
-
- final Set<InjectionPoint> ips = pb.getBean().getInjectionPoints();
- ConfiguredType configuredType = new ConfiguredType(pb.getBean().getBeanClass());
-
- boolean configured = false;
- for (InjectionPoint injectionPoint : ips) {
- if (injectionPoint.getAnnotated().isAnnotationPresent(ConfigProperty.class)) {
- LOG.fine("Configuring: " + injectionPoint);
- final ConfigProperty annotation = injectionPoint.getAnnotated().getAnnotation(ConfigProperty.class);
- String key = !annotation.name().isEmpty()?annotation.name():MicroprofileConfigurationProducer.getDefaultKey(injectionPoint);
- configuredType.addConfiguredMember(injectionPoint, key);
- Type originalType = injectionPoint.getType();
- Type convertedType = unwrapType(originalType);
- types.add(convertedType);
- configured = true;
- LOG.finest(() -> "Enabling Tamaya Microprofile Configuration on bean: " + configuredType.getName());
- }else if(injectionPoint.getMember() instanceof Method){
- Method method = (Method)injectionPoint.getMember();
- for(AnnotatedType paramType: method.getAnnotatedParameterTypes()){
- if(paramType.isAnnotationPresent(ConfigProperty.class)) {
- LOG.fine("Configuring method: " + injectionPoint);
- final ConfigProperty annotation = paramType.getAnnotation(ConfigProperty.class);
- String key = !annotation.name().isEmpty() ? annotation.name() : MicroprofileConfigurationProducer.getDefaultKey(injectionPoint);
- configuredType.addConfiguredMember(injectionPoint, key);
- Type originalType = paramType.getType();
- Type convertedType = unwrapType(originalType);
- types.add(convertedType);
- configured = true;
- LOG.finest(() -> "Enabling Tamaya Microprofile Configuration on bean: " + configuredType.getName());
- }
- }
- }
- }
- if(configured) {
- beanManager.fireEvent(configuredType);
- }
- }
-
-
- public void captureConvertBean(@Observes final ProcessProducerMethod<?, ?> ppm) {
- if (ppm.getAnnotated().isAnnotationPresent(ConfigProperty.class)) {
- convBean = ppm.getBean();
- }
- }
-
- public void addConverter(@Observes final AfterBeanDiscovery abd, final BeanManager bm) {
- if(!types.isEmpty() && convBean!=null) {
- abd.addBean(new BridgingConfigBean(convBean, types));
- }
- }
-
- private Type unwrapType(Type type) {
- if(type instanceof ParameterizedType) {
- Type rawType = ((ParameterizedType) type).getRawType();
- if(rawType == Provider.class || rawType == Instance.class) {
- return ((ParameterizedType) type).getActualTypeArguments()[0];
- }
- }
- return type;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/cfb364cd/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/MicroprofileConfigurationProducer.java
----------------------------------------------------------------------
diff --git a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/MicroprofileConfigurationProducer.java b/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/MicroprofileConfigurationProducer.java
deleted file mode 100644
index bae7287..0000000
--- a/modules/microprofile/src/main/java/org/apache/tamaya/microprofile/cdi/MicroprofileConfigurationProducer.java
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.tamaya.microprofile.cdi;
-
-import org.apache.tamaya.ConfigException;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
-import org.apache.tamaya.TypeLiteral;
-import org.apache.tamaya.spi.ConversionContext;
-import org.apache.tamaya.spi.PropertyConverter;
-import org.eclipse.microprofile.config.Config;
-import org.eclipse.microprofile.config.ConfigProvider;
-import org.eclipse.microprofile.config.inject.ConfigProperty;
-import org.eclipse.microprofile.config.spi.ConfigBuilder;
-import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
-
-import javax.enterprise.context.ApplicationScoped;
-import javax.enterprise.inject.Produces;
-import javax.enterprise.inject.spi.Annotated;
-import javax.enterprise.inject.spi.AnnotatedField;
-import javax.enterprise.inject.spi.AnnotatedType;
-import javax.enterprise.inject.spi.InjectionPoint;
-import javax.inject.Provider;
-import java.lang.reflect.AnnotatedElement;
-import java.lang.reflect.Method;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.util.List;
-import java.util.Optional;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * Producer bean for configuration properties.
- */
-@ApplicationScoped
-public class MicroprofileConfigurationProducer {
-
- private static final Logger LOGGER = Logger.getLogger(MicroprofileConfigurationProducer.class.getName());
-
- @Produces
- @ConfigProperty
- public Object resolveAndConvert(final InjectionPoint injectionPoint) {
- LOGGER.finest( () -> "Inject: " + injectionPoint);
- final ConfigProperty annotation = injectionPoint.getAnnotated().getAnnotation(ConfigProperty.class);
- String key = annotation.name();
- if(key.isEmpty()){
- key = getDefaultKey(injectionPoint);
- }
-
- // unless the extension is not installed, this should never happen because the extension
- // enforces the resolvability of the config
-
- String defaultTextValue = annotation.defaultValue().equals(ConfigProperty.UNCONFIGURED_VALUE) ? null : annotation.defaultValue();
- ConversionContext conversionContext = createConversionContext(key, injectionPoint);
- Object value = resolveValue(defaultTextValue, conversionContext, injectionPoint);
- if (value == null) {
- throw new ConfigException(String.format(
- "Can't resolve any of the possible config keys: %s to the required target type: %s, supported formats: %s",
- key, conversionContext.getTargetType(), conversionContext.getSupportedFormats().toString()));
- }
- LOGGER.finest(String.format("Injecting %s for key %s in class %s", key, value.toString(), injectionPoint.toString()));
- return value;
- }
-
- static String getDefaultKey(InjectionPoint injectionPoint) {
- Class declaringType = injectionPoint.getMember().getDeclaringClass();
- return declaringType.getCanonicalName() + "." + injectionPoint.getMember().getName();
- }
-
- static ConversionContext createConversionContext(String key, InjectionPoint injectionPoint) {
- final Type targetType = injectionPoint.getAnnotated().getBaseType();
- Configuration config = ConfigurationProvider.getConfiguration();
- ConversionContext.Builder builder = new ConversionContext.Builder(config,
- ConfigurationProvider.getConfiguration().getContext(), key, TypeLiteral.of(targetType));
- if(targetType instanceof ParameterizedType){
- ParameterizedType pt = (ParameterizedType)targetType;
- if(pt.getRawType().equals(Provider.class)) {
- builder = new ConversionContext.Builder(config,
- ConfigurationProvider.getConfiguration().getContext(), key,
- TypeLiteral.of(pt.getActualTypeArguments()[0]));
- }
- }
- if (injectionPoint.getMember() instanceof AnnotatedElement) {
- AnnotatedElement annotated = (AnnotatedElement)injectionPoint.getMember();
- if(annotated.isAnnotationPresent(ConfigProperty.class)) {
- builder.setAnnotatedElement(annotated);
- }
- }else if(injectionPoint.getMember() instanceof Method){
- Method method = (Method)injectionPoint.getMember();
- for(Type type:method.getParameterTypes()){
- if(type instanceof AnnotatedElement){
- AnnotatedElement annotated = (AnnotatedElement)type;
- if(annotated.isAnnotationPresent(ConfigProperty.class)) {
- builder.setAnnotatedElement(annotated);
- }
- }
- }
- }
- return builder.build();
- }
-
- static Object resolveValue(String defaultTextValue, ConversionContext context, InjectionPoint injectionPoint) {
- Config config = ConfigProviderResolver.instance().getConfig();
- String textValue = config.getOptionalValue(context.getKey(), String.class).orElse(defaultTextValue);
- if(String.class.equals(context.getTargetType().getRawType())){
- return textValue;
- }
- Object value = null;
- if (textValue != null || Optional.class.equals(context.getTargetType().getRawType())) {
- LOGGER.log(Level.FINEST, () -> "Converting KEY: " + context.getKey() + "("+context.getTargetType()+"), textValue: " + textValue);
- List<PropertyConverter> converters = ConfigurationProvider.getConfiguration().getContext()
- .getPropertyConverters((TypeLiteral)context.getTargetType());
- for (PropertyConverter<Object> converter : converters) {
- try {
- value = converter.convert(textValue, context);
- if (value != null) {
- LOGGER.log(Level.FINEST, "Parsed default value from '" + textValue + "' into " +
- injectionPoint);
- break;
- }
- } catch (Exception e) {
- LOGGER.log(Level.FINEST, "Failed to convert value '" + textValue + "' for " +
- injectionPoint, e);
- }
- }
- }
- return value;
- }
-
- @Produces
- public Config getConfiguration(){
- return ConfigProvider.getConfig();
- }
-
- @Produces
- public ConfigBuilder getConfigBuilder(){
- return ConfigProviderResolver.instance().getBuilder();
- }
-
-
-}
[06/18] incubator-tamaya-extensions git commit: Adapted to comply
with JSR API, fixed bugs. Imrpved API regarding sections, section filtering.
Posted by an...@apache.org.
Adapted to comply with JSR API, fixed bugs. Imrpved API regarding sections, section filtering.
Signed-off-by: Anatole Tresch <an...@apache.org>
Project: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/commit/36b44661
Tree: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/tree/36b44661
Diff: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/diff/36b44661
Branch: refs/heads/configjsr
Commit: 36b446614d7c95b2ed1db9e15ff6ddaeeca1f7ab
Parents: 581c92e
Author: Anatole Tresch <an...@apache.org>
Authored: Wed Dec 27 12:37:03 2017 +0100
Committer: Anatole Tresch <an...@apache.org>
Committed: Wed Dec 27 12:37:03 2017 +0100
----------------------------------------------------------------------
modules/functions/pom.xml | 5 +-
.../tamaya/functions/ConfigSourceFunctions.java | 451 +++++++++++++++++++
.../functions/ConfigurationFunctions.java | 2 +-
.../tamaya/functions/EnrichedConfigSource.java | 93 ++++
.../functions/EnrichedPropertySource.java | 103 -----
.../tamaya/functions/FilteredConfigSource.java | 89 ++++
.../functions/FilteredPropertySource.java | 93 ----
.../tamaya/functions/MappedConfigSource.java | 109 +++++
.../tamaya/functions/MappedPropertySource.java | 119 -----
.../functions/PropertySourceFunctions.java | 410 -----------------
.../functions/ValueMappedConfigSource.java | 75 +++
.../functions/ValueMappedPropertySource.java | 86 ----
.../functions/CombinedConfigurationTest.java | 1 -
.../functions/ConfigSourceFunctionsTest.java | 434 ++++++++++++++++++
.../functions/EnrichedConfigSourceTest.java | 216 +++++++++
.../functions/EnrichedConfigurationTest.java | 4 -
.../functions/EnrichedPropertySourceTest.java | 250 ----------
.../functions/FilteredConfigSourceTest.java | 188 ++++++++
.../functions/FilteredPropertySourceTest.java | 214 ---------
.../tamaya/functions/InMemoryConfigSource.java | 68 +++
.../tamaya/functions/InMemoryConfiguration.java | 35 --
.../functions/InMemoryPropertySource.java | 86 ----
.../functions/MappedConfigSourceTest.java | 159 +++++++
.../functions/MappedPropertySourceTest.java | 176 --------
.../functions/PropertySourceFunctionsTest.java | 367 ---------------
.../functions/ValueMappedConfigSourceTest.java | 148 ++++++
.../ValueMappedPropertySourceTest.java | 183 --------
27 files changed, 2033 insertions(+), 2131 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/pom.xml
----------------------------------------------------------------------
diff --git a/modules/functions/pom.xml b/modules/functions/pom.xml
index 17de980..4baa580 100644
--- a/modules/functions/pom.xml
+++ b/modules/functions/pom.xml
@@ -41,10 +41,9 @@ under the License.
</dependency>
<dependency>
<groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-spisupport</artifactId>
- <version>${project.version}</version>
+ <artifactId>tamaya-base</artifactId>
+ <version>${tamaya-apicore.version}</version>
</dependency>
-
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigSourceFunctions.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigSourceFunctions.java b/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigSourceFunctions.java
new file mode 100644
index 0000000..90081ed
--- /dev/null
+++ b/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigSourceFunctions.java
@@ -0,0 +1,451 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.functions;
+
+import javax.config.ConfigProvider;
+import javax.config.spi.ConfigSource;
+import java.util.*;
+import java.util.function.Function;
+
+/**
+ * Accessor that provides useful functions along with configuration.
+ */
+public final class ConfigSourceFunctions {
+ /**
+ * Implementation of an empty propertySource.
+ */
+ private static final ConfigSource EMPTY_PROPERTYSOURCE = new ConfigSource() {
+
+ @Override
+ public int getOrdinal() {
+ return 0;
+ }
+
+ @Override
+ public String getName() {
+ return "<empty>";
+ }
+
+ @Override
+ public String getValue(String key) {
+ return null;
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ return Collections.emptyMap();
+ }
+
+ @Override
+ public String toString() {
+ return "ConfigSource<empty>";
+ }
+ };
+
+
+ private static final Function<String,Integer> DEFAULT_AREA_CALCULATOR =
+ s -> s.lastIndexOf('.');
+
+ /**
+ * Private singleton constructor.
+ */
+ private ConfigSourceFunctions() {
+ }
+
+ /**
+ * Calculates the current section key and compares it to the given key.
+ *
+ * @param key the fully qualified entry key, not null
+ * @param sectionKey the section key, not null
+ * @param sectionCalculator function to calculate the split point of a key's section, e.g. {@code key.lastIndexOf('.')},
+ * not null.
+ * @param directChildrenOnly if true, only keys with the same area match. Otherwise also containing super-areas can
+ * match.
+ * @return true, if the entry is exact in this section
+ */
+ private static boolean isKeyInSection(String key, String sectionKey,
+ Function<String,Integer> sectionCalculator, boolean directChildrenOnly) {
+ Objects.requireNonNull(key, "Key must be given.");
+ Objects.requireNonNull(sectionCalculator, "Section calculator must be given.");
+ Objects.requireNonNull(sectionKey, "Section key must be given.");
+
+ sectionKey = normalizeSectionKey(sectionKey);
+
+ int lastIndex = sectionCalculator.apply(key);
+ String curAreaKey = lastIndex > 0 ? key.substring(0, lastIndex) : "";
+ if(directChildrenOnly) {
+ return curAreaKey.equals(sectionKey);
+ }else{
+ return curAreaKey.startsWith(sectionKey);
+ }
+ }
+
+ private static String normalizeKey(String key) {
+ return normalizeKey(key, DEFAULT_AREA_CALCULATOR);
+ }
+
+ private static String normalizeKey(String key, Function<String,Integer> sectionCalculator) {
+ if(key.isEmpty()){
+ return key;
+ }
+ int index = sectionCalculator.apply(key.substring(0,1));
+ if(index==0){
+ return key.substring(1);
+ }
+ return key;
+ }
+
+ private static String normalizeSectionKey(String sectionKey) {
+ return normalizeSectionKey(sectionKey, DEFAULT_AREA_CALCULATOR);
+ }
+
+ private static String normalizeSectionKey(String sectionKey, Function<String,Integer> areaCalculator) {
+ // Ignore unneeded and trailing dot at the end of the section key
+ if(sectionKey.isEmpty()){
+ return sectionKey;
+ }
+ int lastIndex = areaCalculator.apply(sectionKey);
+ int firstIndex = areaCalculator.apply(sectionKey.substring(0,1));
+
+ String normalizedKey = lastIndex==(sectionKey.length()-1)
+ ? sectionKey.substring(0, sectionKey.length() - 1)
+ : sectionKey;
+
+ normalizedKey = firstIndex==0 ? sectionKey.length() == 1 ? ""
+ : normalizedKey.substring(1)
+ : normalizedKey;
+
+ return normalizedKey;
+ }
+
+ /**
+ * Checks if the given key is <i>directly</i> included in one of the given sections.
+ *
+ * @param key the fully qualified entry key, not {@code null}
+ * @param sectionKeys the section keys, not {@code null}
+ * @return true, if the entry is in one of the given sections
+ */
+ public static boolean isKeyInSection(String key, String... sectionKeys) {
+ return isKeyInSection(key, true, DEFAULT_AREA_CALCULATOR, sectionKeys);
+ }
+
+ /**
+ * Checks if the given key is included in one of the given sections.
+ *
+ * @param key the fully qualified entry key, not {@code null}
+ * @param sectionKeys the section keys, not {@code null}
+ * @param directChildrenOnly if true, then only keys match, which are a direct child of the given section.
+ * @return true, if the entry is in one of the given sections
+ */
+ public static boolean isKeyInSection(String key, boolean directChildrenOnly, String... sectionKeys) {
+ return isKeyInSection(key, directChildrenOnly, DEFAULT_AREA_CALCULATOR, sectionKeys);
+ }
+
+ /**
+ * Checks if the given key is included in one of the given sections, using the given separator to identify sections.
+ *
+ * @param key the fully qualified entry key, not {@code null}
+ * @param sectionKeys the section keys, not {@code null}
+ * @param areaCalculator the function to calculate the split point to identify the section of a key.
+ * @param directChildrenOnly if true, then only keys match, which are a direct child of the given section.
+ * @return true, if the entry is in one of the given sections
+ */
+ public static boolean isKeyInSection(String key, boolean directChildrenOnly,
+ Function<String,Integer> areaCalculator, String... sectionKeys) {
+ Objects.requireNonNull(key, "Key must be given.");
+ Objects.requireNonNull(sectionKeys, "Section keys must be given.");
+
+ for (String areaKey : sectionKeys) {
+ if (areaKey == null) {
+ continue;
+ }
+ if (isKeyInSection(key, areaKey, areaCalculator, directChildrenOnly)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Return a query to evaluate the set with all fully qualified section names. This method should return the sections as accurate as possible,
+ * but may not provide a complete set of sections that are finally accessible, especially when the underlying storage
+ * does not support key iteration.
+ *
+ * @param properties properties to find sections in.
+ * @return set with all sections, never {@code null}.
+ */
+ public static Set<String> sections(Map<String, String> properties) {
+ return sections(properties, DEFAULT_AREA_CALCULATOR);
+ }
+
+ /**
+ * Return a query to evaluate the set with all fully qualified section names. This method should return the sections as accurate as possible,
+ * but may not provide a complete set of sections that are finally accessible, especially when the underlying storage
+ * does not support key iteration.
+ *
+ * @param properties properties to find sections in.
+ * @return set with all sections, never {@code null}.
+ */
+ public static Set<String> sections(Map<String, String> properties, Function<String,Integer> areaCalculator) {
+ final Set<String> areas = new HashSet<>();
+ for (String key : properties.keySet()) {
+ String normalizedKey = normalizeKey(key, areaCalculator);
+
+ int index = areaCalculator.apply(normalizedKey);
+ if (index > 0) {
+ areas.add(normalizedKey.substring(0, index));
+ } else {
+ areas.add("<root>");
+ }
+ }
+ return areas;
+ }
+
+ /**
+ * Return a query to evaluate the set with all fully qualified section names, containing the transitive closure also including all
+ * subarea names, regardless if properties are accessible or not. This method should return the sections as accurate
+ * as possible, but may not provide a complete set of sections that are finally accessible, especially when the
+ * underlying storage does not support key iteration.
+ *
+ * @param properties properties to find transitive sections in.
+ * @return s set with all transitive sections, never {@code null}.
+ */
+ public static Set<String> transitiveSections(Map<String, String> properties) {
+ return transitiveSections(properties, DEFAULT_AREA_CALCULATOR);
+ }
+
+ /**
+ * Return a query to evaluate the set with all fully qualified section names, containing the transitive closure also including all
+ * subarea names, regardless if properties are accessible or not. This method should return the sections as accurate
+ * as possible, but may not provide a complete set of sections that are finally accessible, especially when the
+ * underlying storage does not support key iteration.
+ *
+ * @param properties properties to find transitive sections in.
+ * @return s set with all transitive sections, never {@code null}.
+ */
+ public static Set<String> transitiveSections(Map<String, String> properties, Function<String,Integer> areaCalculator) {
+ final Set<String> transitiveAreas = new HashSet<>();
+ for (String section : sections(properties, areaCalculator)) {
+ section = normalizeSectionKey(section, areaCalculator);
+
+ int index = areaCalculator.apply(section);
+ if (index < 0 && section.isEmpty()) {
+ transitiveAreas.add("<root>");
+ } if (index < 0) {
+ transitiveAreas.add(section);
+ } else {
+ while (index > 0) {
+ section = section.substring(0, index);
+ transitiveAreas.add(section);
+ index = section.lastIndexOf('.');
+ }
+ }
+ }
+ return transitiveAreas;
+ }
+
+ /**
+ * Return a query to evaluate the set with all fully qualified section names, containing only the
+ * sections that match the predicate and have properties attached. This method should return the sections as accurate as possible,
+ * but may not provide a complete set of sections that are finally accessible, especially when the underlying storage
+ * does not support key iteration.
+ *
+ * @param properties properties to find sections in.
+ * @param predicate A predicate to determine, which sections should be returned, not {@code null}.
+ * @return s set with all sections, never {@code null}.
+ */
+ public static Set<String> sections(Map<String, String> properties, final Predicate<String> predicate) {
+ Set<String> treeSet = new TreeSet<>();
+ for (String area : sections(properties)) {
+ if (predicate.test(area)) {
+ treeSet.add(area);
+ }
+ }
+ return treeSet;
+ }
+
+ /**
+ * Return a query to evaluate the set with all fully qualified section names, containing the transitive closure also including all
+ * subarea names, regardless if properties are accessible or not. This method should return the sections as accurate as possible,
+ * but may not provide a complete set of sections that are finally accessible, especially when the underlying storage
+ * does not support key iteration.
+ *
+ * @param properties properties to find transitive sections in.
+ * @param predicate A predicate to determine, which sections should be returned, not {@code null}.
+ * @return s set with all transitive sections, never {@code null}.
+ */
+ public static Set<String> transitiveSections(Map<String, String> properties, Predicate<String> predicate) {
+ Set<String> treeSet = new TreeSet<>();
+ for (String area : transitiveSections(properties)) {
+ if (predicate.test(area)) {
+ treeSet.add(area);
+ }
+ }
+ return treeSet;
+ }
+
+
+ /**
+ *Extracts the submap containing only entries with keys
+ * that are contained in the given sections. Hereby
+ * the section key is stripped away from the Map of the resulting keys.
+ *
+ * @param properties properties to find recursive sections in.
+ * @param sectionKeys the section keys, not null
+ * @return the section configuration, with the areaKey stripped away.
+ */
+ public static Map<String, String> sectionsRecursive(Map<String, String> properties, String... sectionKeys) {
+ return sectionsRecursive(properties, true, sectionKeys);
+ }
+
+ /**
+ * Extracts the submap containing only entries with keys
+ * that are contained in the given section and it's subsections.
+ *
+ * @param properties properties to find sections in.
+ * @param sectionKeys the section keys, not null
+ * @param stripKeys if set to true, the section key is stripped away fromMap the resulting key.
+ * @return the section configuration, with the areaKey stripped away.
+ */
+ public static Map<String, String> sectionsRecursive(Map<String, String> properties, boolean stripKeys, String... sectionKeys) {
+ Map<String, String> result = new HashMap<>(properties.size());
+ for (Map.Entry<String, String> en : properties.entrySet()) {
+ if (isKeyInSection(en.getKey(), false,DEFAULT_AREA_CALCULATOR, sectionKeys)) {
+ if (stripKeys) {
+ result.put(stripSectionKeys(en.getKey(), sectionKeys), en.getValue());
+ }else {
+ result.put(en.getKey(), en.getValue());
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Strips the section key of the given absolute key, if it is one of the areaKeys passed.
+ *
+ * @param key the current key, not null.
+ * @param areaKeys the areaKeys, not null.
+ * @return the stripped key, or the original key (if no section was matching).
+ */
+ static String stripSectionKeys(String key, String... areaKeys) {
+ for (String areaKey : areaKeys) {
+ if (key.startsWith(areaKey + '.')) {
+ return key.substring(areaKey.length() + 1);
+ }
+ }
+ return key;
+ }
+
+ /**
+ * Creates a ConfigOperator that adds the given items.
+ *
+ * @param propertySource source property source that is changed.
+ * @param items the items to be added/replaced.
+ * @param override if true, all items existing are overridden by the new ones passed.
+ * @return the ConfigOperator, never null.
+ */
+ public static ConfigSource addItems(ConfigSource propertySource, final Map<String, String> items, final boolean override) {
+ return new EnrichedConfigSource(propertySource, items, override);
+ }
+
+ /**
+ * Creates an operator that adds items to the instance (existing items will not be overridden).
+ *
+ * @param propertySource source property source that is changed.
+ * @param items the items, not null.
+ * @return the operator, never null.
+ */
+ public static ConfigSource addItems(ConfigSource propertySource, Map<String, String> items) {
+ return addItems(propertySource, items, false);
+ }
+
+ /**
+ * Creates an operator that replaces the given items.
+ *
+ * @param propertySource source property source that is changed.
+ * @param items the items.
+ * @return the operator for replacing the items.
+ */
+ public static ConfigSource replaceItems(ConfigSource propertySource, Map<String, String> items) {
+ return addItems(propertySource, items, true);
+ }
+
+ /**
+ * Accesses an empty PropertySource.
+ *
+ * @return an empty PropertySource, never null.
+ */
+ public static ConfigSource emptyConfigSource() {
+ return EMPTY_PROPERTYSOURCE;
+ }
+
+ /**
+ * Find all {@link ConfigSource} instances managed by the current
+ * {@link javax.config.Config} that are assignable to the given type.
+ *
+ * @param expression the regular expression to match the source's name.
+ * @return the list of all {@link ConfigSource} instances matching, never null.
+ */
+ public static Collection<? extends ConfigSource> findPropertySourcesByName(String expression) {
+ List result = new ArrayList<>();
+ for (ConfigSource src : ConfigProvider.getConfig().getConfigSources()) {
+ if (src.getName().matches(expression)) {
+ result.add(src);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Get a list of all {@link ConfigSource} instances managed by the current
+ * {@link javax.config.Config} that are assignable to the given type.
+ *
+ * @param <T> the type of the property source instances requested
+ * @param type target type to filter for property sources.
+ * @return the list of all {@link ConfigSource} instances matching, never null.
+ */
+ public static <T> Collection<T> getPropertySources(Class<T> type) {
+ List<T> result = new ArrayList<>();
+ for (ConfigSource src : ConfigProvider.getConfig().getConfigSources()) {
+ if (type.isAssignableFrom(src.getClass())) {
+ result.add((T) src);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Get a list of all {@link ConfigSource} instances managed by the current
+ * {@link javax.config.Config} that are assignable to the given type.
+ *
+ * @param <T> the type of the property source instances requested
+ * @param type target type to filter for property sources.
+ * @return the list of all {@link ConfigSource} instances matching, never null.
+ */
+ public static <T> T getPropertySource(Class<T> type) {
+ for (ConfigSource src : ConfigProvider.getConfig().getConfigSources()) {
+ if (type.isAssignableFrom(src.getClass())) {
+ return (T) src;
+ }
+ }
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigurationFunctions.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigurationFunctions.java b/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigurationFunctions.java
index 76581b7..15e6242 100644
--- a/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigurationFunctions.java
+++ b/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigurationFunctions.java
@@ -303,7 +303,7 @@ public final class ConfigurationFunctions {
if (stripKeys) {
return new MappedConfiguration(
filtered,
- k -> PropertySourceFunctions.stripSectionKeys(k, sectionKeys),
+ k -> ConfigSourceFunctions.stripSectionKeys(k, sectionKeys),
"stripped");
}
return filtered;
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/main/java/org/apache/tamaya/functions/EnrichedConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/main/java/org/apache/tamaya/functions/EnrichedConfigSource.java b/modules/functions/src/main/java/org/apache/tamaya/functions/EnrichedConfigSource.java
new file mode 100644
index 0000000..c628a95
--- /dev/null
+++ b/modules/functions/src/main/java/org/apache/tamaya/functions/EnrichedConfigSource.java
@@ -0,0 +1,93 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.functions;
+
+import org.apache.tamaya.base.configsource.ConfigSourceComparator;
+
+import javax.config.spi.ConfigSource;
+import java.util.*;
+
+/**
+ * PropertySource, that has values added or overridden.
+ */
+class EnrichedConfigSource implements ConfigSource {
+
+ private final ConfigSource basePropertySource;
+
+ private final Map<String, String> addedProperties = new HashMap<>();
+
+ private final boolean overriding;
+
+ /**
+ * Constructor.
+ *
+ * @param propertySource the base property source, not null.
+ * @param properties the properties to be added.
+ * @param overriding flag if existing properties are overridden.
+ */
+ EnrichedConfigSource(ConfigSource propertySource, Map<String, String> properties, boolean overriding) {
+ this.basePropertySource = Objects.requireNonNull(propertySource);
+ for(Map.Entry<String,String> en:properties.entrySet()){
+ this.addedProperties.putAll(properties);
+ }
+ this.overriding = overriding;
+ }
+
+
+ @Override
+ public int getOrdinal() {
+ return ConfigSourceComparator.getOrdinal(basePropertySource);
+ }
+
+ @Override
+ public String getName() {
+ return basePropertySource.getName();
+ }
+
+ @Override
+ public String getValue(String key) {
+ if (overriding) {
+ String val = addedProperties.get(key);
+ if (val != null) {
+ return val;
+ }
+ return basePropertySource.getValue(key);
+ }
+ String val = basePropertySource.getValue(key);
+ if (val != null) {
+ return val;
+ }
+ return addedProperties.get(key);
+
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ Map<String, String> allProps = new HashMap<>();
+ if (overriding) {
+ allProps.putAll(basePropertySource.getProperties());
+ allProps.putAll(addedProperties);
+ } else {
+ allProps.putAll(addedProperties);
+ allProps.putAll(basePropertySource.getProperties());
+ }
+ return allProps;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/main/java/org/apache/tamaya/functions/EnrichedPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/main/java/org/apache/tamaya/functions/EnrichedPropertySource.java b/modules/functions/src/main/java/org/apache/tamaya/functions/EnrichedPropertySource.java
deleted file mode 100644
index c1367b8..0000000
--- a/modules/functions/src/main/java/org/apache/tamaya/functions/EnrichedPropertySource.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.functions;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-import org.apache.tamaya.spisupport.PropertySourceComparator;
-
-import java.util.*;
-
-/**
- * PropertySource, that has values added or overridden.
- */
-class EnrichedPropertySource implements PropertySource {
-
- private final PropertySource basePropertySource;
-
- private final Map<String, PropertyValue> addedProperties = new HashMap<>();
-
- private final boolean overriding;
-
- /**
- * Constructor.
- *
- * @param propertySource the base property source, not null.
- * @param properties the properties to be added.
- * @param overriding flag if existing properties are overridden.
- */
- EnrichedPropertySource(PropertySource propertySource, Map<String, String> properties, boolean overriding) {
- this.basePropertySource = Objects.requireNonNull(propertySource);
- for(Map.Entry<String,String> en:properties.entrySet()){
- this.addedProperties.put(en.getKey(), PropertyValue.of(en.getKey(), en.getValue(), propertySource.getName()));
- }
- this.overriding = overriding;
- }
-
-
- @Override
- public int getOrdinal() {
- return PropertySourceComparator.getOrdinal(basePropertySource);
- }
-
- @Override
- public String getName() {
- return basePropertySource.getName();
- }
-
- @Override
- public PropertyValue get(String key) {
- if (overriding) {
- PropertyValue val = addedProperties.get(key);
- if (val != null) {
- return val;
- }
- return basePropertySource.get(key);
- }
- PropertyValue val = basePropertySource.get(key);
- if (val != null) {
- return val;
- }
- return addedProperties.get(key);
-
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
- Map<String, PropertyValue> allProps;
- if (overriding) {
- allProps = new HashMap<>();
- for(PropertyValue val:basePropertySource.getProperties().values()){
- allProps.put(val.getKey(), val);
- }
- allProps.putAll(addedProperties);
- } else {
- allProps = new HashMap<>(addedProperties);
- for(PropertyValue val:basePropertySource.getProperties().values()){
- allProps.put(val.getKey(), val);
- }
- }
- return allProps;
- }
-
- @Override
- public boolean isScannable() {
- return basePropertySource.isScannable();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/main/java/org/apache/tamaya/functions/FilteredConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/main/java/org/apache/tamaya/functions/FilteredConfigSource.java b/modules/functions/src/main/java/org/apache/tamaya/functions/FilteredConfigSource.java
new file mode 100644
index 0000000..51ccb3b
--- /dev/null
+++ b/modules/functions/src/main/java/org/apache/tamaya/functions/FilteredConfigSource.java
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.functions;
+
+
+import org.apache.tamaya.base.configsource.ConfigSourceComparator;
+
+import javax.config.spi.ConfigSource;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * PropertySource that on the fly filters out part of the key/values of the underlying PropertySource.
+ */
+class FilteredConfigSource implements ConfigSource {
+
+ private final ConfigSource baseSource;
+ private final Predicate<String> filter;
+
+ /**
+ * Creates a new instance
+ * @param baseSource the underlying PropertySource
+ * @param filter the filter to be applied.
+ */
+ public FilteredConfigSource(ConfigSource baseSource, Predicate<String> filter){
+ this.baseSource = Objects.requireNonNull(baseSource);
+ this.filter = Objects.requireNonNull(filter);
+ }
+
+ @Override
+ public int getOrdinal(){
+ return ConfigSourceComparator.getOrdinal(getBaseSource());
+ }
+
+ @Override
+ public String getName() {
+ return baseSource.getName();
+ }
+
+ @Override
+ public String getValue(String key) {
+ String val = this.getBaseSource().getValue(key);
+ if(val!=null && filter.test(key)) {
+ return val;
+ }
+ return null;
+ }
+
+ @Override
+ public Map<String, String> getProperties(){
+ final Map<String,String> result = new HashMap<>();
+ for(Map.Entry<String,String> en: this.getBaseSource().getProperties().entrySet()) {
+ if (filter.test(en.getKey())) {
+ result.put(en.getKey(), en.getValue());
+ }
+ }
+ return result;
+ }
+
+ protected ConfigSource getBaseSource() {
+ return baseSource;
+ }
+
+ @Override
+ public String toString() {
+ return "FilteredPropertySource{" +
+ "baseSource=" + getBaseSource() +
+ ", filter=" + filter +
+ '}';
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/main/java/org/apache/tamaya/functions/FilteredPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/main/java/org/apache/tamaya/functions/FilteredPropertySource.java b/modules/functions/src/main/java/org/apache/tamaya/functions/FilteredPropertySource.java
deleted file mode 100644
index 133862d..0000000
--- a/modules/functions/src/main/java/org/apache/tamaya/functions/FilteredPropertySource.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.functions;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-import org.apache.tamaya.spisupport.PropertySourceComparator;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-
-/**
- * PropertySource that on the fly filters out part of the key/values of the underlying PropertySource.
- */
-class FilteredPropertySource implements PropertySource {
-
- private final PropertySource baseSource;
- private final Predicate<String> filter;
-
- /**
- * Creates a new instance
- * @param baseSource the underlying PropertySource
- * @param filter the filter to be applied.
- */
- public FilteredPropertySource(PropertySource baseSource, Predicate<String> filter){
- this.baseSource = Objects.requireNonNull(baseSource);
- this.filter = Objects.requireNonNull(filter);
- }
-
- @Override
- public int getOrdinal(){
- return PropertySourceComparator.getOrdinal(getBaseSource());
- }
-
- @Override
- public String getName() {
- return baseSource.getName();
- }
-
- @Override
- public PropertyValue get(String key) {
- PropertyValue val = this.getBaseSource().get(key);
- if(val!=null && filter.test(val.getKey())) {
- return val;
- }
- return null;
- }
-
- @Override
- public Map<String, PropertyValue> getProperties(){
- final Map<String,PropertyValue> result = new HashMap<>();
- for(PropertyValue val: this.getBaseSource().getProperties().values()) {
- if (filter.test(val.getKey())) {
- result.put(val.getKey(), val);
- }
- }
- return result;
- }
-
- @Override
- public boolean isScannable() {
- return getBaseSource().isScannable();
- }
-
- @Override
- public String toString() {
- return "FilteredPropertySource{" +
- "baseSource=" + getBaseSource() +
- ", filter=" + filter +
- '}';
- }
-
- protected PropertySource getBaseSource() {
- return baseSource;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/main/java/org/apache/tamaya/functions/MappedConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/main/java/org/apache/tamaya/functions/MappedConfigSource.java b/modules/functions/src/main/java/org/apache/tamaya/functions/MappedConfigSource.java
new file mode 100644
index 0000000..1b3881b
--- /dev/null
+++ b/modules/functions/src/main/java/org/apache/tamaya/functions/MappedConfigSource.java
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.functions;
+
+
+import org.apache.tamaya.base.configsource.ConfigSourceComparator;
+
+import javax.config.spi.ConfigSource;
+import java.util.*;
+
+/**
+ * PropertySource implementation that maps certain parts (defined by an {@code UnaryOperator<String>}) to alternate sections.
+ */
+class MappedConfigSource implements ConfigSource {
+
+ private static final long serialVersionUID = 8690637705511432083L;
+
+ /**
+ * The mapping operator.
+ */
+ private final KeyMapper keyMapper;
+
+ /**
+ * The base configuration.
+ */
+ private final ConfigSource propertySource;
+
+ /**
+ * Creates a new instance.
+ *
+ * @param config the base configuration, not null
+ * @param keyMapper The mapping operator, not null
+ */
+ public MappedConfigSource(ConfigSource config, KeyMapper keyMapper) {
+ this.propertySource = Objects.requireNonNull(config);
+ this.keyMapper = Objects.requireNonNull(keyMapper);
+ }
+
+ @Override
+ public int getOrdinal() {
+ return ConfigSourceComparator.getOrdinal(this.propertySource);
+ }
+
+ @Override
+ public String getName() {
+ return this.propertySource.getName() + "[mapped]";
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ Map<String,String> result = new HashMap<>();
+ for (Map.Entry<String,String> en : this.propertySource.getProperties().entrySet()) {
+ String targetKey = keyMapper.mapKey(en.getKey());
+ if (targetKey != null) {
+ result.put(targetKey, en.getValue());
+ }
+ }
+ return result;
+ }
+
+ /**
+ * <p>Access a property by its key.</p>
+ *
+ * <p>
+ * The key of the property to be returned must be equal to the key
+ * returned by the mapping operator (key mapper) and not equal
+ * to the key of the base configuration.
+ * </p>
+ *
+ * @param key the property's key, not {@code null}.
+ * @return the property value map, where {@code map.get(key) == value},
+ * including also any metadata. In case a value is {@code null},
+ * simply return {@code null}.
+ */
+ @Override
+ public String getValue(String key) {
+ Objects.requireNonNull(key, "Key must be given.");
+
+ String mappedKey = keyMapper.mapKey(key);
+ String result = null;
+
+ if (mappedKey != null) {
+ for (Map.Entry<String,String> en : propertySource.getProperties().entrySet()) {
+ String newKey = keyMapper.mapKey(en.getKey());
+ if (mappedKey.equals(newKey)) {
+ return en.getValue();
+ }
+ }
+ }
+ return result;
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/main/java/org/apache/tamaya/functions/MappedPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/main/java/org/apache/tamaya/functions/MappedPropertySource.java b/modules/functions/src/main/java/org/apache/tamaya/functions/MappedPropertySource.java
deleted file mode 100644
index 7e48f22..0000000
--- a/modules/functions/src/main/java/org/apache/tamaya/functions/MappedPropertySource.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.functions;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-import org.apache.tamaya.spisupport.PropertySourceComparator;
-
-import java.util.*;
-
-/**
- * PropertySource implementation that maps certain parts (defined by an {@code UnaryOperator<String>}) to alternate sections.
- */
-class MappedPropertySource implements PropertySource {
-
- private static final long serialVersionUID = 8690637705511432083L;
-
- /**
- * The mapping operator.
- */
- private final KeyMapper keyMapper;
-
- /**
- * The base configuration.
- */
- private final PropertySource propertySource;
-
- /**
- * Creates a new instance.
- *
- * @param config the base configuration, not null
- * @param keyMapper The mapping operator, not null
- */
- public MappedPropertySource(PropertySource config, KeyMapper keyMapper) {
- this.propertySource = Objects.requireNonNull(config);
- this.keyMapper = Objects.requireNonNull(keyMapper);
- }
-
- @Override
- public int getOrdinal() {
- return PropertySourceComparator.getOrdinal(this.propertySource);
- }
-
- @Override
- public String getName() {
- return this.propertySource.getName() + "[mapped]";
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
- Map<String,PropertyValue> result = new HashMap<>();
- for (PropertyValue en : this.propertySource.getProperties().values()) {
- String targetKey = keyMapper.mapKey(en.getKey());
- if (targetKey != null) {
- result.put(targetKey, PropertyValue.of(targetKey, en.getValue(), getName()));
- }
- }
- return result;
- }
-
- @Override
- public boolean isScannable() {
- return propertySource.isScannable();
- }
-
-
- /**
- * <p>Access a property by its key.</p>
- *
- * <p>
- * The key of the property to be returned must be equal to the key
- * returned by the mapping operator (key mapper) and not equal
- * to the key of the base configuration.
- * </p>
- *
- * @param key the property's key, not {@code null}.
- * @return the property value map, where {@code map.get(key) == value},
- * including also any metadata. In case a value is {@code null},
- * simply return {@code null}.
- */
- @Override
- public PropertyValue get(String key) {
- Objects.requireNonNull(key, "Key must be given.");
-
- String mappedKey = keyMapper.mapKey(key);
- PropertyValue result = null;
-
- if (mappedKey != null) {
- for (PropertyValue property : propertySource.getProperties().values()) {
- String newKey = keyMapper.mapKey(property.getKey());
-
- if (mappedKey.equals(newKey)) {
- String mappedName = getName();
- return property.toBuilder().mapKey(newKey)
- .setSource(mappedName).build();
- }
- }
- }
-
- return result;
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/main/java/org/apache/tamaya/functions/PropertySourceFunctions.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/main/java/org/apache/tamaya/functions/PropertySourceFunctions.java b/modules/functions/src/main/java/org/apache/tamaya/functions/PropertySourceFunctions.java
deleted file mode 100644
index 6f20d6f..0000000
--- a/modules/functions/src/main/java/org/apache/tamaya/functions/PropertySourceFunctions.java
+++ /dev/null
@@ -1,410 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.functions;
-
-import org.apache.tamaya.ConfigurationProvider;
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-
-import java.util.*;
-
-import static java.lang.System.arraycopy;
-
-/**
- * Accessor that provides useful functions along with configuration.
- */
-public final class PropertySourceFunctions {
- /**
- * Implementation of an empty propertySource.
- */
- private static final PropertySource EMPTY_PROPERTYSOURCE = new PropertySource() {
-
- @Override
- public int getOrdinal() {
- return 0;
- }
-
- @Override
- public String getName() {
- return "<empty>";
- }
-
- @Override
- public PropertyValue get(String key) {
- return null;
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
- return Collections.emptyMap();
- }
-
- @Override
- public boolean isScannable() {
- return true;
- }
-
- @Override
- public String toString() {
- return "PropertySource<empty>";
- }
- };
-
- /**
- * Private singleton constructor.
- */
- private PropertySourceFunctions() {
- }
-
- /**
- * Calculates the current section key and compares it to the given key.
- *
- * @param key the fully qualified entry key, not null
- * @param sectionKey the section key, not null
- *
- * @return true, if the entry is exact in this section
- */
- public static boolean isKeyInSection(String key, String sectionKey) {
- Objects.requireNonNull(key, "Key must be given.");
- Objects.requireNonNull(sectionKey, "Section key must be given.");
-
- sectionKey = normalizeSectionKey(sectionKey);
-
- int lastIndex = key.lastIndexOf('.');
- String curAreaKey = lastIndex > 0 ? key.substring(0, lastIndex) : "";
- return curAreaKey.equals(sectionKey);
- }
-
- private static String normalizeKey(String key) {
- return key.startsWith(".") ? key.substring(1)
- : key;
- }
-
- static String normalizeSectionKey(String sectionKey) {
- // Ignore unneeded and trailing dot at the end of the section key
-
- String normalizedKey = sectionKey.endsWith(".")
- ? sectionKey.substring(0, sectionKey.length() - 1)
- : sectionKey;
-
- normalizedKey = sectionKey.startsWith(".") ? sectionKey.length() == 1 ? ""
- : normalizedKey.substring(1)
- : normalizedKey;
-
- return normalizedKey;
- }
-
- /**
- * Calculates the current section key and compares it to the given section keys.
- *
- * @param key the fully qualified entry key, not {@code null}
- * @param sectionKey the section keys, not {@code null}
- * @param moreSectionKeys the more section keys, not {@code null}
- *
- * @return true, if the entry is in one of the given sections
- */
- public static boolean isKeyInSections(String key, String sectionKey, String... moreSectionKeys) {
- Objects.requireNonNull(key, "Key must be given.");
- Objects.requireNonNull(sectionKey, "At least one section key must be given.");
- Objects.requireNonNull(moreSectionKeys, "Additional section keys must not be null.");
-
- String[] sectionKeys = new String[moreSectionKeys.length + 1];
- sectionKeys[0] = sectionKey;
-
- if (moreSectionKeys.length > 0) {
- arraycopy(moreSectionKeys, 0, sectionKeys, 1, moreSectionKeys.length);
- }
-
- return isKeyInSections(key, sectionKeys);
- }
-
- /**
- * Calculates the current section key and compares it to the given section keys.
- *
- * @param key the fully qualified entry key, not {@code null}
- * @param sectionKeys the section keys, not {@code null}
- *
- * @return true, if the entry is in one of the given sections
- */
- public static boolean isKeyInSections(String key, String[] sectionKeys) {
- Objects.requireNonNull(key, "Key must be given.");
- Objects.requireNonNull(sectionKeys, "Section keys must be given.");
-
- boolean result = false;
-
- for (String areaKey : sectionKeys) {
- if (areaKey == null) {
- continue;
- }
-
- if (isKeyInSection(key, areaKey)) {
- result = true;
- break;
- }
- }
-
- return result;
- }
-
- /**
- * Return a query to evaluate the set with all fully qualified section names. This method should return the sections as accurate as possible,
- * but may not provide a complete set of sections that are finally accessible, especially when the underlying storage
- * does not support key iteration.
- *
- * @param properties properties to find sections in.
- * @return set with all sections, never {@code null}.
- */
- public static Set<String> sections(Map<String, String> properties) {
- final Set<String> areas = new HashSet<>();
- for (String key : properties.keySet()) {
- String normalizedKey = normalizeKey(key);
-
- int index = normalizedKey.lastIndexOf('.');
- if (index > 0) {
- areas.add(normalizedKey.substring(0, index));
- } else {
- areas.add("<root>");
- }
- }
- return areas;
- }
-
- /**
- * Return a query to evaluate the set with all fully qualified section names, containing the transitive closure also including all
- * subarea names, regardless if properties are accessible or not. This method should return the sections as accurate
- * as possible, but may not provide a complete set of sections that are finally accessible, especially when the
- * underlying storage does not support key iteration.
- *
- * @param properties properties to find transitive sections in.
- * @return s set with all transitive sections, never {@code null}.
- */
- public static Set<String> transitiveSections(Map<String, String> properties) {
- final Set<String> transitiveAreas = new HashSet<>();
- for (String section : sections(properties)) {
- section = normalizeSectionKey(section);
-
- int index = section.lastIndexOf('.');
- if (index < 0 && section.isEmpty()) {
- transitiveAreas.add("<root>");
- } if (index < 0) {
- transitiveAreas.add(section);
- } else {
- while (index > 0) {
- section = section.substring(0, index);
- transitiveAreas.add(section);
- index = section.lastIndexOf('.');
- }
- }
- }
- return transitiveAreas;
- }
-
- /**
- * Return a query to evaluate the set with all fully qualified section names, containing only the
- * sections that match the predicate and have properties attached. This method should return the sections as accurate as possible,
- * but may not provide a complete set of sections that are finally accessible, especially when the underlying storage
- * does not support key iteration.
- *
- * @param properties properties to find sections in.
- * @param predicate A predicate to determine, which sections should be returned, not {@code null}.
- * @return s set with all sections, never {@code null}.
- */
- public static Set<String> sections(Map<String, String> properties, final Predicate<String> predicate) {
- Set<String> treeSet = new TreeSet<>();
- for (String area : sections(properties)) {
- if (predicate.test(area)) {
- treeSet.add(area);
- }
- }
- return treeSet;
- }
-
- /**
- * Return a query to evaluate the set with all fully qualified section names, containing the transitive closure also including all
- * subarea names, regardless if properties are accessible or not. This method should return the sections as accurate as possible,
- * but may not provide a complete set of sections that are finally accessible, especially when the underlying storage
- * does not support key iteration.
- *
- * @param properties properties to find transitive sections in.
- * @param predicate A predicate to determine, which sections should be returned, not {@code null}.
- * @return s set with all transitive sections, never {@code null}.
- */
- public static Set<String> transitiveSections(Map<String, String> properties, Predicate<String> predicate) {
- Set<String> treeSet = new TreeSet<>();
- for (String area : transitiveSections(properties)) {
- if (predicate.test(area)) {
- treeSet.add(area);
- }
- }
- return treeSet;
- }
-
-
- /**
- * Creates a ConfigOperator that creates a Configuration containing only keys
- * that are contained in the given section (recursive). Hereby
- * the section key is stripped away from the Map of the resulting keys.
- *
- * @param properties properties to find recursive sections in.
- * @param sectionKeys the section keys, not null
- * @return the section configuration, with the areaKey stripped away.
- */
- public static Map<String, String> sectionsRecursive(Map<String, String> properties, String... sectionKeys) {
- return sectionRecursive(properties, true, sectionKeys);
- }
-
- /**
- * Creates a ConfigOperator that creates a Configuration containing only keys
- * that are contained in the given section (recursive).
- *
- * @param properties properties to find sections in.
- * @param sectionKeys the section keys, not null
- * @param stripKeys if set to true, the section key is stripped away fromMap the resulting key.
- * @return the section configuration, with the areaKey stripped away.
- */
- public static Map<String, String> sectionRecursive(Map<String, String> properties, boolean stripKeys, String... sectionKeys) {
- Map<String, String> result = new HashMap<>(properties.size());
- if (stripKeys) {
- for (Map.Entry<String, String> en : properties.entrySet()) {
- if (isKeyInSections(en.getKey(), sectionKeys)) {
- result.put(en.getKey(), en.getValue());
- }
- }
- } else {
- for (Map.Entry<String, String> en : properties.entrySet()) {
- if (isKeyInSections(en.getKey(), sectionKeys)) {
- result.put(stripSectionKeys(en.getKey(), sectionKeys), en.getValue());
- }
- }
- }
- return result;
- }
-
- /**
- * Strips the section key of the given absolute key, if it is one of the areaKeys passed.
- *
- * @param key the current key, not null.
- * @param areaKeys the areaKeys, not null.
- * @return the stripped key, or the original key (if no section was matching).
- */
- static String stripSectionKeys(String key, String... areaKeys) {
- for (String areaKey : areaKeys) {
- if (key.startsWith(areaKey + '.')) {
- return key.substring(areaKey.length() + 1);
- }
- }
- return key;
- }
-
- /**
- * Creates a ConfigOperator that adds the given items.
- *
- * @param propertySource source property source that is changed.
- * @param items the items to be added/replaced.
- * @param override if true, all items existing are overridden by the new ones passed.
- * @return the ConfigOperator, never null.
- */
- public static PropertySource addItems(PropertySource propertySource, final Map<String, String> items, final boolean override) {
- return new EnrichedPropertySource(propertySource, items, override);
- }
-
- /**
- * Creates an operator that adds items to the instance.
- *
- * @param propertySource source property source that is changed.
- * @param items the items, not null.
- * @return the operator, never null.
- */
- public static PropertySource addItems(PropertySource propertySource, Map<String, String> items) {
- return addItems(propertySource, items, false);
- }
-
- /**
- * Creates an operator that replaces the given items.
- *
- * @param propertySource source property source that is changed.
- * @param items the items.
- * @return the operator for replacing the items.
- */
- public static PropertySource replaceItems(PropertySource propertySource, Map<String, String> items) {
- return addItems(propertySource, items, true);
- }
-
- /**
- * Accesses an empty PropertySource.
- *
- * @return an empty PropertySource, never null.
- */
- public static PropertySource emptyPropertySource() {
- return EMPTY_PROPERTYSOURCE;
- }
-
- /**
- * Find all {@link PropertySource} instances managed by the current
- * {@link org.apache.tamaya.spi.ConfigurationContext} that are assignable to the given type.
- *
- * @param expression the regular expression to match the source's name.
- * @return the list of all {@link PropertySource} instances matching, never null.
- */
- public static Collection<? extends PropertySource> findPropertySourcesByName(String expression) {
- List result = new ArrayList<>();
- for (PropertySource src : ConfigurationProvider.getConfigurationContext().getPropertySources()) {
- if (src.getName().matches(expression)) {
- result.add(src);
- }
- }
- return result;
- }
-
- /**
- * Get a list of all {@link PropertySource} instances managed by the current
- * {@link org.apache.tamaya.spi.ConfigurationContext} that are assignable to the given type.
- *
- * @param <T> the type of the property source instances requested
- * @param type target type to filter for property sources.
- * @return the list of all {@link PropertySource} instances matching, never null.
- */
- public static <T> Collection<T> getPropertySources(Class<T> type) {
- List<T> result = new ArrayList<>();
- for (PropertySource src : ConfigurationProvider.getConfigurationContext().getPropertySources()) {
- if (type.isAssignableFrom(src.getClass())) {
- result.add((T) src);
- }
- }
- return result;
- }
-
- /**
- * Get a list of all {@link PropertySource} instances managed by the current
- * {@link org.apache.tamaya.spi.ConfigurationContext} that are assignable to the given type.
- *
- * @param <T> the type of the property source instances requested
- * @param type target type to filter for property sources.
- * @return the list of all {@link PropertySource} instances matching, never null.
- */
- public static <T> T getPropertySource(Class<T> type) {
- for (PropertySource src : ConfigurationProvider.getConfigurationContext().getPropertySources()) {
- if (type.isAssignableFrom(src.getClass())) {
- return (T) src;
- }
- }
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/main/java/org/apache/tamaya/functions/ValueMappedConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/main/java/org/apache/tamaya/functions/ValueMappedConfigSource.java b/modules/functions/src/main/java/org/apache/tamaya/functions/ValueMappedConfigSource.java
new file mode 100644
index 0000000..dd23c66
--- /dev/null
+++ b/modules/functions/src/main/java/org/apache/tamaya/functions/ValueMappedConfigSource.java
@@ -0,0 +1,75 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.functions;
+
+import org.apache.tamaya.base.configsource.ConfigSourceComparator;
+
+import javax.config.spi.ConfigSource;
+import java.util.*;
+
+
+/**
+ * Property source which filters any key/values dynamically.
+ */
+class ValueMappedConfigSource implements ConfigSource{
+
+ private final String name;
+ private final PropertyMapper valueFilter;
+ private final ConfigSource source;
+
+ public ValueMappedConfigSource(String name, PropertyMapper valueFilter, ConfigSource current) {
+ this.name = name!=null?name:"<valueFiltered> -> name="+current.getName()+", valueFilter="+valueFilter.toString();
+ this.valueFilter = valueFilter;
+ this.source = Objects.requireNonNull(current);
+ }
+
+ @Override
+ public int getOrdinal() {
+ return ConfigSourceComparator.getOrdinal(source);
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public String getValue(String key) {
+ return this.source.getValue(key);
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ Map<String,String> result = new HashMap<>();
+ for(Map.Entry<String,String> en: source.getProperties().entrySet()) {
+ String mappedValue = valueFilter.mapProperty(en.getKey(), en.getValue());
+ result.put(en.getKey(), mappedValue);
+ }
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return "ValueMappedConfigSource{" +
+ "source=" + source.getName() +
+ ", name='" + name + '\'' +
+ ", valueFilter=" + valueFilter +
+ '}';
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/main/java/org/apache/tamaya/functions/ValueMappedPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/main/java/org/apache/tamaya/functions/ValueMappedPropertySource.java b/modules/functions/src/main/java/org/apache/tamaya/functions/ValueMappedPropertySource.java
deleted file mode 100644
index dfb128f..0000000
--- a/modules/functions/src/main/java/org/apache/tamaya/functions/ValueMappedPropertySource.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.functions;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-import org.apache.tamaya.spisupport.PropertySourceComparator;
-
-import java.util.*;
-
-
-/**
- * Property source which filters any key/values dynamically.
- */
-class ValueMappedPropertySource implements PropertySource{
-
- private final String name;
- private final PropertyMapper valueFilter;
- private final PropertySource source;
-
- public ValueMappedPropertySource(String name, PropertyMapper valueFilter, PropertySource current) {
- this.name = name!=null?name:"<valueFiltered> -> name="+current.getName()+", valueFilter="+valueFilter.toString();
- this.valueFilter = valueFilter;
- this.source = Objects.requireNonNull(current);
- }
-
- @Override
- public int getOrdinal() {
- return PropertySourceComparator.getOrdinal(source);
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public PropertyValue get(String key) {
- PropertyValue value = this.source.get(key);
- if(value!=null) {
- return PropertyValue.of(key, valueFilter.mapProperty(key, value.getValue()), getName());
- }
- return null;
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
- Map<String,PropertyValue> result = new HashMap<>();
- for(PropertyValue val : source.getProperties().values()) {
- String mappedValue = valueFilter.mapProperty(val.getKey(), val.getValue());
- PropertyValue value = val.toBuilder().setValue(mappedValue).build();
- result.put(val.getKey(), value);
- }
- return result;
- }
-
- @Override
- public boolean isScannable() {
- return source.isScannable();
- }
-
- @Override
- public String toString() {
- return "ValueMappedPropertySource{" +
- "source=" + source.getName() +
- ", name='" + name + '\'' +
- ", valueFilter=" + valueFilter +
- '}';
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/test/java/org/apache/tamaya/functions/CombinedConfigurationTest.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/test/java/org/apache/tamaya/functions/CombinedConfigurationTest.java b/modules/functions/src/test/java/org/apache/tamaya/functions/CombinedConfigurationTest.java
index bb27ccd..432c5c0 100644
--- a/modules/functions/src/test/java/org/apache/tamaya/functions/CombinedConfigurationTest.java
+++ b/modules/functions/src/test/java/org/apache/tamaya/functions/CombinedConfigurationTest.java
@@ -20,7 +20,6 @@ package org.apache.tamaya.functions;
import org.apache.tamaya.base.DefaultConfigBuilder;
import org.apache.tamaya.base.configsource.SimpleConfigSource;
-import org.apache.tamaya.spisupport.DefaultConfiguration;
import org.assertj.core.api.ThrowableAssert;
import org.junit.Test;
import org.mockito.Mockito;
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/test/java/org/apache/tamaya/functions/ConfigSourceFunctionsTest.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/test/java/org/apache/tamaya/functions/ConfigSourceFunctionsTest.java b/modules/functions/src/test/java/org/apache/tamaya/functions/ConfigSourceFunctionsTest.java
new file mode 100644
index 0000000..06734db
--- /dev/null
+++ b/modules/functions/src/test/java/org/apache/tamaya/functions/ConfigSourceFunctionsTest.java
@@ -0,0 +1,434 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.functions;
+
+import org.apache.tamaya.base.configsource.SimpleConfigSource;
+import org.assertj.core.api.ThrowableAssert;
+import org.junit.Test;
+
+import javax.config.spi.ConfigSource;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+import static org.apache.tamaya.functions.ConfigSourceFunctions.*;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.assertj.core.api.Assertions.entry;
+import static org.junit.Assert.*;
+
+
+public class ConfigSourceFunctionsTest {
+
+ /*
+ * Tests for isKeyInSection(String, String)
+ */
+
+ @Test
+ public void isKeyInSectionThrowsNPEIfKeyIsNull() {
+ assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
+ @Override
+ public void call() throws Throwable {
+ isKeyInSection("a.b.c", null);
+ }
+ }).isInstanceOf(NullPointerException.class)
+ .hasMessage("Section keys must be given.");
+ }
+
+ @Test
+ public void isKeyInSectionThrowsNPEIfSectionKeyIsNull() {
+ assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
+ @Override
+ public void call() throws Throwable {
+ isKeyInSection(null, "a.b.c");
+ }
+ }).isInstanceOf(NullPointerException.class)
+ .hasMessage("Key must be given.");
+ }
+
+ @Test
+ public void isKeyInSectionForKeyInRootSection() {
+ String key = "key";
+ String sectionKey = "";
+
+ boolean result = isKeyInSection(key, sectionKey);
+
+ assertThat(result).describedAs("Key '%s' is in root section '%s'")
+ .isTrue();
+ }
+
+ @Test
+ public void isKeyInSectionForKeyInExplicitRootSection() {
+ String key = "key";
+ String sectionKey = ".";
+
+ boolean result = isKeyInSection(key, sectionKey);
+
+ assertThat(result).describedAs("Key '%s' is in root section '%s'")
+ .isTrue();
+ }
+
+ @Test
+ public void isKeyInSectionForKeyInSection() throws Exception {
+ String key = "abc.def.g.h.key";
+ String section = "abc.def.g.h";
+
+ boolean result = isKeyInSection(key, section);
+
+ assertThat(result).describedAs("Key %s is in section %s", key, section)
+ .isTrue();
+ }
+
+ @Test
+ public void isKeyInSectionForKeyNotInSection() throws Exception {
+ String key = "abc.def.g.h.i.key";
+ String section = "abc.def.g.h";
+
+ boolean result = isKeyInSection(key, section);
+
+ assertThat(result).describedAs("Key %s is not in section %s", key, section)
+ .isFalse();
+ }
+
+ @Test
+ public void isKeyInSectionIgnoresTrailingDotAtTheEndOfTheSection() throws Exception {
+ String key = "abc.def.g.h.key";
+ String section = "abc.def.g.h.";
+
+ boolean result = isKeyInSection(key, section);
+
+ assertThat(result).describedAs("Key %s is in section %s", key, section)
+ .isTrue();
+ }
+
+
+ /*
+ * Tests for isKeyInSection(String, String, String...)
+ */
+
+ @Test
+ public void isKeyInSectionsStringStringStringVarargThrowsNPEIfKeyIsNull() {
+ assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
+ @Override
+ public void call() throws Throwable {
+ ConfigSourceFunctions.isKeyInSection(null, "a.b.", "a.b", "b.c");
+ }
+ }).isInstanceOf(NullPointerException.class)
+ .hasMessage("Key must be given.");
+ }
+
+ @Test
+ public void isKeyInSectionStringStringStringVarargshrowsNPEIfMoreSectionKeysIsNull() {
+ // null should not cause any problems
+ boolean result = isKeyInSection("key", "l.b", (String) null);
+
+ assertThat(result).isFalse();
+ }
+
+ @Test
+ public void isKeyInSectionStringStringStringVaragrsSectioOfKeyIsAtEndOfVarargs() {
+ String section = "abc.def.";
+ String key = section + "key";
+
+ // null should not cause any problems
+ boolean result = ConfigSourceFunctions.isKeyInSection(key, "l.b", null, "abc", section);
+
+ assertThat(result).describedAs("Key '%s' is in section '%s'.", key, section).isTrue();
+ }
+
+
+ /*
+ * Tests for sections(Map<String, String>)
+ */
+
+ // null as parameter
+
+ // empty as parameter
+
+ // all keys in root section
+
+ // some keys in packages
+
+ @Test
+ public void sectionsMapReturnsAllSectionsForGivenKeysInMap() {
+ HashMap<String, String> kv = new HashMap<>();
+
+ kv.put("abc.key", "v");
+ kv.put("abc.def.key", "v");
+ kv.put("a.key", "v");
+ kv.put("b.key", "v");
+ kv.put("key", "v");
+
+ Set<String> result = sections(kv);
+
+ assertThat(result).isNotNull()
+ .isNotEmpty()
+ .contains("abc", "abc.def", "a", "b", "<root>");
+ }
+
+ @Test
+ public void sectionsMapTreatsLeadingDotAsOptional() {
+ HashMap<String, String> kv = new HashMap<>();
+
+ kv.put(".abc.key", "v");
+ kv.put(".abc.def.key", "v");
+ kv.put(".a.key", "v");
+ kv.put(".b.key", "v");
+ kv.put(".key", "v");
+
+ Set<String> result = sections(kv);
+
+ assertThat(result).isNotNull()
+ .isNotEmpty()
+ .contains("abc", "abc.def", "a", "b", "<root>");
+ }
+
+ /*
+ * Tests for sections(Map<String, String> , Predicate<String>)
+ */
+
+ @Test
+ public void sectionsMapPredicateFiltersAccordingToFilter() {
+ HashMap<String, String> kv = new HashMap<>();
+
+ kv.put(".abc.key", "v");
+ kv.put(".abc.def.key", "v");
+ kv.put(".a.key", "v");
+ kv.put(".b.key", "v");
+ kv.put(".key", "v");
+
+ Set<String> result = sections(kv, new Predicate<String>() {
+ @Override
+ public boolean test(String s) {
+ return !s.startsWith("a");
+ }
+ });
+
+ assertThat(result).isNotNull()
+ .isNotEmpty()
+ .contains("b", "<root>");
+ }
+
+ /*
+ * Tests for transitiveSections(Map<String, String>)
+ */
+
+ @Test
+ public void bla() {
+ HashMap<String, String> kv = new HashMap<>();
+
+ kv.put(".abc.key", "v");
+ kv.put(".abc.def.key", "v");
+ kv.put(".abc.def.ghi.key", "v");
+ kv.put(".a.key", "v");
+ kv.put(".b.key", "v");
+ kv.put(".key", "v");
+
+ Set<String> result = transitiveSections(kv);
+
+ for (String s : result) {
+ System.out.println(s);
+ }
+
+
+ assertThat(result).isNotNull()
+ .isNotEmpty()
+ .contains("abc", "abc.def", "a", "b", "<root>");
+
+
+ }
+
+
+ @Test
+ public void testIsKeyInSections() throws Exception {
+ SimpleConfigSource configSource = SimpleConfigSource.builder("test")
+ .withProperty("a", "1")
+ .withProperty("a.a.1", "1.1.1")
+ .withProperty("a.a.2", "1.1.2")
+ .withProperty("a.b", "1.2")
+ .withProperty("b", "2")
+ .build();
+
+ assertTrue(ConfigSourceFunctions.isKeyInSection("a.1", "a", "b"));
+ assertTrue(ConfigSourceFunctions.isKeyInSection("a.1", "b", "a"));
+ assertFalse(ConfigSourceFunctions.isKeyInSection("a.1", ""));
+ assertFalse(ConfigSourceFunctions.isKeyInSection("a.b.1", "a"));
+ assertTrue(ConfigSourceFunctions.isKeyInSection("a.b.1", "a.b"));
+ assertFalse(ConfigSourceFunctions.isKeyInSection("a.b.1", "", "a"));
+ assertTrue(ConfigSourceFunctions.isKeyInSection("a.b.1", "", "a.b"));
+ assertFalse(ConfigSourceFunctions.isKeyInSection("c.a", "","c.a"));
+ assertFalse(ConfigSourceFunctions.isKeyInSection("a.3", "b"));
+ }
+
+
+ @Test
+ public void testTransitiveSections() throws Exception {
+ Map<String,String> sections = new HashMap<>();
+ sections.put("a.b.c.d.e", "1");
+ sections.put("a.x.y", "2");
+ sections.put("bb", "2");
+ Set<String> transitiveSections = ConfigSourceFunctions.transitiveSections(sections);
+ assertThat(transitiveSections)
+ .isNotNull()
+ .contains("a", "a.b", "a.b.c", "<root>");
+ }
+
+
+ @Test
+ public void testSectionsRecursive() throws Exception {
+ Map<String,String> sections = new HashMap<>();
+ sections.put("a.b.c.d.e", "1");
+ sections.put("a.x.y", "2");
+ sections.put("b.b", "2");
+ sections.put("bb", "2");
+ Map<String,String> recursiveSections = ConfigSourceFunctions.sectionsRecursive(sections, true,"a.b");
+ assertThat(recursiveSections)
+ .isNotNull()
+ .hasSize(1)
+ .contains(entry("c.d.e", "1"));
+ recursiveSections = ConfigSourceFunctions.sectionsRecursive(sections, true,"a");
+ assertThat(recursiveSections)
+ .isNotNull()
+ .hasSize(2)
+ .contains(entry("b.c.d.e", "1"), entry("x.y", "2"));
+ recursiveSections = ConfigSourceFunctions.sectionsRecursive(sections, true,"b");
+ assertThat(recursiveSections)
+ .isNotNull()
+ .hasSize(1)
+ .contains(entry("b", "2"));
+ recursiveSections = ConfigSourceFunctions.sectionsRecursive(sections, false,"a.b");
+ assertThat(recursiveSections)
+ .isNotNull()
+ .hasSize(1)
+ .contains(entry("a.b.c.d.e", "1"));
+ recursiveSections = ConfigSourceFunctions.sectionsRecursive(sections, false,"a");
+ assertThat(recursiveSections)
+ .isNotNull()
+ .hasSize(2)
+ .contains(entry("a.b.c.d.e", "1"), entry("a.x.y", "2"));
+ recursiveSections = ConfigSourceFunctions.sectionsRecursive(sections, false,"b");
+ assertThat(recursiveSections)
+ .isNotNull()
+ .hasSize(1)
+ .contains(entry("b.b", "2"));
+ recursiveSections = ConfigSourceFunctions.sectionsRecursive(sections, true,"b");
+ assertThat(recursiveSections)
+ .isNotNull()
+ .hasSize(1)
+ .contains(entry("b", "2"));
+ }
+
+ @Test
+ public void testStripSectionKeys() throws Exception {
+ String result = ConfigSourceFunctions.stripSectionKeys("a.b.c", new String[]{ "a.b", "a"});
+ assertThat(result)
+ .isNotNull().isEqualTo("c");
+ result = ConfigSourceFunctions.stripSectionKeys("a", new String[]{ "a"});
+ assertThat(result)
+ .isNotNull().isEqualTo("a");
+ result = ConfigSourceFunctions.stripSectionKeys("foo.bar", new String[]{ ""});
+ assertThat(result)
+ .isNotNull().isEqualTo("foo.bar");
+ }
+
+ @Test
+ public void testAddItems_Override_Default() throws Exception {
+ ConfigSource cs = SimpleConfigSource.builder("test")
+ .withProperty("a", "1")
+ .withProperty("b", "2")
+ .build();
+ Map<String, String> additions = new HashMap<>();
+ additions.put("b", "2-added");
+ additions.put("c", "3");
+ ConfigSource configSource = ConfigSourceFunctions.addItems(cs, additions);
+ assertNotNull(configSource);
+ assertThat(configSource.getPropertyNames())
+ .isNotNull()
+ .contains("a", "b", "c");
+ assertThat(configSource.getProperties())
+ .isNotNull()
+ .contains(entry("a", "1"), entry("b", "2"), entry("c", "3"));
+ }
+
+ @Test
+ public void testAddItemsOverride_Explicit() throws Exception {
+ ConfigSource cs = SimpleConfigSource.builder("test")
+ .withProperty("a", "1")
+ .withProperty("b", "2")
+ .build();
+ Map<String, String> additions = new HashMap<>();
+ additions.put("b", "2-added");
+ additions.put("c", "3");
+ ConfigSource configSource = ConfigSourceFunctions.addItems(cs, additions, true);
+ assertNotNull(configSource);
+ assertThat(configSource.getPropertyNames())
+ .isNotNull()
+ .contains("a", "b", "c");
+ assertThat(configSource.getProperties())
+ .isNotNull()
+ .contains(entry("a", "1"), entry("b", "2-added"), entry("c", "3"));
+ }
+
+ @Test
+ public void testAddItemsOverride_False() throws Exception {
+ ConfigSource cs = SimpleConfigSource.builder("test")
+ .withProperty("a", "1")
+ .withProperty("b", "2")
+ .build();
+ Map<String, String> additions = new HashMap<>();
+ additions.put("b", "2-added");
+ additions.put("c", "3");
+ ConfigSource configSource = ConfigSourceFunctions.addItems(cs, additions, false);
+ assertNotNull(configSource);
+ assertThat(configSource.getPropertyNames())
+ .isNotNull()
+ .contains("a", "b", "c");
+ assertThat(configSource.getProperties())
+ .isNotNull()
+ .contains(entry("a", "1"), entry("b", "2"), entry("c", "3"));
+ }
+
+ @Test
+ public void testReplaceItems() throws Exception {
+ ConfigSource cs = SimpleConfigSource.builder("test")
+ .withProperty("a", "1")
+ .withProperty("b", "2")
+ .build();
+ Map<String, String> replacements = new HashMap<>();
+ replacements.put("b", "2-added");
+ replacements.put("c", "3");
+ ConfigSource configSource = ConfigSourceFunctions.replaceItems(cs, replacements);
+ assertNotNull(configSource);
+ assertThat(configSource.getPropertyNames())
+ .isNotNull()
+ .contains("a", "b", "c");
+ assertThat(configSource.getProperties())
+ .isNotNull()
+ .contains(entry("a", "1"), entry("b", "2-added"), entry("c", "3"));
+ }
+
+ @Test
+ public void testEmptyPropertySource() throws Exception {
+ ConfigSource ps = ConfigSourceFunctions.emptyConfigSource();
+ assertThat(ps).isNotNull();
+ assertNotNull(ps.getProperties());
+ assertTrue(ps.getProperties().isEmpty());
+ assertEquals(ps.getName(), "<empty>" );
+ }
+}
\ No newline at end of file
[08/18] incubator-tamaya-extensions git commit: Adapted to comply
with JSR API.
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/main/java/org/apache/tamaya/events/PropertySourceChange.java
----------------------------------------------------------------------
diff --git a/modules/events/src/main/java/org/apache/tamaya/events/PropertySourceChange.java b/modules/events/src/main/java/org/apache/tamaya/events/PropertySourceChange.java
deleted file mode 100644
index e7782a0..0000000
--- a/modules/events/src/main/java/org/apache/tamaya/events/PropertySourceChange.java
+++ /dev/null
@@ -1,212 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.events;
-
-import org.apache.tamaya.spi.PropertySource;
-
-import java.beans.PropertyChangeEvent;
-import java.io.Serializable;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-
-/**
- * Event that contains a set current changes that were applied or could be applied.
- * This class is immutable and thread-safe. To create instances use
- * {@link PropertySourceChangeBuilder}.
- *
- * Created by Anatole on 22.10.2014.
- */
-public final class PropertySourceChange implements ConfigEvent<PropertySource>, Serializable{
-
- private static final long serialVersionUID = 1L;
- /** The base property provider/configuration. */
- private final FrozenPropertySource propertySource;
- /** The base version, usable for optimistic locking. */
- private String version = UUID.randomUUID().toString();
- /** The timestamp of the change set in millis from the epoch. */
- private long timestamp = System.currentTimeMillis();
- /** The recorded changes. */
- private final Map<String,PropertyChangeEvent> changes = new HashMap<>();
-
- /**
- * Constructor used by {@link PropertySourceChangeBuilder}.
- * @param builder The builder used, not null.
- */
- PropertySourceChange(PropertySourceChangeBuilder builder) {
- this.propertySource = FrozenPropertySource.of(builder.source);
- for (PropertyChangeEvent c : builder.delta.values()) {
- this.changes.put(c.getPropertyName(), c);
- }
- if(builder.version!=null){
- this.version = builder.version;
- }
- if(builder.timestamp!=null){
- this.timestamp = builder.timestamp;
- }
- }
-
- @Override
- public Class<PropertySource> getResourceType() {
- return PropertySource.class;
- }
-
- /**
- * Get the underlying property provider/configuration.
- * @return the underlying property provider/configuration, or null, if the change instance was deserialized.
- */
- @Override
- public PropertySource getResource(){
- return this.propertySource;
- }
-
- /**
- * Get the base version, usable for optimistic locking.
- * @return the base version.
- */
- @Override
- public String getVersion(){
- return version;
- }
-
- /**
- * Get the timestamp in millis from the current epoch. it is expected that the timestamp and the version are unique to
- * identify a changeset.
- * @return the timestamp, when this changeset was created.
- */
- @Override
- public long getTimestamp(){
- return timestamp;
- }
-
- /**
- * Get the changes recorded.
- * @return the recorded changes, never null.
- */
- public Collection<PropertyChangeEvent> getChanges(){
- return Collections.unmodifiableCollection(this.changes.values());
- }
-
- /**
- * Access the number current removed entries.
- * @return the number current removed entries.
- */
- public int getRemovedSize() {
- int removedCount = 0;
- for (PropertyChangeEvent ev : this.changes.values()) {
- if (ev.getNewValue() == null) {
- removedCount++;
- }
- }
- return removedCount;
-// return (int) this.changes.values().stream().filter((e) -> e.getNewValue() == null).count();
- }
-
- /**
- * Access the number current added entries.
- * @return the number current added entries.
- */
- public int getAddedSize() {
- int addedCount = 0;
- for (PropertyChangeEvent ev : this.changes.values()) {
- if (ev.getOldValue() == null &&
- ev.getNewValue() != null) {
- addedCount++;
- }
- }
- return addedCount;
-// return (int) this.changes.values().stream().filter((e) -> e.getOldValue() == null).count();
- }
-
- /**
- * Access the number current updated entries.
- * @return the number current updated entries.
- */
- public int getUpdatedSize() {
- int updatedCount = 0;
- for (PropertyChangeEvent ev : this.changes.values()) {
- if (ev.getOldValue() != null && ev.getNewValue() != null) {
- updatedCount++;
- }
- }
- return updatedCount;
-// return (int) this.changes.values().stream().filter((e) -> e.getOldValue()!=null && e.getNewValue()!=null).count();
- }
-
-
- /**
- * Checks if the given key was removed.
- * @param key the target key, not null.
- * @return true, if the given key was removed.
- */
- public boolean isRemoved(String key) {
- PropertyChangeEvent change = this.changes.get(key);
- return change != null && change.getNewValue() == null;
- }
-
- /**
- * Checks if the given key was added.
- * @param key the target key, not null.
- * @return true, if the given key was added.
- */
- public boolean isAdded(String key) {
- PropertyChangeEvent change = this.changes.get(key);
- return change != null && change.getOldValue() == null;
- }
-
- /**
- * Checks if the given key was updated.
- * @param key the target key, not null.
- * @return true, if the given key was updated.
- */
- public boolean isUpdated(String key) {
- PropertyChangeEvent change = this.changes.get(key);
- return change != null && change.getOldValue() != null && change.getNewValue() != null;
- }
-
- /**
- * Checks if the given key is added, or updated AND NOT removed.
- * @param key the target key, not null.
- * @return true, if the given key was added, or updated BUT NOT removed.
- */
- public boolean isKeyAffected(String key) {
- PropertyChangeEvent change = this.changes.get(key);
- return change != null && change.getNewValue() != null;
- }
-
- /**
- * CHecks if the current change set does not contain any changes.
- * @return tru, if the change set is empty.
- */
- public boolean isEmpty(){
- return this.changes.isEmpty();
- }
-
-
- @Override
- public String toString() {
- return "PropertySourceChange{" +
- ", propertySource=" + propertySource +
- ", version='" + version + '\'' +
- ", timestamp=" + timestamp +
- '}';
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/main/java/org/apache/tamaya/events/PropertySourceChangeBuilder.java
----------------------------------------------------------------------
diff --git a/modules/events/src/main/java/org/apache/tamaya/events/PropertySourceChangeBuilder.java b/modules/events/src/main/java/org/apache/tamaya/events/PropertySourceChangeBuilder.java
deleted file mode 100644
index 1e58855..0000000
--- a/modules/events/src/main/java/org/apache/tamaya/events/PropertySourceChangeBuilder.java
+++ /dev/null
@@ -1,252 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.events;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-
-import java.beans.PropertyChangeEvent;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.SortedMap;
-import java.util.TreeMap;
-
-/**
- * Models a set current changes applied to a {@link org.apache.tamaya.spi.PropertySource}. Consumers of these events
- * can observing changes to property sources and
- * <ol>
- * <li>Check if their current configuration instance ({@link org.apache.tamaya.spi.ConfigurationContext}
- * contains the changed {@link org.apache.tamaya.spi.PropertySource} (Note: the reference tova property source is never affected by a
- * change, its only the data of the property source).</li>
- * <li>If so corresponding action may be taken, such as reevaluating the configuration values (depending on
- * the update policy) or reevaluating the complete {@link org.apache.tamaya.Configuration} to create a change
- * event on configuration level.
- * </ol>
- */
-public final class PropertySourceChangeBuilder {
- /**
- * The recorded changes.
- */
- final SortedMap<String, PropertyChangeEvent> delta = new TreeMap<>();
- /**
- * The underlying configuration/provider.
- */
- final PropertySource source;
- /**
- * The version configured, or null, for generating a default.
- */
- String version;
- /**
- * The optional timestamp in millis of this epoch.
- */
- Long timestamp;
-
- /**
- * Constructor.
- *
- * @param source the underlying configuration/provider, not null.
- */
- private PropertySourceChangeBuilder(PropertySource source) {
- this.source = Objects.requireNonNull(source);
- }
-
- /**
- * Creates a new instance of this builder.
- *
- * @param source the underlying property provider/configuration, not null.
- * @return the builder for chaining.
- */
- public static PropertySourceChangeBuilder of(PropertySource source) {
- return new PropertySourceChangeBuilder(source);
- }
-
- /**
- * Compares the two property config/configurations and creates a collection current all changes
- * that must be applied to render {@code map1} into {@code map2}.
- *
- * @param map1 the source map, not null.
- * @param map2 the target map, not null.
- * @return a collection current change events, never null.
- */
- public static Collection<PropertyChangeEvent> compare(PropertySource map1, PropertySource map2) {
- List<PropertyChangeEvent> changes = new ArrayList<>();
- for (Map.Entry<String, PropertyValue> en : map1.getProperties().entrySet()) {
- PropertyValue val = map2.get(en.getKey());
- if (val == null) {
- changes.add(new PropertyChangeEvent(map1, en.getKey(), null, en.getValue().getValue()));
- } else if (!val.equals(en.getValue())) {
- changes.add(new PropertyChangeEvent(map1, en.getKey(), val.getValue(), en.getValue().getValue()));
- }
- }
- for (Map.Entry<String, PropertyValue> en : map2.getProperties().entrySet()) {
- PropertyValue val = map1.get(en.getKey());
- if (val == null) {
- changes.add(new PropertyChangeEvent(map1, en.getKey(), en.getValue().getValue(), null));
- } else if (!val.equals(en.getValue())) {
- changes.add(new PropertyChangeEvent(map1, en.getKey(), en.getValue().getValue(), val.getValue()));
- }
- }
- return changes;
- }
-
- /*
- * Apply a version/UUID to the set being built.
- * @param version the version to apply, or null, to let the system generate a version for you.
- * @return the builder for chaining.
- */
- public PropertySourceChangeBuilder setVersion(String version) {
- this.version = version;
- return this;
- }
-
- /*
- * Apply given timestamp to the set being built.
- * @param version the version to apply, or null, to let the system generate a version for you.
- * @return the builder for chaining.
- */
- public PropertySourceChangeBuilder setTimestamp(long timestamp) {
- this.timestamp = timestamp;
- return this;
- }
-
- /**
- * This method records all changes to be applied to the base property provider/configuration to
- * achieve the given target state.
- *
- * @param newState the new target state, not null.
- * @return the builder for chaining.
- */
- public PropertySourceChangeBuilder addChanges(PropertySource newState) {
- Collection<PropertyChangeEvent> events = PropertySourceChangeBuilder.compare(newState, this.source);
- for (PropertyChangeEvent c : events) {
- this.delta.put(c.getPropertyName(), c);
- }
- return this;
- }
-
- /**
- * Get the current values, also considering any changes recorded within this change set.
- *
- * @param key the key current the entry, not null.
- * @return the keys, or null.
- */
- public String get(String key) {
- PropertyChangeEvent change = this.delta.get(key);
- if (change != null && !(change.getNewValue() == null)) {
- return (String) change.getNewValue();
- }
- return null;
- }
-
- /**
- * Marks the given key(s) fromMap the configuration/properties to be removed.
- *
- * @param key the key current the entry, not null.
- * @param otherKeys additional keys to be removed (convenience), not null.
- * @return the builder for chaining.
- */
- public PropertySourceChangeBuilder remove(String key, String... otherKeys) {
- PropertyValue oldValue = this.source.get(key);
- if (oldValue == null) {
- this.delta.remove(key);
- }
- this.delta.put(key, new PropertyChangeEvent(this.source, key, oldValue, null));
- for (String addKey : otherKeys) {
- oldValue = this.source.get(addKey);
- if (oldValue == null) {
- this.delta.remove(addKey);
- }
- this.delta.put(addKey, new PropertyChangeEvent(this.source, addKey, oldValue, null));
- }
- return this;
- }
-
- /**
- * Apply all the given values to the base configuration/properties.
- * Note that all values passed must be convertible to String, either
- * <ul>
- * <li>the registered codecs provider provides codecs for the corresponding keys, or </li>
- * <li>default codecs are present for the given type, or</li>
- * <li>the value is an instanceof String</li>
- * </ul>
- *
- * @param changes the changes to be applied, not null.
- * @return the builder for chaining.
- */
- public PropertySourceChangeBuilder putAll(Map<String, String> changes) {
- for (Map.Entry<String, PropertyValue> en : this.source.getProperties().entrySet()) {
- this.delta.put(en.getKey(), new PropertyChangeEvent(this.source, en.getKey(), null, en.getValue()));
- }
- return this;
- }
-
- /**
- * This method will create a change set that clears all entries fromMap the given base configuration/properties.
- *
- * @return the builder for chaining.
- */
- public PropertySourceChangeBuilder deleteAll() {
- this.delta.clear();
- for (Map.Entry<String, PropertyValue> en : this.source.getProperties().entrySet()) {
- this.delta.put(en.getKey(), new PropertyChangeEvent(this.source, en.getKey(), en.getValue().getValue(), null));
- }
- return this;
- }
-
- /**
- * Checks if the change set is empty, i.e. does not contain any changes.
- *
- * @return true, if the set is empty.
- */
- public boolean isEmpty() {
- return this.delta.isEmpty();
- }
-
- /**
- * Resets this change set instance. This will clear all changes done to this builder, so the
- * set will be empty.
- */
- public void reset() {
- this.delta.clear();
- }
-
-
- /**
- * Builds the corresponding change set.
- *
- * @return the new change set, never null.
- */
- public PropertySourceChange build() {
- return new PropertySourceChange(this);
- }
-
- /*
- * (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
- return "PropertiesChangeBuilder [source=" + source + ", " +
- ", delta=" + delta + "]";
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/main/java/org/apache/tamaya/events/internal/DefaultConfigChangeObserver.java
----------------------------------------------------------------------
diff --git a/modules/events/src/main/java/org/apache/tamaya/events/internal/DefaultConfigChangeObserver.java b/modules/events/src/main/java/org/apache/tamaya/events/internal/DefaultConfigChangeObserver.java
index 51951de..0138aa7 100644
--- a/modules/events/src/main/java/org/apache/tamaya/events/internal/DefaultConfigChangeObserver.java
+++ b/modules/events/src/main/java/org/apache/tamaya/events/internal/DefaultConfigChangeObserver.java
@@ -18,12 +18,12 @@
*/
package org.apache.tamaya.events.internal;
-import org.apache.tamaya.ConfigurationProvider;
import org.apache.tamaya.events.ConfigEventManager;
-import org.apache.tamaya.events.ConfigurationChange;
-import org.apache.tamaya.events.ConfigurationChangeBuilder;
-import org.apache.tamaya.events.FrozenConfiguration;
+import org.apache.tamaya.events.ConfigChange;
+import org.apache.tamaya.events.ConfigChangeBuilder;
+import org.apache.tamaya.events.FrozenConfig;
+import javax.config.ConfigProvider;
import java.util.*;
import java.util.logging.Logger;
@@ -40,7 +40,7 @@ public class DefaultConfigChangeObserver {
private long checkPeriod = 2000L;
- private volatile FrozenConfiguration lastConfig;
+ private volatile FrozenConfig lastConfig;
private volatile boolean running;
@@ -61,11 +61,11 @@ public class DefaultConfigChangeObserver {
public void checkConfigurationUpdate() {
LOG.finest("Checking configuration for changes...");
- FrozenConfiguration frozenConfig = FrozenConfiguration.of(ConfigurationProvider.getConfiguration());
- ConfigurationChange changes;
+ FrozenConfig frozenConfig = FrozenConfig.of(ConfigProvider.getConfig());
+ ConfigChange changes;
if (getLastConfig() != null) {
- changes = ConfigurationChangeBuilder.of(getLastConfig()).addChanges(frozenConfig)
+ changes = ConfigChangeBuilder.of(getLastConfig()).addChanges(frozenConfig)
.build();
if(!changes.isEmpty()) {
LOG.info("Identified configuration changes, publishing changes:\n" + changes);
@@ -77,11 +77,11 @@ public class DefaultConfigChangeObserver {
}
- protected FrozenConfiguration getLastConfig() {
+ protected FrozenConfig getLastConfig() {
return lastConfig;
}
- protected void setLastConfig(FrozenConfiguration newConfiguration) {
+ protected void setLastConfig(FrozenConfig newConfiguration) {
lastConfig = newConfiguration;
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/main/java/org/apache/tamaya/events/internal/LoggingConfigListener.java
----------------------------------------------------------------------
diff --git a/modules/events/src/main/java/org/apache/tamaya/events/internal/LoggingConfigListener.java b/modules/events/src/main/java/org/apache/tamaya/events/internal/LoggingConfigListener.java
index 6483154..13b74d7 100644
--- a/modules/events/src/main/java/org/apache/tamaya/events/internal/LoggingConfigListener.java
+++ b/modules/events/src/main/java/org/apache/tamaya/events/internal/LoggingConfigListener.java
@@ -18,11 +18,11 @@
*/
package org.apache.tamaya.events.internal;
-import org.apache.tamaya.Configuration;
import org.apache.tamaya.events.ConfigEvent;
import org.apache.tamaya.events.ConfigEventListener;
import org.osgi.service.component.annotations.Component;
+import javax.config.Config;
import java.util.logging.Logger;
/**
@@ -35,7 +35,7 @@ public class LoggingConfigListener implements ConfigEventListener {
@Override
public void onConfigEvent(ConfigEvent<?> event) {
- if(event.getResourceType()== Configuration.class) {
+ if(event.getResourceType()== Config.class) {
LOG.info("Configuration changed: " + event);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/main/java/org/apache/tamaya/events/spi/ConfigEventManagerSpi.java
----------------------------------------------------------------------
diff --git a/modules/events/src/main/java/org/apache/tamaya/events/spi/ConfigEventManagerSpi.java b/modules/events/src/main/java/org/apache/tamaya/events/spi/ConfigEventManagerSpi.java
index 4c90224..c4e512a 100644
--- a/modules/events/src/main/java/org/apache/tamaya/events/spi/ConfigEventManagerSpi.java
+++ b/modules/events/src/main/java/org/apache/tamaya/events/spi/ConfigEventManagerSpi.java
@@ -18,6 +18,7 @@
*/
package org.apache.tamaya.events.spi;
+import org.apache.tamaya.events.ConfigChange;
import org.apache.tamaya.events.ConfigEvent;
import org.apache.tamaya.events.ConfigEventListener;
@@ -119,7 +120,7 @@ public interface ConfigEventManagerSpi {
* and trigger ConfigurationChange events if something is changed. This is quite handy for publishing
* configuration changes to whatever systems are interested in. Hereby the origin of a configuration change
* can be on this machine, or also remotely. For handling corresponding {@link ConfigEventListener} have
- * to be registered, e.g. listening on {@link org.apache.tamaya.events.ConfigurationChange} events.
+ * to be registered, e.g. listening on {@link ConfigChange} events.
*
* @param enable whether to enable or disable the change monitoring.
*/
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/java/org/apache/tamaya/events/ChangeableGlobalConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/events/src/test/java/org/apache/tamaya/events/ChangeableGlobalConfigSource.java b/modules/events/src/test/java/org/apache/tamaya/events/ChangeableGlobalConfigSource.java
new file mode 100644
index 0000000..6e3ae13
--- /dev/null
+++ b/modules/events/src/test/java/org/apache/tamaya/events/ChangeableGlobalConfigSource.java
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.events;
+
+import org.apache.tamaya.base.configsource.BaseConfigSource;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * PropertySource implementation that accesses properties that are statically stored.
+ */
+public class ChangeableGlobalConfigSource extends BaseConfigSource{
+
+ private static final Map<String,String> STORED_ENTRIES = new ConcurrentHashMap<>();
+
+ @Override
+ public String getName() {
+ return getClass().getSimpleName();
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ return Collections.emptyMap();
+ }
+
+ /**
+ * Put a value (globally) into this property source.
+ * @param key the key, not null
+ * @param value the value, not null
+ * @return the entry replaced, or null.
+ */
+ public static String put(String key, String value){
+ return STORED_ENTRIES.put(key,value);
+ }
+
+ /**
+ * Put all the properties, overriding any existing ones with the same key.
+ * @param properties the properties, not null.
+ */
+ public static void putAll(Map<String,String> properties){
+ STORED_ENTRIES.putAll(properties);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/java/org/apache/tamaya/events/ChangeableGlobalPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/events/src/test/java/org/apache/tamaya/events/ChangeableGlobalPropertySource.java b/modules/events/src/test/java/org/apache/tamaya/events/ChangeableGlobalPropertySource.java
deleted file mode 100644
index 94a0a9d..0000000
--- a/modules/events/src/test/java/org/apache/tamaya/events/ChangeableGlobalPropertySource.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.events;
-
-import org.apache.tamaya.spisupport.propertysource.BasePropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * PropertySource implementation that accesses properties that are statically stored.
- */
-public class ChangeableGlobalPropertySource extends BasePropertySource{
-
- private static final Map<String,String> STORED_ENTRIES = new ConcurrentHashMap<>();
-
- @Override
- public String getName() {
- return getClass().getSimpleName();
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
- return null;
- }
-
- /**
- * Put a value (globally) into this property source.
- * @param key the key, not null
- * @param value the value, not null
- * @return the entry replaced, or null.
- */
- public static String put(String key, String value){
- return STORED_ENTRIES.put(key,value);
- }
-
- /**
- * Put all the properties, overriding any existing ones with the same key.
- * @param properties the properties, not null.
- */
- public static void putAll(Map<String,String> properties){
- STORED_ENTRIES.putAll(properties);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/java/org/apache/tamaya/events/ChangeableThreadLocalPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/events/src/test/java/org/apache/tamaya/events/ChangeableThreadLocalPropertySource.java b/modules/events/src/test/java/org/apache/tamaya/events/ChangeableThreadLocalPropertySource.java
index f8fd413..df7425c 100644
--- a/modules/events/src/test/java/org/apache/tamaya/events/ChangeableThreadLocalPropertySource.java
+++ b/modules/events/src/test/java/org/apache/tamaya/events/ChangeableThreadLocalPropertySource.java
@@ -18,8 +18,7 @@
*/
package org.apache.tamaya.events;
-import org.apache.tamaya.spisupport.propertysource.BasePropertySource;
-import org.apache.tamaya.spi.PropertyValue;
+import org.apache.tamaya.base.configsource.BaseConfigSource;
import java.util.HashMap;
import java.util.Map;
@@ -29,7 +28,7 @@ import java.util.Map;
* PropertySource implementation that accesses properties that are stored on ThreadLocal level, e.g. good to use for
* testing..
*/
-public class ChangeableThreadLocalPropertySource extends BasePropertySource{
+public class ChangeableThreadLocalPropertySource extends BaseConfigSource{
private static final ThreadLocal<Map<String,String>> STORED_ENTRIES = new ThreadLocal<Map<String,String>>(){
protected Map<String,String> initialValue(){
@@ -43,7 +42,7 @@ public class ChangeableThreadLocalPropertySource extends BasePropertySource{
}
@Override
- public Map<String, PropertyValue> getProperties() {
+ public Map<String, String> getProperties() {
return null;
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/java/org/apache/tamaya/events/ConfigChangeBuilderTest.java
----------------------------------------------------------------------
diff --git a/modules/events/src/test/java/org/apache/tamaya/events/ConfigChangeBuilderTest.java b/modules/events/src/test/java/org/apache/tamaya/events/ConfigChangeBuilderTest.java
new file mode 100644
index 0000000..bd4a4f9
--- /dev/null
+++ b/modules/events/src/test/java/org/apache/tamaya/events/ConfigChangeBuilderTest.java
@@ -0,0 +1,134 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.events;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import javax.config.Config;
+import java.beans.PropertyChangeEvent;
+import java.util.*;
+
+import static java.util.Collections.emptySet;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
+
+public class ConfigChangeBuilderTest {
+
+ @Test
+ public void compareReturnAnEmptyListOfChangesForTwoEmptyConfigs() {
+ Config oc = Mockito.mock(Config.class, new MethodNotMockedAnswer());
+ Config nc = Mockito.mock(Config.class, new MethodNotMockedAnswer());
+
+ doReturn(emptySet()).when(oc).getPropertyNames();
+ doReturn(emptySet()).when(nc).getPropertyNames();
+
+ Collection<PropertyChangeEvent> diff = ConfigChangeBuilder.compare(oc, nc);
+
+ assertThat(diff).isNotNull().isEmpty();
+ }
+
+ @Test
+ public void compareReturnsAChangeEventIfThereIsANewKeyInTheNewVersionOfTheConfig() {
+ Config oc = Mockito.mock(Config.class, new MethodNotMockedAnswer());
+ Config nc = Mockito.mock(Config.class, new MethodNotMockedAnswer());
+
+ doReturn(emptySet()).when(oc).getPropertyNames();
+ doThrow(new NoSuchElementException()).when(oc).getValue("a", String.class);
+ doReturn(Optional.empty()).when(oc).getOptionalValue("a", String.class);
+
+ Map<String, String> valuesNC = new HashMap<String, String>();
+ valuesNC.put("a", "19");
+
+ doReturn(valuesNC.keySet()).when(nc).getPropertyNames();
+ doReturn(Optional.of("19")).when(nc).getOptionalValue("a", String.class);
+
+ Collection<PropertyChangeEvent> diff = ConfigChangeBuilder.compare(oc, nc);
+
+ assertThat(diff).isNotNull().isNotEmpty().hasSize(1);
+
+ PropertyChangeEvent change = diff.iterator().next();
+
+ assertThat(change).isNotNull();
+ assertThat(change.getNewValue()).isEqualTo("19");
+ assertThat(change.getOldValue()).isNull();
+ assertThat(change.getPropertyName()).isEqualTo("a");
+ }
+
+ @Test
+ public void compareReturnsAChangeEventIfAKeyHasBeenRemovedInTheNewVersionOfTheConfig() {
+ Config oc = Mockito.mock(Config.class, new MethodNotMockedAnswer());
+ Config nc = Mockito.mock(Config.class, new MethodNotMockedAnswer());
+
+ Map<String, String> valuesOC = new HashMap<String, String>();
+ valuesOC.put("a", "19");
+
+ doReturn(valuesOC.keySet()).when(oc).getPropertyNames();
+ doReturn("19").when(oc).getValue("a", String.class);
+
+ doReturn(emptySet()).when(nc).getPropertyNames();
+ doReturn(Optional.empty()).when(nc).getOptionalValue("a", String.class);
+
+ Collection<PropertyChangeEvent> diff = ConfigChangeBuilder.compare(oc, nc);
+
+ assertThat(diff).isNotNull().isNotEmpty().hasSize(1);
+
+ PropertyChangeEvent change = diff.iterator().next();
+
+ assertThat(change).isNotNull();
+ assertThat(change.getNewValue()).isNull();
+ assertThat(change.getOldValue()).isEqualTo("19");
+ assertThat(change.getPropertyName()).isEqualTo("a");
+ }
+
+ @Test
+ public void compareReturnsAChangeEventIfValueOfExistingKeyHasChanged() {
+ Config oc = Mockito.mock(Config.class, new MethodNotMockedAnswer());
+ Config nc = Mockito.mock(Config.class, new MethodNotMockedAnswer());
+
+ Map<String, String> valuesOC = new HashMap<String, String>();
+ valuesOC.put("a", "91");
+
+ doReturn(valuesOC.keySet()).when(oc).getPropertyNames();
+ doReturn(Optional.of("91")).when(oc).getOptionalValue("a", String.class);
+ doReturn("91").when(oc).getValue("a",String.class);
+ doReturn("old Config").when(oc).toString();
+
+ Map<String, String> valuesNC = new HashMap<String, String>();
+ valuesNC.put("a", "19");
+
+ doReturn(valuesNC.keySet()).when(nc).getPropertyNames();
+ doReturn(Optional.of("19")).when(nc).getOptionalValue("a",String.class);
+ doReturn("19").when(nc).getValue("a",String.class);
+ doReturn("new Config").when(nc).toString();
+
+ Collection<PropertyChangeEvent> diff = ConfigChangeBuilder.compare(oc, nc);
+
+ assertThat(diff).isNotNull().isNotEmpty().hasSize(1);
+
+ PropertyChangeEvent change = diff.iterator().next();
+
+ assertThat(change).isNotNull();
+ assertThat(change.getNewValue()).isEqualTo("19");
+ assertThat(change.getOldValue()).isEqualTo("91");
+ assertThat(change.getPropertyName()).isEqualTo("a");
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/java/org/apache/tamaya/events/ConfigChangeTest.java
----------------------------------------------------------------------
diff --git a/modules/events/src/test/java/org/apache/tamaya/events/ConfigChangeTest.java b/modules/events/src/test/java/org/apache/tamaya/events/ConfigChangeTest.java
new file mode 100644
index 0000000..6090576
--- /dev/null
+++ b/modules/events/src/test/java/org/apache/tamaya/events/ConfigChangeTest.java
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.events;
+
+import org.junit.Test;
+
+import javax.config.Config;
+import javax.config.ConfigProvider;
+
+import static org.junit.Assert.*;
+
+
+/**
+ * Test class for {@link ConfigChange}.
+ */
+public class ConfigChangeTest {
+
+ @Test
+ public void testEmptyChangeSet() throws Exception {
+ ConfigChange change = ConfigChange.emptyChangeSet(ConfigProvider.getConfig());
+ assertNotNull(change);
+ assertTrue(change.getChanges().isEmpty());
+ }
+
+ @Test
+ public void testGetConfig() throws Exception {
+ Config config = ConfigProvider.getConfig();
+ ConfigChange change = ConfigChangeBuilder.of(config).build();
+ assertNotNull(change);
+ assertTrue(change.getUpdatedSize()==0);
+ assertTrue(change.getAddedSize()==0);
+ assertTrue(change.getRemovedSize()==0);
+ assertTrue(change.getChanges().size()==0);
+ for (String key : config.getPropertyNames()) {
+ if (!"[meta]frozenAt".equals(key)) {
+ if(key.contains("random.new")){ // dynamic generated value!
+ continue;
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testGetVersion() throws Exception {
+ Config config = ConfigProvider.getConfig();
+ ConfigChange change = ConfigChangeBuilder.of(config).build();
+ assertNotNull(change.getVersion());
+ change = ConfigChangeBuilder.of(config).setVersion("version2").build();
+ assertEquals("version2", change.getVersion());
+ }
+
+ @Test
+ public void testGetTimestamp() throws Exception {
+ Config config = ConfigProvider.getConfig();
+ Thread.sleep(10L);
+ ConfigChange change = ConfigChangeBuilder.of(config).build();
+ assertTrue((System.currentTimeMillis() - change.getTimestamp()) > 0L);
+ change = ConfigChangeBuilder.of(config).setTimestamp(10L).build();
+ assertEquals(10L, change.getTimestamp());
+ }
+
+ @Test
+ public void testGetEvents() throws Exception {
+ Config config = ConfigProvider.getConfig();
+ ConfigChange change = ConfigChangeBuilder.of(config).removeKey("key1", "key2").build();
+ assertTrue(change.getChanges().size() == 2);
+ change = ConfigChangeBuilder.of(config).addChange("key1Added", "value1Added").build();
+ assertTrue(change.getChanges().size() == 1);
+ }
+
+ @Test
+ public void testGetRemovedSize() throws Exception {
+ Config config = ConfigProvider.getConfig();
+ ConfigChange change = ConfigChangeBuilder.of(config).removeKey("java.version", "key2").build();
+ assertTrue(change.getRemovedSize() == 2);
+ assertTrue(change.getAddedSize() == 0);
+ }
+
+ @Test
+ public void testGetAddedSize() throws Exception {
+ Config config = ConfigProvider.getConfig();
+ ConfigChange change = ConfigChangeBuilder.of(config).addChange("key1", "key2").build();
+ assertTrue(change.getAddedSize() == 1);
+ assertTrue(change.getRemovedSize() == 0);
+ }
+
+ @Test
+ public void testGetUpdatedSize() throws Exception {
+ Config config = ConfigProvider.getConfig();
+ ConfigChange change = ConfigChangeBuilder.of(config).addChange("java.version", "1.8").build();
+ assertTrue(change.getUpdatedSize() == 1);
+ }
+
+ @Test
+ public void testIsRemoved() throws Exception {
+ Config config = ConfigProvider.getConfig();
+ ConfigChange change = ConfigChangeBuilder.of(config).removeKey("java.version").build();
+ assertTrue(change.isRemoved("java.version"));
+ }
+
+ @Test
+ public void testIsAdded() throws Exception {
+ Config config = ConfigProvider.getConfig();
+ ConfigChange change = ConfigChangeBuilder.of(config).addChange("key1", "key2").build();
+ assertTrue(change.isAdded("key1"));
+ }
+
+ @Test
+ public void testIsUpdated() throws Exception {
+ Config config = ConfigProvider.getConfig();
+ ConfigChange change = ConfigChangeBuilder.of(config).addChange("java.version", "1.8").build();
+ assertTrue(change.isUpdated("java.version"));
+ }
+
+ @Test
+ public void testContainsKey() throws Exception {
+ Config config = ConfigProvider.getConfig();
+ ConfigChange change = ConfigChangeBuilder.of(config).addChange("key1", "key2").build();
+ assertTrue(change.isKeyAffected("key1"));
+ assertFalse(change.isKeyAffected("key2"));
+ change = ConfigChangeBuilder.of(config).removeKey("java.version").build();
+ assertFalse(change.isKeyAffected("java.version"));
+ assertFalse(change.isKeyAffected("key2"));
+ }
+
+ @Test
+ public void testIsEmpty() throws Exception {
+ Config config = ConfigProvider.getConfig();
+ ConfigChange change = ConfigChangeBuilder.of(config).build();
+ assertTrue(change.isEmpty());
+ }
+
+ @Test
+ public void testToString() throws Exception {
+ Config config = ConfigProvider.getConfig();
+ ConfigChange change = ConfigChangeBuilder.of(config).removeKey("java.version").build();
+ String toString =
+ change.toString();
+ assertTrue(toString.contains("timestamp"));
+ assertTrue(toString.contains("change-id"));
+ assertTrue(toString.contains("config-id"));
+ assertFalse(toString.contains("key1"));
+ assertFalse(toString.contains("key2"));
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/java/org/apache/tamaya/events/ConfigSourceChangeTest.java
----------------------------------------------------------------------
diff --git a/modules/events/src/test/java/org/apache/tamaya/events/ConfigSourceChangeTest.java b/modules/events/src/test/java/org/apache/tamaya/events/ConfigSourceChangeTest.java
new file mode 100644
index 0000000..30bf940
--- /dev/null
+++ b/modules/events/src/test/java/org/apache/tamaya/events/ConfigSourceChangeTest.java
@@ -0,0 +1,180 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.events;
+
+import org.apache.tamaya.base.configsource.EnvironmentConfigSource;
+import org.apache.tamaya.base.configsource.SimpleConfigSource;
+import org.apache.tamaya.base.configsource.SystemConfigSource;
+import org.junit.Test;
+
+import javax.config.spi.ConfigSource;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.Assert.*;
+
+/**
+ * Tests for {@link ConfigSourceChange} and its builder.
+ */
+public class ConfigSourceChangeTest {
+
+ private static final ConfigSource myPS = new SystemConfigSource();
+
+ @Test
+ public void testGetPropertySource() throws Exception {
+ ConfigSourceChange change = ConfigSourceChangeBuilder.of(myPS).build();
+ assertEquals(change.getResource().getName(), myPS.getName());
+ }
+
+ @Test
+ public void testGetVersion() throws Exception {
+ ConfigSourceChange change = ConfigSourceChangeBuilder.of(myPS)
+ .setVersion("myVersion1").build();
+ assertEquals(change.getVersion(), "myVersion1");
+ }
+
+ @Test
+ public void testGetTimestamp() throws Exception {
+ ConfigSourceChange change = ConfigSourceChangeBuilder.of(myPS)
+ .setTimestamp(111L).build();
+ assertEquals(change.getTimestamp(), 111L);
+ }
+
+ @Test
+ public void testGetEvents() throws Exception {
+ ConfigSourceChange change = ConfigSourceChangeBuilder.of(myPS)
+ .addChanges(
+ new EnvironmentConfigSource()
+ ).build();
+ assertTrue(change.getChanges().size()>0);
+ }
+
+ @Test
+ public void testGetRemovedSize() throws Exception {
+ ConfigSourceChange change = ConfigSourceChangeBuilder.of(myPS)
+ .addChanges(
+ new EnvironmentConfigSource()
+ ).build();
+ assertTrue(change.getRemovedSize()>0);
+ }
+
+ @Test
+ public void testGetAddedSize() throws Exception {
+ ConfigSourceChange change = ConfigSourceChangeBuilder.of(myPS)
+ .addChanges(
+ new EnvironmentConfigSource()
+ ).build();
+ assertTrue(change.getAddedSize()>0);
+ }
+
+ @Test
+ public void testGetUpdatedSize() throws Exception {
+ ConfigSourceChange change = ConfigSourceChangeBuilder.of(myPS)
+ .addChanges(
+ new EnvironmentConfigSource()
+ ).build();
+ assertTrue(change.getUpdatedSize()==0);
+ }
+
+ @Test
+ public void testIsRemoved() throws Exception {
+ Map<String, String> testData = new HashMap<>();
+ testData.put("key1", "value1");
+ testData.put("key2", "value2");
+ SimpleConfigSource ps1 = new SimpleConfigSource("test", testData);
+ testData = new HashMap<>();
+ testData.put("key1", "value2");
+ testData.put("key3", "value3");
+ SimpleConfigSource ps2 = new SimpleConfigSource("test", testData);
+ ConfigSourceChange change = ConfigSourceChangeBuilder.of(ps1)
+ .addChanges(
+ ps2
+ ).build();
+ assertFalse(change.isRemoved("key1"));
+ assertTrue(change.isRemoved("key2"));
+ assertFalse(change.isRemoved("key3"));
+ }
+
+ @Test
+ public void testIsAdded() throws Exception {
+ Map<String, String> testData = new HashMap<>();
+ testData.put("key1", "value1");
+ testData.put("key2", "value2");
+ ConfigSource ps1 = new SimpleConfigSource("test", testData);
+ testData = new HashMap<>();
+ testData.put("key1", "value2");
+ testData.put("key3", "value3");
+ ConfigSource ps2 = new SimpleConfigSource("test", testData);
+ ConfigSourceChange change = ConfigSourceChangeBuilder.of(ps1)
+ .addChanges(
+ ps2
+ ).build();
+ assertTrue(change.isAdded("key3"));
+ assertFalse(change.isAdded("key2"));
+ assertFalse(change.isAdded("key1"));
+ }
+
+ @Test
+ public void testIsUpdated() throws Exception {
+ Map<String, String> testData = new HashMap<>();
+ testData.put("key1", "value1");
+ testData.put("key2", "value2");
+ SimpleConfigSource ps1 = new SimpleConfigSource("test", testData);
+ testData = new HashMap<>();
+ testData.put("key1", "value2");
+ testData.put("key3", "value3");
+ SimpleConfigSource ps2 = new SimpleConfigSource("test", testData);
+ ConfigSourceChange change = ConfigSourceChangeBuilder.of(ps1)
+ .addChanges(
+ ps2
+ ).build();
+ assertTrue(change.isUpdated("key1"));
+ assertFalse(change.isUpdated("key2"));
+ assertFalse(change.isUpdated("key3"));
+ }
+
+ @Test
+ public void testContainsKey() throws Exception {
+ ConfigSourceChange change = ConfigSourceChangeBuilder.of(new EnvironmentConfigSource())
+ .addChanges(
+ myPS
+ ).build();
+ assertTrue(change.isKeyAffected("java.version"));
+ }
+
+ @Test
+ public void testIsEmpty() throws Exception {
+ ConfigSourceChange change = ConfigSourceChangeBuilder.of(new EnvironmentConfigSource())
+ .build();
+ assertTrue(change.isEmpty());
+ change = ConfigSourceChangeBuilder.of(new EnvironmentConfigSource())
+ .addChanges(
+ myPS
+ ).build();
+ assertFalse(change.isEmpty());
+ }
+
+ @Test
+ public void testToString() throws Exception {
+ ConfigSourceChange change = ConfigSourceChangeBuilder.of(myPS).build();
+ String toString = change.toString();
+ assertNotNull(toString);
+ assertTrue(toString.contains(myPS.getName()));
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/java/org/apache/tamaya/events/ConfigurationChangeBuilderTest.java
----------------------------------------------------------------------
diff --git a/modules/events/src/test/java/org/apache/tamaya/events/ConfigurationChangeBuilderTest.java b/modules/events/src/test/java/org/apache/tamaya/events/ConfigurationChangeBuilderTest.java
deleted file mode 100644
index d0ee77a..0000000
--- a/modules/events/src/test/java/org/apache/tamaya/events/ConfigurationChangeBuilderTest.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.events;
-
-import org.apache.tamaya.Configuration;
-import org.junit.Test;
-import org.mockito.Mockito;
-
-import java.beans.PropertyChangeEvent;
-import java.util.*;
-
-import static java.util.Collections.emptyMap;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.doReturn;
-
-public class ConfigurationChangeBuilderTest {
-
- @Test
- public void compareReturnAnEmptyListOfChangesForTwoEmptyConfigurations() {
- Configuration oc = Mockito.mock(Configuration.class, new MethodNotMockedAnswer());
- Configuration nc = Mockito.mock(Configuration.class, new MethodNotMockedAnswer());
-
- doReturn(emptyMap()).when(oc).getProperties();
- doReturn(emptyMap()).when(nc).getProperties();
-
- Collection<PropertyChangeEvent> diff = ConfigurationChangeBuilder.compare(oc, nc);
-
- assertThat(diff).isNotNull().isEmpty();
- }
-
- @Test
- public void compareReturnsAChangeEventIfThereIsANewKeyInTheNewVersionOfTheConfiguration() {
- Configuration oc = Mockito.mock(Configuration.class, new MethodNotMockedAnswer());
- Configuration nc = Mockito.mock(Configuration.class, new MethodNotMockedAnswer());
-
- doReturn(emptyMap()).when(oc).getProperties();
- doReturn(null).when(oc).get(eq("a"));
-
- Map<String, String> valuesNC = new HashMap<String, String>();
- valuesNC.put("a", "19");
-
- doReturn(valuesNC).when(nc).getProperties();
- doReturn("19").when(nc).get(eq("a"));
-
- Collection<PropertyChangeEvent> diff = ConfigurationChangeBuilder.compare(oc, nc);
-
- assertThat(diff).isNotNull().isNotEmpty().hasSize(1);
-
- PropertyChangeEvent change = diff.iterator().next();
-
- assertThat(change).isNotNull();
- assertThat(change.getNewValue()).isEqualTo("19");
- assertThat(change.getOldValue()).isNull();
- assertThat(change.getPropertyName()).isEqualTo("a");
- }
-
- @Test
- public void compareReturnsAChangeEventIfAKeyHasBeenRemovedInTheNewVersionOfTheConfiguration() {
- Configuration oc = Mockito.mock(Configuration.class, new MethodNotMockedAnswer());
- Configuration nc = Mockito.mock(Configuration.class, new MethodNotMockedAnswer());
-
- Map<String, String> valuesOC = new HashMap<String, String>();
- valuesOC.put("a", "19");
-
- doReturn(valuesOC).when(oc).getProperties();
- doReturn("19").when(oc).get(eq("a"));
-
- doReturn(emptyMap()).when(nc).getProperties();
- doReturn(null).when(nc).get(eq("a"));
-
- Collection<PropertyChangeEvent> diff = ConfigurationChangeBuilder.compare(oc, nc);
-
- assertThat(diff).isNotNull().isNotEmpty().hasSize(1);
-
- PropertyChangeEvent change = diff.iterator().next();
-
- assertThat(change).isNotNull();
- assertThat(change.getNewValue()).isNull();
- assertThat(change.getOldValue()).isEqualTo("19");
- assertThat(change.getPropertyName()).isEqualTo("a");
- }
-
- @Test
- public void compareReturnsAChangeEventIfValueOfExistingKeyHasChanged() {
- Configuration oc = Mockito.mock(Configuration.class, new MethodNotMockedAnswer());
- Configuration nc = Mockito.mock(Configuration.class, new MethodNotMockedAnswer());
-
- Map<String, String> valuesOC = new HashMap<String, String>();
- valuesOC.put("a", "91");
-
- doReturn(valuesOC).when(oc).getProperties();
- doReturn("91").when(oc).get(eq("a"));
- doReturn("old configuration").when(oc).toString();
-
- Map<String, String> valuesNC = new HashMap<String, String>();
- valuesNC.put("a", "19");
-
- doReturn(valuesNC).when(nc).getProperties();
- doReturn("19").when(nc).get(eq("a"));
- doReturn("new configuration").when(nc).toString();
-
- Collection<PropertyChangeEvent> diff = ConfigurationChangeBuilder.compare(oc, nc);
-
- assertThat(diff).isNotNull().isNotEmpty().hasSize(1);
-
- PropertyChangeEvent change = diff.iterator().next();
-
- assertThat(change).isNotNull();
- assertThat(change.getNewValue()).isEqualTo("19");
- assertThat(change.getOldValue()).isEqualTo("91");
- assertThat(change.getPropertyName()).isEqualTo("a");
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/java/org/apache/tamaya/events/ConfigurationChangeTest.java
----------------------------------------------------------------------
diff --git a/modules/events/src/test/java/org/apache/tamaya/events/ConfigurationChangeTest.java b/modules/events/src/test/java/org/apache/tamaya/events/ConfigurationChangeTest.java
deleted file mode 100644
index 60f40c2..0000000
--- a/modules/events/src/test/java/org/apache/tamaya/events/ConfigurationChangeTest.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.events;
-
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.ConfigurationProvider;
-import org.junit.Test;
-
-import java.util.Map;
-
-import static org.junit.Assert.*;
-import static org.assertj.core.api.Assertions.*;
-/**
- * Test class for {@link ConfigurationChange}.
- */
-public class ConfigurationChangeTest {
-
- @Test
- public void testEmptyChangeSet() throws Exception {
- ConfigurationChange change = ConfigurationChange.emptyChangeSet(ConfigurationProvider.getConfiguration());
- assertThat(change).isNotNull();
- assertThat(change.getChanges()).isEmpty();
- }
-
- @Test
- public void testGetConfiguration() throws Exception {
- Configuration config = ConfigurationProvider.getConfiguration();
- ConfigurationChange change = ConfigurationChangeBuilder.of(config).build();
- assertNotNull(change);
- assertTrue(change.getUpdatedSize()==0);
- assertTrue(change.getAddedSize()==0);
- assertTrue(change.getRemovedSize()==0);
- assertTrue(change.getChanges().size()==0);
- for (Map.Entry<String, String> en : config.getProperties().entrySet()) {
- if (!"[meta]frozenAt".equals(en.getKey())) {
- if(en.getKey().contains("random.new")){ // dynamic generated value!
- continue;
- }
- assertEquals("Error for " + en.getKey(), en.getValue(), change.getResource().get(en.getKey()));
- }
- }
- }
-
- @Test
- public void testGetVersion() throws Exception {
- Configuration config = ConfigurationProvider.getConfiguration();
- ConfigurationChange change = ConfigurationChangeBuilder.of(config).build();
- assertNotNull(change.getVersion());
- change = ConfigurationChangeBuilder.of(config).setVersion("version2").build();
- assertEquals("version2", change.getVersion());
- }
-
- @Test
- public void testGetTimestamp() throws Exception {
- Configuration config = ConfigurationProvider.getConfiguration();
- Thread.sleep(10L);
- ConfigurationChange change = ConfigurationChangeBuilder.of(config).build();
- assertTrue((System.currentTimeMillis() - change.getTimestamp()) > 0L);
- change = ConfigurationChangeBuilder.of(config).setTimestamp(10L).build();
- assertEquals(10L, change.getTimestamp());
- }
-
- @Test
- public void testGetEvents() throws Exception {
- Configuration config = ConfigurationProvider.getConfiguration();
- ConfigurationChange change = ConfigurationChangeBuilder.of(config).removeKey("key1", "key2").build();
- assertTrue(change.getChanges().size() == 2);
- change = ConfigurationChangeBuilder.of(config).addChange("key1Added", "value1Added").build();
- assertTrue(change.getChanges().size() == 1);
- }
-
- @Test
- public void testGetRemovedSize() throws Exception {
- Configuration config = ConfigurationProvider.getConfiguration();
- ConfigurationChange change = ConfigurationChangeBuilder.of(config).removeKey("java.version", "key2").build();
- assertTrue(change.getRemovedSize() == 2);
- assertTrue(change.getAddedSize() == 0);
- }
-
- @Test
- public void testGetAddedSize() throws Exception {
- Configuration config = ConfigurationProvider.getConfiguration();
- ConfigurationChange change = ConfigurationChangeBuilder.of(config).addChange("key1", "key2").build();
- assertTrue(change.getAddedSize() == 1);
- assertTrue(change.getRemovedSize() == 0);
- }
-
- @Test
- public void testGetUpdatedSize() throws Exception {
- Configuration config = ConfigurationProvider.getConfiguration();
- ConfigurationChange change = ConfigurationChangeBuilder.of(config).addChange("java.version", "1.8").build();
- assertTrue(change.getUpdatedSize() == 1);
- }
-
- @Test
- public void testIsRemoved() throws Exception {
- Configuration config = ConfigurationProvider.getConfiguration();
- ConfigurationChange change = ConfigurationChangeBuilder.of(config).removeKey("java.version").build();
- assertTrue(change.isRemoved("java.version"));
- }
-
- @Test
- public void testIsAdded() throws Exception {
- Configuration config = ConfigurationProvider.getConfiguration();
- ConfigurationChange change = ConfigurationChangeBuilder.of(config).addChange("key1", "key2").build();
- assertTrue(change.isAdded("key1"));
- }
-
- @Test
- public void testIsUpdated() throws Exception {
- Configuration config = ConfigurationProvider.getConfiguration();
- ConfigurationChange change = ConfigurationChangeBuilder.of(config).addChange("java.version", "1.8").build();
- assertTrue(change.isUpdated("java.version"));
- }
-
- @Test
- public void testContainsKey() throws Exception {
- Configuration config = ConfigurationProvider.getConfiguration();
- ConfigurationChange change = ConfigurationChangeBuilder.of(config).addChange("key1", "key2").build();
- assertTrue(change.isKeyAffected("key1"));
- assertFalse(change.isKeyAffected("key2"));
- change = ConfigurationChangeBuilder.of(config).removeKey("java.version").build();
- assertFalse(change.isKeyAffected("java.version"));
- assertFalse(change.isKeyAffected("key2"));
- }
-
- @Test
- public void testIsEmpty() throws Exception {
- Configuration config = ConfigurationProvider.getConfiguration();
- ConfigurationChange change = ConfigurationChangeBuilder.of(config).build();
- assertTrue(change.isEmpty());
- }
-
- @Test
- public void testToString() throws Exception {
- Configuration config = ConfigurationProvider.getConfiguration();
- ConfigurationChange change = ConfigurationChangeBuilder.of(config).removeKey("java.version").build();
- String toString =
- change.toString();
- assertTrue(toString.contains("timestamp"));
- assertTrue(toString.contains("change-id"));
- assertTrue(toString.contains("configuration-id"));
- assertFalse(toString.contains("key1"));
- assertFalse(toString.contains("key2"));
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/java/org/apache/tamaya/events/FrozenConfigSourceTest.java
----------------------------------------------------------------------
diff --git a/modules/events/src/test/java/org/apache/tamaya/events/FrozenConfigSourceTest.java b/modules/events/src/test/java/org/apache/tamaya/events/FrozenConfigSourceTest.java
new file mode 100644
index 0000000..8e06ece
--- /dev/null
+++ b/modules/events/src/test/java/org/apache/tamaya/events/FrozenConfigSourceTest.java
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.events;
+
+import org.apache.tamaya.base.configsource.ConfigSourceComparator;
+import org.apache.tamaya.base.configsource.SystemConfigSource;
+import org.junit.Test;
+
+import javax.config.spi.ConfigSource;
+import java.util.Map;
+
+import static org.junit.Assert.*;
+
+/**
+ * Tests for {@link FrozenConfigSource}.
+ */
+public class FrozenConfigSourceTest {
+
+ private static final ConfigSource myPS = new SystemConfigSource();
+
+ @Test
+ public void testOf() throws Exception {
+ ConfigSource ps = FrozenConfigSource.of(myPS);
+ assertNotNull(ps);
+ }
+
+ @Test
+ public void testGetName() throws Exception {
+ ConfigSource ps = FrozenConfigSource.of(myPS);
+ String name = ps.getName();
+ assertNotNull(name);
+ assertEquals(name, ps.getName());
+ }
+
+ @Test
+ public void testGetOrdinal() throws Exception {
+ ConfigSource ps = FrozenConfigSource.of(myPS);
+ assertEquals(ConfigSourceComparator.getOrdinal(myPS),
+ ConfigSourceComparator.getOrdinal(ps));
+ }
+
+ @Test
+ public void testGet() throws Exception {
+ ConfigSource ps = FrozenConfigSource.of(myPS);
+ assertNotNull(ps);
+ for (Map.Entry<String, String> e : myPS.getProperties().entrySet()) {
+ assertEquals(ps.getValue(e.getKey()), e.getValue());
+ }
+ }
+
+ @Test
+ public void testGetProperties() throws Exception {
+ ConfigSource ps = FrozenConfigSource.of(myPS);
+ assertNotNull(ps);
+ assertNotNull(ps.getProperties());
+ assertFalse(ps.getProperties().isEmpty());
+ }
+
+ @Test
+ public void testEquals() throws Exception {
+ ConfigSource ps1 = FrozenConfigSource.of(myPS);
+ ConfigSource ps2 = FrozenConfigSource.of(myPS);
+ assertEquals(ps1.getName(), ps2.getName());
+ assertEquals(ps1.getProperties().size(), ps2.getProperties().size());
+ }
+
+ @Test
+ public void testHashCode() throws Exception {
+ boolean alwaysDifferent = true;
+ for(int i=0;i<10;i++){
+ ConfigSource ps1 = FrozenConfigSource.of(myPS);
+ ConfigSource ps2 = FrozenConfigSource.of(myPS);
+ // sometimes not same, because frozenAt in ms maybe different
+ if(ps1.hashCode()==ps2.hashCode()){
+ alwaysDifferent=false;
+ break;
+ }
+ }
+ if(alwaysDifferent){
+ fail("HashCode should be same if frozenAt is in the same ms...");
+ }
+ }
+
+ @Test
+ public void testToString() throws Exception {
+ ConfigSource ps = FrozenConfigSource.of(myPS);
+ String toString = ps.toString();
+ assertNotNull(toString);
+ assertTrue(toString.contains("FrozenPropertySource"));
+ assertTrue(toString.contains(myPS.getName()));
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/java/org/apache/tamaya/events/FrozenConfigurationTest.java
----------------------------------------------------------------------
diff --git a/modules/events/src/test/java/org/apache/tamaya/events/FrozenConfigurationTest.java b/modules/events/src/test/java/org/apache/tamaya/events/FrozenConfigurationTest.java
index 264d99a..03e9b7c 100644
--- a/modules/events/src/test/java/org/apache/tamaya/events/FrozenConfigurationTest.java
+++ b/modules/events/src/test/java/org/apache/tamaya/events/FrozenConfigurationTest.java
@@ -18,10 +18,11 @@
*/
package org.apache.tamaya.events;
-import org.apache.tamaya.Configuration;
import org.junit.Test;
import org.mockito.Mockito;
+import javax.config.Config;
+import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@@ -32,11 +33,11 @@ public class FrozenConfigurationTest {
@Test
public void getFrozenAtReturnsTheCorrectTimestamp() {
- Configuration source = Mockito.mock(Configuration.class);
-
+ Config source = Mockito.mock(Config.class);
+ doReturn(Collections.emptySet()).when(source).getPropertyNames();
long poiStart = System.nanoTime();
- FrozenConfiguration fc = FrozenConfiguration.of(source);
+ FrozenConfig fc = FrozenConfig.of(source);
long poiEnd = System.nanoTime();
@@ -47,9 +48,9 @@ public class FrozenConfigurationTest {
@Test
public void idMustBeNotNull() {
- Configuration source = Mockito.mock(Configuration.class);
-
- FrozenConfiguration fc = FrozenConfiguration.of(source);
+ Config source = Mockito.mock(Config.class);
+ doReturn(Collections.emptySet()).when(source).getPropertyNames();
+ FrozenConfig fc = FrozenConfig.of(source);
assertThat(fc.getId()).isNotNull();
}
@@ -62,11 +63,11 @@ public class FrozenConfigurationTest {
Map<String, String> properties = new HashMap<>();
properties.put("key", "value");
- Configuration configuration = Mockito.mock(Configuration.class);
- doReturn(properties).when(configuration).getProperties();
+ Config configuration = Mockito.mock(Config.class);
+ doReturn(properties.keySet()).when(configuration).getPropertyNames();
- FrozenConfiguration fcA = FrozenConfiguration.of(configuration);
- FrozenConfiguration fcB = FrozenConfiguration.of(configuration);
+ FrozenConfig fcA = FrozenConfig.of(configuration);
+ FrozenConfig fcB = FrozenConfig.of(configuration);
assertThat(fcA.getId()).isNotEqualTo(fcB.getId());
assertThat(fcA).isNotEqualTo(fcB);
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/java/org/apache/tamaya/events/FrozenPropertySourceTest.java
----------------------------------------------------------------------
diff --git a/modules/events/src/test/java/org/apache/tamaya/events/FrozenPropertySourceTest.java b/modules/events/src/test/java/org/apache/tamaya/events/FrozenPropertySourceTest.java
deleted file mode 100644
index cdc70b8..0000000
--- a/modules/events/src/test/java/org/apache/tamaya/events/FrozenPropertySourceTest.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.events;
-
-import org.apache.tamaya.spisupport.propertysource.SystemPropertySource;
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-import org.apache.tamaya.spisupport.PropertySourceComparator;
-import org.junit.Test;
-
-import java.util.Map;
-
-import static org.junit.Assert.*;
-
-/**
- * Tests for {@link org.apache.tamaya.events.FrozenPropertySource}.
- */
-public class FrozenPropertySourceTest {
-
- private static final PropertySource myPS = new SystemPropertySource();
-
- @Test
- public void testOf() throws Exception {
- PropertySource ps = FrozenPropertySource.of(myPS);
- assertNotNull(ps);
- }
-
- @Test
- public void testGetName() throws Exception {
- PropertySource ps = FrozenPropertySource.of(myPS);
- String name = ps.getName();
- assertNotNull(name);
- assertEquals(name, ps.getName());
- }
-
- @Test
- public void testGetOrdinal() throws Exception {
- PropertySource ps = FrozenPropertySource.of(myPS);
- assertEquals(PropertySourceComparator.getOrdinal(myPS),
- PropertySourceComparator.getOrdinal(ps));
- }
-
- @Test
- public void testGet() throws Exception {
- PropertySource ps = FrozenPropertySource.of(myPS);
- assertNotNull(ps);
- for (Map.Entry<String, PropertyValue> e : myPS.getProperties().entrySet()) {
- assertEquals(ps.get(e.getKey()).getValue(), e.getValue().getValue());
- }
- }
-
- @Test
- public void testGetProperties() throws Exception {
- PropertySource ps = FrozenPropertySource.of(myPS);
- assertNotNull(ps);
- assertNotNull(ps.getProperties());
- assertFalse(ps.getProperties().isEmpty());
- }
-
- @Test
- public void testEquals() throws Exception {
- PropertySource ps1 = FrozenPropertySource.of(myPS);
- PropertySource ps2 = FrozenPropertySource.of(myPS);
- assertEquals(ps1.getName(), ps2.getName());
- assertEquals(ps1.getProperties().size(), ps2.getProperties().size());
- }
-
- @Test
- public void testHashCode() throws Exception {
- boolean alwaysDifferent = true;
- for(int i=0;i<10;i++){
- PropertySource ps1 = FrozenPropertySource.of(myPS);
- PropertySource ps2 = FrozenPropertySource.of(myPS);
- // sometimes not same, because frozenAt in ms maybe different
- if(ps1.hashCode()==ps2.hashCode()){
- alwaysDifferent=false;
- break;
- }
- }
- if(alwaysDifferent){
- fail("HashCode should be same if frozenAt is in the same ms...");
- }
- }
-
- @Test
- public void testToString() throws Exception {
- PropertySource ps = FrozenPropertySource.of(myPS);
- String toString = ps.toString();
- assertNotNull(toString);
- assertTrue(toString.contains("FrozenPropertySource"));
- assertTrue(toString.contains(myPS.getName()));
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/java/org/apache/tamaya/events/ObservedConfigTest.java
----------------------------------------------------------------------
diff --git a/modules/events/src/test/java/org/apache/tamaya/events/ObservedConfigTest.java b/modules/events/src/test/java/org/apache/tamaya/events/ObservedConfigTest.java
index da749c3..3d81fd1 100644
--- a/modules/events/src/test/java/org/apache/tamaya/events/ObservedConfigTest.java
+++ b/modules/events/src/test/java/org/apache/tamaya/events/ObservedConfigTest.java
@@ -40,8 +40,8 @@ public class ObservedConfigTest {
}
ConfigEvent<?> event = MyConfigObserver.event;
if(event!=null) {
- assertTrue(event instanceof ConfigurationChange);
- ConfigurationChange cChange = (ConfigurationChange) event;
+ assertTrue(event instanceof ConfigChange);
+ ConfigChange cChange = (ConfigChange) event;
if(cChange.isAdded("random.new")){
MyConfigObserver.event=null;
}else {
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/java/org/apache/tamaya/events/PropertySourceChangeTest.java
----------------------------------------------------------------------
diff --git a/modules/events/src/test/java/org/apache/tamaya/events/PropertySourceChangeTest.java b/modules/events/src/test/java/org/apache/tamaya/events/PropertySourceChangeTest.java
deleted file mode 100644
index a1a9200..0000000
--- a/modules/events/src/test/java/org/apache/tamaya/events/PropertySourceChangeTest.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.events;
-
-import org.apache.tamaya.spisupport.propertysource.EnvironmentPropertySource;
-import org.apache.tamaya.spisupport.propertysource.SimplePropertySource;
-import org.apache.tamaya.spisupport.propertysource.SystemPropertySource;
-import org.apache.tamaya.spi.PropertySource;
-import org.junit.Test;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.junit.Assert.*;
-
-/**
- * Tests for {@link PropertySourceChange} and its builder.
- */
-public class PropertySourceChangeTest {
-
- private static final PropertySource myPS = new SystemPropertySource();
-
- @Test
- public void testGetPropertySource() throws Exception {
- PropertySourceChange change = PropertySourceChangeBuilder.of(myPS).build();
- assertEquals(change.getResource().getName(), myPS.getName());
- }
-
- @Test
- public void testGetVersion() throws Exception {
- PropertySourceChange change = PropertySourceChangeBuilder.of(myPS)
- .setVersion("myVersion1").build();
- assertEquals(change.getVersion(), "myVersion1");
- }
-
- @Test
- public void testGetTimestamp() throws Exception {
- PropertySourceChange change = PropertySourceChangeBuilder.of(myPS)
- .setTimestamp(111L).build();
- assertEquals(change.getTimestamp(), 111L);
- }
-
- @Test
- public void testGetEvents() throws Exception {
- PropertySourceChange change = PropertySourceChangeBuilder.of(myPS)
- .addChanges(
- new EnvironmentPropertySource()
- ).build();
- assertTrue(change.getChanges().size()>0);
- }
-
- @Test
- public void testGetRemovedSize() throws Exception {
- PropertySourceChange change = PropertySourceChangeBuilder.of(myPS)
- .addChanges(
- new EnvironmentPropertySource()
- ).build();
- assertTrue(change.getRemovedSize()>0);
- }
-
- @Test
- public void testGetAddedSize() throws Exception {
- PropertySourceChange change = PropertySourceChangeBuilder.of(myPS)
- .addChanges(
- new EnvironmentPropertySource()
- ).build();
- assertTrue(change.getAddedSize()>0);
- }
-
- @Test
- public void testGetUpdatedSize() throws Exception {
- PropertySourceChange change = PropertySourceChangeBuilder.of(myPS)
- .addChanges(
- new EnvironmentPropertySource()
- ).build();
- assertTrue(change.getUpdatedSize()==0);
- }
-
- @Test
- public void testIsRemoved() throws Exception {
- Map<String, String> testData = new HashMap<>();
- testData.put("key1", "value1");
- testData.put("key2", "value2");
- PropertySource ps1 = new SimplePropertySource("test", testData);
- testData = new HashMap<>();
- testData.put("key1", "value2");
- testData.put("key3", "value3");
- PropertySource ps2 = new SimplePropertySource("test", testData);
- PropertySourceChange change = PropertySourceChangeBuilder.of(ps1)
- .addChanges(
- ps2
- ).build();
- assertFalse(change.isRemoved("key1"));
- assertTrue(change.isRemoved("key2"));
- assertFalse(change.isRemoved("key3"));
- }
-
- @Test
- public void testIsAdded() throws Exception {
- Map<String, String> testData = new HashMap<>();
- testData.put("key1", "value1");
- testData.put("key2", "value2");
- PropertySource ps1 = new SimplePropertySource("test", testData);
- testData = new HashMap<>();
- testData.put("key1", "value2");
- testData.put("key3", "value3");
- PropertySource ps2 = new SimplePropertySource("test", testData);
- PropertySourceChange change = PropertySourceChangeBuilder.of(ps1)
- .addChanges(
- ps2
- ).build();
- assertTrue(change.isAdded("key3"));
- assertFalse(change.isAdded("key2"));
- assertFalse(change.isAdded("key1"));
- }
-
- @Test
- public void testIsUpdated() throws Exception {
- Map<String, String> testData = new HashMap<>();
- testData.put("key1", "value1");
- testData.put("key2", "value2");
- PropertySource ps1 = new SimplePropertySource("test", testData);
- testData = new HashMap<>();
- testData.put("key1", "value2");
- testData.put("key3", "value3");
- PropertySource ps2 = new SimplePropertySource("test", testData);
- PropertySourceChange change = PropertySourceChangeBuilder.of(ps1)
- .addChanges(
- ps2
- ).build();
- assertTrue(change.isUpdated("key1"));
- assertFalse(change.isUpdated("key2"));
- assertFalse(change.isUpdated("key3"));
- }
-
- @Test
- public void testContainsKey() throws Exception {
- PropertySourceChange change = PropertySourceChangeBuilder.of(new EnvironmentPropertySource())
- .addChanges(
- myPS
- ).build();
- assertTrue(change.isKeyAffected("java.version"));
- }
-
- @Test
- public void testIsEmpty() throws Exception {
- PropertySourceChange change = PropertySourceChangeBuilder.of(new EnvironmentPropertySource())
- .build();
- assertTrue(change.isEmpty());
- change = PropertySourceChangeBuilder.of(new EnvironmentPropertySource())
- .addChanges(
- myPS
- ).build();
- assertFalse(change.isEmpty());
- }
-
- @Test
- public void testToString() throws Exception {
- PropertySourceChange change = PropertySourceChangeBuilder.of(myPS).build();
- String toString = change.toString();
- assertNotNull(toString);
- assertTrue(toString.contains(myPS.getName()));
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/java/org/apache/tamaya/events/RandomConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/events/src/test/java/org/apache/tamaya/events/RandomConfigSource.java b/modules/events/src/test/java/org/apache/tamaya/events/RandomConfigSource.java
new file mode 100644
index 0000000..8019037
--- /dev/null
+++ b/modules/events/src/test/java/org/apache/tamaya/events/RandomConfigSource.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.events;
+
+import javax.config.spi.ConfigSource;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * PropertySource that provides a random entry, different on each access!
+ */
+public class RandomConfigSource implements ConfigSource{
+
+ private Map<String, String> data = new HashMap<>();
+
+ @Override
+ public int getOrdinal() {
+ return 0;
+ }
+
+ @Override
+ public String getName() {
+ return "random";
+ }
+
+ @Override
+ public String getValue(String key) {
+ if(key.equals("random.new")){
+ return String.valueOf(Math.random());
+ }
+ return data.get(key);
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ synchronized(data) {
+ data.put("random.new", String.valueOf(Math.random()));
+ data.put("_random.new.timestamp", String.valueOf(System.currentTimeMillis()));
+ return new HashMap<>(data);
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/4869d946/modules/events/src/test/java/org/apache/tamaya/events/RandomPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/events/src/test/java/org/apache/tamaya/events/RandomPropertySource.java b/modules/events/src/test/java/org/apache/tamaya/events/RandomPropertySource.java
deleted file mode 100644
index 4faa1b5..0000000
--- a/modules/events/src/test/java/org/apache/tamaya/events/RandomPropertySource.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.events;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * PropertySource that provides a random entry, different on each access!
- */
-public class RandomPropertySource implements PropertySource{
-
- private Map<String, PropertyValue> data = new HashMap<>();
-
- @Override
- public int getOrdinal() {
- return 0;
- }
-
- @Override
- public String getName() {
- return "random";
- }
-
- @Override
- public PropertyValue get(String key) {
- if(key.equals("random.new")){
- return PropertyValue.of(key, String.valueOf(Math.random()),getName());
- }
- return null;
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
- synchronized(data) {
- data.put("random.new", PropertyValue.builder("random.new", String.valueOf(Math.random()), getName())
- .addMetaEntry("_random.new.timestamp", String.valueOf(System.currentTimeMillis())).build());
- return new HashMap<>(data);
- }
- }
-
- @Override
- public boolean isScannable() {
- return true;
- }
-}
[05/18] incubator-tamaya-extensions git commit: Adapted to comply
with JSR API, fixed bugs. Imrpved API regarding sections, section filtering.
Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/test/java/org/apache/tamaya/functions/EnrichedConfigSourceTest.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/test/java/org/apache/tamaya/functions/EnrichedConfigSourceTest.java b/modules/functions/src/test/java/org/apache/tamaya/functions/EnrichedConfigSourceTest.java
new file mode 100644
index 0000000..beb2390
--- /dev/null
+++ b/modules/functions/src/test/java/org/apache/tamaya/functions/EnrichedConfigSourceTest.java
@@ -0,0 +1,216 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.functions;
+
+import org.junit.Test;
+
+import javax.config.spi.ConfigSource;
+import java.util.HashMap;
+import java.util.Map;
+
+import static java.util.Collections.EMPTY_MAP;
+import static org.apache.tamaya.functions.MethodNotMockedAnswer.NOT_MOCKED_ANSWER;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+
+public class EnrichedConfigSourceTest {
+
+ /*
+ * Tests for getName()
+ */
+
+ @Test
+ public void getNameReturnsTheNameOfTheBaseConfiguration() {
+ ConfigSource propertySource = mock(ConfigSource.class, NOT_MOCKED_ANSWER);
+ doReturn("abc").when(propertySource).getName();
+
+ EnrichedConfigSource sut = new EnrichedConfigSource(propertySource, EMPTY_MAP, false);
+
+ String name = sut.getName();
+
+ assertThat(name).isEqualTo("abc");
+ }
+
+
+ /*
+ * Tests for getOrdinal()
+ */
+
+ @Test
+ public void getOrdinalReturnsTheValueOfTheBaseConfiguration() {
+ ConfigSource propertySource = mock(ConfigSource.class, NOT_MOCKED_ANSWER);
+ doReturn(13).when(propertySource).getOrdinal();
+
+ EnrichedConfigSource sut = new EnrichedConfigSource(propertySource, EMPTY_MAP, false);
+
+ int ordinal = sut.getOrdinal();
+
+ assertThat(ordinal).isEqualTo(13);
+ }
+
+ /*
+ * Tests for EnrichedConfigSource(ConfigSource, Map<String, String>, boolean)
+ */
+
+ /*
+ * Tests for get(String)
+ */
+
+ @Test
+ public void getReturnsAdditional() {
+ InMemoryConfigSource base = new InMemoryConfigSource();
+
+ base.setName("name").add("a", "1").add("b", "2").add("c", "3").add("d", "4");
+
+ Map<String, String> additions = new HashMap<>();
+ additions.put("e", "9");
+ additions.put("f", "11");
+
+ EnrichedConfigSource sut = new EnrichedConfigSource(base, additions, false);
+
+ assertThat(sut.getValue("e")).isNotNull().isNotNull().isEqualTo("9");
+ }
+
+ @Test
+ public void getReturnsOverriddenValue() {
+ InMemoryConfigSource base = new InMemoryConfigSource();
+
+ base.setName("name").add("a", "1").add("b", "2").add("c", "3").add("d", "4");
+
+ Map<String, String> additions = new HashMap<>();
+ additions.put("b", "9");
+ additions.put("d", "11");
+
+ EnrichedConfigSource sut = new EnrichedConfigSource(base, additions, true);
+
+ String result = sut.getValue("b");
+
+ assertThat(result).isNotNull().isEqualTo("9");
+ }
+
+ @Test
+ public void getReturnsGivenValueWhichIsNotOverridden() {
+ InMemoryConfigSource base = new InMemoryConfigSource();
+
+ base.setName("name").add("a", "1").add("b", "2").add("c", "3").add("d", "4");
+
+ Map<String, String> additions = new HashMap<>();
+ additions.put("b", "9");
+ additions.put("d", "11");
+
+ EnrichedConfigSource sut = new EnrichedConfigSource(base, additions, true);
+
+ String result = sut.getValue("a");
+
+ assertThat(result).isNotNull().isEqualTo("1");
+ }
+
+ @Test
+ public void getPropertiesReturnsNotOverriddenValue() {
+ InMemoryConfigSource base = new InMemoryConfigSource();
+
+ base.setName("name").add("a", "1").add("b", "2").add("c", "3").add("d", "4");
+
+ Map<String, String> additions = new HashMap<>();
+ additions.put("b", "9");
+ additions.put("d", "11");
+
+ EnrichedConfigSource sut = new EnrichedConfigSource(base, additions, false);
+
+ String result = sut.getValue("b");
+
+ assertThat(result).isNotNull().isEqualTo("2");
+ }
+
+
+ /*
+ * Tests for getProperties()
+ */
+
+ @Test
+ public void getPropertiesReturnsAllAdditionalToo() {
+ InMemoryConfigSource base = new InMemoryConfigSource();
+
+ base.setName("name").add("a", "1").add("b", "2").add("c", "3").add("d", "4");
+
+ Map<String, String> additions = new HashMap<>();
+ additions.put("e", "9");
+ additions.put("f", "11");
+
+ EnrichedConfigSource sut = new EnrichedConfigSource(base, additions, false);
+
+ Map<String, String> properties = sut.getProperties();
+
+ assertThat(properties).isNotNull().isNotEmpty()
+ .containsEntry("a", "1")
+ .containsEntry("b", "2")
+ .containsEntry("c", "3")
+ .containsEntry("d", "4")
+ .containsEntry("e", "9")
+ .containsEntry("f", "11")
+ .hasSize(6);
+ }
+
+ @Test
+ public void getPropertiesReturnsAllWithOverriddenValues() {
+ InMemoryConfigSource base = new InMemoryConfigSource();
+
+ base.setName("name").add("a", "1").add("b", "2").add("c", "3").add("d", "4");
+
+ Map<String, String> additions = new HashMap<>();
+ additions.put("b", "9");
+ additions.put("d", "11");
+
+ EnrichedConfigSource sut = new EnrichedConfigSource(base, additions, true);
+
+ Map<String, String> properties = sut.getProperties();
+
+ assertThat(properties).isNotNull().isNotEmpty()
+ .containsEntry("a", "1")
+ .containsEntry("b", "9")
+ .containsEntry("c", "3")
+ .containsEntry("d", "11")
+ .hasSize(4);
+
+ }
+
+ @Test
+ public void getPropertiesReturnsAllNoOverriddenValues() {
+ InMemoryConfigSource base = new InMemoryConfigSource();
+
+ base.setName("name").add("a", "1").add("b", "2").add("c", "3").add("d", "4");
+
+ Map<String, String> additions = new HashMap<>();
+ additions.put("b", "9");
+ additions.put("d", "11");
+
+ EnrichedConfigSource sut = new EnrichedConfigSource(base, additions, false);
+
+ Map<String, String> properties = sut.getProperties();
+
+ assertThat(properties).isNotNull().isNotEmpty()
+ .containsEntry("a", "1")
+ .containsEntry("b", "2")
+ .containsEntry("c", "3")
+ .containsEntry("d", "4")
+ .hasSize(4);
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/test/java/org/apache/tamaya/functions/EnrichedConfigurationTest.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/test/java/org/apache/tamaya/functions/EnrichedConfigurationTest.java b/modules/functions/src/test/java/org/apache/tamaya/functions/EnrichedConfigurationTest.java
index 6134144..5bb3eb4 100644
--- a/modules/functions/src/test/java/org/apache/tamaya/functions/EnrichedConfigurationTest.java
+++ b/modules/functions/src/test/java/org/apache/tamaya/functions/EnrichedConfigurationTest.java
@@ -18,11 +18,7 @@
*/
package org.apache.tamaya.functions;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.TypeLiteral;
-import org.assertj.core.api.Assertions;
import org.assertj.core.api.ThrowableAssert;
-import org.junit.Ignore;
import org.junit.Test;
import javax.config.Config;
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/test/java/org/apache/tamaya/functions/EnrichedPropertySourceTest.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/test/java/org/apache/tamaya/functions/EnrichedPropertySourceTest.java b/modules/functions/src/test/java/org/apache/tamaya/functions/EnrichedPropertySourceTest.java
deleted file mode 100644
index 563a986..0000000
--- a/modules/functions/src/test/java/org/apache/tamaya/functions/EnrichedPropertySourceTest.java
+++ /dev/null
@@ -1,250 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.functions;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-import org.junit.Test;
-
-import javax.management.RuntimeMBeanException;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-import static java.util.Collections.EMPTY_MAP;
-import static org.apache.tamaya.functions.MethodNotMockedAnswer.NOT_MOCKED_ANSWER;
-import static org.apache.tamaya.spi.PropertyValue.of;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
-public class EnrichedPropertySourceTest {
-
- /*
- * Tests for getName()
- */
-
- @Test
- public void getNameReturnsTheNameOfTheBaseConfiguration() {
- PropertySource propertySource = mock(PropertySource.class, NOT_MOCKED_ANSWER);
- doReturn("abc").when(propertySource).getName();
-
- EnrichedPropertySource sut = new EnrichedPropertySource(propertySource, EMPTY_MAP, false);
-
- String name = sut.getName();
-
- assertThat(name).isEqualTo("abc");
- }
-
-
- /*
- * Tests for getOrdinal()
- */
-
- @Test
- public void getOrdinalReturnsTheValueOfTheBaseConfiguration() {
- PropertySource propertySource = mock(PropertySource.class, NOT_MOCKED_ANSWER);
- doReturn(13).when(propertySource).getOrdinal();
-
- EnrichedPropertySource sut = new EnrichedPropertySource(propertySource, EMPTY_MAP, false);
-
- int ordinal = sut.getOrdinal();
-
- assertThat(ordinal).isEqualTo(13);
- }
-
- /*
- * Tests for EnrichedPropertySource(PropertySource, Map<String, String>, boolean)
- */
-
- /*
- * Tests for get(String)
- */
-
- @Test
- public void getReturnsAdditional() {
- InMemoryPropertySource base = new InMemoryPropertySource();
-
- base.setName("name").add("a", "1").add("b", "2").add("c", "3").add("d", "4");
-
- Map<String, String> additions = new HashMap<>();
- additions.put("e", "9");
- additions.put("f", "11");
-
- EnrichedPropertySource sut = new EnrichedPropertySource(base, additions, false);
-
- PropertyValue result = sut.get("e");
-
- assertThat(result).isNotNull().isNotNull().isEqualTo(of("e", "9", "name"));
- }
-
- @Test
- public void getReturnsOverriddenValue() {
- InMemoryPropertySource base = new InMemoryPropertySource();
-
- base.setName("name").add("a", "1").add("b", "2").add("c", "3").add("d", "4");
-
- Map<String, String> additions = new HashMap<>();
- additions.put("b", "9");
- additions.put("d", "11");
-
- EnrichedPropertySource sut = new EnrichedPropertySource(base, additions, true);
-
- PropertyValue result = sut.get("b");
-
- assertThat(result).isNotNull().isEqualTo(of("b", "9", "name"));
- }
-
- @Test
- public void getReturnsGivenValueWhichIsNotOverridden() {
- InMemoryPropertySource base = new InMemoryPropertySource();
-
- base.setName("name").add("a", "1").add("b", "2").add("c", "3").add("d", "4");
-
- Map<String, String> additions = new HashMap<>();
- additions.put("b", "9");
- additions.put("d", "11");
-
- EnrichedPropertySource sut = new EnrichedPropertySource(base, additions, true);
-
- PropertyValue result = sut.get("a");
-
- assertThat(result).isNotNull().isEqualTo(of("a", "1", "name"));
- }
-
- @Test
- public void getPropertiesReturnsNotOverriddenValue() {
- InMemoryPropertySource base = new InMemoryPropertySource();
-
- base.setName("name").add("a", "1").add("b", "2").add("c", "3").add("d", "4");
-
- Map<String, String> additions = new HashMap<>();
- additions.put("b", "9");
- additions.put("d", "11");
-
- EnrichedPropertySource sut = new EnrichedPropertySource(base, additions, false);
-
- PropertyValue result = sut.get("b");
-
- assertThat(result).isNotNull().isEqualTo(of("b", "2", "name"));
- }
-
-
- /*
- * Tests for getProperties()
- */
-
- @Test
- public void getPropertiesReturnsAllAdditionalToo() {
- InMemoryPropertySource base = new InMemoryPropertySource();
-
- base.setName("name").add("a", "1").add("b", "2").add("c", "3").add("d", "4");
-
- Map<String, String> additions = new HashMap<>();
- additions.put("e", "9");
- additions.put("f", "11");
-
- EnrichedPropertySource sut = new EnrichedPropertySource(base, additions, false);
-
- Map<String, PropertyValue> properties = sut.getProperties();
-
- assertThat(properties).isNotNull().isNotEmpty()
- .containsEntry("a", of("a", "1", "name"))
- .containsEntry("b", of("b", "2", "name"))
- .containsEntry("c", of("c", "3", "name"))
- .containsEntry("d", of("d", "4", "name"))
- .containsEntry("e", of("e", "9", "name"))
- .containsEntry("f", of("f", "11", "name"))
- .hasSize(6);
- }
-
- @Test
- public void getPropertiesReturnsAllWithOverriddenValues() {
- InMemoryPropertySource base = new InMemoryPropertySource();
-
- base.setName("name").add("a", "1").add("b", "2").add("c", "3").add("d", "4");
-
- Map<String, String> additions = new HashMap<>();
- additions.put("b", "9");
- additions.put("d", "11");
-
- EnrichedPropertySource sut = new EnrichedPropertySource(base, additions, true);
-
- Map<String, PropertyValue> properties = sut.getProperties();
-
- assertThat(properties).isNotNull().isNotEmpty()
- .containsEntry("a", of("a", "1", "name"))
- .containsEntry("b", of("b", "9", "name"))
- .containsEntry("c", of("c", "3", "name"))
- .containsEntry("d", of("d", "11", "name"))
- .hasSize(4);
-
- }
-
- @Test
- public void getPropertiesReturnsAllNoOverriddenValues() {
- InMemoryPropertySource base = new InMemoryPropertySource();
-
- base.setName("name").add("a", "1").add("b", "2").add("c", "3").add("d", "4");
-
- Map<String, String> additions = new HashMap<>();
- additions.put("b", "9");
- additions.put("d", "11");
-
- EnrichedPropertySource sut = new EnrichedPropertySource(base, additions, false);
-
- Map<String, PropertyValue> properties = sut.getProperties();
-
- assertThat(properties).isNotNull().isNotEmpty()
- .containsEntry("a", of("a", "1", "name"))
- .containsEntry("b", of("b", "2", "name"))
- .containsEntry("c", of("c", "3", "name"))
- .containsEntry("d", of("d", "4", "name"))
- .hasSize(4);
- }
-
- /*
- * Tests for isScannable()
- */
-
- @Test
- public void isScannableReturnsTheValueOfTheBaseConfigurationWhichIsTrue() {
- PropertySource propertySource = mock(PropertySource.class, NOT_MOCKED_ANSWER);
- doReturn(true).when(propertySource).isScannable();
-
- EnrichedPropertySource sut = new EnrichedPropertySource(propertySource, EMPTY_MAP, false);
-
- boolean isScannable = sut.isScannable();
-
- assertThat(isScannable).isEqualTo(true);
- }
-
- @Test
- public void isScannableReturnsTheValueOfTheBaseConfigurationWhichIsFalse() {
- PropertySource propertySource = mock(PropertySource.class, NOT_MOCKED_ANSWER);
- doReturn(false).when(propertySource).isScannable();
-
- EnrichedPropertySource sut = new EnrichedPropertySource(propertySource, EMPTY_MAP, false);
-
- boolean isScannable = sut.isScannable();
-
- assertThat(isScannable).isEqualTo(false);
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/test/java/org/apache/tamaya/functions/FilteredConfigSourceTest.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/test/java/org/apache/tamaya/functions/FilteredConfigSourceTest.java b/modules/functions/src/test/java/org/apache/tamaya/functions/FilteredConfigSourceTest.java
new file mode 100644
index 0000000..65e08f5
--- /dev/null
+++ b/modules/functions/src/test/java/org/apache/tamaya/functions/FilteredConfigSourceTest.java
@@ -0,0 +1,188 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.functions;
+
+import org.junit.Test;
+
+import javax.config.spi.ConfigSource;
+
+import static org.apache.tamaya.functions.MethodNotMockedAnswer.NOT_MOCKED_ANSWER;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+
+public class FilteredConfigSourceTest {
+
+ /*
+ * Tests for getName()
+ */
+
+ @Test
+ public void getNameReturnsTheNameOfTheBaseConfiguration() {
+ ConfigSource propertySource = mock(ConfigSource.class, NOT_MOCKED_ANSWER);
+ doReturn("abc").when(propertySource).getName();
+
+ Predicate<String> filter = new Predicate<String>() {
+ @Override
+ public boolean test(String s) {
+ return false;
+ }
+ };
+
+ FilteredConfigSource sut = new FilteredConfigSource(propertySource, filter);
+
+ String name = sut.getName();
+
+ assertThat(name).isEqualTo("abc");
+ }
+
+ /*
+ * Tests for getOrdinal()
+ */
+
+ @Test
+ public void getOrdinalReturnsTheValueOfTheBaseConfiguration() {
+ ConfigSource propertySource = mock(ConfigSource.class, NOT_MOCKED_ANSWER);
+ doReturn(13).when(propertySource).getOrdinal();
+
+ Predicate<String> filter = new Predicate<String>() {
+ @Override
+ public boolean test(String s) {
+ return false;
+ }
+ };
+
+ FilteredConfigSource sut = new FilteredConfigSource(propertySource, filter);
+
+ int ordinal = sut.getOrdinal();
+
+ assertThat(ordinal).isEqualTo(13);
+ }
+
+ /*
+ * Tests for get(String)
+ */
+
+ @Test
+ public void getReturnsNullInsteadOfValueBecausOfFilter() {
+ ConfigSource propertySource = mock(ConfigSource.class, NOT_MOCKED_ANSWER);
+ doReturn("000").when(propertySource).getValue(eq("abc"));
+
+ Predicate<String> filter = new Predicate<String>() {
+ @Override
+ public boolean test(String s) {
+ return !"abc".equals(s);
+ }
+ };
+
+ FilteredConfigSource sut = new FilteredConfigSource(propertySource, filter);
+
+ String result = sut.getValue("abc");
+
+ assertThat(result).isNull();
+ }
+
+ @Test
+ public void getReturnsValueBecauseItIsNotFiltered() {
+ ConfigSource propertySource = mock(ConfigSource.class, NOT_MOCKED_ANSWER);
+ doReturn("000").when(propertySource).getValue(eq("abc"));
+
+ Predicate<String> filter = new Predicate<String>() {
+ @Override
+ public boolean test(String s) {
+ return true;
+ }
+ };
+
+ FilteredConfigSource sut = new FilteredConfigSource(propertySource, filter);
+
+ String result = sut.getValue("abc");
+
+ assertThat(result).isNotNull();
+ }
+
+ /*
+ * Tests for getProperties()
+ */
+
+ @Test
+ public void getPropertiesAndFilterRemovesAllProperties() {
+ InMemoryConfigSource imps = new InMemoryConfigSource();
+ imps.add("a", "1").add("b", "2").add("c", "3");
+ imps.setName("s");
+
+ Predicate<String> filter = new Predicate<String>() {
+ @Override
+ public boolean test(String s) {
+ return false;
+ }
+ };
+
+ FilteredConfigSource fps = new FilteredConfigSource(imps, filter);
+
+ assertThat(fps.getProperties()).isEmpty();;
+ }
+
+ @Test
+ public void getPropertiesAndFilterRemovesNoProperties() {
+ InMemoryConfigSource imps = new InMemoryConfigSource();
+ imps.add("a", "1").add("b", "2").add("c", "3");
+ imps.setName("s");
+
+ Predicate<String> filter = new Predicate<String>() {
+ @Override
+ public boolean test(String s) {
+ return true;
+ }
+ };
+
+ FilteredConfigSource fps = new FilteredConfigSource(imps, filter);
+
+ assertThat(fps.getProperties()).isNotEmpty()
+ .containsEntry("a", "1")
+ .containsEntry("b", "2")
+ .containsEntry("c","3")
+ .hasSize(3);
+ }
+
+ @Test
+ public void getPropertiesAndFilterRemovesSomeProperties() {
+ InMemoryConfigSource imps = new InMemoryConfigSource();
+ imps.add("a", "1").add("b", "2").add("c", "3");
+ imps.setName("s");
+
+ Predicate<String> filter = new Predicate<String>() {
+ @Override
+ public boolean test(String s) {
+ return !s.startsWith("a");
+ }
+ };
+
+ FilteredConfigSource fps = new FilteredConfigSource(imps, filter);
+
+ assertThat(fps.getProperties()).isNotEmpty()
+ .containsEntry("b", "2")
+ .containsEntry("c", "3")
+ .hasSize(2);
+
+ }
+
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/test/java/org/apache/tamaya/functions/FilteredPropertySourceTest.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/test/java/org/apache/tamaya/functions/FilteredPropertySourceTest.java b/modules/functions/src/test/java/org/apache/tamaya/functions/FilteredPropertySourceTest.java
deleted file mode 100644
index e86cbc5..0000000
--- a/modules/functions/src/test/java/org/apache/tamaya/functions/FilteredPropertySourceTest.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.functions;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-import org.junit.Test;
-
-import static org.apache.tamaya.functions.MethodNotMockedAnswer.NOT_MOCKED_ANSWER;
-import static org.apache.tamaya.spi.PropertyValue.of;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
-public class FilteredPropertySourceTest {
-
- /*
- * Tests for getName()
- */
-
- @Test
- public void getNameReturnsTheNameOfTheBaseConfiguration() {
- PropertySource propertySource = mock(PropertySource.class, NOT_MOCKED_ANSWER);
- doReturn("abc").when(propertySource).getName();
-
- Predicate<String> filter = new Predicate<String>() {
- @Override
- public boolean test(String s) {
- return false;
- }
- };
-
- FilteredPropertySource sut = new FilteredPropertySource(propertySource, filter);
-
- String name = sut.getName();
-
- assertThat(name).isEqualTo("abc");
- }
-
- /*
- * Tests for isScannable()
- */
-
- @Test
- public void isScannableReturnsTheValueOfTheBaseConfiguration() {
- PropertySource propertySource = mock(PropertySource.class, NOT_MOCKED_ANSWER);
- doReturn(true).when(propertySource).isScannable();
-
- Predicate<String> filter = new Predicate<String>() {
- @Override
- public boolean test(String s) {
- return false;
- }
- };
-
- FilteredPropertySource sut = new FilteredPropertySource(propertySource, filter);
-
- boolean isScannable = sut.isScannable();
-
- assertThat(isScannable).isEqualTo(true);
- }
-
- /*
- * Tests for getOrdinal()
- */
-
- @Test
- public void getOrdinalReturnsTheValueOfTheBaseConfiguration() {
- PropertySource propertySource = mock(PropertySource.class, NOT_MOCKED_ANSWER);
- doReturn(13).when(propertySource).getOrdinal();
-
- Predicate<String> filter = new Predicate<String>() {
- @Override
- public boolean test(String s) {
- return false;
- }
- };
-
- FilteredPropertySource sut = new FilteredPropertySource(propertySource, filter);
-
- int ordinal = sut.getOrdinal();
-
- assertThat(ordinal).isEqualTo(13);
- }
-
- /*
- * Tests for get(String)
- */
-
- @Test
- public void getReturnsNullInsteadOfValueBecausOfFilter() {
- PropertyValue pv = of("abc", "000", "UT");
- PropertySource propertySource = mock(PropertySource.class, NOT_MOCKED_ANSWER);
- doReturn(pv).when(propertySource).get(eq("abc"));
-
- Predicate<String> filter = new Predicate<String>() {
- @Override
- public boolean test(String s) {
- return !"abc".equals(s);
- }
- };
-
- FilteredPropertySource sut = new FilteredPropertySource(propertySource, filter);
-
- PropertyValue result = sut.get("abc");
-
- assertThat(result).isNull();
- }
-
- @Test
- public void getReturnsValueBecauseItIsNotFiltered() {
- PropertyValue pv = of("abc", "000", "UT");
- PropertySource propertySource = mock(PropertySource.class, NOT_MOCKED_ANSWER);
- doReturn(pv).when(propertySource).get(eq("abc"));
-
- Predicate<String> filter = new Predicate<String>() {
- @Override
- public boolean test(String s) {
- return true;
- }
- };
-
- FilteredPropertySource sut = new FilteredPropertySource(propertySource, filter);
-
- PropertyValue result = sut.get("abc");
-
- assertThat(result).isNotNull();
- }
-
- /*
- * Tests for getProperties()
- */
-
- @Test
- public void getPropertiesAndFilterRemovesAllProperties() {
- InMemoryPropertySource imps = new InMemoryPropertySource();
- imps.add("a", "1").add("b", "2").add("c", "3");
- imps.setName("s");
-
- Predicate<String> filter = new Predicate<String>() {
- @Override
- public boolean test(String s) {
- return false;
- }
- };
-
- FilteredPropertySource fps = new FilteredPropertySource(imps, filter);
-
- assertThat(fps.getProperties()).isEmpty();;
- }
-
- @Test
- public void getPropertiesAndFilterRemovesNoProperties() {
- InMemoryPropertySource imps = new InMemoryPropertySource();
- imps.add("a", "1").add("b", "2").add("c", "3");
- imps.setName("s");
-
- Predicate<String> filter = new Predicate<String>() {
- @Override
- public boolean test(String s) {
- return true;
- }
- };
-
- FilteredPropertySource fps = new FilteredPropertySource(imps, filter);
-
- assertThat(fps.getProperties()).isNotEmpty()
- .containsEntry("a", of("a", "1", "s"))
- .containsEntry("b", of("b", "2", "s"))
- .containsEntry("c", of("c", "3", "s"))
- .hasSize(3);
- }
-
- @Test
- public void getPropertiesAndFilterRemovesSomeProperties() {
- InMemoryPropertySource imps = new InMemoryPropertySource();
- imps.add("a", "1").add("b", "2").add("c", "3");
- imps.setName("s");
-
- Predicate<String> filter = new Predicate<String>() {
- @Override
- public boolean test(String s) {
- return !s.startsWith("a");
- }
- };
-
- FilteredPropertySource fps = new FilteredPropertySource(imps, filter);
-
- assertThat(fps.getProperties()).isNotEmpty()
- .containsEntry("b", of("b", "2", "s"))
- .containsEntry("c", of("c", "3", "s"))
- .hasSize(2);
-
- }
-
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/test/java/org/apache/tamaya/functions/InMemoryConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/test/java/org/apache/tamaya/functions/InMemoryConfigSource.java b/modules/functions/src/test/java/org/apache/tamaya/functions/InMemoryConfigSource.java
new file mode 100644
index 0000000..c22c108
--- /dev/null
+++ b/modules/functions/src/test/java/org/apache/tamaya/functions/InMemoryConfigSource.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.functions;
+
+import javax.config.spi.ConfigSource;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+public class InMemoryConfigSource implements ConfigSource {
+ private int ordinal;
+ private String name;
+ private Map<String, String> properties = new HashMap<>();
+ private boolean isScannable;
+
+ @Override
+ public int getOrdinal() {
+ return ordinal;
+ }
+
+ public void setOrdinal(int ordinal) {
+ this.ordinal = ordinal;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ public InMemoryConfigSource setName(String name) {
+ this.name = name;
+
+ return this;
+ }
+
+ @Override
+ public String getValue(String key) {
+ return properties.get(key);
+ }
+
+ public InMemoryConfigSource add(String key, String value) {
+ properties.put(key, value);
+
+ return this;
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ return Collections.unmodifiableMap(properties);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/test/java/org/apache/tamaya/functions/InMemoryConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/test/java/org/apache/tamaya/functions/InMemoryConfiguration.java b/modules/functions/src/test/java/org/apache/tamaya/functions/InMemoryConfiguration.java
deleted file mode 100644
index deb544c..0000000
--- a/modules/functions/src/test/java/org/apache/tamaya/functions/InMemoryConfiguration.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.functions;
-
-import org.apache.tamaya.spi.ConfigurationContext;
-import org.apache.tamaya.spisupport.DefaultConfiguration;
-
-class InMemoryConfiguration extends DefaultConfiguration {
- public InMemoryConfiguration(ConfigurationContext configurationContext) {
- super(configurationContext);
- }
- // private Map<String, String> entries = new TreeMap<>();
-
-// public InMemoryConfiguration addEntry(String key, String value) {
-// entries.put(key, value);
-//
-// return this;
-// }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/test/java/org/apache/tamaya/functions/InMemoryPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/test/java/org/apache/tamaya/functions/InMemoryPropertySource.java b/modules/functions/src/test/java/org/apache/tamaya/functions/InMemoryPropertySource.java
deleted file mode 100644
index 77ad378..0000000
--- a/modules/functions/src/test/java/org/apache/tamaya/functions/InMemoryPropertySource.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.functions;
-
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-
-import java.util.HashMap;
-import java.util.Map;
-
-public class InMemoryPropertySource implements PropertySource {
- private int ordinal;
- private String name;
- private Map<String, String> properties = new HashMap<>();
- private boolean isScannable;
-
- @Override
- public int getOrdinal() {
- return ordinal;
- }
-
- public void setOrdinal(int ordinal) {
- this.ordinal = ordinal;
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- public InMemoryPropertySource setName(String name) {
- this.name = name;
-
- return this;
- }
-
- @Override
- public PropertyValue get(String key) {
- String value = properties.get(key);
-
- return PropertyValue.of(key, value, getName());
- }
-
- public InMemoryPropertySource add(String key, String value) {
- properties.put(key, value);
-
- return this;
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
- Map<String, PropertyValue> result = new HashMap<>();
-
- for (Map.Entry<String, String> entry : properties.entrySet()) {
- PropertyValue value = PropertyValue.of(entry.getKey(), entry.getValue(), getName());
- result.put(entry.getKey(), value);
- }
-
- return result;
- }
-
- @Override
- public boolean isScannable() {
- return isScannable;
- }
-
- public void setScannable(boolean scannable) {
- isScannable = scannable;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/test/java/org/apache/tamaya/functions/MappedConfigSourceTest.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/test/java/org/apache/tamaya/functions/MappedConfigSourceTest.java b/modules/functions/src/test/java/org/apache/tamaya/functions/MappedConfigSourceTest.java
new file mode 100644
index 0000000..f0dd3ed
--- /dev/null
+++ b/modules/functions/src/test/java/org/apache/tamaya/functions/MappedConfigSourceTest.java
@@ -0,0 +1,159 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.functions;
+
+import org.junit.Test;
+
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class MappedConfigSourceTest {
+ private static final KeyMapper KEY_MAPPER = new KeyMapper() {
+ @Override
+ public String mapKey(String key) {
+ String result = key;
+
+ if ("M".compareTo(key.toUpperCase()) <= 0) {
+ result = key.toUpperCase();
+ }
+
+ return result;
+ }
+ };
+
+ /*
+ * Tests for getProperties()
+ */
+
+ @Test
+ public void getPropertiesWithMappedKeys() {
+ InMemoryConfigSource propertySource = new InMemoryConfigSource();
+ propertySource.setName("PS");
+ propertySource.add("a", "1");
+ propertySource.add("b", "2");
+ propertySource.add("m", "3");
+
+ MappedConfigSource mappedConfigSource = new MappedConfigSource(propertySource, KEY_MAPPER);
+
+ Map<String, String> result = mappedConfigSource.getProperties();
+
+ assertThat(result).isNotNull()
+ .containsEntry("a", "1")
+ .containsEntry("b", "2")
+ .containsEntry("M", "3")
+ .hasSize(3);
+ }
+
+ @Test
+ public void getPropertiesWithoutMappedKeys() {
+ InMemoryConfigSource propertySource = new InMemoryConfigSource();
+ propertySource.setName("PS");
+ propertySource.add("a", "1");
+ propertySource.add("b", "2");
+ propertySource.add("c", "3");
+
+ MappedConfigSource mappedConfigSource = new MappedConfigSource(propertySource, KEY_MAPPER);
+
+ Map<String, String> result = mappedConfigSource.getProperties();
+
+ assertThat(result).isNotNull()
+ .containsEntry("a", "1")
+ .containsEntry("b", "2")
+ .containsEntry("c", "3")
+ .hasSize(3);
+ }
+
+ @Test
+ public void getPropertiesMapperDiscardsOneKey() {
+ InMemoryConfigSource propertySource = new InMemoryConfigSource();
+ propertySource.setName("PS");
+ propertySource.add("a", "1");
+ propertySource.add("b", "2");
+ propertySource.add("c", "3");
+
+ MappedConfigSource mappedConfigSource = new MappedConfigSource(propertySource, new KeyMapper() {
+ @Override
+ public String mapKey(String key) {
+ return "c".equals(key) ? null : key;
+ }
+ });
+
+ Map<String, String> result = mappedConfigSource.getProperties();
+
+ assertThat(result).isNotNull()
+ .containsEntry("a", "1")
+ .containsEntry("b", "2")
+ .hasSize(2);
+ }
+
+ @Test
+ public void getPropertiesAndNoKeys() {
+ InMemoryConfigSource propertySource = new InMemoryConfigSource();
+ propertySource.setName("PS");
+
+ MappedConfigSource mappedConfigSource = new MappedConfigSource(propertySource, KEY_MAPPER);
+
+ Map<String, String> result = mappedConfigSource.getProperties();
+
+ assertThat(result).isNotNull()
+ .isEmpty();
+ }
+
+ /*
+ * Test for getOrdinal()
+ */
+
+ @Test
+ public void getOrdinalReturnsCorrectOrdinal() {
+ InMemoryConfigSource propertySource = new InMemoryConfigSource();
+ MappedConfigSource mappedConfigSource = new MappedConfigSource(propertySource, KEY_MAPPER);
+
+ propertySource.setOrdinal(999);
+
+ assertThat(mappedConfigSource.getOrdinal()).isEqualTo(999);
+ }
+
+ /*
+ * Tests for get(String)
+ */
+
+ @Test
+ public void getReturnsNullIfKeyIsNotInUnderlayingConfiguration() {
+ InMemoryConfigSource propertySource = new InMemoryConfigSource();
+ MappedConfigSource mappedConfigSource = new MappedConfigSource(propertySource, KEY_MAPPER);
+
+ assertThat(mappedConfigSource.getValue("nonexisting")).isNull();
+ }
+
+ @Test
+ public void getReturnsCorrectValueIfKeyIsMapped() {
+ InMemoryConfigSource propertySource = new InMemoryConfigSource();
+ propertySource.add("m", "_a_");
+ propertySource.setName("PS");
+
+ MappedConfigSource mappedConfigSource = new MappedConfigSource(propertySource, KEY_MAPPER);
+
+ assertThat(mappedConfigSource.getValue("M")).isNotNull().isEqualTo("_a_");
+ }
+
+
+
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/test/java/org/apache/tamaya/functions/MappedPropertySourceTest.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/test/java/org/apache/tamaya/functions/MappedPropertySourceTest.java b/modules/functions/src/test/java/org/apache/tamaya/functions/MappedPropertySourceTest.java
deleted file mode 100644
index 56c8921..0000000
--- a/modules/functions/src/test/java/org/apache/tamaya/functions/MappedPropertySourceTest.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.functions;
-
-import org.apache.tamaya.spi.PropertyValue;
-import org.junit.Test;
-
-import javax.management.ImmutableDescriptor;
-import java.util.Map;
-
-import static org.apache.tamaya.spi.PropertyValue.of;
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class MappedPropertySourceTest {
- private static final KeyMapper KEY_MAPPER = new KeyMapper() {
- @Override
- public String mapKey(String key) {
- String result = key;
-
- if ("M".compareTo(key.toUpperCase()) <= 0) {
- result = key.toUpperCase();
- }
-
- return result;
- }
- };
-
- /*
- * Tests for getProperties()
- */
-
- @Test
- public void getPropertiesWithMappedKeys() {
- InMemoryPropertySource propertySource = new InMemoryPropertySource();
- propertySource.setName("PS");
- propertySource.add("a", "1");
- propertySource.add("b", "2");
- propertySource.add("m", "3");
-
- MappedPropertySource mappedPropertySource = new MappedPropertySource(propertySource, KEY_MAPPER);
-
- Map<String, PropertyValue> result = mappedPropertySource.getProperties();
-
- assertThat(result).isNotNull()
- .containsEntry("a", of("a", "1", "PS[mapped]"))
- .containsEntry("b", of("b", "2", "PS[mapped]"))
- .containsEntry("M", of("M", "3", "PS[mapped]"))
- .hasSize(3);
- }
-
- @Test
- public void getPropertiesWithoutMappedKeys() {
- InMemoryPropertySource propertySource = new InMemoryPropertySource();
- propertySource.setName("PS");
- propertySource.add("a", "1");
- propertySource.add("b", "2");
- propertySource.add("c", "3");
-
- MappedPropertySource mappedPropertySource = new MappedPropertySource(propertySource, KEY_MAPPER);
-
- Map<String, PropertyValue> result = mappedPropertySource.getProperties();
-
- assertThat(result).isNotNull()
- .containsEntry("a", of("a", "1", "PS[mapped]"))
- .containsEntry("b", of("b", "2", "PS[mapped]"))
- .containsEntry("c", of("c", "3", "PS[mapped]"))
- .hasSize(3);
- }
-
- @Test
- public void getPropertiesMapperDiscardsOneKey() {
- InMemoryPropertySource propertySource = new InMemoryPropertySource();
- propertySource.setName("PS");
- propertySource.add("a", "1");
- propertySource.add("b", "2");
- propertySource.add("c", "3");
-
- MappedPropertySource mappedPropertySource = new MappedPropertySource(propertySource, new KeyMapper() {
- @Override
- public String mapKey(String key) {
- return "c".equals(key) ? null : key;
- }
- });
-
- Map<String, PropertyValue> result = mappedPropertySource.getProperties();
-
- assertThat(result).isNotNull()
- .containsEntry("a", of("a", "1", "PS[mapped]"))
- .containsEntry("b", of("b", "2", "PS[mapped]"))
- .hasSize(2);
- }
-
- @Test
- public void getPropertiesAndNoKeys() {
- InMemoryPropertySource propertySource = new InMemoryPropertySource();
- propertySource.setName("PS");
-
- MappedPropertySource mappedPropertySource = new MappedPropertySource(propertySource, KEY_MAPPER);
-
- Map<String, PropertyValue> result = mappedPropertySource.getProperties();
-
- assertThat(result).isNotNull()
- .isEmpty();
- }
-
- /*
- * Test for getOrdinal()
- */
-
- @Test
- public void getOrdinalReturnsCorrectOrdinal() {
- InMemoryPropertySource propertySource = new InMemoryPropertySource();
- MappedPropertySource mappedPropertySource = new MappedPropertySource(propertySource, KEY_MAPPER);
-
- propertySource.setOrdinal(999);
-
- assertThat(mappedPropertySource.getOrdinal()).isEqualTo(999);
- }
-
- /*
- * Tests for isScannable()
- */
-
- @Test
- public void isScannableReturnsTrueIfIsTrue() {
- InMemoryPropertySource propertySource = new InMemoryPropertySource();
- MappedPropertySource mappedPropertySource = new MappedPropertySource(propertySource, KEY_MAPPER);
-
- propertySource.setScannable(false);
-
- assertThat(mappedPropertySource.isScannable()).isFalse();
- }
-
- /*
- * Tests for get(String)
- */
-
- @Test
- public void getReturnsNullIfKeyIsNotInUnderlayingConfiguration() {
- InMemoryPropertySource propertySource = new InMemoryPropertySource();
- MappedPropertySource mappedPropertySource = new MappedPropertySource(propertySource, KEY_MAPPER);
-
- assertThat(mappedPropertySource.get("nonexisting")).isNull();
- }
-
- @Test
- public void getReturnsCorrectValueIfKeyIsMapped() {
- InMemoryPropertySource propertySource = new InMemoryPropertySource();
- propertySource.add("m", "_a_");
- propertySource.setName("PS");
-
- MappedPropertySource mappedPropertySource = new MappedPropertySource(propertySource, KEY_MAPPER);
-
- assertThat(mappedPropertySource.get("M")).isNotNull().isEqualTo(of("M", "_a_", "PS[mapped]"));
- }
-
-
-
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/test/java/org/apache/tamaya/functions/PropertySourceFunctionsTest.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/test/java/org/apache/tamaya/functions/PropertySourceFunctionsTest.java b/modules/functions/src/test/java/org/apache/tamaya/functions/PropertySourceFunctionsTest.java
deleted file mode 100644
index aa51135..0000000
--- a/modules/functions/src/test/java/org/apache/tamaya/functions/PropertySourceFunctionsTest.java
+++ /dev/null
@@ -1,367 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.functions;
-
-import org.apache.tamaya.functions.PropertySourceFunctions;
-import org.apache.tamaya.spi.PropertySource;
-import org.assertj.core.api.ThrowableAssert;
-import org.assertj.core.description.TextDescription;
-import org.junit.Ignore;
-import org.junit.Test;
-
-import java.util.HashMap;
-import java.util.Set;
-
-import static org.apache.tamaya.functions.PropertySourceFunctions.*;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-
-public class PropertySourceFunctionsTest {
-
- @Ignore
- @Test
- public void testAddMetaData() throws Exception {
- throw new RuntimeException("Not implement or look at me!");
- }
-
- /*
- * Tests for isKeyInSection(String, String)
- */
-
- @Test
- public void isKeyInSectionThrowsNPEIfKeyIsNull() {
- assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- @Override
- public void call() throws Throwable {
- isKeyInSection("a.b.c", null);
- }
- }).isInstanceOf(NullPointerException.class)
- .hasMessage("Section key must be given.");
- }
-
- @Test
- public void isKeyInSectionThrowsNPEIfSectionKeyIsNull() {
- assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- @Override
- public void call() throws Throwable {
- isKeyInSection(null, "a.b.c");
- }
- }).isInstanceOf(NullPointerException.class)
- .hasMessage("Key must be given.");
- }
-
- @Test
- public void isKeyInSectionForKeyInRootSection() {
- String key = "key";
- String sectionKey = "";
-
- boolean result = isKeyInSection(key, sectionKey);
-
- assertThat(result).describedAs("Key '%s' is in root section '%s'")
- .isTrue();
- }
-
- @Test
- public void isKeyInSectionForKeyInExplicitRootSection() {
- String key = "key";
- String sectionKey = ".";
-
- boolean result = isKeyInSection(key, sectionKey);
-
- assertThat(result).describedAs("Key '%s' is in root section '%s'")
- .isTrue();
- }
-
- @Test
- public void isKeyInSectionForKeyInSection() throws Exception {
- String key = "abc.def.g.h.key";
- String section = "abc.def.g.h";
-
- boolean result = isKeyInSection(key, section);
-
- assertThat(result).describedAs("Key %s is in section %s", key, section)
- .isTrue();
- }
-
- @Test
- public void isKeyInSectionForKeyNotInSection() throws Exception {
- String key = "abc.def.g.h.i.key";
- String section = "abc.def.g.h";
-
- boolean result = isKeyInSection(key, section);
-
- assertThat(result).describedAs("Key %s is not in section %s", key, section)
- .isFalse();
- }
-
- @Test
- public void isKeyInSectionIgnoresTrailingDotAtTheEndOfTheSection() throws Exception {
- String key = "abc.def.g.h.key";
- String section = "abc.def.g.h.";
-
- boolean result = isKeyInSection(key, section);
-
- assertThat(result).describedAs("Key %s is in section %s", key, section)
- .isTrue();
- }
-
-
- /*
- * Tests for isKeyInSections(String, String, String...)
- */
-
- @Test
- public void isKeyInSectionsStringStringStringVarargThrowsNPEIfKeyIsNull() {
- assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- @Override
- public void call() throws Throwable {
- isKeyInSections(null, "a.b.", "a.b", "b.c");
- }
- }).isInstanceOf(NullPointerException.class)
- .hasMessage("Key must be given.");
- }
-
- @Test
- public void isKeyInSectionsStringStringStringVarargsThrowsNPEIfFirstSectionIsNotGiven() {
- assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- @Override
- public void call() throws Throwable {
- isKeyInSections("key", (String)null, "a.b");
- }
- }).isInstanceOf(NullPointerException.class)
- .hasMessage("At least one section key must be given.");
- }
-
- @Test
- public void isKeyInSectionsStringStringStringVarargshrowsNPEIfMoreSectionKeysIsNull() {
- // null should not cause any problems
- boolean result = isKeyInSections("key", "l.b", (String) null);
-
- assertThat(result).isFalse();
- }
-
- @Test
- public void isKeyInSectionsStringStringStringVaragrsSectioOfKeyIsAtEndOfVarargs() {
- String section = "abc.def.";
- String key = section + "key";
-
- // null should not cause any problems
- boolean result = isKeyInSections(key, "l.b", null, "abc", section);
-
- assertThat(result).describedAs("Key '%s' is in section '%s'.", key, section).isTrue();
- }
-
- /*
- * Tests for isKeyInSections(String, String[])
- */
-
- @Test
- public void isKeyInSectionsStringStringStringArrayCopesWithEmptyArrayForMoreSectionKeys() {
- String key = "a.b.key";
- String first = "a.b";
-
- boolean result = isKeyInSections(key, first, new String[]{});
-
- assertThat(result).describedAs("Key '%s' is in section '%s'.", key, first)
- .isTrue();
- }
-
-
- /*
- * Tests for sections(Map<String, String>)
- */
-
- // null as parameter
-
- // empty as parameter
-
- // all keys in root section
-
- // some keys in packages
-
- @Test
- public void sectionsMapReturnsAllSectionsForGivenKeysInMap() {
- HashMap<String, String> kv = new HashMap<>();
-
- kv.put("abc.key", "v");
- kv.put("abc.def.key", "v");
- kv.put("a.key", "v");
- kv.put("b.key", "v");
- kv.put("key", "v");
-
- Set<String> result = sections(kv);
-
- assertThat(result).isNotNull()
- .isNotEmpty()
- .contains("abc", "abc.def", "a", "b", "<root>");
- }
-
- @Test
- public void sectionsMapTreatsLeadingDotAsOptional() {
- HashMap<String, String> kv = new HashMap<>();
-
- kv.put(".abc.key", "v");
- kv.put(".abc.def.key", "v");
- kv.put(".a.key", "v");
- kv.put(".b.key", "v");
- kv.put(".key", "v");
-
- Set<String> result = sections(kv);
-
- assertThat(result).isNotNull()
- .isNotEmpty()
- .contains("abc", "abc.def", "a", "b", "<root>");
- }
-
- /*
- * Tests for sections(Map<String, String> , Predicate<String>)
- */
-
- @Test
- public void sectionsMapPredicateFiltersAccordingToFilter() {
- HashMap<String, String> kv = new HashMap<>();
-
- kv.put(".abc.key", "v");
- kv.put(".abc.def.key", "v");
- kv.put(".a.key", "v");
- kv.put(".b.key", "v");
- kv.put(".key", "v");
-
- Set<String> result = sections(kv, new Predicate<String>() {
- @Override
- public boolean test(String s) {
- return !s.startsWith("a");
- }
- });
-
- assertThat(result).isNotNull()
- .isNotEmpty()
- .contains("b", "<root>");
- }
-
- /*
- * Tests for transitiveSections(Map<String, String>)
- */
-
- @Test
- public void bla() {
- HashMap<String, String> kv = new HashMap<>();
-
- kv.put(".abc.key", "v");
- kv.put(".abc.def.key", "v");
- kv.put(".abc.def.ghi.key", "v");
- kv.put(".a.key", "v");
- kv.put(".b.key", "v");
- kv.put(".key", "v");
-
- Set<String> result = transitiveSections(kv);
-
- for (String s : result) {
- System.out.println(s);
- }
-
-
- assertThat(result).isNotNull()
- .isNotEmpty()
- .contains("abc", "abc.def", "a", "b", "<root>");
-
-
- }
-
-
- //----
- @Ignore
- @Test
- public void testIsKeyInSections() throws Exception {
- throw new RuntimeException("Not implement or look at me!");
- }
-
- @Ignore
- @Test
- public void testSections() throws Exception {
- throw new RuntimeException("Not implement or look at me!");
- }
-
- @Ignore
- @Test
- public void testTransitiveSections() throws Exception {
- throw new RuntimeException("Not implement or look at me!");
- }
-
- @Ignore
- @Test
- public void testSections1() throws Exception {
- throw new RuntimeException("Not implement or look at me!");
- }
-
- @Ignore
- @Test
- public void testTransitiveSections1() throws Exception {
- throw new RuntimeException("Not implement or look at me!");
- }
-
- @Ignore
- @Test
- public void testSectionsRecursive() throws Exception {
- throw new RuntimeException("Not implement or look at me!");
- }
-
- @Ignore
- @Test
- public void testSectionRecursive() throws Exception {
- throw new RuntimeException("Not implement or look at me!");
- }
-
- @Ignore
- @Test
- public void testStripSectionKeys() throws Exception {
- throw new RuntimeException("Not implement or look at me!");
- }
-
- @Ignore
- @Test
- public void testAddItems() throws Exception {
- throw new RuntimeException("Not implement or look at me!");
- }
-
- @Ignore
- @Test
- public void testAddItems1() throws Exception {
- throw new RuntimeException("Not implement or look at me!");
- }
-
- @Ignore
- @Test
- public void testReplaceItems() throws Exception {
- throw new RuntimeException("Not implement or look at me!");
- }
-
- @Ignore
- @Test
- public void testEmptyPropertySource() throws Exception {
- PropertySource ps = PropertySourceFunctions.emptyPropertySource();
-// assertNotNull(ps);
-// assertNotNull(ps.getProperties());
-// assertTrue(ps.getProperties().isEmpty());
-// assertEquals(ps.getName(), "<empty>" );
-// assertTrue(ps.isScannable());
-
- throw new RuntimeException("Not implement or look at me!");
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/test/java/org/apache/tamaya/functions/ValueMappedConfigSourceTest.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/test/java/org/apache/tamaya/functions/ValueMappedConfigSourceTest.java b/modules/functions/src/test/java/org/apache/tamaya/functions/ValueMappedConfigSourceTest.java
new file mode 100644
index 0000000..f8126aa
--- /dev/null
+++ b/modules/functions/src/test/java/org/apache/tamaya/functions/ValueMappedConfigSourceTest.java
@@ -0,0 +1,148 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.functions;
+
+import org.junit.Test;
+
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class ValueMappedConfigSourceTest {
+
+ private PropertyMapper mapper = new PropertyMapper() {
+ @Override
+ public String mapProperty(String key, String value) {
+ String startOfOtherKey = key.toLowerCase().substring(0, 1);
+ if ("m".compareTo(startOfOtherKey) <= 0) {
+ return value + "m";
+ }
+
+ return value;
+ }
+ };
+
+ /*
+ * Tests for getOrdinal()
+ */
+
+ @Test
+ public void getOrdinalReturnsGivenOrdinal() throws Exception {
+ InMemoryConfigSource source = new InMemoryConfigSource();
+ source.add("a", "1").add("b", "2").add("c", "3").setName("S");
+ source.setOrdinal(99);
+
+ ValueMappedConfigSource mappingSource = new ValueMappedConfigSource("vmps", mapper, source);
+
+ assertThat(mappingSource.getOrdinal()).isEqualTo(99);
+ }
+
+ /*
+ * Tests for getName()
+ */
+
+ @Test
+ public void getNameReturnsGivenName() throws Exception {
+ InMemoryConfigSource source = new InMemoryConfigSource();
+ source.add("a", "1").add("b", "2").add("c", "3").setName("S");
+
+ ValueMappedConfigSource mappingSource = new ValueMappedConfigSource("vmps", mapper, source);
+
+ assertThat(mappingSource.getName()).isEqualTo("vmps");
+ }
+
+ /*
+ * Tests for get(String)
+ */
+
+ @Test
+ public void getReturnNullIfKeyIsNotInBasePropertySource() throws Exception {
+ InMemoryConfigSource source = new InMemoryConfigSource();
+ source.add("a", "1").add("b", "2").add("m", "3").setName("S");
+
+ ValueMappedConfigSource mappingSource = new ValueMappedConfigSource("vmps", mapper, source);
+
+ assertThat(mappingSource.getValue("z")).isNull();
+ }
+
+ @Test
+ public void getReturnsUnmappedValue() throws Exception {
+ InMemoryConfigSource source = new InMemoryConfigSource();
+ source.add("a", "1").add("b", "2").add("m", "3").setName("S");
+
+ ValueMappedConfigSource mappingSource = new ValueMappedConfigSource("vmps", mapper, source);
+
+ assertThat(mappingSource.getValue("a")).isNotNull()
+ .isEqualTo("1");
+ }
+
+ @Test
+ public void getReturnsMappedValue() throws Exception {
+ InMemoryConfigSource source = new InMemoryConfigSource();
+ source.add("a", "1").add("b", "2").add("m", "3").setName("S");
+
+ ValueMappedConfigSource mappingSource = new ValueMappedConfigSource("vmps", mapper, source);
+
+ assertThat(mappingSource.getValue("m")).isNotNull()
+ .isEqualTo("3");
+ }
+
+ /*
+ * Tests for getProperties()
+ */
+
+ @Test
+ public void getPropertiesMapperMapsNoValue() {
+ InMemoryConfigSource source = new InMemoryConfigSource();
+ source.add("a", "1").add("b", "2").add("c", "3").setName("S");
+
+ ValueMappedConfigSource mappingSource = new ValueMappedConfigSource("vmps", mapper, source);
+
+ Map<String, String> result = mappingSource.getProperties();
+
+ assertThat(result).isNotNull()
+ .isNotEmpty()
+ .containsEntry("a", "1")
+ .containsEntry("b", "2")
+ .containsEntry("c", "3")
+ .hasSize(3);
+
+ }
+
+ @Test
+ public void getPropertiesMapperMapsSomeValues() throws Exception {
+ InMemoryConfigSource source = new InMemoryConfigSource();
+ source.add("a", "1").add("b", "2").add("m", "3").setName("S");
+
+ ValueMappedConfigSource mappingSource = new ValueMappedConfigSource("vmps", mapper, source);
+
+ Map<String, String> result = mappingSource.getProperties();
+
+ assertThat(result).isNotNull()
+ .isNotEmpty()
+ .containsEntry("a", "1")
+ .containsEntry("b", "2")
+ .containsEntry("m", "3m")
+ .hasSize(3);
+ }
+
+
+
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/36b44661/modules/functions/src/test/java/org/apache/tamaya/functions/ValueMappedPropertySourceTest.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/test/java/org/apache/tamaya/functions/ValueMappedPropertySourceTest.java b/modules/functions/src/test/java/org/apache/tamaya/functions/ValueMappedPropertySourceTest.java
deleted file mode 100644
index 1ce5025..0000000
--- a/modules/functions/src/test/java/org/apache/tamaya/functions/ValueMappedPropertySourceTest.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.functions;
-
-import org.apache.tamaya.spi.PropertyValue;
-import org.assertj.core.api.Condition;
-import org.junit.Test;
-
-import java.util.Map;
-
-import static org.apache.tamaya.spi.PropertyValue.of;
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class ValueMappedPropertySourceTest {
-
- private PropertyMapper mapper = new PropertyMapper() {
- @Override
- public String mapProperty(String key, String value) {
- String startOfOtherKey = key.toLowerCase().substring(0, 1);
- if ("m".compareTo(startOfOtherKey) <= 0) {
- return value + "m";
- }
-
- return value;
- }
- };
-
- /*
- * Tests for getOrdinal()
- */
-
- @Test
- public void getOrdinalReturnsGivenOrdinal() throws Exception {
- InMemoryPropertySource source = new InMemoryPropertySource();
- source.add("a", "1").add("b", "2").add("c", "3").setName("S");
- source.setOrdinal(99);
-
- ValueMappedPropertySource mappingSource = new ValueMappedPropertySource("vmps", mapper, source);
-
- assertThat(mappingSource.getOrdinal()).isEqualTo(99);
- }
-
- /*
- * Tests for isScannable()
- */
-
- @Test
- public void isScannableReturnsTrueIfSetToTrue() throws Exception {
- InMemoryPropertySource source = new InMemoryPropertySource();
- source.add("a", "1").add("b", "2").add("c", "3").setName("S");
- source.setScannable(true);
-
- ValueMappedPropertySource mappingSource = new ValueMappedPropertySource("vmps", mapper, source);
-
- assertThat(mappingSource.isScannable()).isTrue();
- }
-
-
- /*
- * Tests for getName()
- */
-
- @Test
- public void getNameReturnsGivenName() throws Exception {
- InMemoryPropertySource source = new InMemoryPropertySource();
- source.add("a", "1").add("b", "2").add("c", "3").setName("S");
-
- ValueMappedPropertySource mappingSource = new ValueMappedPropertySource("vmps", mapper, source);
-
- assertThat(mappingSource.getName()).isEqualTo("vmps");
- }
-
- /*
- * Tests for get(String)
- */
-
- @Test
- public void getReturnNullIfKeyIsNotInBasePropertySource() throws Exception {
- InMemoryPropertySource source = new InMemoryPropertySource();
- source.add("a", "1").add("b", "2").add("m", "3").setName("S");
-
- ValueMappedPropertySource mappingSource = new ValueMappedPropertySource("vmps", mapper, source);
-
- PropertyValue result = mappingSource.get("z");
-
- assertThat(result).isNull();
- }
-
- @Test
- public void getReturnsUnmappedValue() throws Exception {
- InMemoryPropertySource source = new InMemoryPropertySource();
- source.add("a", "1").add("b", "2").add("m", "3").setName("S");
-
- ValueMappedPropertySource mappingSource = new ValueMappedPropertySource("vmps", mapper, source);
-
- PropertyValue result = mappingSource.get("a");
-
- assertThat(result).isNotNull()
- .has(new Condition<PropertyValue>() {
- @Override
- public boolean matches(PropertyValue propertyValue) {
- return "1".equals(propertyValue.getValue());
- }
- });
- }
-
- @Test
- public void getReturnsMappedValue() throws Exception {
- InMemoryPropertySource source = new InMemoryPropertySource();
- source.add("a", "1").add("b", "2").add("m", "3").setName("S");
-
- ValueMappedPropertySource mappingSource = new ValueMappedPropertySource("vmps", mapper, source);
-
- PropertyValue result = mappingSource.get("m");
-
- assertThat(result).isNotNull()
- .has(new Condition<PropertyValue>() {
- @Override
- public boolean matches(PropertyValue propertyValue) {
- return "3m".equals(propertyValue.getValue());
- }
- });
- }
-
- /*
- * Tests for getProperties()
- */
-
- @Test
- public void getPropertiesMapperMapsNoValue() {
- InMemoryPropertySource source = new InMemoryPropertySource();
- source.add("a", "1").add("b", "2").add("c", "3").setName("S");
-
- ValueMappedPropertySource mappingSource = new ValueMappedPropertySource("vmps", mapper, source);
-
- Map<String, PropertyValue> result = mappingSource.getProperties();
-
- assertThat(result).isNotNull()
- .isNotEmpty()
- .containsEntry("a", of("a", "1", "S"))
- .containsEntry("b", of("b", "2", "S"))
- .containsEntry("c", of("c", "3", "S"))
- .hasSize(3);
-
- }
-
- @Test
- public void getPropertiesMapperMapsSomeValues() throws Exception {
- InMemoryPropertySource source = new InMemoryPropertySource();
- source.add("a", "1").add("b", "2").add("m", "3").setName("S");
-
- ValueMappedPropertySource mappingSource = new ValueMappedPropertySource("vmps", mapper, source);
-
- Map<String, PropertyValue> result = mappingSource.getProperties();
-
- assertThat(result).isNotNull()
- .isNotEmpty()
- .containsEntry("a", of("a", "1", "S"))
- .containsEntry("b", of("b", "2", "S"))
- .containsEntry("m", of("m", "3m", "S"))
- .hasSize(3);
- }
-
-
-
-
-}
\ No newline at end of file
[04/18] incubator-tamaya-extensions git commit: Adapted to comply
with JSR API.
Posted by an...@apache.org.
Adapted to comply with JSR API.
Signed-off-by: Anatole Tresch <an...@apache.org>
Project: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/commit/581c92e7
Tree: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/tree/581c92e7
Diff: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/diff/581c92e7
Branch: refs/heads/configjsr
Commit: 581c92e70777af1fa9ec6a4af0ca8d95b334526b
Parents: 06f29e1
Author: Anatole Tresch <an...@apache.org>
Authored: Mon Dec 25 11:41:21 2017 +0100
Committer: Anatole Tresch <an...@apache.org>
Committed: Mon Dec 25 11:41:21 2017 +0100
----------------------------------------------------------------------
modules/functions/pom.xml | 5 -
.../tamaya/functions/CombinedConfiguration.java | 130 ++----
.../functions/ConfigWrappingConfigSource.java | 73 ++++
.../functions/ConfigWrappingPropertySource.java | 84 ----
.../functions/ConfigurationFunctions.java | 415 ++++++------------
.../tamaya/functions/EnrichedConfiguration.java | 138 ++----
.../tamaya/functions/FilteredConfiguration.java | 88 +---
.../tamaya/functions/MappedConfiguration.java | 92 ++--
.../functions/CombinedConfigurationTest.java | 420 ++++++-------------
.../functions/ConfigurationFunctionsTest.java | 38 +-
.../functions/EnrichedConfigurationTest.java | 355 +++++++---------
.../functions/MappedConfigurationTest.java | 11 +-
12 files changed, 620 insertions(+), 1229 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/581c92e7/modules/functions/pom.xml
----------------------------------------------------------------------
diff --git a/modules/functions/pom.xml b/modules/functions/pom.xml
index 839b67e..17de980 100644
--- a/modules/functions/pom.xml
+++ b/modules/functions/pom.xml
@@ -32,11 +32,6 @@ under the License.
<packaging>jar</packaging>
<dependencies>
- <dependency>
- <groupId>org.apache.tamaya</groupId>
- <artifactId>tamaya-api</artifactId>
- <version>${tamaya-apicore.version}</version>
- </dependency>
<!-- Test scope only, do not create a code dependency! -->
<dependency>
<groupId>org.apache.tamaya</groupId>
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/581c92e7/modules/functions/src/main/java/org/apache/tamaya/functions/CombinedConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/main/java/org/apache/tamaya/functions/CombinedConfiguration.java b/modules/functions/src/main/java/org/apache/tamaya/functions/CombinedConfiguration.java
index 2e3f0cc..10961b4 100644
--- a/modules/functions/src/main/java/org/apache/tamaya/functions/CombinedConfiguration.java
+++ b/modules/functions/src/main/java/org/apache/tamaya/functions/CombinedConfiguration.java
@@ -18,19 +18,15 @@
*/
package org.apache.tamaya.functions;
-import org.apache.tamaya.ConfigOperator;
-import org.apache.tamaya.ConfigQuery;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.TypeLiteral;
-import org.apache.tamaya.spi.ConfigurationContext;
-
+import javax.config.Config;
+import javax.config.spi.ConfigSource;
import java.util.*;
/**
* Combines a set of child configurations to a new one, by overriding the first entries with result from
* later instances.
*/
-class CombinedConfiguration implements Configuration{
+class CombinedConfiguration implements Config{
/** The name of the new configuration. */
private final String name;
@@ -38,85 +34,48 @@ class CombinedConfiguration implements Configuration{
* The configuration's in evaluation order. Instances with higher indices
* override results with lower ones.
*/
- private final ArrayList<Configuration> configurations = new ArrayList<>();
+ private final ArrayList<Config> configurations = new ArrayList<>();
/**
* Creates a combined configuration instance.
* @param configName the name of the new config.
* @param configs the configurations hereby instances with higher indices override results with lower ones.
*/
- public CombinedConfiguration(String configName, Configuration... configs) {
+ public CombinedConfiguration(String configName, Config... configs) {
this.name = configName;
if (null != configs) {
- for (Configuration config : configs) {
+ for (Config config : configs) {
if (config == null) {
continue;
}
-
- addConfiguration(config);
+ configurations.add(config);
}
}
}
@Override
- public String get(String key) {
- String curValue = null;
- for(Configuration config: getConfigurations()){
- String value = config.get(key);
- if(value!=null){
- curValue = value;
+ public <T> T getValue(String key, Class<T> type) {
+ T curValue = null;
+ for(Config config: configurations){
+ Optional<T> value = config.getOptionalValue(key, type);
+ if(value.isPresent()){
+ curValue = value.get();
}
}
return curValue;
}
@Override
- public String getOrDefault(String key, String defaultValue) {
+ public <T> Optional<T> getOptionalValue(String key, Class<T> type) {
Objects.requireNonNull(key, "Key must be given.");
- Objects.requireNonNull(defaultValue, "Value must be given.");
-
- String val = get(key);
-
- if (val == null) {
- return defaultValue;
- }
-
- return val;
- }
-
- @Override
- public <T> T getOrDefault(String key, Class<T> type, T defaultValue) {
Objects.requireNonNull(type, "Type must be given.");
- Objects.requireNonNull(key, "Key must be given.");
- Objects.requireNonNull(defaultValue, "Default value must be given.");
-
- T val = get(key, type);
- if(val==null){
- return defaultValue;
- }
- return val;
- }
-
- @Override
- public <T> T get(String key, Class<T> type) {
- T curValue = null;
- for(Configuration config: getConfigurations()){
- T value = config.get(key, type);
- if(value!=null){
- curValue = value;
- }
- }
- return curValue;
- }
- @Override
- public <T> T get(String key, TypeLiteral<T> type) {
- T curValue = null;
- for(Configuration config: getConfigurations()){
- T value = config.get(key, type);
- if(value!=null){
+ Optional<T> curValue = Optional.empty();
+ for(Config config: configurations){
+ Optional<T> value = config.getOptionalValue(key, type);
+ if(value!=null && value.isPresent()){
curValue = value;
}
}
@@ -124,45 +83,21 @@ class CombinedConfiguration implements Configuration{
}
@Override
- public <T> T getOrDefault(String key, TypeLiteral<T> type, T defaultValue) {
- Objects.requireNonNull(key, "Key must be given.");
- Objects.requireNonNull(type, "Type must be given.");
- Objects.requireNonNull(defaultValue, "Default value must be given.");
-
- T val = get(key, type);
- if(val==null){
- return defaultValue;
- }
- return val;
- }
-
- @Override
- public Map<String, String> getProperties() {
- Map<String, String> result = new HashMap<>();
- for(Configuration ps : getConfigurations()){
- result.putAll(ps.getProperties());
+ public Iterable<String> getPropertyNames() {
+ Set<String> result = new HashSet<>();
+ for(Config ps : configurations){
+ ps.getPropertyNames().forEach(result::add);
}
return result;
}
@Override
- public Configuration with(ConfigOperator operator) {
- Objects.requireNonNull(operator, "Operator must be given.");
-
- return operator.operate(this);
- }
-
- @Override
- public <T> T query(ConfigQuery<T> query) {
- Objects.requireNonNull(query, "Query must be given.");
-
- return query.query(this);
- }
-
- @Override
- public ConfigurationContext getContext() {
- // TODO thjink on combining the participating contexts...
- return configurations.get(0).getContext();
+ public Iterable<ConfigSource> getConfigSources() {
+ List<ConfigSource> configSources = new ArrayList<>();
+ for(Config ps : configurations){
+ ps.getConfigSources().forEach(configSources::add);
+ }
+ return configSources;
}
@Override
@@ -173,13 +108,4 @@ class CombinedConfiguration implements Configuration{
'}';
}
- protected void addConfiguration(Configuration config) {
- configurations.add(config);
- }
-
- protected List<Configuration> getConfigurations() {
- return configurations;
- }
-
-
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/581c92e7/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigWrappingConfigSource.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigWrappingConfigSource.java b/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigWrappingConfigSource.java
new file mode 100644
index 0000000..3461ed4
--- /dev/null
+++ b/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigWrappingConfigSource.java
@@ -0,0 +1,73 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tamaya.functions;
+
+import javax.config.Config;
+import javax.config.spi.ConfigSource;
+import java.util.*;
+
+/**
+ * PropertySource that wraps a Configuration instance.
+ */
+final class ConfigWrappingConfigSource implements ConfigSource {
+ /** The property source name. */
+ private final String name;
+ /** The ordinal. */
+ private final int ordinal;
+ /** The wrapped config. */
+ private final Config config;
+
+ /**
+ * Constructor.
+ * @param name the property source name, not null.
+ * @param ordinal ths ordinal
+ * @param config the wrapped config, not null.
+ */
+ public ConfigWrappingConfigSource(String name, int ordinal, Config config){
+ this.name = Objects.requireNonNull(name);
+ this.ordinal = ordinal;
+ this.config = Objects.requireNonNull(config);
+ }
+
+ public int getOrdinal() {
+ return ordinal;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public String getValue(String key) {
+ return config.getOptionalValue(key, String.class).orElse(null);
+ }
+
+ @Override
+ public Map<String,String> getProperties() {
+ Map<String,String> result = new HashMap<>();
+ config.getPropertyNames().forEach(key -> result.put(key, config.getValue(key, String.class)));
+ return result;
+ }
+
+ @Override
+ public String toString(){
+ return "ConfigWrappingPropertySource(name="+name+", ordinal="+ordinal+", config="+config+")";
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/581c92e7/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigWrappingPropertySource.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigWrappingPropertySource.java b/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigWrappingPropertySource.java
deleted file mode 100644
index dbad205..0000000
--- a/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigWrappingPropertySource.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.tamaya.functions;
-
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValue;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-
-/**
- * PropertySource that wraps a Configuration instance.
- */
-final class ConfigWrappingPropertySource implements PropertySource {
- /** The property source name. */
- private final String name;
- /** The ordinal. */
- private final int ordinal;
- /** The wrapped config. */
- private final Configuration config;
-
- /**
- * Constructor.
- * @param name the property source name, not null.
- * @param ordinal ths ordinal
- * @param config the wrapped config, not null.
- */
- public ConfigWrappingPropertySource(String name, int ordinal, Configuration config){
- this.name = Objects.requireNonNull(name);
- this.ordinal = ordinal;
- this.config = Objects.requireNonNull(config);
- }
-
- public int getOrdinal() {
- return ordinal;
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public PropertyValue get(String key) {
- return PropertyValue.of(key, config.get(key), getName());
- }
-
- @Override
- public Map<String, PropertyValue> getProperties() {
- Map<String,PropertyValue> result = new HashMap<>();
- for(Map.Entry<String,String> en:config.getProperties().entrySet()){
- result.put(en.getKey(), PropertyValue.of(en.getKey(), en.getValue(), getName()));
- }
- return result;
- }
-
- @Override
- public boolean isScannable() {
- return true;
- }
-
- @Override
- public String toString(){
- return "ConfigWrappingPropertySource(name="+name+", ordinal="+ordinal+", config="+config+")";
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/581c92e7/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigurationFunctions.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigurationFunctions.java b/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigurationFunctions.java
index ccb6396..76581b7 100644
--- a/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigurationFunctions.java
+++ b/modules/functions/src/main/java/org/apache/tamaya/functions/ConfigurationFunctions.java
@@ -18,26 +18,12 @@
*/
package org.apache.tamaya.functions;
-import org.apache.tamaya.ConfigOperator;
-import org.apache.tamaya.ConfigQuery;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.TypeLiteral;
-import org.apache.tamaya.spi.ConfigurationContext;
-import org.apache.tamaya.spi.ConfigurationContextBuilder;
-import org.apache.tamaya.spi.PropertyConverter;
-import org.apache.tamaya.spi.PropertyFilter;
-import org.apache.tamaya.spi.PropertySource;
-import org.apache.tamaya.spi.PropertyValueCombinationPolicy;
-
+import javax.config.Config;
+import javax.config.spi.ConfigSource;
import java.net.Inet4Address;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-import java.util.TreeSet;
+import java.util.*;
+import java.util.function.Function;
+import java.util.function.UnaryOperator;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -54,56 +40,26 @@ public final class ConfigurationFunctions {
/**
* Implementation of an empty propertySource.
*/
- private static final Configuration EMPTY_CONFIGURATION = new Configuration() {
-
- @Override
- public String get(String key) {
- return null;
- }
-
- @Override
- public String getOrDefault(String key, String defaultValue) {
- return defaultValue;
- }
-
- @Override
- public <T> T getOrDefault(String key, Class<T> type, T defaultValue) {
- return defaultValue;
- }
+ private static final Config EMPTY_CONFIGURATION = new Config() {
@Override
- public <T> T get(String key, Class<T> type) {
+ public <T> T getValue(String key, Class<T> type) {
return null;
}
@Override
- public <T> T get(String key, TypeLiteral<T> type) {
- return null;
- }
-
- @Override
- public <T> T getOrDefault(String key, TypeLiteral<T> type, T defaultValue) {
- return defaultValue;
+ public <T> Optional<T> getOptionalValue(String key, Class<T> type) {
+ return Optional.empty();
}
@Override
- public Map<String, String> getProperties() {
- return Collections.emptyMap();
+ public Iterable<String> getPropertyNames() {
+ return Collections.emptySet();
}
@Override
- public Configuration with(ConfigOperator operator) {
- return operator.operate(this);
- }
-
- @Override
- public <T> T query(ConfigQuery<T> query) {
- return query.query(this);
- }
-
- @Override
- public ConfigurationContext getContext() {
- return EMPTY_CONFIGURATION_CONTEXT;
+ public Iterable<ConfigSource> getConfigSources() {
+ return Collections.emptySet();
}
@Override
@@ -112,58 +68,6 @@ public final class ConfigurationFunctions {
}
};
- private static final ConfigurationContext EMPTY_CONFIGURATION_CONTEXT = new ConfigurationContext() {
- @Override
- public void addPropertySources(PropertySource... propertySourcesToAdd) {
- // ignore
- }
-
- @Override
- public List<PropertySource> getPropertySources() {
- return Collections.emptyList();
- }
-
- @Override
- public PropertySource getPropertySource(String name) {
- return null;
- }
-
- @Override
- public <T> void addPropertyConverter(TypeLiteral<T> typeToConvert, PropertyConverter<T> propertyConverter) {
- // ignore
- }
-
- @Override
- public Map<TypeLiteral<?>, List<PropertyConverter<?>>> getPropertyConverters() {
- return Collections.emptyMap();
- }
-
- @Override
- public <T> List<PropertyConverter<T>> getPropertyConverters(TypeLiteral<T> type) {
- return Collections.emptyList();
- }
-
- @Override
- public List<PropertyFilter> getPropertyFilters() {
- return Collections.emptyList();
- }
-
- @Override
- public PropertyValueCombinationPolicy getPropertyValueCombinationPolicy() {
- return PropertyValueCombinationPolicy.DEFAULT_OVERRIDING_COLLECTOR;
- }
-
- @Override
- public ConfigurationContextBuilder toBuilder() {
- throw new UnsupportedOperationException("Cannot build from ConfigurationContext.EMPTY.");
- }
-
- @Override
- public String toString(){
- return "ConfigurationContext.EMPTY";
- }
- };
-
/**
* Private singleton constructor.
*/
@@ -177,13 +81,8 @@ public final class ConfigurationFunctions {
* @param filter the filter, not null
* @return the section configuration, with the areaKey stripped away.
*/
- public static ConfigOperator filter(final PropertyMatcher filter) {
- return new ConfigOperator() {
- @Override
- public Configuration operate(Configuration config) {
- return new FilteredConfiguration(config, filter, "FilterClass: " + filter.getClass().getName());
- }
- };
+ public static UnaryOperator<Config> filter(final PropertyMatcher filter) {
+ return config -> new FilteredConfiguration(config, filter, "FilterClass: " + filter.getClass().getName());
}
/**
@@ -193,13 +92,8 @@ public final class ConfigurationFunctions {
* @param keyMapper the keyMapper, not null
* @return the section configuration, with the areaKey stripped away.
*/
- public static ConfigOperator map(final KeyMapper keyMapper) {
- return new ConfigOperator() {
- @Override
- public Configuration operate(Configuration config) {
- return new MappedConfiguration(config, keyMapper, null);
- }
- };
+ public static UnaryOperator<Config> map(final KeyMapper keyMapper) {
+ return config -> new MappedConfiguration(config, keyMapper, null);
}
/**
@@ -210,7 +104,7 @@ public final class ConfigurationFunctions {
* @param areaKey the section key, not null
* @return the section configuration, with the areaKey stripped away.
*/
- public static ConfigOperator section(String areaKey) {
+ public static UnaryOperator<Config> section(String areaKey) {
return section(areaKey, false);
}
@@ -222,30 +116,24 @@ public final class ConfigurationFunctions {
* @param stripKeys if set to true, the section key is stripped away fromMap the resulting key.
* @return the section configuration, with the areaKey stripped away.
*/
- public static ConfigOperator section(final String areaKey, final boolean stripKeys) {
- return new ConfigOperator() {
- @Override
- public Configuration operate(Configuration config) {
- Configuration filtered = new FilteredConfiguration(config,
- new PropertyMatcher() {
- @Override
- public boolean test(String k, String v) {
- return isKeyInSection(k, areaKey);
- }
- }, "section: " + areaKey);
+ public static UnaryOperator<Config> section(final String areaKey, final boolean stripKeys) {
+ return config -> {
+ Config filtered = new FilteredConfiguration(
+ config,
+ (k, v) -> isKeyInSection(k, areaKey),
+ "section: " + areaKey);
if (stripKeys) {
- return new MappedConfiguration(filtered, new KeyMapper(){
- @Override
- public String mapKey(String key) {
- if(key.startsWith(areaKey)) {
- return key.substring(areaKey.length());
- }
- return areaKey + key;
- }
- }, "stripped");
+ return new MappedConfiguration(
+ filtered,
+ key -> {
+ if(key.startsWith(areaKey)) {
+ return key.substring(areaKey.length());
+ }
+ return areaKey + key;
+ },
+ "stripped");
}
return filtered;
- }
};
}
@@ -283,19 +171,16 @@ public final class ConfigurationFunctions {
*
* @return s set with all sections, never {@code null}.
*/
- public static ConfigQuery<Set<String>> sections() {
- return new ConfigQuery<Set<String>>() {
- @Override
- public Set<String> query(Configuration config) {
+ public static Function<Config,Set<String>> sections() {
+ return config -> {
final Set<String> areas = new TreeSet<>();
- for (String s : config.getProperties().keySet()) {
+ for (String s : config.getPropertyNames()) {
int index = s.lastIndexOf('.');
if (index > 0) {
areas.add(s.substring(0, index));
}
}
return areas;
- }
};
}
@@ -307,12 +192,10 @@ public final class ConfigurationFunctions {
*
* @return s set with all transitive sections, never {@code null}.
*/
- public static ConfigQuery<Set<String>> transitiveSections() {
- return new ConfigQuery<Set<String>>() {
- @Override
- public Set<String> query(Configuration config) {
+ public static Function<Config,Set<String>> transitiveSections() {
+ return config -> {
final Set<String> transitiveAreas = new TreeSet<>();
- for (String s : config.query(sections())) {
+ for (String s : sections().apply(config)) {
transitiveAreas.add(s);
int index = s.lastIndexOf('.');
while (index > 0) {
@@ -322,7 +205,6 @@ public final class ConfigurationFunctions {
}
}
return transitiveAreas;
- }
};
}
@@ -335,20 +217,16 @@ public final class ConfigurationFunctions {
* @param predicate A predicate to deternine, which sections should be returned, not {@code null}.
* @return s set with all sections, never {@code null}.
*/
- public static ConfigQuery<Set<String>> sections(final Predicate<String> predicate) {
- return new ConfigQuery<Set<String>>() {
- @Override
- public Set<String> query(Configuration config) {
+ public static Function<Config,Set<String>> sections(final Predicate<String> predicate) {
+ return config -> {
Set<String> result = new TreeSet<>();
- for (String s : sections().query(config)) {
+ for (String s : sections().apply(config)) {
if (predicate.test(s)) {
result.add(s);
}
}
return result;
- }
};
-
}
/**
@@ -360,18 +238,15 @@ public final class ConfigurationFunctions {
* @param predicate A predicate to deternine, which sections should be returned, not {@code null}.
* @return s set with all transitive sections, never {@code null}.
*/
- public static ConfigQuery<Set<String>> transitiveSections(final Predicate<String> predicate) {
- return new ConfigQuery<Set<String>>() {
- @Override
- public Set<String> query(Configuration config) {
+ public static Function<Config,Set<String>> transitiveSections(final Predicate<String> predicate) {
+ return config -> {
Set<String> result = new TreeSet<>();
- for (String s : transitiveSections().query(config)) {
+ for (String s : transitiveSections().apply(config)) {
if (predicate.test(s)) {
result.add(s);
}
}
return result;
- }
};
}
@@ -382,7 +257,7 @@ public final class ConfigurationFunctions {
* @param sectionKeys the section keys, not null
* @return the section configuration, with the areaKey stripped away.
*/
- public static ConfigOperator sectionsRecursive(String... sectionKeys) {
+ public static UnaryOperator<Config> sectionsRecursive(String... sectionKeys) {
return sectionRecursive(false, sectionKeys);
}
@@ -395,20 +270,20 @@ public final class ConfigurationFunctions {
* by entries of the later instances.
* @return the resulting configuration instance.
*/
- public static Configuration combine(String configName, Configuration... configs) {
+ public static Config combine(String configName, Config... configs) {
return new CombinedConfiguration(configName, configs);
}
/**
- * Creates a {@link PropertySource}, based on the given {@link Configuration}. The keys and propertx map
+ * Creates a {@link ConfigSource}, based on the given {@link Config}. The keys and propertx map
* are dynamically calculated, so the returned PropertySource is a real dynamic wrapper.
* @param name the name of the property source, not null.
* @param ordinal ordinal of the property source.
* @param config the config to be mapped, not null.
* @return a property source wrapping the configuration.
*/
- public static PropertySource propertySourceFrom(final String name, final int ordinal, final Configuration config){
- return new ConfigWrappingPropertySource(name, ordinal, config);
+ public static ConfigSource propertySourceFrom(final String name, final int ordinal, final Config config){
+ return new ConfigWrappingConfigSource(name, ordinal, config);
}
/**
@@ -419,26 +294,19 @@ public final class ConfigurationFunctions {
* @param stripKeys if set to true, the section key is stripped away fromMap the resulting key.
* @return the section configuration, with the areaKey stripped away.
*/
- public static ConfigOperator sectionRecursive(final boolean stripKeys, final String... sectionKeys) {
- return new ConfigOperator() {
- @Override
- public Configuration operate(Configuration config) {
- Configuration filtered = new FilteredConfiguration(config, new PropertyMatcher() {
- @Override
- public boolean test(final String k, String v) {
- return isKeyInSections(k, sectionKeys);
- }
- }, "sections: " + Arrays.toString(sectionKeys));
- if (stripKeys) {
- return new MappedConfiguration(filtered, new KeyMapper() {
- @Override
- public String mapKey(String key) {
- return PropertySourceFunctions.stripSectionKeys(key, sectionKeys);
- }
- }, "stripped");
- }
- return filtered;
+ public static UnaryOperator<Config> sectionRecursive(final boolean stripKeys, final String... sectionKeys) {
+ return (config) -> {
+ Config filtered = new FilteredConfiguration(
+ config,
+ (k,v) -> isKeyInSections(k, sectionKeys),
+ "sections: " + Arrays.toString(sectionKeys));
+ if (stripKeys) {
+ return new MappedConfiguration(
+ filtered,
+ k -> PropertySourceFunctions.stripSectionKeys(k, sectionKeys),
+ "stripped");
}
+ return filtered;
};
}
@@ -447,7 +315,7 @@ public final class ConfigurationFunctions {
*
* @return the given query.
*/
- public static ConfigQuery<String> jsonInfo() {
+ public static Function<Config,String> jsonInfo() {
return jsonInfo(null);
}
@@ -458,29 +326,27 @@ public final class ConfigurationFunctions {
* parameters.
* @return the given query.
*/
- public static ConfigQuery<String> jsonInfo(final Map<String, String> info) {
- return new ConfigQuery<String>() {
- @Override
- public String query(Configuration config) {
- Map<String, String> props = new TreeMap<>(config.getProperties());
- props.put("__timestamp", String.valueOf(System.currentTimeMillis()));
- if(info!=null) {
- for (Map.Entry<String, String> en : info.entrySet()) {
- props.put("__" + escape(en.getKey()), escape(en.getValue()));
- }
+ public static Function<Config,String> jsonInfo(final Map<String, String> info) {
+ return config -> {
+ Map<String, String> props = new TreeMap<>();
+ config.getPropertyNames().forEach(key -> props.put(key, config.getValue(key, String.class)));
+ props.put("__timestamp", String.valueOf(System.currentTimeMillis()));
+ if(info!=null) {
+ for (Map.Entry<String, String> en : info.entrySet()) {
+ props.put("__" + escape(en.getKey()), escape(en.getValue()));
}
- StringBuilder builder = new StringBuilder(400).append("{\n");
- for (Map.Entry<String, String> en : props.entrySet()) {
- builder.append(" \"").append(escape(en.getKey())).append("\": \"" )
- .append(escape(en.getValue())).append("\",\n");
- }
- if(builder.toString().endsWith(",\n")){
- builder.setLength(builder.length()-2);
- builder.append('\n');
- }
- builder.append("}\n");
- return builder.toString();
}
+ StringBuilder builder = new StringBuilder(400).append("{\n");
+ for (Map.Entry<String, String> en : props.entrySet()) {
+ builder.append(" \"").append(escape(en.getKey())).append("\": \"" )
+ .append(escape(en.getValue())).append("\",\n");
+ }
+ if(builder.toString().endsWith(",\n")){
+ builder.setLength(builder.length()-2);
+ builder.append('\n');
+ }
+ builder.append("}\n");
+ return builder.toString();
};
}
@@ -489,7 +355,7 @@ public final class ConfigurationFunctions {
*
* @return the given query.
*/
- public static ConfigQuery<String> xmlInfo() {
+ public static Function<Config,String> xmlInfo() {
return xmlInfo(null);
}
@@ -500,25 +366,23 @@ public final class ConfigurationFunctions {
* parameters.
* @return the given query.
*/
- public static ConfigQuery<String> xmlInfo(final Map<String, String> info) {
- return new ConfigQuery<String>() {
- @Override
- public String query(Configuration config) {
- Map<String, String> props = new TreeMap<>(config.getProperties());
- props.put("__timestamp", String.valueOf(System.currentTimeMillis()));
- if(info!=null) {
- for (Map.Entry<String, String> en : info.entrySet()) {
- props.put("__" + escape(en.getKey()), escape(en.getValue()));
- }
- }
- StringBuilder builder = new StringBuilder(400);
- builder.append("<configuration>\n");
- for (Map.Entry<String, String> en : props.entrySet()) {
- builder.append(" <entry key=\"" + escape(en.getKey()) + "\">" + escape(en.getValue()) + "</entry>\n");
+ public static Function<Config,String> xmlInfo(final Map<String, String> info) {
+ return config -> {
+ Map<String, String> props = new TreeMap<>();
+ config.getPropertyNames().forEach(key -> props.put(key, config.getValue(key, String.class)));
+ props.put("__timestamp", String.valueOf(System.currentTimeMillis()));
+ if(info!=null) {
+ for (Map.Entry<String, String> en : info.entrySet()) {
+ props.put("__" + escape(en.getKey()), escape(en.getValue()));
}
- builder.append("</configuration>\n");
- return builder.toString();
}
+ StringBuilder builder = new StringBuilder(400);
+ builder.append("<configuration>\n");
+ for (Map.Entry<String, String> en : props.entrySet()) {
+ builder.append(" <entry key=\"" + escape(en.getKey()) + "\">" + escape(en.getValue()) + "</entry>\n");
+ }
+ builder.append("</configuration>\n");
+ return builder.toString();
};
}
@@ -527,7 +391,7 @@ public final class ConfigurationFunctions {
*
* @return the given query.
*/
- public static ConfigQuery<String> textInfo() {
+ public static Function<Config,String> textInfo() {
return textInfo(null);
}
@@ -536,27 +400,25 @@ public final class ConfigurationFunctions {
* @param info configuration values to use for filtering.
* @return the given query.
*/
- public static ConfigQuery<String> textInfo(final Map<String, String> info) {
- return new ConfigQuery<String>() {
- @Override
- public String query(Configuration config) {
- Map<String, String> props = new TreeMap<>(config.getProperties());
- props.put("__timestamp", String.valueOf(System.currentTimeMillis()));
- if(info!=null) {
- for (Map.Entry<String, String> en : info.entrySet()) {
- props.put("__" + escape(en.getKey()), escape(en.getValue()));
- }
+ public static Function<Config,String> textInfo(final Map<String, String> info) {
+ return config -> {
+ Map<String, String> props = new TreeMap<>();
+ config.getPropertyNames().forEach(key -> props.put(key, config.getValue(key, String.class)));
+ props.put("__timestamp", String.valueOf(System.currentTimeMillis()));
+ if(info!=null) {
+ for (Map.Entry<String, String> en : info.entrySet()) {
+ props.put("__" + escape(en.getKey()), escape(en.getValue()));
}
- StringBuilder builder = new StringBuilder(400).append("Configuration:\n");
- for (Map.Entry<String, String> en : props.entrySet()) {
- builder.append(" " + escape(en.getKey()) + ": " + escape(en.getValue()).replace("\n", "\n ") + ",\n");
- }
- if(builder.toString().endsWith(",\n")){
- builder.setLength(builder.length() - 2);
- }
- builder.append("\n");
- return builder.toString();
}
+ StringBuilder builder = new StringBuilder(400).append("Configuration:\n");
+ for (Map.Entry<String, String> en : props.entrySet()) {
+ builder.append(" " + escape(en.getKey()) + ": " + escape(en.getValue()).replace("\n", "\n ") + ",\n");
+ }
+ if(builder.toString().endsWith(",\n")){
+ builder.setLength(builder.length() - 2);
+ }
+ builder.append("\n");
+ return builder.toString();
};
}
@@ -566,13 +428,8 @@ public final class ConfigurationFunctions {
* @param override if true, all items existing are overridden by the new ones passed.
* @return the ConfigOperator, never null.
*/
- public static ConfigOperator addItems(final Map<String,Object> items, final boolean override){
- return new ConfigOperator() {
- @Override
- public Configuration operate(Configuration config) {
- return new EnrichedConfiguration(config,items, override);
- }
- };
+ public static UnaryOperator<Config> addItems(final Map<String,Object> items, final boolean override){
+ return config -> new EnrichedConfiguration(config,items, override);
}
/**
@@ -580,7 +437,7 @@ public final class ConfigurationFunctions {
* @param items the items, not null.
* @return the operator, never null.
*/
- public static ConfigOperator addItems(Map<String,Object> items){
+ public static UnaryOperator<Config> addItems(Map<String,Object> items){
return addItems(items, false);
}
@@ -589,7 +446,7 @@ public final class ConfigurationFunctions {
* @param items the items.
* @return the operator for replacing the items.
*/
- public static ConfigOperator replaceItems(Map<String,Object> items){
+ public static UnaryOperator<Config> replaceItems(Map<String,Object> items){
return addItems(items, true);
}
@@ -598,7 +455,7 @@ public final class ConfigurationFunctions {
*
* @return the given query.
*/
- public static ConfigQuery<String> htmlInfo() {
+ public static Function<Config,String> htmlInfo() {
return htmlInfo(null);
}
@@ -607,16 +464,13 @@ public final class ConfigurationFunctions {
* @param info configuration values to use for filtering.
* @return the given query.
*/
- public static ConfigQuery<String> htmlInfo(final Map<String, String> info) {
- return new ConfigQuery<String>() {
- @Override
- public String query(Configuration config) {
- StringBuilder builder = new StringBuilder();
- addHeader(builder);
- builder.append("<pre>\n").append(textInfo(info).query(config)).append("</pre>\n");
- addFooter(builder);
- return builder.toString();
- }
+ public static Function<Config,String> htmlInfo(final Map<String, String> info) {
+ return config -> {
+ StringBuilder builder = new StringBuilder();
+ addHeader(builder);
+ builder.append("<pre>\n").append(textInfo(info).apply(config)).append("</pre>\n");
+ addFooter(builder);
+ return builder.toString();
};
}
@@ -649,19 +503,12 @@ public final class ConfigurationFunctions {
}
/**
- * Accesses an empty {@link Configuration}.
- * @return an empty {@link Configuration}, never null.
+ * Accesses an empty {@link Config}.
+ * @return an empty {@link Config}, never null.
*/
- public static Configuration emptyConfiguration(){
+ public static Config emptyConfig(){
return EMPTY_CONFIGURATION;
}
- /**
- * Accesses an empty {@link ConfigurationContext}.
- * @return an empty {@link ConfigurationContext}, never null.
- */
- public static ConfigurationContext emptyConfigurationContext(){
- return EMPTY_CONFIGURATION_CONTEXT;
- }
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/581c92e7/modules/functions/src/main/java/org/apache/tamaya/functions/EnrichedConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/main/java/org/apache/tamaya/functions/EnrichedConfiguration.java b/modules/functions/src/main/java/org/apache/tamaya/functions/EnrichedConfiguration.java
index a223a45..0a9c549 100644
--- a/modules/functions/src/main/java/org/apache/tamaya/functions/EnrichedConfiguration.java
+++ b/modules/functions/src/main/java/org/apache/tamaya/functions/EnrichedConfiguration.java
@@ -18,22 +18,16 @@
*/
package org.apache.tamaya.functions;
-import org.apache.tamaya.ConfigOperator;
-import org.apache.tamaya.ConfigQuery;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.TypeLiteral;
-import org.apache.tamaya.spi.ConfigurationContext;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
+import javax.config.Config;
+import javax.config.spi.ConfigSource;
+import java.util.*;
/**
* Configuration, that has values added or overridden.
*/
-class EnrichedConfiguration implements Configuration {
+class EnrichedConfiguration implements Config {
- private final Configuration baseConfiguration;
+ private final Config baseConfiguration;
private final Map<String, Object> addedProperties = new HashMap<>();
@@ -46,127 +40,59 @@ class EnrichedConfiguration implements Configuration {
* @param properties the properties to be added, not null.
* @param overriding true, if existing keys should be overriden, or config should be extended only.
*/
- EnrichedConfiguration(Configuration configuration, Map<String, Object> properties, boolean overriding) {
+ EnrichedConfiguration(Config configuration, Map<String, Object> properties, boolean overriding) {
this.baseConfiguration = Objects.requireNonNull(configuration);
this.addedProperties.putAll(properties);
this.overriding = overriding;
}
@Override
- public String get(String key) {
- Objects.requireNonNull(key, "Key must be given.");
-
- if (overriding) {
- Object val = addedProperties.get(key);
- if (val != null) {
- return val.toString();
- }
- return baseConfiguration.get(key);
- }
- String val = baseConfiguration.get(key);
- if (val != null) {
- return val;
- }
- Object val2 = addedProperties.get(key);
- if (val2 != null) {
- return val2.toString();
- }
- return null;
+ public <T> T getValue(String key, Class<T> type) {
+ return getOptionalValue(key, type).orElse(null);
}
@Override
- public String getOrDefault(String key, String defaultValue) {
+ public <T> Optional<T> getOptionalValue(String key, Class<T> type) {
Objects.requireNonNull(key, "Key must be given.");
- Objects.requireNonNull(defaultValue, "Default value must be given.");
-
- String val = get(key);
- if (val == null) {
- return defaultValue;
- }
- return val;
- }
-
- @Override
- public <T> T getOrDefault(String key, Class<T> type, T defaultValue) {
- Objects.requireNonNull(key, "Key not given.");
- Objects.requireNonNull(type, "Class not given.");
- Objects.requireNonNull(defaultValue, "Default value not given.");
-
- T val = get(key, type);
- if (val == null) {
- return defaultValue;
- }
- return val;
- }
-
- @Override
- public <T> T get(String key, Class<T> type) {
- return (T) get(key, TypeLiteral.of(type));
- }
-
- @Override
- public <T> T get(String key, TypeLiteral<T> type) {
+ Objects.requireNonNull(type, "Type must be given.");
if (overriding) {
Object val = addedProperties.get(key);
- if (val != null && type.getRawType().isAssignableFrom(val.getClass())) {
- return (T) val;
+ if (val != null){
+ if(type.isAssignableFrom(type)){
+ return Optional.of((T)val);
+ }else if(type == String.class) {
+ return Optional.of((T)val.toString());
+ }
+ return baseConfiguration.getOptionalValue(key, type);
}
- return baseConfiguration.get(key, type);
}
- T val = baseConfiguration.get(key, type);
- if (val != null) {
+ Optional<T> val = baseConfiguration.getOptionalValue(key, type);
+ if (val !=null && val.isPresent()) {
return val;
}
Object val2 = addedProperties.get(key);
- if (val2 != null && type.getRawType().isAssignableFrom(val2.getClass())) {
- return (T) val2;
- }
- return null;
- }
-
- @Override
- public <T> T getOrDefault(String key, TypeLiteral<T> type, T defaultValue) {
- Objects.requireNonNull(key, "Key not given.");
- Objects.requireNonNull(type, "Type not given.");
- Objects.requireNonNull(defaultValue, "Default value not given.");
-
- T val = get(key, type);
- if (val == null) {
- return defaultValue;
- }
- return val;
- }
-
- @Override
- public Map<String, String> getProperties() {
- Map<String, String> allProps = new HashMap<>();
- if (overriding) {
- allProps.putAll(baseConfiguration.getProperties());
- for (Map.Entry<String, Object> en : addedProperties.entrySet()) {
- allProps.put(en.getKey(), en.getValue().toString());
- }
- } else {
- for (Map.Entry<String, Object> en : addedProperties.entrySet()) {
- allProps.put(en.getKey(), en.getValue().toString());
+ if (val2 != null){
+ if(type.isAssignableFrom(val2.getClass())) {
+ return Optional.of((T) val2);
+ }else if(type == String.class) {
+ return Optional.of((T)val2.toString());
}
- allProps.putAll(baseConfiguration.getProperties());
}
- return allProps;
+ return Optional.empty();
}
- @Override
- public Configuration with(ConfigOperator operator) {
- return operator.operate(this);
- }
@Override
- public <T> T query(ConfigQuery<T> query) {
- return query.query(this);
+ public Iterable<String> getPropertyNames() {
+ Set<String> allKeys = new HashSet<>();
+ baseConfiguration.getPropertyNames().forEach(allKeys::add);
+ addedProperties.keySet().forEach(allKeys::add);
+ return allKeys;
}
@Override
- public ConfigurationContext getContext() {
- return baseConfiguration.getContext();
+ public Iterable<ConfigSource> getConfigSources() {
+ return baseConfiguration.getConfigSources();
}
}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/581c92e7/modules/functions/src/main/java/org/apache/tamaya/functions/FilteredConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/main/java/org/apache/tamaya/functions/FilteredConfiguration.java b/modules/functions/src/main/java/org/apache/tamaya/functions/FilteredConfiguration.java
index e8acaaa..b61c730 100644
--- a/modules/functions/src/main/java/org/apache/tamaya/functions/FilteredConfiguration.java
+++ b/modules/functions/src/main/java/org/apache/tamaya/functions/FilteredConfiguration.java
@@ -18,101 +18,57 @@
*/
package org.apache.tamaya.functions;
-import org.apache.tamaya.ConfigOperator;
-import org.apache.tamaya.ConfigQuery;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.TypeLiteral;
-import org.apache.tamaya.spi.ConfigurationContext;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
+import javax.config.Config;
+import javax.config.spi.ConfigSource;
+import java.util.*;
/**
* Configuration that filters part of the entries defined by a matcher predicate.
*/
-class FilteredConfiguration implements Configuration {
+class FilteredConfiguration implements Config {
- private final Configuration baseConfiguration;
+ private final Config baseConfiguration;
private final PropertyMatcher matcher;
private final String filterType;
- FilteredConfiguration(Configuration baseConfiguration, PropertyMatcher matcher, String filterType) {
+ FilteredConfiguration(Config baseConfiguration, PropertyMatcher matcher, String filterType) {
this.baseConfiguration = Objects.requireNonNull(baseConfiguration);
this.matcher = Objects.requireNonNull(matcher);
this.filterType = filterType!=null?filterType:this.matcher.toString();
}
@Override
- public String get(String key) {
- return get(key, String.class);
- }
-
- @Override
- public String getOrDefault(String key, String defaultValue) {
- String val = get(key);
- if(val==null){
- return defaultValue;
- }
- return val;
- }
-
- @Override
- public <T> T getOrDefault(String key, Class<T> type, T defaultValue) {
- T val = get(key, type);
- if(val==null){
- return defaultValue;
- }
- return val;
- }
-
- @Override
- public <T> T get(String key, Class<T> type) {
- return (T)get(key, TypeLiteral.of(type));
- }
-
- @Override
- public <T> T get(String key, TypeLiteral<T> type) {
- String value = baseConfiguration.get(key);
- if (matcher.test(key, value)) {
- return baseConfiguration.get(key, type);
+ public <T> T getValue(String key, Class<T> type) {
+ String stringValue = baseConfiguration.getValue(key, String.class);
+ if (matcher.test(key, stringValue)) {
+ return baseConfiguration.getValue(key, type);
}
return null;
}
@Override
- public <T> T getOrDefault(String key, TypeLiteral<T> type, T defaultValue) {
- T val = get(key, type);
- if(val==null){
- return defaultValue;
+ public <T> Optional<T> getOptionalValue(String key, Class<T> type) {
+ Optional<String> value = baseConfiguration.getOptionalValue(key, String.class);
+ if(value.isPresent() && matcher.test(key, value.get())) {
+ return baseConfiguration.getOptionalValue(key, type);
}
- return val;
+ return Optional.empty();
}
@Override
- public Map<String, String> getProperties() {
- Map<String, String> result = new HashMap<>();
- for(Map.Entry<String,String> en:baseConfiguration.getProperties().entrySet()){
- if(matcher.test(en.getKey(), en.getValue())){
- result.put(en.getKey(), en.getValue());
+ public Iterable<String> getPropertyNames() {
+ Set<String> result = new HashSet<>();
+ for(String name:baseConfiguration.getPropertyNames()){
+ if(matcher.test(name, null)){
+ result.add(name);
}
}
return result;
}
@Override
- public Configuration with(ConfigOperator operator) {
- return null;
- }
-
- @Override
- public <T> T query(ConfigQuery<T> query) {
- return query.query(this);
- }
-
- @Override
- public ConfigurationContext getContext() {
- return baseConfiguration.getContext();
+ public Iterable<ConfigSource> getConfigSources() {
+ return this.baseConfiguration.getConfigSources();
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/581c92e7/modules/functions/src/main/java/org/apache/tamaya/functions/MappedConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/main/java/org/apache/tamaya/functions/MappedConfiguration.java b/modules/functions/src/main/java/org/apache/tamaya/functions/MappedConfiguration.java
index dd2547f..ec48b2f 100644
--- a/modules/functions/src/main/java/org/apache/tamaya/functions/MappedConfiguration.java
+++ b/modules/functions/src/main/java/org/apache/tamaya/functions/MappedConfiguration.java
@@ -18,110 +18,66 @@
*/
package org.apache.tamaya.functions;
-import org.apache.tamaya.ConfigOperator;
-import org.apache.tamaya.ConfigQuery;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.TypeLiteral;
-import org.apache.tamaya.spi.ConfigurationContext;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
+import javax.config.Config;
+import javax.config.spi.ConfigSource;
+import java.util.*;
import java.util.logging.Logger;
/**
* Configuration that filters part of the entries defined by a filter predicate.
*/
-class MappedConfiguration implements Configuration {
+class MappedConfiguration implements Config {
private static final Logger LOG = Logger.getLogger(MappedConfiguration.class.getName());
- private final Configuration baseConfiguration;
+ private final Config baseConfiguration;
private final KeyMapper keyMapper;
private final String mapType;
- MappedConfiguration(Configuration baseConfiguration, KeyMapper keyMapper, String mapType) {
+ MappedConfiguration(Config baseConfiguration, KeyMapper keyMapper, String mapType) {
this.baseConfiguration = Objects.requireNonNull(baseConfiguration);
this.keyMapper = Objects.requireNonNull(keyMapper);
this.mapType = mapType!=null?mapType:this.keyMapper.toString();
}
@Override
- public String get(String key) {
- return get(key, String.class);
- }
-
- @Override
- public String getOrDefault(String key, String defaultValue) {
- Objects.requireNonNull(key, "Key must be given");
- Objects.requireNonNull(defaultValue, "DefaultValue must be given.");
- String val = get(key);
-
- if(val==null){
- return defaultValue;
- }
- return val;
- }
-
- @Override
- public <T> T getOrDefault(String key, Class<T> type, T defaultValue) {
- T val = get(key, type);
- if(val==null){
- return defaultValue;
+ public <T> T getValue(String key, Class<T> type) {
+ String targetKey = keyMapper.mapKey(key);
+ if (targetKey != null) {
+ return baseConfiguration.getValue(targetKey, type);
}
- return val;
- }
+ LOG.finest("Configuration property hidden by KeyMapper, key="+key+", mapper="+keyMapper+", config="+this);
+ return null;
- @Override
- public <T> T get(String key, Class<T> type) {
- return (T)get(key, TypeLiteral.of(type));
}
@Override
- public <T> T get(String key, TypeLiteral<T> type) {
+ public <T> Optional<T> getOptionalValue(String key, Class<T> type) {
String targetKey = keyMapper.mapKey(key);
if (targetKey != null) {
- return baseConfiguration.get(targetKey, type);
+ return baseConfiguration.getOptionalValue(targetKey, type);
}
LOG.finest("Configuration property hidden by KeyMapper, key="+key+", mapper="+keyMapper+", config="+this);
- return null;
+ return Optional.empty();
}
- @Override
- public <T> T getOrDefault(String key, TypeLiteral<T> type, T defaultValue) {
- T val = get(key, type);
- if(val==null){
- return defaultValue;
- }
- return val;
- }
@Override
- public Map<String, String> getProperties() {
- Map<String, String> baseProps = baseConfiguration.getProperties();
- Map<String, String> props = new HashMap<>(baseProps.size());
- for(Map.Entry<String,String> en:baseProps.entrySet()){
- String targetKey = keyMapper.mapKey(en.getKey());
+ public Iterable<String> getPropertyNames() {
+ Iterable<String> propertyNames = baseConfiguration.getPropertyNames();
+ Set<String> result = new HashSet<>();
+ for(String key:propertyNames){
+ String targetKey = keyMapper.mapKey(key);
if (targetKey != null) {
- props.put(targetKey, en.getValue());
+ result.add(targetKey);
}
}
- return props;
- }
-
- @Override
- public Configuration with(ConfigOperator operator) {
- return operator.operate(this);
- }
-
- @Override
- public <T> T query(ConfigQuery<T> query) {
- return query.query(this);
+ return result;
}
@Override
- public ConfigurationContext getContext() {
- return baseConfiguration.getContext();
+ public Iterable<ConfigSource> getConfigSources() {
+ return baseConfiguration.getConfigSources();
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-extensions/blob/581c92e7/modules/functions/src/test/java/org/apache/tamaya/functions/CombinedConfigurationTest.java
----------------------------------------------------------------------
diff --git a/modules/functions/src/test/java/org/apache/tamaya/functions/CombinedConfigurationTest.java b/modules/functions/src/test/java/org/apache/tamaya/functions/CombinedConfigurationTest.java
index 16cabeb..bb27ccd 100644
--- a/modules/functions/src/test/java/org/apache/tamaya/functions/CombinedConfigurationTest.java
+++ b/modules/functions/src/test/java/org/apache/tamaya/functions/CombinedConfigurationTest.java
@@ -18,21 +18,15 @@
*/
package org.apache.tamaya.functions;
-import org.apache.tamaya.ConfigOperator;
-import org.apache.tamaya.ConfigQuery;
-import org.apache.tamaya.Configuration;
-import org.apache.tamaya.TypeLiteral;
-import org.apache.tamaya.spi.ConfigurationContext;
+import org.apache.tamaya.base.DefaultConfigBuilder;
+import org.apache.tamaya.base.configsource.SimpleConfigSource;
import org.apache.tamaya.spisupport.DefaultConfiguration;
-import org.apache.tamaya.core.internal.CoreConfigurationBuilder;
-import org.apache.tamaya.spisupport.propertysource.SimplePropertySource;
import org.assertj.core.api.ThrowableAssert;
import org.junit.Test;
import org.mockito.Mockito;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
+import javax.config.Config;
+import java.util.*;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonMap;
@@ -40,53 +34,43 @@ import static org.apache.tamaya.functions.MethodNotMockedAnswer.NOT_MOCKED_ANSWE
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.within;
+import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class CombinedConfigurationTest {
- private Configuration configWithA1;
- private Configuration configWithA2;
- private Configuration configWithB;
- private Configuration configWithC;
- private Configuration configWithoutEntries;
+ private Config configWithA1;
+ private Config configWithA2;
+ private Config configWithB;
+ private Config configWithC;
+ private Config configWithoutEntries;
{
- SimplePropertySource sourceWithKeyA1 = new SimplePropertySource("A", singletonMap("a", "a1"));
- SimplePropertySource sourceWithKeyA2 = new SimplePropertySource("A", singletonMap("a", "a2"));
- SimplePropertySource sourceWithKeyB = new SimplePropertySource("B", singletonMap("b", "b"));
- SimplePropertySource sourceWithKeyC = new SimplePropertySource("C", singletonMap("c", "c"));
- SimplePropertySource sourceWithoutKeys = new SimplePropertySource("NONE", Collections.<String, String>emptyMap());
-
- Configuration ccWithA1 = new CoreConfigurationBuilder().addPropertySources(sourceWithKeyA1)
- .build();
- Configuration ccWithA2 = new CoreConfigurationBuilder().addPropertySources(sourceWithKeyA2)
- .build();
- Configuration ccWithB = new CoreConfigurationBuilder().addPropertySources(sourceWithKeyB)
- .build();
- Configuration ccWithC = new CoreConfigurationBuilder().addPropertySources(sourceWithKeyC)
- .build();
- Configuration ccWithoutEntries = new CoreConfigurationBuilder().addPropertySources(sourceWithoutKeys)
- .build();
-
- configWithA1 = new DefaultConfiguration(ccWithA1.getContext());
- configWithA2 = new DefaultConfiguration(ccWithA2.getContext());
- configWithB = new DefaultConfiguration(ccWithB.getContext());
- configWithC = new DefaultConfiguration(ccWithC.getContext());
- configWithoutEntries = new DefaultConfiguration(ccWithoutEntries.getContext());
+ SimpleConfigSource sourceWithKeyA1 = new SimpleConfigSource("A", singletonMap("a", "a1"));
+ SimpleConfigSource sourceWithKeyA2 = new SimpleConfigSource("A", singletonMap("a", "a2"));
+ SimpleConfigSource sourceWithKeyB = new SimpleConfigSource("B", singletonMap("b", "b"));
+ SimpleConfigSource sourceWithKeyC = new SimpleConfigSource("C", singletonMap("c", "c"));
+ SimpleConfigSource sourceWithoutKeys = new SimpleConfigSource("NONE", Collections.<String, String>emptyMap());
+
+ configWithA1 = new DefaultConfigBuilder().withSources(sourceWithKeyA1).build();
+ configWithA2 = new DefaultConfigBuilder().withSources(sourceWithKeyA2).build();
+ configWithB = new DefaultConfigBuilder().withSources(sourceWithKeyB).build();
+ configWithC = new DefaultConfigBuilder().withSources(sourceWithKeyC).build();
+ configWithoutEntries = new DefaultConfigBuilder().withSources(sourceWithoutKeys).build();
}
@Test
public void createCombinedConfigurationWithNullAsSingleConfiguration() {
CombinedConfiguration cc = new CombinedConfiguration("abc", null);
- assertThat(cc.get("nil")).isNull();
+ assertThat(cc.getValue("nil", String.class)).isNull();
}
@Test
public void createCombinedConfigurationWithNullNullAsSingleConfiguration() {
CombinedConfiguration cc = new CombinedConfiguration("abc", null, null);
- assertThat(cc.get("nil")).isNull();
+ assertThat(cc.getValue("nil", String.class)).isNull();
}
@Test
@@ -94,21 +78,21 @@ public class CombinedConfigurationTest {
CombinedConfiguration cc = new CombinedConfiguration("abc", configWithA1, configWithB, configWithC);
- assertThat(cc.get("key")).isNull();
+ assertThat(cc.getValue("key", String.class)).isNull();
}
@Test
public void requestedEntryIsInTheFirstAndThridConfiguration() {
CombinedConfiguration cc = new CombinedConfiguration("abc", configWithA1, configWithB, configWithA2);
- assertThat(cc.get("a")).isEqualTo("a2");
+ assertThat(cc.getValue("a", String.class)).isEqualTo("a2");
}
@Test
public void requestedEntryIsOnlyInOneConfiguration() {
CombinedConfiguration cc = new CombinedConfiguration("abc", configWithA1, configWithB, configWithC);
- assertThat(cc.get("b")).isEqualTo("b");
+ assertThat(cc.getValue("b", String.class)).isEqualTo("b");
}
/*
@@ -116,49 +100,25 @@ public class CombinedConfigurationTest {
*/
@Test
- public void getOrDefaultWithSignatureStringStringThrowsNPEIfKeyIsNull() {
+ public void getOptionalValueWithSignatureStringStringThrowsNPEIfKeyIsNull() {
final CombinedConfiguration cc = mock(CombinedConfiguration.class, CALLS_REAL_METHODS);
assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
@Override
public void call() throws Throwable {
- cc.getOrDefault(null, "d");
+ cc.getOptionalValue(null, String.class).orElse("d");
}
}).isInstanceOf(NullPointerException.class)
.hasMessage("Key must be given.");
}
@Test
- public void getOrDefaultWithSignatureStringStringThrowsNPEIfValueIsNull() {
- final CombinedConfiguration cc = mock(CombinedConfiguration.class, CALLS_REAL_METHODS);
-
- assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- @Override
- public void call() throws Throwable {
- cc.getOrDefault("key", (String)null);
- }
- }).isInstanceOf(NullPointerException.class)
- .hasMessage("Value must be given.");
- }
-
- @Test
- public void getOrDefaultWithSignatureStringStringReturnsDefaultIfKeyIsUnknown() {
- CombinedConfiguration cc = mock(CombinedConfiguration.class);
- doReturn(null).when(cc).get("a");
- doCallRealMethod().when(cc).getOrDefault(anyString(), anyString());
-
- String result = cc.getOrDefault("a", "tzui");
+ public void getOptionalValueWithSignatureStringStringReturnsFoundValueIfKeyIsKnown() {
+ Config cfg = mock(Config.class);
+ doReturn(Optional.of("b")).when(cfg).getOptionalValue("a", String.class);
- assertThat(result).isEqualTo("tzui");
- }
-
- @Test
- public void getOrDefaultWithSignatureStringStringReturnsFoundValueIfKeyIsKnown() {
- CombinedConfiguration cc = mock(CombinedConfiguration.class);
- doReturn("b").when(cc).get(Mockito.eq("a"));
- doCallRealMethod().when(cc).getOrDefault(anyString(), anyString());
-
- String result = cc.getOrDefault("a", "z");
+ String result = new CombinedConfiguration("test", cfg)
+ .getOptionalValue("a", String.class).get();
assertThat(result).isEqualTo("b");
}
@@ -168,15 +128,15 @@ public class CombinedConfigurationTest {
*/
@Test
- public void getOrDefaultStringTypeLiteralTThrowsNPEIfKeyIsNull() throws Exception {
- final CombinedConfiguration cc = mock(CombinedConfiguration.class);
- doCallRealMethod().when(cc).getOrDefault(anyString(), eq(TypeLiteral.of(Integer.class)),
- Mockito.any(Integer.class));
+ public void getOptionalValueStringTypeTThrowsNPEIfKeyIsNull() throws Exception {
+ final Config cfg = mock(Config.class);
+ doReturn(Optional.of(Integer.valueOf(67))).when(cfg).getOptionalValue("a", Integer.class);
assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
@Override
public void call() throws Throwable {
- cc.getOrDefault(null, TypeLiteral.of(Integer.class), 1);
+ new CombinedConfiguration("test", cfg)
+ .getOptionalValue(null, Integer.class).orElse(1);
}
}).isInstanceOf(NullPointerException.class)
.hasMessage("Key must be given.");
@@ -184,59 +144,40 @@ public class CombinedConfigurationTest {
}
@Test
- public void getOrDefaultStringTypeLiteralTThrowsNPEIfTypeIsNull() throws Exception {
+ public void getOptionalValueStringTypeThrowsNPEIfTypeIsNull() throws Exception {
final CombinedConfiguration cc = mock(CombinedConfiguration.class, NOT_MOCKED_ANSWER);
- doCallRealMethod().when(cc).getOrDefault(anyString(), eq((TypeLiteral<Integer>)null),
- Mockito.any(Integer.class));
+ doCallRealMethod().when(cc).getOptionalValue(eq("a"), any(Class.class));
assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
@Override
public void call() throws Throwable {
- cc.<Integer>getOrDefault("a", (TypeLiteral<Integer>)null, 1);
+ cc.<Integer>getOptionalValue("a", (Class)null);
}
}).isInstanceOf(NullPointerException.class)
.hasMessage("Type must be given.");
}
@Test
- public void getOrDefaultStringTypeLiteralTThrowsNPEIfDefaultValueIsNull() throws Exception {
- final CombinedConfiguration cc = mock(CombinedConfiguration.class, NOT_MOCKED_ANSWER);
- doCallRealMethod().when(cc).getOrDefault(anyString(), eq(TypeLiteral.of(Integer.class)),
- Mockito.any(Integer.class));
-
- assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- @Override
- public void call() throws Throwable {
- cc.getOrDefault("a", TypeLiteral.of(Integer.class), null);
- }
- }).isInstanceOf(NullPointerException.class)
- .hasMessage("Default value must be given.");
- }
-
- @Test
- public void getOrDefaultStringTypeLiteralTReturnsDefaultValueIfKeyIsUnknown() throws Exception {
- final CombinedConfiguration cc = mock(CombinedConfiguration.class, NOT_MOCKED_ANSWER);
- doReturn(null).when(cc).get(eq("a"), eq(TypeLiteral.<Integer>of(Integer.class)));
- doCallRealMethod().when(cc).getOrDefault(anyString(), eq(TypeLiteral.of(Integer.class)),
- Mockito.any(Integer.class));
-
- TypeLiteral<Integer> typeLiteral = TypeLiteral.of(Integer.class);
- Integer result = cc.<Integer>getOrDefault("a", typeLiteral, 789);
-
- assertThat(result).isEqualTo(789);
+ public void getOptionalValueStringTypeTReturnsEmptyOptionalIfKeyIsUnknown() throws Exception {
+ final Config cfg = mock(Config.class);
+ doReturn(null).when(cfg).getOptionalValue(any(), any(Class.class));
+ Optional<Integer> val = new CombinedConfiguration("test", cfg)
+ .getOptionalValue("b", Integer.class);
+ assertNotNull(val);
+ assertFalse(val.isPresent());
}
@Test
- public void getOrDefaultStringTypeLiteralTReturnsFoundValueIfKeyIsKnown() throws Exception {
- final CombinedConfiguration cc = mock(CombinedConfiguration.class, NOT_MOCKED_ANSWER);
- doReturn(999).when(cc).get(eq("a"), eq(TypeLiteral.<Integer>of(Integer.class)));
- doCallRealMethod().when(cc).getOrDefault(anyString(), eq(TypeLiteral.of(Integer.class)),
- Mockito.anyInt());
-
- Integer result = cc.<Integer>getOrDefault("a", TypeLiteral.<Integer>of(Integer.class), 789);
-
- assertThat(result).isEqualTo(999);
+ public void getOptionalValueStringTypeReturnsFoundValueIfKeyIsKnown() throws Exception {
+ final Config cfg = mock(Config.class);
+ doReturn(Optional.of(Integer.valueOf(768))).when(cfg).getOptionalValue("a", Integer.class);
+
+ Optional<Integer> val = new CombinedConfiguration("test", cfg)
+ .getOptionalValue("a", Integer.class);
+ assertNotNull(val);
+ assertTrue(val.isPresent());
+ assertEquals(Integer.valueOf(768), val.get());
}
/*
@@ -244,72 +185,38 @@ public class CombinedConfigurationTest {
*/
@Test
- public void getOrDefaultStringClassTThrowsNPEIfKeyIsNull() throws Exception {
- final CombinedConfiguration cc = mock(CombinedConfiguration.class);
- doCallRealMethod().when(cc).getOrDefault(anyString(), Mockito.any(Class.class),
- Mockito.any(Integer.class));
-
+ public void getOptionalValueStringClassTThrowsNPEIfKeyIsNull() throws Exception {
+ final Config cfg = mock(Config.class,NOT_MOCKED_ANSWER);
assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
@Override
public void call() throws Throwable {
- cc.getOrDefault(null, Integer.class, 1);
+ new CombinedConfiguration("test", cfg).getOptionalValue(null, Integer.class);
}
}).isInstanceOf(NullPointerException.class)
.hasMessage("Key must be given.");
}
@Test
- public void getOrDefaultStringClassTThrowsNPEIfTypeIsNull() throws Exception {
- final CombinedConfiguration cc = mock(CombinedConfiguration.class);
- doCallRealMethod().when(cc).getOrDefault(anyString(), Mockito.any(Class.class), Mockito.anyInt());
+ public void getOptionalValueStringClassTThrowsNPEIfTypeIsNull() throws Exception {
+ final Config cfg = mock(Config.class,NOT_MOCKED_ANSWER);
assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
@Override
public void call() throws Throwable {
- cc.getOrDefault("a", (Class<Integer>) null, 1);
+ new CombinedConfiguration("test", cfg)
+ .getOptionalValue("a", (Class<Integer>) null);
}
}).isInstanceOf(NullPointerException.class)
.hasMessage("Type must be given.");
}
@Test
- public void getOrDefaultStringClassTThrowsNPEIfDefaultValueIsNull() throws Exception {
- final CombinedConfiguration cc = mock(CombinedConfiguration.class, NOT_MOCKED_ANSWER);
- doCallRealMethod().when(cc).getOrDefault(anyString(), any(Class.class),
- Mockito.any(Integer.class));
-
- assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- @Override
- public void call() throws Throwable {
- cc.getOrDefault("a", Integer.class, null);
- }
- }).isInstanceOf(NullPointerException.class)
- .hasMessage("Default value must be given.");
- }
-
- @Test
- public void getOrDefaultStringClassTReturnsDefaultValueIfKeyIsUnknown() throws Exception {
- final CombinedConfiguration cc = mock(CombinedConfiguration.class, NOT_MOCKED_ANSWER);
- doReturn(null).when(cc).get(eq("a"), any(Class.class));
- doCallRealMethod().when(cc).getOrDefault(anyString(), any(Class.class),
- Mockito.any(Integer.class));
-
- TypeLiteral<Integer> typeLiteral = TypeLiteral.of(Integer.class);
- Integer result = cc.<Integer>getOrDefault("a", Integer.class, 789);
-
- assertThat(result).isEqualTo(789);
- }
-
-
- @Test
- public void getOrDefaultStringClassTReturnsFoundValueIfKeyIsKnown() throws Exception {
- final CombinedConfiguration cc = mock(CombinedConfiguration.class, NOT_MOCKED_ANSWER);
- doReturn(999).when(cc).get(eq("a"), any(Class.class));
- doCallRealMethod().when(cc).getOrDefault(anyString(), any(Class.class),
- Mockito.anyInt());
-
- Integer result = cc.<Integer>getOrDefault("a", Integer.class, 789);
-
+ public void getOptionalValueStringClassTReturnsFoundValueIfKeyIsKnown() throws Exception {
+ final Config cfg = mock(Config.class);
+ doReturn(Optional.of(Integer.valueOf(999))).when(cfg).getOptionalValue(eq("a"), any(Class.class));
+ doReturn(Optional.of(Integer.valueOf(999))).when(cfg).getOptionalValue(eq("a"), any(Class.class));
+ Integer result = new CombinedConfiguration("test", cfg)
+ .getOptionalValue("a", Integer.class).orElse(789);
assertThat(result).isEqualTo(999);
}
@@ -319,152 +226,79 @@ public class CombinedConfigurationTest {
@Test
public void getPropertiesReturnsEmptyMapIfAllConfigurationsAreEmpty() throws Exception {
- Map<String, String> propsOfA = new HashMap<>();
- Map<String, String> propsOfB = new HashMap<>();
- Map<String, String> propsOfC = new HashMap<>();
-
- Configuration configA = Mockito.mock(Configuration.class, NOT_MOCKED_ANSWER);
- Configuration configB = Mockito.mock(Configuration.class, NOT_MOCKED_ANSWER);
- Configuration configC = Mockito.mock(Configuration.class, NOT_MOCKED_ANSWER);
+ Iterable<String> namesOfA = new HashSet<>();
+ Iterable<String> namesOfB = new HashSet<>();
+ Iterable<String> namesOfC = new HashSet<>();
- doReturn(propsOfA).when(configA).getProperties();
- doReturn(propsOfB).when(configB).getProperties();
- doReturn(propsOfC).when(configC).getProperties();
+ Config configA = Mockito.mock(Config.class, NOT_MOCKED_ANSWER);
+ Config configB = Mockito.mock(Config.class, NOT_MOCKED_ANSWER);
+ Config configC = Mockito.mock(Config.class, NOT_MOCKED_ANSWER);
- CombinedConfiguration cc = mock(CombinedConfiguration.class, NOT_MOCKED_ANSWER);
-
- doReturn(asList(configA, configB, configC)).when(cc).getConfigurations();
- doCallRealMethod().when(cc).getProperties();
-
- Map<String, String> result = cc.getProperties();
+ doReturn(namesOfA).when(configA).getPropertyNames();
+ doReturn(namesOfB).when(configB).getPropertyNames();
+ doReturn(namesOfC).when(configC).getPropertyNames();
+ CombinedConfiguration cc = new CombinedConfiguration("test", configA, configB, configC);
+ Iterable<String> result = cc.getPropertyNames();
assertThat(result).isEmpty();
}
@Test
- public void getPropertiesReturnsLastValueOfManyForAGivenKey() throws Exception {
- Map<String, String> propsOfA = new HashMap<String, String>() {{ put("a", "A"); }};
- Map<String, String> propsOfB = new HashMap<String, String>() {{ put("b", "B"); }};
- Map<String, String> propsOfC = new HashMap<String, String>() {{ put("a", "Z"); }};
-
- Configuration configA = Mockito.mock(Configuration.class, NOT_MOCKED_ANSWER);
- Configuration configB = Mockito.mock(Configuration.class, NOT_MOCKED_ANSWER);
- Configuration configC = Mockito.mock(Configuration.class, NOT_MOCKED_ANSWER);
-
- doReturn(propsOfA).when(configA).getProperties();
- doReturn(propsOfB).when(configB).getProperties();
- doReturn(propsOfC).when(configC).getProperties();
-
- CombinedConfiguration cc = mock(CombinedConfiguration.class, NOT_MOCKED_ANSWER);
-
- doReturn(asList(configA, configB, configC)).when(cc).getConfigurations();
- doCallRealMethod().when(cc).getProperties();
-
- Map<String, String> result = cc.getProperties();
-
- assertThat(result).containsEntry("a", "Z")
- .doesNotContainEntry("a", "A");
+ public void getPropertyValueReturnsLastValueOfManyForAGivenKey() throws Exception {
+ Set<String> propsOfA = new HashSet<String>() {{ add("a"); }};
+ Set<String> propsOfB = new HashSet<String>() {{ add("a"); }};
+ Set<String> propsOfC = new HashSet<String>() {{ add("a"); }};
+
+ Config configA = Mockito.mock(Config.class, NOT_MOCKED_ANSWER);
+ Config configB = Mockito.mock(Config.class, NOT_MOCKED_ANSWER);
+ Config configC = Mockito.mock(Config.class, NOT_MOCKED_ANSWER);
+
+ doReturn(Optional.of("A")).when(configA).getOptionalValue(eq("a"), any());
+ doReturn(Optional.of("B")).when(configB).getOptionalValue(eq("a"), any());
+ doReturn(Optional.of("C")).when(configC).getOptionalValue(eq("a"), any());
+ doReturn(Optional.empty()).when(configA).getOptionalValue(eq("foo"), any());
+ doReturn(Optional.empty()).when(configB).getOptionalValue(eq("foo"), any());
+ doReturn(Optional.empty()).when(configC).getOptionalValue(eq("foo"), any());
+ doReturn(propsOfA).when(configA).getPropertyNames();
+ doReturn(propsOfB).when(configB).getPropertyNames();
+ doReturn(propsOfC).when(configC).getPropertyNames();
+
+ CombinedConfiguration cc = new CombinedConfiguration("test", configA, configB, configC);
+ Iterable<String> result = cc.getPropertyNames();
+
+ assertThat(result).hasSize(1)
+ .contains("a");
+ assertThat(cc.getValue("a", String.class))
+ .isEqualTo("C");
+ assertThat(cc.getValue("foo", String.class))
+ .isNull();
}
@Test
- public void getPropertiesReturnsAllProperties() throws Exception {
- Map<String, String> propsOfA = new HashMap<String, String>() {{ put("a", "A"); }};
- Map<String, String> propsOfB = new HashMap<String, String>() {{ put("b", "B"); }};
- Map<String, String> propsOfC = new HashMap<String, String>() {{ put("c", "C"); }};
-
- Configuration configA = Mockito.mock(Configuration.class, NOT_MOCKED_ANSWER);
- Configuration configB = Mockito.mock(Configuration.class, NOT_MOCKED_ANSWER);
- Configuration configC = Mockito.mock(Configuration.class, NOT_MOCKED_ANSWER);
+ public void getPropertyNamesReturnsAllProperties() throws Exception {
+ Set<String> propsOfA = new HashSet<String>() {{ add("a"); }};
+ Set<String> propsOfB = new HashSet<String>() {{ add("b"); }};
+ Set<String> propsOfC = new HashSet<String>() {{ add("c"); }};
- doReturn(propsOfA).when(configA).getProperties();
- doReturn(propsOfB).when(configB).getProperties();
- doReturn(propsOfC).when(configC).getProperties();
+ Config configA = Mockito.mock(Config.class, NOT_MOCKED_ANSWER);
+ Config configB = Mockito.mock(Config.class, NOT_MOCKED_ANSWER);
+ Config configC = Mockito.mock(Config.class, NOT_MOCKED_ANSWER);
- CombinedConfiguration cc = mock(CombinedConfiguration.class, NOT_MOCKED_ANSWER);
+ doReturn("A").when(configA).getValue("a", String.class);
+ doReturn("B").when(configB).getValue("b", String.class);
+ doReturn("C").when(configC).getValue("c", String.class);
+ doReturn(propsOfA).when(configA).getPropertyNames();
+ doReturn(propsOfB).when(configB).getPropertyNames();
+ doReturn(propsOfC).when(configC).getPropertyNames();
- doReturn(asList(configA, configB, configC)).when(cc).getConfigurations();
- doCallRealMethod().when(cc).getProperties();
-
- Map<String, String> result = cc.getProperties();
+ CombinedConfiguration cc = new CombinedConfiguration("test", configA, configB, configC);
+ Iterable<String> result = cc.getPropertyNames();
assertThat(result).hasSize(3)
- .containsEntry("a", "A")
- .containsEntry("b", "B")
- .containsEntry("c", "C");
- }
-
- /*
- * Tests for with(ConfigOperator)
- */
-
- @Test
- public void withWithIndentityOperatorReturnsEqualConfiguration() throws Exception {
- class IdentityOpr implements ConfigOperator {
- @Override
- public Configuration operate(Configuration config) {
- return config;
- }
- }
-
- final CombinedConfiguration cc = mock(CombinedConfiguration.class, NOT_MOCKED_ANSWER);
- doCallRealMethod().when(cc).with(Mockito.any(ConfigOperator.class));
-
- Configuration result = cc.with(new IdentityOpr());
-
- assertThat(result).isNotNull()
- .isEqualTo(result);
- }
-
- @Test
- public void withWithNullAsOperatorParmeterThrowsNPE() throws Exception {
- final CombinedConfiguration cc = mock(CombinedConfiguration.class, NOT_MOCKED_ANSWER);
- doCallRealMethod().when(cc).with(Mockito.any(ConfigOperator.class));
-
- assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- @Override
- public void call() throws Throwable {
- cc.with(null);
- }
- }).isInstanceOf(NullPointerException.class)
- .hasMessage("Operator must be given.");
- }
-
- /*
- * Tests for query(ConfigQuery)
- */
-
- @Test
- public void queryWithNullAsQueryParameterThrowsNPE() throws Exception {
- final CombinedConfiguration cc = mock(CombinedConfiguration.class, NOT_MOCKED_ANSWER);
- doCallRealMethod().when(cc).query(Mockito.any(ConfigQuery.class));
-
- assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- @Override
- public void call() throws Throwable {
- cc.query(null);
- }
- }).isInstanceOf(NullPointerException.class)
- .hasMessage("Query must be given.");
- }
-
- @Test
- public void queryWithRealQueryReturnsCorrectResult() throws Exception {
- class GetZahl implements ConfigQuery<Integer> {
- @Override
- public Integer query(Configuration config) {
- return config.get("zahl", Integer.class);
- }
- }
-
- final CombinedConfiguration cc = mock(CombinedConfiguration.class, NOT_MOCKED_ANSWER);
- doCallRealMethod().when(cc).query(Mockito.any(ConfigQuery.class));
- doReturn(1).when(cc).<Integer>get(eq("zahl"), eq(Integer.class));
-
- Integer result = cc.query(new GetZahl());
-
- assertThat(result).isEqualTo(1);
+ .contains("a")
+ .contains("b")
+ .contains("c");
}
- // ConfigurationContext getContext(); none one three
}
\ No newline at end of file