http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/d0e14ed7/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/BuildablePropertySourceProvider.java ---------------------------------------------------------------------- diff --git a/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/BuildablePropertySourceProvider.java b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/BuildablePropertySourceProvider.java new file mode 100644 index 0000000..1becb50 --- /dev/null +++ b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/BuildablePropertySourceProvider.java @@ -0,0 +1,114 @@ +/* + * 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.propertysource; + +import org.apache.tamaya.spi.PropertySource; +import org.apache.tamaya.spi.PropertySourceProvider; + +import java.util.*; + +/** + * A Buildable property source. + */ +public class BuildablePropertySourceProvider implements PropertySourceProvider{ + + private List<PropertySource> sources = new ArrayList<>(); + + @Override + public Collection<PropertySource> getPropertySources() { + return Collections.unmodifiableCollection(sources); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + BuildablePropertySourceProvider that = (BuildablePropertySourceProvider) o; + + return sources.equals(that.sources); + } + + @Override + public int hashCode() { + return sources.hashCode(); + } + + @Override + public String toString() { + return "BuildablePropertySourceProvider{" + + "sources=" + sources + + '}'; + } + + /** + * Builder builder. + * + * @return the builder + */ + public static Builder builder() { + return new Builder(); + } + + + + + /** + * The type Builder. + */ + public static final class Builder { + private List<PropertySource> sources = new ArrayList<>(); + + private Builder() { + } + + /** + * With propertySources. + * + * @param propertySources the propertySources + * @return the builder + */ + public Builder withPropertySourcs(PropertySource... propertySources) { + this.sources.addAll(Arrays.asList(propertySources)); + return this; + } + + /** + * With property sources builder. + * + * @param sources the property sources + * @return the builder + */ + public Builder withPropertySourcs(Collection<PropertySource> sources) { + this.sources.addAll(sources); + return this; + } + + /** + * Build buildable property source. + * + * @return the buildable property source + */ + public BuildablePropertySourceProvider build() { + BuildablePropertySourceProvider buildablePropertySource = new BuildablePropertySourceProvider(); + buildablePropertySource.sources.addAll(this.sources); + return buildablePropertySource; + } + } +}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/d0e14ed7/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/CLIPropertySource.java ---------------------------------------------------------------------- diff --git a/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/CLIPropertySource.java b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/CLIPropertySource.java new file mode 100644 index 0000000..a83722f --- /dev/null +++ b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/CLIPropertySource.java @@ -0,0 +1,137 @@ +/* + * 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.propertysource; + +import org.apache.tamaya.spi.PropertyValue; + +import java.util.*; + +/** + * PropertySource that allows to add the programs main arguments as configuration entries. Unix syntax using '--' and + * '-' params is supported. + */ +public class CLIPropertySource extends BasePropertySource { + + /** The original main arguments. */ + private static String[] args = new String[0]; + + /** The map of parsed main arguments. */ + private static Map<String,PropertyValue> mainArgs; + + /** Initializes the initial state. */ + static{ + initMainArgs(args); + } + + /** + * Creates a new instance. + */ + public CLIPropertySource(){ + this((String[])null); + } + + /** + * Creates a new instance, allows optionally to pass the main arguments. + * @param args the args, or null. + */ + public CLIPropertySource(String... args){ + super("CLI"); + if(args!=null){ + initMainArgs(args); + } + } + + /** + * Creates a new instance, allows optionally to pass the main arguments. + * @param args the args, or null. + * @param ordinal the ordinal to be applied. + */ + public CLIPropertySource(int ordinal, String... args){ + if(args!=null){ + initMainArgs(args); + } + setOrdinal(ordinal); + } + + + + /** + * Configure the main arguments, hereby parsing and mapping the main arguments into + * configuration propertiesi as key-value pairs. + * @param args the main arguments, not null. + */ + public static void initMainArgs(String... args){ + CLIPropertySource.args = Objects.requireNonNull(args); + // TODO is there a way to figure out the args? + String argsProp = System.getProperty("main.args"); + if(argsProp!=null){ + CLIPropertySource.args = argsProp.split("\\s"); + } + Map<String,String> result = null; + if(CLIPropertySource.args==null){ + result = Collections.emptyMap(); + }else{ + result = new HashMap<>(); + String prefix = System.getProperty("main.args.prefix"); + if(prefix==null){ + prefix=""; + } + String key = null; + for(String arg:CLIPropertySource.args){ + if(arg.startsWith("--")){ + arg = arg.substring(2); + int index = arg.indexOf("="); + if(index>0){ + key = arg.substring(0,index).trim(); + result.put(prefix+key, arg.substring(index+1).trim()); + key = null; + }else{ + result.put(prefix+arg, arg); + } + }else if(arg.startsWith("-")){ + key = arg.substring(1); + }else{ + if(key!=null){ + result.put(prefix+key, arg); + key = null; + }else{ + result.put(prefix+arg, arg); + } + } + } + } + Map<String,PropertyValue> finalProps = new HashMap<>(); + for(Map.Entry<String,String> en:result.entrySet()) { + finalProps.put(en.getKey(), + PropertyValue.of(en.getKey(), en.getValue(), "main-args")); + } + CLIPropertySource.mainArgs = Collections.unmodifiableMap(finalProps); + } + + @Override + public Map<String, PropertyValue> getProperties() { + return Collections.unmodifiableMap(mainArgs); + } + + @Override + protected String toStringValues() { + return super.toStringValues() + + " args=" + Arrays.toString(args) + '\n'; + } +} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/d0e14ed7/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/EnvironmentPropertySource.java ---------------------------------------------------------------------- diff --git a/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/EnvironmentPropertySource.java b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/EnvironmentPropertySource.java new file mode 100644 index 0000000..920f37b --- /dev/null +++ b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/EnvironmentPropertySource.java @@ -0,0 +1,287 @@ +/* + * 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.propertysource; + +import org.apache.tamaya.spi.PropertyValue; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +/** + * <p>{@link PropertySource} to access environment variables via Tamaya + * which are set via {@code export VARIABLE=value} on UNIX systems or + * {@code set VARIABLE=value} on Windows systems.</p> + * + * <p>Using the {@linkplain EnvironmentPropertySource} without any + * additional configuration gives access to all existing environment + * variables available to the Java process Tamaya is running in.</p> + * + * <h1>Simple usage example</h1> + * + * <pre> + * $ export OPS_MODE=production + * $ export COLOR=false + * $ java -jar application.jar + * </pre> + * + * <p>To access {@code OPS_MODE} and {@code COLOR} with the following code + * fragment could be used:</p> + * + * <pre> + * PropertySource ps = new EnvironmentPropertySource(); + * PropertyValue opsMode = ps.get("OPS_MODE"); + * PropertyValue color = ps.get("COLOR"); + * </pre> + * + * <h1>Application specific environmet variables with prefix</h1> + * + * <p>Given the case where to instances of the same application are running on + * a single machine but need different values for the environment variable + * {@code CUSTOMER}. The {@linkplain EnvironmentPropertySource} allows you + * to prefix the environment variable with an application specific prefix + * and to access it by the non-prefixed variable name.</p> + * + * <pre> + * $ export CUSTOMER=none + * $ export a81.CUSTOMER=moon + * $ export b78.CUSTOMER=luna + * </pre> + * + * <p>Given an environment with these tree variables the application running + * for the customer called Moon could be started with the following command:</p> + * + * <pre> + * $ java -Dtamaya.envprops.prefix=a81 -jar application.jar + * </pre> + * + * <p>The application specific value can now be accessed from the code of the + * application like this:</p> + * + * <pre> + * PropertySource ps = new EnvironmentPropertySource(); + * PropertyValue pv = ps.get("CUSTOMER"); + * System.out.println(pv.getValue()); + * </pre> + * + * <p>The output of application would be {@code moon}.</p> + * + * <h1>Disabling the access to environment variables</h1> + * + * <p>The access to environment variables could be simply + * disabled by the setting the systemproperty {@code tamaya.envprops.disable} + * or {@code tamaya.defaults.disable} to {@code true}.</p> + */ +public class EnvironmentPropertySource extends BasePropertySource { + private static final String TAMAYA_ENVPROPS_PREFIX = "tamaya.envprops.prefix"; + private static final String TAMAYA_ENVPROPS_DISABLE = "tamaya.envprops.disable"; + private static final String TAMAYA_DEFAULT_DISABLE = "tamaya.defaults.disable"; + + /** + * Default ordinal for {@link EnvironmentPropertySource} + */ + public static final int DEFAULT_ORDINAL = 300; + + /** + * Prefix that allows environment properties to virtually be mapped on specified sub section. + */ + private String prefix; + + /** + * If true, this property source does not return any properties. This is useful since this + * property source is applied by default, but can be switched off by setting the + * {@code tamaya.envprops.disable} system/environment property to {@code true}. + */ + private boolean disabled = false; + + private SystemPropertiesProvider propertiesProvider = new SystemPropertiesProvider(); + + /** + * Creates a new instance. Also initializes the {@code prefix} and {@code disabled} properties + * from the system-/ environment properties: + * <pre> + * tamaya.envprops.prefix + * tamaya.envprops.disable + * </pre> + */ + public EnvironmentPropertySource(){ + initFromSystemProperties(); + } + + /** + * Initializes the {@code prefix} and {@code disabled} properties from the system-/ + * environment properties: + * <pre> + * tamaya.envprops.prefix + * tamaya.envprops.disable + * </pre> + */ + private void initFromSystemProperties() { + String value = System.getProperty("tamaya.envprops.prefix"); + if(value==null){ + prefix = System.getenv("tamaya.envprops.prefix"); + } + value = System.getProperty("tamaya.envprops.disable"); + if(value==null){ + value = System.getenv("tamaya.envprops.disable"); + } + if(value==null){ + value = System.getProperty("tamaya.defaults.disable"); + } + if(value==null){ + value = System.getenv("tamaya.defaults.disable"); + } + if(value!=null && !value.isEmpty()) { + this.disabled = Boolean.parseBoolean(value); + } + } + + /** + * Creates a new instance using a fixed ordinal value. + * @param ordinal the ordinal number. + */ + public EnvironmentPropertySource(int ordinal){ + this(null, ordinal); + } + + /** + * Creates a new instance. + * @param prefix the prefix to be used, or null. + * @param ordinal the ordinal to be used. + */ + public EnvironmentPropertySource(String prefix, int ordinal){ + super("environment-properties"); + this.prefix = prefix; + setOrdinal(ordinal); + } + + /** + * Creates a new instance. + * @param prefix the prefix to be used, or null. + */ + public EnvironmentPropertySource(String prefix){ + this.prefix = prefix; + } + + @Override + public int getDefaultOrdinal() { + return DEFAULT_ORDINAL; + } + + @Override + public String getName() { + if (isDisabled()) { + return "environment-properties(disabled)"; + } + return "environment-properties"; + } + + @Override + public PropertyValue get(String key) { + if (isDisabled()) { + return null; + } + + String effectiveKey = hasPrefix() ? getPrefix() + "." + key + : key; + + String value = getPropertiesProvider().getenv(effectiveKey); + + return PropertyValue.of(key, value, getName()); + } + + private boolean hasPrefix() { + return null != prefix; + } + + @Override + public Map<String, PropertyValue> getProperties() { + if(disabled){ + return Collections.emptyMap(); + } + String prefix = this.prefix; + if(prefix==null) { + Map<String, PropertyValue> entries = new HashMap<>(System.getenv().size()); + for (Map.Entry<String, String> entry : System.getenv().entrySet()) { + entries.put(entry.getKey(), PropertyValue.of(entry.getKey(), entry.getValue(), getName())); + } + return entries; + }else{ + Map<String, PropertyValue> entries = new HashMap<>(System.getenv().size()); + for (Map.Entry<String, String> entry : System.getenv().entrySet()) { + entries.put(prefix + entry.getKey(), PropertyValue.of(prefix + entry.getKey(), entry.getValue(), getName())); + } + return entries; + } + } + + + @Override + protected String toStringValues() { + return super.toStringValues() + + " prefix=" + prefix + '\n' + + " disabled=" + disabled + '\n'; + } + + void setPropertiesProvider(SystemPropertiesProvider spp) { + propertiesProvider = spp; + initFromSystemProperties(); + } + + SystemPropertiesProvider getPropertiesProvider() { + return propertiesProvider; + } + + public String getPrefix() { + return prefix; + } + + public boolean isDisabled() { + return disabled; + } + + /** + * <p>Provides access to the system properties used to configure + * {@linkplain EnvironmentPropertySource}.</p> + * + * <p>This implementation delegates all property lookups + * to {@linkplain System#getProperty(String)}.</p> + */ + static class SystemPropertiesProvider { + String getEnvPropsPrefix() { + return System.getenv(TAMAYA_ENVPROPS_PREFIX); + } + + String getEnvPropsDisable() { + return System.getenv(TAMAYA_ENVPROPS_DISABLE); + } + + String getDefaultsDisable() { + return System.getenv(TAMAYA_DEFAULT_DISABLE); + } + + String getenv(String name) { + return System.getenv(name); + } + + Map<String, String> getenv() { + return System.getenv(); + } + } +} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/d0e14ed7/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/JavaConfigurationPropertySource.java ---------------------------------------------------------------------- diff --git a/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/JavaConfigurationPropertySource.java b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/JavaConfigurationPropertySource.java new file mode 100644 index 0000000..92f520e --- /dev/null +++ b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/JavaConfigurationPropertySource.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.spisupport.propertysource; + +import org.apache.tamaya.ConfigException; +import org.apache.tamaya.spi.PropertySource; +import org.apache.tamaya.spi.PropertyValue; +import org.apache.tamaya.spi.ServiceContextManager; +import org.apache.tamaya.spisupport.PropertySourceComparator; + +import java.io.IOException; +import java.net.URL; +import java.util.*; + +import static java.lang.String.format; +import static java.lang.Thread.currentThread; + +/** + * Provider which reads all {@value DEFAULT_SIMPLE_PROPERTIES_FILE_NAME} and + * {@value DEFAULT_XML_PROPERTIES_FILE_NAME} files found in the + * classpath. By setting + * {@code tamaya.defaultprops.disable} or {@code tamaya.defaults.disable} + * as system or environment property this feature can be disabled. + */ +public class JavaConfigurationPropertySource extends BasePropertySource { + /** + * Default location in the classpath, where Tamaya looks for simple line based configuration by default. + */ + public static final String DEFAULT_SIMPLE_PROPERTIES_FILE_NAME="META-INF/javaconfiguration.properties"; + + /** + * Default location in the classpath, where Tamaya looks for XML based configuration by default. + */ + public static final String DEFAULT_XML_PROPERTIES_FILE_NAME = "META-INF/javaconfiguration.xml"; + + private static final int DEFAULT_ORDINAL = 900; + + private boolean enabled = evaluateEnabled(); + + public JavaConfigurationPropertySource(){ + super("resource:META-INF/javaconfiguration.*", DEFAULT_ORDINAL); + } + + private boolean evaluateEnabled() { + String value = System.getProperty("tamaya.defaultprops.disable"); + if(value==null){ + value = System.getenv("tamaya.defaultprops.disable"); + } + if(value==null){ + value = System.getProperty("tamaya.defaults.disable"); + } + if(value==null){ + value = System.getenv("tamaya.defaults.disable"); + } + if(value==null){ + return true; + } + return value.isEmpty() || !Boolean.parseBoolean(value); + } + + private List<PropertySource> getPropertySources() { + List<PropertySource> propertySources = new ArrayList<>(); + propertySources.addAll(loadPropertySourcesByName(DEFAULT_SIMPLE_PROPERTIES_FILE_NAME)); + propertySources.addAll(loadPropertySourcesByName(DEFAULT_XML_PROPERTIES_FILE_NAME)); + Collections.sort(propertySources, PropertySourceComparator.getInstance()); + return propertySources; + } + + private Collection<? extends PropertySource> loadPropertySourcesByName(String filename) { + List<PropertySource> propertySources = new ArrayList<>(); + Enumeration<URL> propertyLocations; + try { + propertyLocations = ServiceContextManager.getServiceContext() + .getResources(filename, currentThread().getContextClassLoader()); + } catch (IOException e) { + String msg = format("Error while searching for %s", filename); + + throw new ConfigException(msg, e); + } + + while (propertyLocations.hasMoreElements()) { + URL currentUrl = propertyLocations.nextElement(); + SimplePropertySource sps = new SimplePropertySource(currentUrl); + + propertySources.add(sps); + } + + return propertySources; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled){ + this.enabled = enabled; + } + + + @Override + public Map<String, PropertyValue> getProperties() { + if (!isEnabled()) { + return Collections.emptyMap(); + } + Map<String,PropertyValue> result = new HashMap<>(); + for(PropertySource ps:getPropertySources()){ + result.putAll(ps.getProperties()); + } + return result; + } + + @Override + public String toString() { + return "JavaConfigurationPropertySource{" + + "enabled=" + enabled + + '}'; + } +} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/d0e14ed7/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/MapPropertySource.java ---------------------------------------------------------------------- diff --git a/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/MapPropertySource.java b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/MapPropertySource.java new file mode 100644 index 0000000..0cabb35 --- /dev/null +++ b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/MapPropertySource.java @@ -0,0 +1,102 @@ +/* + * 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.propertysource; + +import org.apache.tamaya.spi.PropertyValue; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +/** + * Simple PropertySource implementation that just takes a Map and an (optional) priority. + * Optionally the entries passed can be mapped to a different rootContext. + */ +public class MapPropertySource extends BasePropertySource { + + /** + * The current properties. + */ + private final Map<String, PropertyValue> props = new HashMap<>(); + + /** + * Creates a new instance, hereby using the default mechanism for evaluating the property source's + * priority. + * + * @param name unique name of this source. + * @param props the properties + */ + public MapPropertySource(String name, Map<String, String> props) { + this(name, props, null); + } + + /** + * Creates a new instance, hereby using the default mechanism for evaluating the property source's + * priority, but applying a custom mapping {@code prefix} to the entries provided. + * + * @param name unique name of this source. + * @param props the properties + * @param prefix the prefix context mapping, or null (for no mapping). + */ + public MapPropertySource(String name, Map<String, String> props, String prefix) { + super(name); + if (prefix == null) { + for (Map.Entry<String, String> en : props.entrySet()) { + this.props.put(en.getKey(), + PropertyValue.of(en.getKey(), en.getValue(), name)); + } + } else { + for (Map.Entry<String, String> en : props.entrySet()) { + this.props.put(prefix + en.getKey(), + PropertyValue.of(prefix + en.getKey(), en.getValue(), name)); + } + } + } + + /** + * Creates a new instance, hereby using the default mechanism for evaluating the property source's + * priority, but applying a custom mapping {@code rootContext} to the entries provided. + * + * @param name unique name of this source. + * @param props the properties + * @param prefix the prefix context mapping, or null (for no mapping). + */ + public MapPropertySource(String name, Properties props, String prefix) { + this(name, getMap(props), prefix); + } + + /** + * Simple method to convert Properties into a Map instance. + * @param props the properties, not null. + * @return the corresponding Map instance. + */ + public static Map<String, String> getMap(Properties props) { + Map<String, String> result = new HashMap<>(); + for (Map.Entry en : props.entrySet()) { + result.put(en.getKey().toString(), en.getValue().toString()); + } + return result; + } + + + @Override + public Map<String, PropertyValue> getProperties() { + return Collections.unmodifiableMap(this.props); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/d0e14ed7/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/PropertiesResourcePropertySource.java ---------------------------------------------------------------------- diff --git a/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/PropertiesResourcePropertySource.java b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/PropertiesResourcePropertySource.java new file mode 100644 index 0000000..27b6e4b --- /dev/null +++ b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/PropertiesResourcePropertySource.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.spisupport.propertysource; + +import org.apache.tamaya.spi.ServiceContextManager; + +import java.io.InputStream; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Simple PropertySource, with a fixed ordinal that reads a .properties file from a given URL. + */ +public class PropertiesResourcePropertySource extends MapPropertySource { + /** The logger used. */ + private static final Logger LOGGER = Logger.getLogger(PropertiesResourcePropertySource.class.getName()); + + /** + * Creates a new instance. + * @param url the resource URL, not null. + */ + public PropertiesResourcePropertySource(URL url){ + this(url, null); + } + + /** + * Creates a new instance. + * @param prefix the (optional) prefix context for mapping (prefixing) the properties loaded. + * @param url the resource URL, not null. + */ + public PropertiesResourcePropertySource(URL url, String prefix){ + super(url.toExternalForm(), loadProps(url), prefix); + } + + /** + * Creates a new instance. + * @param prefix the (optional) prefix context for mapping (prefixing) the properties loaded. + * @param path the resource path, not null. + */ + public PropertiesResourcePropertySource(String path, String prefix){ + super(path, loadProps(path, null), prefix); + } + + /** + * Creates a new instance. + * @param prefix the (optional) prefix context for mapping (prefixing) the properties loaded. + * @param path the resource path, not null. + */ + public PropertiesResourcePropertySource(String path, String prefix, ClassLoader cl){ + super(path, loadProps(path, cl), prefix); + } + + /** + * Loads the properties using the JDK's Property loading mechanism. + * @param path the resource classpath, not null. + * @return the loaded properties. + */ + private static Map<String, String> loadProps(String path, ClassLoader cl) { + if(cl==null){ + cl = PropertiesResourcePropertySource.class.getClassLoader(); + } + URL url = ServiceContextManager.getServiceContext().getResource(path, cl); + return loadProps(url); + } + + /** + * Loads the properties using the JDK's Property loading mechanism. + * @param url the resource URL, not null. + * @return the loaded properties. + */ + private static Map<String, String> loadProps(URL url) { + Map<String,String> result = new HashMap<>(); + if(url!=null) { + try (InputStream is = url.openStream()) { + Properties props = new Properties(); + props.load(is); + for (Map.Entry en : props.entrySet()) { + result.put(en.getKey().toString(), en.getValue().toString()); + } + } catch (Exception e) { + LOGGER.log(Level.WARNING, "Failed to read properties from " + url, e); + } + }else{ + LOGGER.log(Level.WARNING, "No properties found at " + url); + } + return result; + } + +} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/d0e14ed7/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/SimplePropertySource.java ---------------------------------------------------------------------- diff --git a/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/SimplePropertySource.java b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/SimplePropertySource.java new file mode 100644 index 0000000..070a564 --- /dev/null +++ b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/SimplePropertySource.java @@ -0,0 +1,284 @@ +/* + * 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.propertysource; + +import org.apache.tamaya.ConfigException; +import org.apache.tamaya.spi.PropertyValue; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Properties; +import java.util.UUID; +import java.util.logging.Logger; + +/** + * Simple implementation of a {@link org.apache.tamaya.spi.PropertySource} for + * simple property files and XML property files. + */ +public class SimplePropertySource extends BasePropertySource { + + private static final Logger LOG = Logger.getLogger(SimplePropertySource.class.getName()); + + /** + * The current properties. + */ + private Map<String, PropertyValue> properties = new HashMap<>(); + + /** + * Creates a new Properties based PropertySource based on the given URL. + * + * @param propertiesLocation the URL encoded location, not null. + */ + public SimplePropertySource(File propertiesLocation) { + super(propertiesLocation.toString(), 0); + try { + this.properties = load(propertiesLocation.toURI().toURL()); + } catch (IOException e) { + throw new ConfigException("Failed to load properties from " + propertiesLocation, e); + } + } + + /** + * Creates a new Properties based PropertySource based on the given URL. + * + * @param propertiesLocation the URL encoded location, not null. + */ + public SimplePropertySource(URL propertiesLocation) { + super(propertiesLocation.toString(), 0); + this.properties = load(Objects.requireNonNull(propertiesLocation)); + } + + /** + * Creates a new Properties based PropertySource. + * + * @param name the property source name, not null. + * @param properties the properties, not null + * @param defaultOrdinal the default ordinal + */ + public SimplePropertySource(String name, Map<String, String> properties, int defaultOrdinal){ + super(name, defaultOrdinal); + for(Map.Entry<String,String> en: properties.entrySet()) { + this.properties.put(en.getKey(), PropertyValue.of(en.getKey(), en.getValue(), name)); + } + } + + /** + * Creates a new Properties based PropertySource based on the given properties map. + * + * @param name the name, not null. + * @param properties the properties, not null. + */ + public SimplePropertySource(String name, Map<String, String> properties) { + this(name, properties, 0); + } + + /** + * Creates a new Properties based PropertySource based on the given URL. + * + * @param name The property source name + * @param propertiesLocation the URL encoded location, not null. + */ + public SimplePropertySource(String name, URL propertiesLocation) { + super(name, 0); + this.properties = load(propertiesLocation); + } + + private SimplePropertySource(Builder builder) { + properties = builder.properties; + if(builder.defaultOrdinal!=null){ + setDefaultOrdinal(builder.defaultOrdinal); + } + if(builder.ordinal!=null){ + setOrdinal(builder.ordinal); + } + setName(builder.name); + } + + public static Builder newBuilder() { + return new Builder(); + } + + @Override + public Map<String, PropertyValue> getProperties() { + return this.properties; + } + + /** + * loads the Properties from the given URL + * + * @param propertiesFile {@link URL} to load Properties from + * @return loaded {@link Properties} + * @throws IllegalStateException in case of an error while reading properties-file + */ + private static Map<String, PropertyValue> load(URL propertiesFile) { + boolean isXML = isXMLPropertieFiles(propertiesFile); + + Map<String, PropertyValue> properties = new HashMap<>(); + try (InputStream stream = propertiesFile.openStream()) { + Properties props = new Properties(); + if (stream != null) { + if (isXML) { + props.loadFromXML(stream); + } else { + props.load(stream); + } + } + String source = propertiesFile.toString(); + for (String key : props.stringPropertyNames()) { + properties.put(key, PropertyValue.of(key, props.getProperty(key), source)); + } + } catch (IOException e) { + throw new ConfigException("Error loading properties from " + propertiesFile, e); + } + + return properties; + } + + private static boolean isXMLPropertieFiles(URL url) { + return url.getFile().endsWith(".xml"); + } + + + /** + * {@code SimplePropertySource} builder static inner class. + */ + public static final class Builder { + private String name; + private Integer defaultOrdinal; + private Integer ordinal; + private Map<String, PropertyValue> properties = new HashMap<>(); + + private Builder() { + } + + /** + * Sets the {@code name} to a new UUID and returns a reference to this Builder so that the methods + * can be chained together. + * + * @return a reference to this Builder + */ + public Builder withUuidName() { + this.name = UUID.randomUUID().toString(); + return this; + } + + /** + * Sets the {@code name} and returns a reference to this Builder so that the methods + * can be chained together. + * + * @param val the {@code name} to set, not null. + * @return a reference to this Builder + */ + public Builder withName(String val) { + this.name = Objects.requireNonNull(name); + return this; + } + + /** + * Sets the {@code ordinal} and returns a reference to this Builder so that the methods + * can be chained together. + * + * @param val the {@code ordinal} to set + * @return a reference to this Builder + */ + public Builder withOrdinal(int val) { + this.ordinal = val; + return this; + } + + /** + * Sets the {@code defaultOrdinal} and returns a reference to this Builder so that the methods + * can be chained together. + * + * @param val the {@code defaultOrdinal} to set + * @return a reference to this Builder + */ + public Builder withDefaultOrdinal(int val) { + this.defaultOrdinal = val; + return this; + } + + /** + * Reads the {@code properties} from the given resource and returns a reference + * to this Builder so that the methods can be chained together. + * + * @param resource the {@code resource} to read + * @return a reference to this Builder + */ + public Builder withProperties(URL resource) { + this.properties.putAll(load(resource)); + return this; + } + + /** + * Reads the {@code properties} from the given resource and returns a reference + * to this Builder so that the methods can be chained together. + * + * @param file the {@code file} to read from (xml or properties format). + * @return a reference to this Builder + */ + public Builder withProperties(File file) { + try { + this.properties.putAll(load(file.toURI().toURL())); + } catch (MalformedURLException e) { + throw new IllegalArgumentException("Failed to read file: " + file, e); + } + return this; + } + + /** + * Sets the {@code properties} and returns a reference to this Builder so that the methods can be chained together. + * + * @param val the {@code properties} to set + * @return a reference to this Builder + */ + public Builder withProperties(Map<String, String> val) { + for(Map.Entry<String,String> en: val.entrySet()) { + this.properties.put(en.getKey(), PropertyValue.of(en.getKey(), en.getValue(), name)); + } + return this; + } + + /** + * Sets the {@code properties} and returns a reference to this Builder so that the methods can be chained together. + * + * @param val the {@code properties} to set + * @return a reference to this Builder + */ + public Builder withProperty(String key, String val) { + this.properties.put(key, PropertyValue.of(key, val, name)); + return this; + } + + /** + * Returns a {@code SimplePropertySource} built from the parameters previously set. + * + * @return a {@code SimplePropertySource} built with parameters of this {@code SimplePropertySource.Builder} + */ + public SimplePropertySource build() { + return new SimplePropertySource(this); + } + } +} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/d0e14ed7/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/SystemPropertySource.java ---------------------------------------------------------------------- diff --git a/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/SystemPropertySource.java b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/SystemPropertySource.java new file mode 100644 index 0000000..cfc60bb --- /dev/null +++ b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/SystemPropertySource.java @@ -0,0 +1,199 @@ +/* + * 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.propertysource; + +import org.apache.tamaya.spi.PropertyValue; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +/** + * This {@link org.apache.tamaya.spi.PropertySource} manages the system properties. You can disable this feature by + * setting {@code tamaya.envprops.disable} or {@code tamaya.defaults.disable}. + */ +public class SystemPropertySource extends BasePropertySource { + + /** + * default ordinal used. + */ + public static final int DEFAULT_ORDINAL = 1000; + + private volatile Map<String,PropertyValue> cachedProperties; + + /** + * previous System.getProperties().hashCode() + * so we can check if we need to reload + */ + private volatile int previousHash; + + /** + * Prefix that allows system properties to virtually be mapped on specified sub section. + */ + private String prefix; + + /** + * If true, this property source does not return any properties. This is useful since this + * property source is applied by default, but can be switched off by setting the + * {@code tamaya.envprops.disable} system/environment property to {@code true}. + */ + private boolean disabled = false; + + /** + * Creates a new instance. Also initializes the {@code prefix} and {@code disabled} properties + * from the system-/ environment properties: + * <pre> + * tamaya.envprops.prefix + * tamaya.envprops.disable + * </pre> + */ + public SystemPropertySource(){ + super("system-properties", DEFAULT_ORDINAL); + initFromSystemProperties(); + if(!disabled){ + cachedProperties = Collections.unmodifiableMap(loadProperties()); + } + } + + /** + * Initializes the {@code prefix} and {@code disabled} properties from the system-/ + * environment properties: + * <pre> + * tamaya.envprops.prefix + * tamaya.envprops.disable + * </pre> + */ + private void initFromSystemProperties() { + String value = System.getProperty("tamaya.sysprops.prefix"); + if(value==null){ + prefix = System.getenv("tamaya.sysprops.prefix"); + } + value = System.getProperty("tamaya.sysprops.disable"); + if(value==null){ + value = System.getenv("tamaya.sysprops.disable"); + } + if(value==null){ + value = System.getProperty("tamaya.defaults.disable"); + } + if(value==null){ + value = System.getenv("tamaya.defaults.disable"); + } + if(value!=null && !value.isEmpty()) { + this.disabled = Boolean.parseBoolean(value); + } + } + + /** + * Creates a new instance using a fixed ordinal value. + * @param ordinal the ordinal number. + */ + public SystemPropertySource(int ordinal){ + this(null, ordinal); + } + + /** + * Creates a new instance. + * @param prefix the prefix to be used, or null. + * @param ordinal the ordinal to be used. + */ + public SystemPropertySource(String prefix, int ordinal){ + this.prefix = prefix; + setOrdinal(ordinal); + } + + /** + * Creates a new instance. + * @param prefix the prefix to be used, or null. + */ + public SystemPropertySource(String prefix){ + this.prefix = prefix; + } + + + private Map<String, PropertyValue> loadProperties() { + Properties sysProps = System.getProperties(); + previousHash = System.getProperties().hashCode(); + final String prefix = this.prefix; + Map<String, PropertyValue> entries = new HashMap<>(); + for (Map.Entry<Object,Object> entry : sysProps.entrySet()) { + if(entry.getKey() instanceof String && entry.getValue() instanceof String) { + if (prefix == null) { + entries.put((String) entry.getKey(), + PropertyValue.of((String) entry.getKey(), + (String) entry.getValue(), + getName())); + } else { + entries.put(prefix + entry.getKey(), + PropertyValue.of(prefix + entry.getKey(), + (String) entry.getValue(), + getName())); + } + } + } + return entries; + } + + @Override + public String getName() { + if(disabled){ + return super.getName() + "(disabled)"; + } + return super.getName(); + } + + @Override + public PropertyValue get(String key) { + if(disabled){ + return null; + } + String prefix = this.prefix; + if(prefix==null) { + return PropertyValue.of(key, System.getProperty(key), getName()); + } + return PropertyValue.of(key, System.getProperty(key.substring(prefix.length())), getName()); + } + + @Override + public Map<String, PropertyValue> getProperties() { + if(disabled){ + return Collections.emptyMap(); + } + // only need to reload and fill our map if something has changed + // synchronization was removed, Instance was marked as volatile. In the worst case it + // is reloaded twice, but the values will be the same. + if (previousHash != System.getProperties().hashCode()) { + Map<String, PropertyValue> properties = loadProperties(); + this.cachedProperties = Collections.unmodifiableMap(properties); + } + return this.cachedProperties; + } + + @Override + public boolean isScannable() { + return true; + } + + @Override + protected String toStringValues() { + return super.toStringValues() + + " prefix=" + prefix + '\n' + + " disabled=" + disabled + '\n'; + } +} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/d0e14ed7/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/WrappedPropertySource.java ---------------------------------------------------------------------- diff --git a/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/WrappedPropertySource.java b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/WrappedPropertySource.java new file mode 100644 index 0000000..feaaf7b --- /dev/null +++ b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/WrappedPropertySource.java @@ -0,0 +1,126 @@ +/* + * 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.propertysource; + +import org.apache.tamaya.spi.PropertySource; +import org.apache.tamaya.spi.PropertyValue; +import org.apache.tamaya.spisupport.PropertySourceComparator; + +import java.util.Map; +import java.util.Objects; + +/** + * Property source effectively managed by the configuration context, allowing resetting of ordinal and its + * delegate (e.g. in case of refresh). + */ +class WrappedPropertySource implements PropertySource{ + + private Integer ordinal; + private PropertySource delegate; + private long loaded = System.currentTimeMillis(); + + private WrappedPropertySource(PropertySource delegate) { + this(delegate, null); + } + + private WrappedPropertySource(PropertySource delegate, Integer ordinal) { + this.delegate = Objects.requireNonNull(delegate); + this.ordinal = ordinal; + } + + public static WrappedPropertySource of(PropertySource ps) { + if(ps instanceof WrappedPropertySource){ + return (WrappedPropertySource)ps; + } + return new WrappedPropertySource(ps); + } + + public static WrappedPropertySource of(PropertySource ps, Integer ordinal) { + if(ps instanceof WrappedPropertySource){ + return new WrappedPropertySource(((WrappedPropertySource)ps).getDelegate(), ordinal); + } + return new WrappedPropertySource(ps, ordinal); + } + + public int getOrdinal() { + if(this.ordinal!=null){ + return this.ordinal; + } + return PropertySourceComparator.getOrdinal(delegate); + } + + public void setOrdinal(Integer ordinal) { + this.ordinal = ordinal; + } + + public void setDelegate(PropertySource delegate) { + this.delegate = Objects.requireNonNull(delegate); + this.loaded = System.currentTimeMillis(); + } + + @Override + public String getName() { + return delegate.getName(); + } + + @Override + public PropertyValue get(String key) { + return delegate.get(key); + } + + @Override + public Map<String, PropertyValue> getProperties() { + return delegate.getProperties(); + } + + @Override + public boolean isScannable() { + return delegate.isScannable(); + } + + public PropertySource getDelegate() { + return delegate; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof WrappedPropertySource)) return false; + + WrappedPropertySource that = (WrappedPropertySource) o; + + return getDelegate().getName().equals(that.getDelegate().getName()); + } + + @Override + public int hashCode() { + return getDelegate().getName().hashCode(); + } + + @Override + public String toString() { + return "WrappedPropertySource{" + + "name=" + getName() + + ", ordinal=" + getOrdinal() + + ", scannable=" + isScannable() + + ", loadedAt=" + loaded + + ", delegate-class=" + delegate.getClass().getName() + + '}'; + } +} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/d0e14ed7/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/package-info.java ---------------------------------------------------------------------- diff --git a/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/package-info.java b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/package-info.java new file mode 100644 index 0000000..21e5aec --- /dev/null +++ b/code/compat/src/main/java/org/apache/tamaya/spisupport/propertysource/package-info.java @@ -0,0 +1,23 @@ +/* + * 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. + */ + +/** + * Contains internal implementations artifacts registered as services. + */ +package org.apache.tamaya.spisupport.propertysource; \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/d0e14ed7/code/compat/src/main/resources/tamaya-banner.txt ---------------------------------------------------------------------- diff --git a/code/compat/src/main/resources/tamaya-banner.txt b/code/compat/src/main/resources/tamaya-banner.txt new file mode 100644 index 0000000..b4ceca4 --- /dev/null +++ b/code/compat/src/main/resources/tamaya-banner.txt @@ -0,0 +1,11 @@ + + ââââââ âââââââ ââââââ ââââââââââ âââââââââââ âââââââââ ââââââ ââââ ââââ ââââââ âââ âââ ââââââ +âââââââââââââââââââââââââââââââââââ âââââââââââ ââââââââââââââââââââââ âââââââââââââââââ ââââââââââââ +âââââââââââââââââââââââââââ ââââââââââââââ âââ âââââââââââââââââââââââââââ âââââââ ââââââââ +âââââââââââââââ âââââââââââ ââââââââââââââ âââ âââââââââââââââââââââââââââ âââââ ââââââââ +âââ ââââââ âââ ââââââââââââââ âââââââââââ âââ âââ ââââââ âââ ââââââ âââ âââ âââ âââ +âââ ââââââ âââ âââ ââââââââââ âââââââââââ âââ âââ ââââââ ââââââ âââ âââ âââ âââ + +Apache Tamaya Configuration API: http://tamaya.incubator.apache.org + + http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/d0e14ed7/code/compat/src/test/java/org/apache/tamaya/ConfigExceptionTest.java ---------------------------------------------------------------------- diff --git a/code/compat/src/test/java/org/apache/tamaya/ConfigExceptionTest.java b/code/compat/src/test/java/org/apache/tamaya/ConfigExceptionTest.java new file mode 100644 index 0000000..fa7da0a --- /dev/null +++ b/code/compat/src/test/java/org/apache/tamaya/ConfigExceptionTest.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; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Tests instantiating {@link ConfigException}. + */ +public class ConfigExceptionTest { + + @Test + public void testCreationMessage(){ + ConfigException ex = new ConfigException("test"); + assertNull(ex.getCause()); + assertEquals(ex.getMessage(), "test"); + } + + @Test + public void testCreationMessageThrowable(){ + Exception e = new IllegalStateException("blabla"); + ConfigException ex = new ConfigException("test", e); + assertTrue(ex.getCause() == e); + assertEquals("test", ex.getMessage()); + } + +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/d0e14ed7/code/compat/src/test/java/org/apache/tamaya/ConfigurationTest.java ---------------------------------------------------------------------- diff --git a/code/compat/src/test/java/org/apache/tamaya/ConfigurationTest.java b/code/compat/src/test/java/org/apache/tamaya/ConfigurationTest.java new file mode 100644 index 0000000..ecbb75c --- /dev/null +++ b/code/compat/src/test/java/org/apache/tamaya/ConfigurationTest.java @@ -0,0 +1,63 @@ +/* + * 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; + +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * Test class that tests the default methods implemented on {@link org.apache.tamaya.Configuration}. The provided + * {@link org.apache.tamaya.TestConfiguration} is implemeted with maximal use of the default methods. + */ +public class ConfigurationTest { + + @Test + public void testget() throws Exception { + assertEquals(Boolean.TRUE, ConfigurationProvider.getConfiguration().get("booleanTrue", Boolean.class)); + assertEquals(Boolean.FALSE, ConfigurationProvider.getConfiguration().get("booleanFalse", Boolean.class)); + assertEquals((int)Byte.MAX_VALUE, (int)ConfigurationProvider.getConfiguration().get("byte", Byte.class)); + assertEquals(Integer.MAX_VALUE, (int)ConfigurationProvider.getConfiguration().get("int", Integer.class)); + assertEquals(Long.MAX_VALUE, (long)ConfigurationProvider.getConfiguration().get("long", Long.class)); + assertEquals(Float.MAX_VALUE, (double)ConfigurationProvider.getConfiguration().get("float", Float.class), 0.0d); + assertEquals(Double.MAX_VALUE, ConfigurationProvider.getConfiguration().get("double", Double.class), 0.0d); + } + + @Test + public void testGetBoolean() throws Exception { + assertTrue(ConfigurationProvider.getConfiguration().get("booleanTrue", Boolean.class)); + assertFalse(ConfigurationProvider.getConfiguration().get("booleanFalse", Boolean.class)); + assertFalse(ConfigurationProvider.getConfiguration().get("foorBar", Boolean.class)); + } + + @Test + public void testGetInteger() throws Exception { + assertEquals(Integer.MAX_VALUE,(int) ConfigurationProvider.getConfiguration().get("int", Integer.class)); + } + + @Test + public void testGetLong() throws Exception { + assertEquals(Long.MAX_VALUE,(long) ConfigurationProvider.getConfiguration().get("long", Long.class)); + } + + @Test + public void testGetDouble() throws Exception { + assertEquals(Double.MAX_VALUE,ConfigurationProvider.getConfiguration().get("double", Double.class), 0.0d); + } + +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/d0e14ed7/code/compat/src/test/java/org/apache/tamaya/TestConfiguration.java ---------------------------------------------------------------------- diff --git a/code/compat/src/test/java/org/apache/tamaya/TestConfiguration.java b/code/compat/src/test/java/org/apache/tamaya/TestConfiguration.java new file mode 100644 index 0000000..a035467 --- /dev/null +++ b/code/compat/src/test/java/org/apache/tamaya/TestConfiguration.java @@ -0,0 +1,138 @@ +/* + * 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; + + +import org.apache.tamaya.spi.ConfigurationContext; +import org.apache.tamaya.spi.TypeLiteral; + +import java.util.HashMap; +import java.util.Map; + +/** + * Test Configuration class, that is used to testdata the default methods provided by the API. + */ +public class TestConfiguration implements Configuration{ + + private static final Map<String, String> VALUES; + static { + VALUES = new HashMap<>(); + VALUES.put("long", String.valueOf(Long.MAX_VALUE)); + VALUES.put("int", String.valueOf(Integer.MAX_VALUE)); + VALUES.put("double", String.valueOf(Double.MAX_VALUE)); + VALUES.put("float", String.valueOf(Float.MAX_VALUE)); + VALUES.put("short", String.valueOf(Short.MAX_VALUE)); + VALUES.put("byte", String.valueOf(Byte.MAX_VALUE)); + VALUES.put("booleanTrue", "true"); + VALUES.put("booleanFalse", "false"); + VALUES.put("String", "aStringValue"); + } + + @Override + public String get(String key) { + return VALUES.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) { + if(type.equals(Long.class)){ + return (T)(Object)Long.MAX_VALUE; + } + else if(type.equals(Integer.class)){ + return (T)(Object) Integer.MAX_VALUE; + } + else if(type.equals(Double.class)){ + return (T)(Object) Double.MAX_VALUE; + } + else if(type.equals(Float.class)){ + return (T)(Object) Float.MAX_VALUE; + } + else if(type.equals(Short.class)){ + return (T)(Object) Short.MAX_VALUE; + } + else if(type.equals(Byte.class)){ + return (T)(Object) Byte.MAX_VALUE; + } + else if(type.equals(Boolean.class)){ + if("booleanTrue".equals(key)) { + return (T)Boolean.TRUE; + } + else{ + return (T)Boolean.FALSE; + } + } + else if(type.equals(String.class)){ + return (T)"aStringValue"; + } + throw new ConfigException("No such property: " + key); + } + + @Override + public <T> T get(String key, org.apache.tamaya.spi.TypeLiteral<T> type) { + throw new RuntimeException("Method not implemented yet."); + } + + @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 Configuration with(ConfigOperator operator) { + return null; + } + + @Override + public <T> T query(ConfigQuery<T> query) { + throw new RuntimeException("Method not implemented yet."); + } + + @Override + public ConfigurationContext getContext() { + return null; + } + + @Override + public Map<String, String> getProperties() { + throw new RuntimeException("Method not implemented yet."); + } +} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/d0e14ed7/code/compat/src/test/java/org/apache/tamaya/TestConfigurationProvider.java ---------------------------------------------------------------------- diff --git a/code/compat/src/test/java/org/apache/tamaya/TestConfigurationProvider.java b/code/compat/src/test/java/org/apache/tamaya/TestConfigurationProvider.java new file mode 100644 index 0000000..cc1e2c3 --- /dev/null +++ b/code/compat/src/test/java/org/apache/tamaya/TestConfigurationProvider.java @@ -0,0 +1,76 @@ +/* + * 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; + +import javax.annotation.Priority; + +import org.apache.tamaya.spi.*; + +/** + * Test Configuration class, that is used to testdata the default methods provided by the API. + */ +@Priority(-1) +public class TestConfigurationProvider implements ConfigurationProviderSpi { + + private static final Configuration config = new TestConfiguration(); + + @Override + public Configuration getConfiguration() { + return config; + } + + @Override + public Configuration createConfiguration(ConfigurationContext context) { + return config; + } + + @Override + public ConfigurationContext getConfigurationContext() { + return config.getContext(); + } + + @Override + public void setConfigurationContext(ConfigurationContext context) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean isConfigurationContextSettable() { + return false; + } + + @Override + public ConfigurationBuilder getConfigurationBuilder() { + return null; + } + + @Override + public ConfigurationContextBuilder getConfigurationContextBuilder() { + return null; + } + + @Override + public void setConfiguration(Configuration config) { + } + + @Override + public boolean isConfigurationSettable() { + return false; + } +} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/d0e14ed7/code/compat/src/test/java/org/apache/tamaya/TypeLiteralTest.java ---------------------------------------------------------------------- diff --git a/code/compat/src/test/java/org/apache/tamaya/TypeLiteralTest.java b/code/compat/src/test/java/org/apache/tamaya/TypeLiteralTest.java new file mode 100644 index 0000000..8e2ddc6 --- /dev/null +++ b/code/compat/src/test/java/org/apache/tamaya/TypeLiteralTest.java @@ -0,0 +1,91 @@ +/* + * 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; + +import static org.apache.tamaya.spi.TypeLiteral.getGenericInterfaceTypeParameters; +import static org.apache.tamaya.spi.TypeLiteral.getTypeParameters; +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.apache.tamaya.spi.TypeLiteral; +import org.junit.Test; + +/** + * Tests for the {@link org.apache.tamaya.spi.TypeLiteral} class. + */ +@SuppressWarnings("serial") +public class TypeLiteralTest { + + @Test(expected = NullPointerException.class) + public void constructorRequiresNonNullParameter() { + new org.apache.tamaya.spi.TypeLiteral<List<String>>(null){}; + } + + @Test + public void test_constrcutor(){ + org.apache.tamaya.spi.TypeLiteral<List<String>> listTypeLiteral = new org.apache.tamaya.spi.TypeLiteral<List<String>>(){}; + assertEquals(List.class, listTypeLiteral.getRawType()); + assertEquals(String.class, org.apache.tamaya.spi.TypeLiteral.getTypeParameters(listTypeLiteral.getType())[0]); + } + + @Test + public void test_of(){ + class MyListClass extends ArrayList<String>{} + org.apache.tamaya.spi.TypeLiteral<MyListClass> listTypeLiteral = org.apache.tamaya.spi.TypeLiteral.of(MyListClass.class); + assertEquals(MyListClass.class, listTypeLiteral.getRawType()); + assertEquals(MyListClass.class, listTypeLiteral.getType()); + } + + @Test(expected = NullPointerException.class) + public void ofDoesNotAcceptNullAsParamter() { + org.apache.tamaya.spi.TypeLiteral.of(null); + } + + @Test + public void test_getTypeParameter(){ + org.apache.tamaya.spi.TypeLiteral<List<String>> listTypeLiteral = new org.apache.tamaya.spi.TypeLiteral<List<String>>(){}; + assertEquals(List.class, listTypeLiteral.getRawType()); + assertEquals(String.class, TypeLiteral.getTypeParameters(listTypeLiteral.getType())[0]); + } + + @Test + public void test_getGenericInterfaceTypeParameter(){ + class MyListClass extends ArrayList<String> implements List<String>{} + assertEquals(String.class, getGenericInterfaceTypeParameters(MyListClass.class, List.class)[0]); + } + + @Test(expected = NullPointerException.class) + public void getGenericInterfaceTypeParametersRequiredNonNullValueForClassParameter() { + getGenericInterfaceTypeParameters(null, Iterator.class); + } + + @Test(expected = NullPointerException.class) + public void getGenericInterfaceTypeParametersRequiredNonNullValueForInterfaceParameter() { + getGenericInterfaceTypeParameters(String.class, null); + } + + @Test(expected = NullPointerException.class) + public void getTypeParametersRequiresNonNullParameter() { + getTypeParameters(null); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/d0e14ed7/code/compat/src/test/java/org/apache/tamaya/spi/ConversionContextTest.java ---------------------------------------------------------------------- diff --git a/code/compat/src/test/java/org/apache/tamaya/spi/ConversionContextTest.java b/code/compat/src/test/java/org/apache/tamaya/spi/ConversionContextTest.java new file mode 100644 index 0000000..42673f8 --- /dev/null +++ b/code/compat/src/test/java/org/apache/tamaya/spi/ConversionContextTest.java @@ -0,0 +1,193 @@ +/* + * 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.spi; + +import org.apache.tamaya.ConfigOperator; +import org.apache.tamaya.ConfigQuery; +import org.apache.tamaya.Configuration; +import org.junit.Test; + +import java.net.InetAddress; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.*; + +/** + * Tests for {@link org.apache.tamaya.base.convert.ConversionContext}, created by atsticks on 20.08.16. + */ +public class ConversionContextTest { + @Test + public void getKey() throws Exception { + ConversionContext ctx = new org.apache.tamaya.spi.ConversionContext.Builder("getKey", TypeLiteral.of(String.class)).build(); + assertEquals("getKey", ctx.getKey()); + } + + @Test + public void getTargetType() throws Exception { + ConversionContext ctx = new ConversionContext.Builder("getTargetType", TypeLiteral.of(String.class)).build(); + assertEquals(TypeLiteral.of(String.class), ctx.getTargetType()); + } + + @Test + public void getAnnotatedElement() throws Exception { + ConversionContext ctx = new ConversionContext.Builder("getAnnotatedElement", TypeLiteral.of(List.class)).build(); + assertNull(ctx.getAnnotatedElement()); + } + + @Test + public void testConfiguration() throws Exception { + Configuration config = new MyConfiguration(); + ConversionContext ctx = new ConversionContext.Builder("testConfiguration", TypeLiteral.of(List.class)) + .setConfiguration(config).build(); + assertEquals(config, ctx.getConfiguration()); + } + + @Test + public void testSupportedFormats() throws Exception { + ConversionContext ctx = new ConversionContext.Builder("getAnnotatedElement", TypeLiteral.of(List.class)) + .addSupportedFormats(MyConverter.class, "0.0.0.0/nnn").build(); + assertTrue(ctx.getSupportedFormats().contains("0.0.0.0/nnn (MyConverter)")); + } + + @Test + public void testToString() throws Exception { + ConversionContext ctx = new ConversionContext.Builder("getAnnotatedElement", TypeLiteral.of(List.class)) + .addSupportedFormats(MyConverter.class, "0.0.0.0/nnn").build(); + assertEquals("ConversionContext{configuration=null, key='getAnnotatedElement', targetType=TypeLiteral{type=interface java.util.List}, annotatedElement=null, supportedFormats=[0.0.0.0/nnn (MyConverter)]}", ctx.toString()); + } + + @Test + public void getConfigurationContext() throws Exception { + ConfigurationContext context = new MyConfigurationContext(); + ConversionContext ctx = new ConversionContext.Builder("getAnnotatedElement", TypeLiteral.of(List.class)) + .setConfigurationContext(context).build(); + assertEquals(context, ctx.getConfigurationContext()); + } + + + private static final class MyConverter implements PropertyConverter<InetAddress>{ + @Override + public InetAddress convert(String value, ConversionContext context) { + return null; + } + } + + private static final class MyConfigurationContext implements ConfigurationContext { + + @Override + public void addPropertySources(PropertySource... propertySources) { + + } + + @Override + public List<PropertySource> getPropertySources() { + return null; + } + + @Override + public PropertySource getPropertySource(String name) { + return null; + } + + @Override + public <T> void addPropertyConverter(TypeLiteral<T> typeToConvert, PropertyConverter<T> propertyConverter) { + + } + + @Override + public Map<TypeLiteral<?>, List<PropertyConverter<?>>> getPropertyConverters() { + return null; + } + + @Override + public <T> List<PropertyConverter<T>> getPropertyConverters(TypeLiteral<T> type) { + return null; + } + + @Override + public List<PropertyFilter> getPropertyFilters() { + return null; + } + + @Override + public PropertyValueCombinationPolicy getPropertyValueCombinationPolicy() { + return null; + } + + @Override + public ConfigurationContextBuilder toBuilder() { + return null; + } + } + + private static final class MyConfiguration implements Configuration{ + + @Override + public String get(String key) { + return null; + } + + @Override + public String getOrDefault(String key, String defaultValue) { + return null; + } + + @Override + public <T> T getOrDefault(String key, Class<T> type, T defaultValue) { + return null; + } + + @Override + public <T> T get(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 null; + } + + @Override + public Map<String, String> getProperties() { + return null; + } + + @Override + public Configuration with(ConfigOperator operator) { + return null; + } + + @Override + public <T> T query(ConfigQuery<T> query) { + return null; + } + + @Override + public ConfigurationContext getContext() { + return null; + } + } + +} \ No newline at end of file
