TAMAYA-145: Further progress and preparation work. Factored out unrelated concerns into separate modules.
Project: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-sandbox/repo Commit: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-sandbox/commit/9f71f2d8 Tree: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-sandbox/tree/9f71f2d8 Diff: http://git-wip-us.apache.org/repos/asf/incubator-tamaya-sandbox/diff/9f71f2d8 Branch: refs/heads/master Commit: 9f71f2d80c46547febb7a0224f1068eb5ed0c060 Parents: 791632b Author: anatole <[email protected]> Authored: Sun Nov 13 23:22:28 2016 +0100 Committer: anatole <[email protected]> Committed: Sun Nov 13 23:22:28 2016 +0100 ---------------------------------------------------------------------- metamodel/pom.xml | 42 +- .../metamodel/ConfigurationContextBuilder.java | 354 -------------- .../org/apache/tamaya/metamodel/Context.java | 91 +++- .../tamaya/metamodel/dsl/DSLFormatManager.java | 230 ++++----- .../tamaya/metamodel/dsl/MetaConfiguration.java | 264 +++++------ .../tamaya/metamodel/dsl/ProfileManager.java | 426 ++++++++--------- .../metamodel/dsl/TamayaConfigurator.java | 468 +++++++++---------- .../metamodel/dsl/WrappedPropertySource.java | 31 +- .../metamodel/internal/FactoryManager.java | 4 +- .../spi/BaseStagedPropertySourceProvider.java | 121 ----- .../spi/DSLPropertySourceProvider.java | 51 -- .../metamodel/spi/MetaConfigurationReader.java | 41 ++ .../metamodel/spi/PropertySourceFactory.java | 5 +- .../spi/PropertySourceProviderFactory.java | 5 +- .../spi/StagedConfigPropertiesProvider.java | 137 ------ metamodel/src/test/resources/tamaya-TEST.yaml | 27 -- metamodel/src/test/resources/tamaya-config.json | 39 -- metamodel/src/test/resources/tamaya-config.xml | 63 ++- metamodel/src/test/resources/tamaya-config.yaml | 87 ---- 19 files changed, 885 insertions(+), 1601 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/incubator-tamaya-sandbox/blob/9f71f2d8/metamodel/pom.xml ---------------------------------------------------------------------- diff --git a/metamodel/pom.xml b/metamodel/pom.xml index f7f9dd8..11301dd 100644 --- a/metamodel/pom.xml +++ b/metamodel/pom.xml @@ -71,24 +71,24 @@ <artifactId>tamaya-formats</artifactId> <version>${project.version}</version> </dependency> - <dependency> - <groupId>org.apache.tamaya.ext</groupId> - <artifactId>tamaya-json</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - <optional>true</optional> - </dependency> - <dependency> - <groupId>org.apache.johnzon</groupId> - <artifactId>johnzon-core</artifactId> - <version>0.9-incubating</version> - </dependency> - <dependency> - <groupId>org.apache.geronimo.specs</groupId> - <artifactId>geronimo-json_1.0_spec</artifactId> - <version>1.0-alpha-1</version> - <scope>compile</scope> - </dependency> + <!--<dependency>--> + <!--<groupId>org.apache.tamaya.ext</groupId>--> + <!--<artifactId>tamaya-json</artifactId>--> + <!--<version>${project.version}</version>--> + <!--<scope>provided</scope>--> + <!--<optional>true</optional>--> + <!--</dependency>--> + <!--<dependency>--> + <!--<groupId>org.apache.johnzon</groupId>--> + <!--<artifactId>johnzon-core</artifactId>--> + <!--<version>0.9-incubating</version>--> + <!--</dependency>--> + <!--<dependency>--> + <!--<groupId>org.apache.geronimo.specs</groupId>--> + <!--<artifactId>geronimo-json_1.0_spec</artifactId>--> + <!--<version>1.0-alpha-1</version>--> + <!--<scope>compile</scope>--> + <!--</dependency>--> <dependency> <groupId>org.hamcrest</groupId> <artifactId>java-hamcrest</artifactId> @@ -108,11 +108,11 @@ <configuration> <instructions> <Export-Package> - org.apache.tamaya.model, - org.apache.tamaya.model.spi + org.apache.tamaya.metamodel, + org.apache.tamaya.metamodel.spi </Export-Package> <Private-Package> - org.apache.tamaya.model.internal + org.apache.tamaya.metamodel.internal </Private-Package> </instructions> </configuration> http://git-wip-us.apache.org/repos/asf/incubator-tamaya-sandbox/blob/9f71f2d8/metamodel/src/main/java/org/apache/tamaya/metamodel/ConfigurationContextBuilder.java ---------------------------------------------------------------------- diff --git a/metamodel/src/main/java/org/apache/tamaya/metamodel/ConfigurationContextBuilder.java b/metamodel/src/main/java/org/apache/tamaya/metamodel/ConfigurationContextBuilder.java deleted file mode 100644 index a84ab96..0000000 --- a/metamodel/src/main/java/org/apache/tamaya/metamodel/ConfigurationContextBuilder.java +++ /dev/null @@ -1,354 +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.metamodel; - -import org.apache.tamaya.Configuration; -import org.apache.tamaya.TypeLiteral; -import org.apache.tamaya.spi.PropertyConverter; -import org.apache.tamaya.spi.PropertyFilter; -import org.apache.tamaya.spi.PropertySource; -import org.apache.tamaya.spi.PropertySourceProvider; -import org.apache.tamaya.spi.PropertyValueCombinationPolicy; - -import java.util.Collection; -import java.util.List; -import java.util.Map; - -/** - * Builder to create or change a {@link Configuration}. This build allows to programmatically - * assemble any kind of configuration based on {@link PropertySource}s. It also provides - * methods to change the overall ordering and add the source processors that are configured as - * ServiceLoader services, either directly, or indirectly using the {@link org.apache.tamaya.spi.PropertySourceProvider} - * SPI. - * - * Additionally this builder also implements the SPI that provides the default configuration - * as returned by {@link org.apache.tamaya.ConfigurationProvider#getConfiguration()}, since by definition the - * default configuration equals to the configuration that is created by calling - * <pre> - * ConfigurationContextBuilderFactory factory = ...; - * Configuration config = factory.createBuilder().loadDefaults().build(); - * </pre> - */ -public interface ConfigurationContextBuilder { - - /** - * Adds one or more property filter instances to the configuration to be build. - * - * <pre>{@code PropertyFilter quoteReplacingFilter = new QuoteFilter(); - * PropertyFilter commaRemovingFilter = new CommaFilter(); - * - * builder.addPropertyFilters(commaRemovingFilter, quoteReplacingFilter)}; - * </pre> - * - * @param filters list of property filter instances which should be applied - * to the properties of the configuration to be build. - * - * @return the builder instance currently used - * - * @see org.apache.tamaya.spi.PropertyFilter - * @see #getDefaultPropertyFilters() - */ - ConfigurationContextBuilder addPropertyFilters(PropertyFilter... filters); - - /** - * Adds one or more property filter instances to the configuration to be build. - * - * <pre>{@code PropertyFilter quoteReplacingFilter = new QuoteFilter(); - * PropertyFilter commaRemovingFilter = new CommaFilter(); - * - * builder.addPropertyFilters(commaRemovingFilter, quoteReplacingFilter)}; - * </pre> - * - * @param filters list of property filter instances which should be applied - * to the properties of the configuration to be build. - * - * @return the builder instance currently used - * - * @see org.apache.tamaya.spi.PropertyFilter - * @see #getDefaultPropertyFilters() - */ - ConfigurationContextBuilder addPropertyFilters(Collection<PropertyFilter> filters); - - /** - * @param propertyValueCombinationPolicy combination policy to use for this builder. - * @return the builder instance currently in use. - */ - ConfigurationContextBuilder setPropertyValueCombinationPolicy( - PropertyValueCombinationPolicy propertyValueCombinationPolicy); - - /** - * Adds a property converter for the a given type to the configuration to - * be build. - * - * <pre>{@code PropertyConverter<MyType> converter = value -> new MyType(value, 42); - * - * builder.addPropertyConverters(MyType.class, converter} - * </pre> - * - * @param <T> the type of the configuration - * @param type the required target type the converter should be applied to - * @param converter the converter to be used to convert the string property - * to the given target type, not null. - * - * @return the builder instance currently used - * - * @see org.apache.tamaya.spi.PropertyConverter - * @see #getDefaultPropertyConverters() - */ - <T> ConfigurationContextBuilder addPropertyConverter(Class<T> type, PropertyConverter<T>... converter); - - /** - * Adds a property converter for the a given type to the configuration to - * be build. - * - * <pre>{@code PropertyConverter<MyType> converter = value -> new MyType(value, 42); - * - * builder.addPropertyConverters(MyType.class, converter} - * </pre> - * - * @param <T> the type of the configuration - * @param type the required target type the converter should be applied to - * @param converter the converter to be used to convert the string property - * to the given target type, not null. - * - * @return the builder instance currently used - * - * @see org.apache.tamaya.spi.PropertyConverter - * @see #getDefaultPropertyConverters() - */ - <T> ConfigurationContextBuilder addPropertyConverter(Class<T> type, Collection<PropertyConverter<T>> converter); - - /** - * Adds a propertyConverter of a given type. - * - * @param <T> the type of the configuration - * @param type type literal of this converter. - * @param propertyConverter property converter, not null. - * @return the builder instance currently used - */ - <T> ConfigurationContextBuilder addPropertyConverter(TypeLiteral<T> type, PropertyConverter<T>... propertyConverter); - - /** - * Adds a propertyConverter of a given type. - * - * @param <T> the type of the configuration - * @param type type literal of this converter. - * @param propertyConverter property converter, not null. - * @return the builder instance currently used - */ - <T> ConfigurationContextBuilder addPropertyConverter(TypeLiteral<T> type, Collection<PropertyConverter<T>> propertyConverter); - - /** - * Loads the {@link org.apache.tamaya.spi.PropertyConverter}s provided - * via the SPI API returns them for adding all or parts of it using the - * builder's add methods. - * - * @return the collection of default instances, not yet registered - * within this builder. - * - * @see #addPropertyConverter(TypeLiteral, PropertyConverter...) - * @see #addPropertyConverter(TypeLiteral, Collection) - * @see org.apache.tamaya.spi.PropertyConverter - */ - Map<TypeLiteral<?>, Collection<PropertyConverter<?>>> getDefaultPropertyConverters(); - - - /** - * Loads the {@link org.apache.tamaya.spi.PropertySource}s provided - * via the SPI API, but does not yet register them into this builder. - * - * @return the builder instance currently used - * - * @see #addPropertySources(Collection) - * @see #addPropertySources(PropertySource...) - * @see org.apache.tamaya.spi.PropertySource - */ - Collection<PropertySource> getDefaultPropertySources(); - - - /** - * Loads the {@link org.apache.tamaya.spi.PropertyFilter}s provided via the SPI API, - * but does not register them into this instance. - * - * @return the builder instance currently used - * - * @see #addPropertyFilters(Collection<PropertyFilter>) - * @see org.apache.tamaya.spi.PropertyFilter - */ - Collection<PropertyFilter> getDefaultPropertyFilters(); - - - /** - * Loads the {@link org.apache.tamaya.spi.PropertySourceProvider - * property source providers} provided via the SPI API and - * returns them. No property sources are registered. - * - * @return the builder instance currently used - * - * @see #addPropertySources(Collection) - * @see org.apache.tamaya.spi.PropertySourceProvider - */ - Collection<PropertySourceProvider> getDefaultPropertySourceProviders(); - - /** - * This method loads the default configuration, which involves the following - * steps: - * <ol> - * <li>Loading {@link PropertySource} instances registered with the - * {@link java.util.ServiceLoader}.</li> - * <li>Loading {@link org.apache.tamaya.spi.PropertySourceProvider} instances registered with the - * {@link java.util.ServiceLoader}, extracting the provided processors and add them - * to the list of loaded processors</li> - * <li>Sorting the processors collecting based on {@link PropertySource#getOrdinal()} and the - * fully qualified class name as an additional fallback criteria, when the ordinal - * is the same.</li> - * <li>Putting together a {@link Configuration} instance incorporating this - * chain of processors. Hereby when {@link Configuration#get(String)} is called - * the first processor in the chain is asked for a value. If the processor returns {@code null} - * the processChain is repeated until the end of the chain is reached, or a processor returns - * non non-null value. Hereby each processor can actively decide how and if its parent processors - * will be included for subsequent value evaluation for a given key. In other words a processor - * can either simply provide configuration properties (values) or implement a more active functionality - * such as filtering or value collection.</li> - * </ol> - * @return the builder for further chaining of logic. - */ - ConfigurationContextBuilder loadDefaults(); - - /** - * Get the current number of processors on the chain. - * @return the number of registered processors of this instance. - */ - int getChainSize(); - - /** - * Increses the priority of the given processor instance, meaning moving the processor one - * position ahead in the overall processor chain. This will be done regardless of any - * ordinal value. If the procerssor already has maximal significance (is on the head of - * processors), this method does not have any effect. - * @param processor the target procerssor, not null. - * @return the builder for further chaining of logic. - */ - ConfigurationContextBuilder increasePriority(PropertySource processor); - - /** - * Decreses the priority of the given processor instance, meaning moving the processor one - * position back in the overall processor chain. This will be done regardless of any - * ordinal value. If the procerssor already has minimal significance (is the tail of - * processors), this method does not have any effect. - * @param processor the target procerssor, not null. - * @return the builder for further chaining of logic. - */ - ConfigurationContextBuilder decreasePriority(PropertySource processor); - - /** - * Maximizes the priority of the given processor instance, moving it to the head of the - * processor chain. This will be done regardless of any - * ordinal value. If the procerssor already has minimal significance (is the tail of - * processors), this method does not have any effect. - * @param processor the target procerssor, not null. - * @return the builder for further chaining of logic. - */ - ConfigurationContextBuilder highestPriority(PropertySource processor); - - /** - * Minimizes the priority of the given property source instance, moving it to the tail of the - * property source chain. This will be done regardless of any - * ordinal value. If the property source already has minimal significance (is the tail of - * processors), this method does not have any effect. - * @param propertySource the target property source, not null. - * @return the builder for further chaining of logic. - */ - ConfigurationContextBuilder lowestPriority(PropertySource propertySource); - - /** - * Add the property sources to the property source chain using thei provided ordinals - * for ordering. - * @param propertySources the property sources to add, not null. - * @return the builder for further chaining of logic. - */ - ConfigurationContextBuilder addPropertySources(PropertySource... propertySources); - - /** - * Add the property sources to the property source chain. - * @param propertySources the property sources to add, not null. - * @param index index where the new property sources should be inserted. - * @return the builder for further chaining of logic. - */ - ConfigurationContextBuilder addPropertySources(int index, PropertySource... propertySources); - - /** - * Add the property sources to the property source chain using thei provided ordinals - * for ordering. - * @param propertySources the property sources to add, not null. - * @return the builder for further chaining of logic. - */ - ConfigurationContextBuilder addPropertySources(Collection<PropertySource> propertySources); - - /** - * Add the property sources to the property source chain with highest priority (as new chain head). - * @param propertySources the property sources to add, not null. - * @param index index where the new property sources should be inserted. - * @return the builder for further chaining of logic. - */ - ConfigurationContextBuilder addPropertySources(int index, Collection<PropertySource> propertySources); - - /** - * Removes the given property source from the property source chain. - * @param propertySource the property source. not null. - * @return the builder for further chaining of logic. - */ - ConfigurationContextBuilder removePropertySource(PropertySource propertySource); - - /** - * Access a processor using it's unique property source name. If no such property source - * is present, this method has no effect. - * @param name the property source name, not null. - * @return the builder for further chaining of logic. - */ - PropertySource getPropertySource(String name); - - /** - * Get access to the current chain of property sources. This returns an immutable list. Use the - * methods of this factory to change the ordering or adding/removing of property sources. - * @return the current chain of property sources (immutable list). - */ - List<PropertySource> getPropertySourcesChain(); - - /** - * Get access to the current property sources with a given type. This returns an immutable list. Use the - * methods of this factory to change the ordering or adding/removing of property sources. - * @return the current chain of property sources (immutable list). - */ - List<PropertySource> getPropertySources(Class<? extends PropertySource> type); - - /** - * Get access to the current chain of property sources. This returns an immutable list. Use the - * methods of this factory to change the ordering or adding/removing of property sources. - * @return the current chain of property sources as names (immutable list). - */ - List<String> getPropertySourcesNames(); - - /** - * Builds a new configuration based on the current property sources chain. - * @return a new configuration instance, never null. - */ - Configuration build(); -} - http://git-wip-us.apache.org/repos/asf/incubator-tamaya-sandbox/blob/9f71f2d8/metamodel/src/main/java/org/apache/tamaya/metamodel/Context.java ---------------------------------------------------------------------- diff --git a/metamodel/src/main/java/org/apache/tamaya/metamodel/Context.java b/metamodel/src/main/java/org/apache/tamaya/metamodel/Context.java index ce6d99c..b4b65d2 100644 --- a/metamodel/src/main/java/org/apache/tamaya/metamodel/Context.java +++ b/metamodel/src/main/java/org/apache/tamaya/metamodel/Context.java @@ -30,38 +30,62 @@ import java.util.concurrent.ConcurrentHashMap; */ public final class Context { - private static final Map<String,Context> CONTEXTS = new ConcurrentHashMap(); + private static final ThreadLocal<Context> THREAD_CONTEXT = new ThreadLocal<Context>(){ + @Override + protected Context initialValue() { + return new Context(); + } + }; + private final Map<String,String> properties = new ConcurrentHashMap<>(); - public static Context getInstance(){ - return getInstance(""); + /** + * Access the thread-based context. If no such context + * exists a new one will be created. + * @return the corresponding context, never null. + */ + public static Context getThreadInstance(){ + return THREAD_CONTEXT.get(); } /** - * Access the context with a goven contextId, this allows to manage multiple - * contexts, e.g. for different EE application's deployed. If no such context - * exists a new one will be created. - * @param contextId the contextId, not null. + * Access the current context, which actually is the current context, combined with the thread based + * context (overriding). * @return the corresponding context, never null. */ - public static Context getInstance(String contextId){ - Context context = CONTEXTS.get(contextId); - if(context==null){ - synchronized (Context.class){ - context = CONTEXTS.get(contextId); - if(context==null){ - context = new Context(); - CONTEXTS.put(contextId, context); - } - } + public Context getCurrentInstance(){ + return this.combineWith(THREAD_CONTEXT.get()); + } + + /** + * Combine this context with the other contexts given. + * @param contexts the context to merge with this context. + * @return the newly created Context. + */ + public Context combineWith(Context... contexts) { + Context newContext = new Context(); + newContext.properties.putAll(getProperties()); + for(Context ctx:contexts) { + newContext.properties.putAll(ctx.getProperties()); } - return context; + return newContext; } + /** + * Access the given context property. + * @param key the key, not null + * @return the value, or null. + */ public String getProperty(String key){ return getProperty(key, null); } + /** + * Access the given context property. + * @param key the key, not the default value. + * @param defaultValue the default value to be returned, if no value is defined. + * @return the value, default value or null. + */ public String getProperty(String key, String defaultValue){ String value = this.properties.get(key); if(value==null){ @@ -70,10 +94,21 @@ public final class Context { return value; } + /** + * Sets the given context property. + * @param key the key, not null. + * @param value the value, not null. + * @return the porevious value, or null. + */ public String setProperty(String key, String value){ return this.properties.put(key,value); } + /** + * Sets the given property unless there is already a value defined. + * @param key the key, not null. + * @param value the value, not null. + */ public void setPropertyIfAbsent(String key, String value){ String prev = this.properties.get(key); if(prev==null){ @@ -81,10 +116,19 @@ public final class Context { } } + /** + * Adds all properties given, overriding any existing properties. + * @param properties the properties, not null. + */ public void setProperties(Map<String,String> properties){ this.properties.putAll(properties); } + /** + * Checks if all the given properties are present. + * @param keys the keys to check, not null. + * @return true, if all the given keys are existing. + */ public boolean checkProperties(String... keys){ for(String key:keys) { if (getProperty(key, null) == null) { @@ -94,13 +138,10 @@ public final class Context { return true; } - public boolean checkProperty(String key, String value){ - if(value!=null){ - return value.equals(getProperty(key, null)); - } - return !checkProperties(key); - } - + /** + * Access all the current context properties. + * @return the properties, never null. + */ public Map<String,String> getProperties(){ return Collections.unmodifiableMap(this.properties); } http://git-wip-us.apache.org/repos/asf/incubator-tamaya-sandbox/blob/9f71f2d8/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/DSLFormatManager.java ---------------------------------------------------------------------- diff --git a/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/DSLFormatManager.java b/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/DSLFormatManager.java index b7c0074..2d84c48 100644 --- a/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/DSLFormatManager.java +++ b/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/DSLFormatManager.java @@ -1,115 +1,115 @@ -/* - * 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.metamodel.dsl; - -import org.apache.tamaya.Configuration; -import org.apache.tamaya.format.ConfigurationFormat; -import org.apache.tamaya.format.ConfigurationFormats; -import org.apache.tamaya.functions.ConfigurationFunctions; - -import java.util.*; - -/** - * Component that manages the current supported formats: - * <pre> - * TAMAYA: - * FORMAT-DEF: - * - formats: yaml, properties, xml-properties - * </pre> - * Hereby: - * <ul> - * <li><b>profiles</b> defines the available profiles, including implicit default profiles.</li> - * </ul> - */ -public final class DSLFormatManager { - - private static final DSLFormatManager INSTANCE = new DSLFormatManager(); - - /** The currently active formats, in order of precedence, the most significant are the last ones. */ - private List<ConfigurationFormat> formats = new ArrayList<>(); - /** The currently active suffixes, in order of precedence, the most significant are the last ones. */ - private List<String> suffixes = new ArrayList<>(); - - - /** - * Get the current instance. - * @return the current profile manager, never null. - */ - public static DSLFormatManager getInstance(){ - return INSTANCE; - } - - private DSLFormatManager(){ - Configuration metaConfig = MetaConfiguration.getConfiguration(); - Configuration formatsConfig = metaConfig.with( - ConfigurationFunctions.section("TAMAYA.FORMATS")); - String[] formats = formatsConfig.getOrDefault("formats","yamk,properties,ini").split(","); - this.formats.addAll(ConfigurationFormats.getFormats(formats)); - String[] suffixes = formatsConfig.getOrDefault("suffixes","yml,properties,ini").split(","); - for(String sfx:suffixes){ - sfx = sfx.trim(); - if(sfx.isEmpty()){ - continue; - } - this.suffixes.add(sfx); - } - } - - - /** - * Allows to check if a suffix is currently activated. - * @param suffix the suffix name, not null. - * @return true, if the profile is defined. - */ - public boolean isSuffixDefined(String suffix){ - return this.suffixes.contains(suffix); - } - - /** - * Allows to check if a format is selected. - * @param formatName the format name, not null. - * @return true, if the format is a selected. - */ - public boolean isFormatSelected(String formatName){ - for(ConfigurationFormat format:formats){ - if(format.getName().equals(formatName)){ - return true; - } - } - return false; - } - - /** - * Get the list of currently active suffixes. - * @return the list of currently active suffixes, never null. - */ - public List<String> getSuffixes(){ - return Collections.unmodifiableList(suffixes); - } - - /** - * Get the list of currently active formats. - * @return the list of currently active formats, never null. - */ - public List<ConfigurationFormat> getFormats(){ - return Collections.unmodifiableList(formats); - } - - -} +///* +// * 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.metamodel.dsl; +// +//import org.apache.tamaya.Configuration; +//import org.apache.tamaya.format.ConfigurationFormat; +//import org.apache.tamaya.format.ConfigurationFormats; +//import org.apache.tamaya.functions.ConfigurationFunctions; +// +//import java.util.*; +// +///** +// * Component that manages the current supported formats: +// * <pre> +// * TAMAYA: +// * FORMAT-DEF: +// * - formats: yaml, properties, xml-properties +// * </pre> +// * Hereby: +// * <ul> +// * <li><b>profiles</b> defines the available profiles, including implicit default profiles.</li> +// * </ul> +// */ +//public final class DSLFormatManager { +// +// private static final DSLFormatManager INSTANCE = new DSLFormatManager(); +// +// /** The currently active formats, in order of precedence, the most significant are the last ones. */ +// private List<ConfigurationFormat> formats = new ArrayList<>(); +// /** The currently active suffixes, in order of precedence, the most significant are the last ones. */ +// private List<String> suffixes = new ArrayList<>(); +// +// +// /** +// * Get the current instance. +// * @return the current profile manager, never null. +// */ +// public static DSLFormatManager getInstance(){ +// return INSTANCE; +// } +// +// private DSLFormatManager(){ +// Configuration metaConfig = MetaConfiguration.getConfiguration(); +// Configuration formatsConfig = metaConfig.with( +// ConfigurationFunctions.section("TAMAYA.FORMATS")); +// String[] formats = formatsConfig.getOrDefault("formats","yamk,properties,ini").split(","); +// this.formats.addAll(ConfigurationFormats.getFormats(formats)); +// String[] suffixes = formatsConfig.getOrDefault("suffixes","yml,properties,ini").split(","); +// for(String sfx:suffixes){ +// sfx = sfx.trim(); +// if(sfx.isEmpty()){ +// continue; +// } +// this.suffixes.add(sfx); +// } +// } +// +// +// /** +// * Allows to check if a suffix is currently activated. +// * @param suffix the suffix name, not null. +// * @return true, if the profile is defined. +// */ +// public boolean isSuffixDefined(String suffix){ +// return this.suffixes.contains(suffix); +// } +// +// /** +// * Allows to check if a format is selected. +// * @param formatName the format name, not null. +// * @return true, if the format is a selected. +// */ +// public boolean isFormatSelected(String formatName){ +// for(ConfigurationFormat format:formats){ +// if(format.getName().equals(formatName)){ +// return true; +// } +// } +// return false; +// } +// +// /** +// * Get the list of currently active suffixes. +// * @return the list of currently active suffixes, never null. +// */ +// public List<String> getSuffixes(){ +// return Collections.unmodifiableList(suffixes); +// } +// +// /** +// * Get the list of currently active formats. +// * @return the list of currently active formats, never null. +// */ +// public List<ConfigurationFormat> getFormats(){ +// return Collections.unmodifiableList(formats); +// } +// +// +//} http://git-wip-us.apache.org/repos/asf/incubator-tamaya-sandbox/blob/9f71f2d8/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/MetaConfiguration.java ---------------------------------------------------------------------- diff --git a/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/MetaConfiguration.java b/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/MetaConfiguration.java index b3f7da0..2e88c6b 100644 --- a/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/MetaConfiguration.java +++ b/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/MetaConfiguration.java @@ -1,142 +1,122 @@ -/* - * 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.metamodel.dsl; - -import org.apache.tamaya.Configuration; -import org.apache.tamaya.ConfigurationProvider; -import org.apache.tamaya.format.ConfigurationData; -import org.apache.tamaya.format.ConfigurationFormat; -import org.apache.tamaya.format.ConfigurationFormats; -import org.apache.tamaya.json.YAMLFormat; -import org.apache.tamaya.resource.ConfigResources; -import org.apache.tamaya.spi.ConfigurationContextBuilder; - -import java.io.InputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Meta environment configuration builder and accessor. Normally this class shoulds never be accessed - * by client code. But it could be useful for extensions that extend the meta-configuration capabilities - * of tamaya having access to the meta-configuration, so they can read their own meta-entries to - * setup whatever features they implement. - */ -public final class MetaConfiguration { - - private static final Logger LOGGER = Logger.getLogger(MetaConfiguration.class.getName()); - private static MetaConfiguration INSTANCE = new MetaConfiguration(); - - private Configuration config; - private String resourceExpression; - private String[] formatNames; - - /** - * Initializes the metaconfiguration. - * @param resourceExpression the resource expression that defines the resources to load. - * @param formatNames the format names to be used. - */ - private void init(String resourceExpression, String... formatNames){ - if(this.config!=null){ - LOGGER.warning(">>> Reset of Meta-Configuration resource : " + resourceExpression); - LOGGER.warning(">>> Reset of Meta-Configuration formats : " + Arrays.toString(formatNames)); - } - if(resourceExpression==null){ - resourceExpression = "tamaya-config.*"; - } - LOGGER.info(">>> Meta-Configuration resource : " + resourceExpression); - ConfigurationFormat[] formats = loadFormats(formatNames); - ConfigurationContextBuilder builder = ConfigurationProvider.getConfigurationContextBuilder(); - for(URL url:ConfigResources.getResourceResolver().getResources(resourceExpression)) { - for(ConfigurationFormat format:formats) { - if(format.accepts(url)){ - try(InputStream is = url.openStream()){ - ConfigurationData data = format.readConfiguration(url.toString(), is); - builder.addPropertySources(PropertySourceBuilder( - url.toString(), data.getCombinedProperties())); - }catch(Exception e){ - LOGGER.log(Level.INFO, "Failed to read " + url + " with format " + format, e); - } - } - } - } - this.config = ConfigurationProvider.createConfiguration(builder.build()); - LOGGER.info("Meta-Configuration read: " + this.config.getProperties().size() + " entries."); - } - - private ConfigurationFormat[] loadFormats(String... formatNames) { - List<ConfigurationFormat> formats = new ArrayList<>(); - if(formatNames.length==0) { - String metaFormats = System.getProperty("tamaya.meta-formats"); - if (metaFormats != null) { - formatNames = metaFormats.split(","); - } - } - for (String formatName : formatNames) { - formats.addAll(ConfigurationFormats.getFormats(formatName)); - } - if(formats.isEmpty()){ - formats.addAll(ConfigurationFormats.getFormats("yaml")); - } - if(formats.isEmpty()){ - formats.add(new YAMLFormat()); - } - LOGGER.info(">>> Meta-Configuration formats : " + formats); - return formats.toArray(new ConfigurationFormat[formats.size()]); - } - - /** - * Access the system's meta-configuration, initialize if necessary. Normally this class shoulds never be accessed - * by client code. But it could be useful for extensions that extend the meta-configuration capabilities - * of tamaya having access to the meta-configuration, so they can read their own meta-entries to - * setup whatever features they implement. - * @return the meta-configuration instance used for setting up the Tamaya's application configuration - * model. - */ - public static Configuration getConfiguration(){ - if(INSTANCE.config==null) { - INSTANCE.init(null); - } - return INSTANCE.config; - } - - /** - * Access the system's meta-configuration, initialize if necessary. Normally this class shoulds never be accessed - * by client code. But it could be useful for extensions that extend the meta-configuration capabilities - * of tamaya having access to the meta-configuration, so they can read their own meta-entries to - * setup whatever features they implement. - * - * @param resourceExpression the resource expression that defines where the metaconfiguration - * files/resources are located. - * @param formatNames the formats supported, if null all formats found are tried for each resource(=URL). - * @return the meta-configuration instance used for setting up the Tamaya's application configuration - * model. - */ - public static Configuration getConfiguration(String resourceExpression, - String... formatNames){ - if(INSTANCE.config==null) { - INSTANCE.init(resourceExpression, formatNames); - } - return INSTANCE.config; - } - -} +///* +// * 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.metamodel.dsl; +// +//import org.apache.tamaya.Configuration; +//import org.apache.tamaya.ConfigurationProvider; +//import org.apache.tamaya.format.ConfigurationData; +//import org.apache.tamaya.format.ConfigurationFormat; +//import org.apache.tamaya.format.ConfigurationFormats; +//import org.apache.tamaya.json.YAMLFormat; +//import org.apache.tamaya.resource.ConfigResources; +//import org.apache.tamaya.spi.ConfigurationContextBuilder; +// +//import java.io.InputStream; +//import java.net.URL; +//import java.util.ArrayList; +//import java.util.Arrays; +//import java.util.List; +//import java.util.logging.Level; +//import java.util.logging.Logger; +// +///** +// * Meta environment configuration builder and accessor. Normally this class shoulds never be accessed +// * by client code. But it could be useful for extensions that extend the meta-configuration capabilities +// * of tamaya having access to the meta-configuration, so they can read their own meta-entries to +// * setup whatever features they implement. +// */ +//public final class MetaConfiguration { +// +// private static final Logger LOGGER = Logger.getLogger(MetaConfiguration.class.getName()); +// private static MetaConfiguration INSTANCE = new MetaConfiguration(); +// +// private Configuration config; +// private String resourceExpression; +// private String[] formatNames; +// +// /** +// * Initializes the metaconfiguration. +// * @param resourceExpression the resource expression that defines the resources to load. +// * @param formatNames the format names to be used. +// */ +// private void init(String resourceExpression, String... formatNames){ +// if(this.config!=null){ +// LOGGER.warning(">>> Reset of Meta-Configuration resource : " + resourceExpression); +// LOGGER.warning(">>> Reset of Meta-Configuration formats : " + Arrays.toString(formatNames)); +// } +// if(resourceExpression==null){ +// resourceExpression = "tamaya-config.*"; +// } +// LOGGER.info(">>> Meta-Configuration resource : " + resourceExpression); +// ConfigurationFormat[] formats = loadFormats(formatNames); +// ConfigurationContextBuilder builder = ConfigurationProvider.getConfigurationContextBuilder(); +// for(URL url:ConfigResources.getResourceResolver().getResources(resourceExpression)) { +// for(ConfigurationFormat format:formats) { +// if(format.accepts(url)){ +// try(InputStream is = url.openStream()){ +// ConfigurationData data = format.readConfiguration(url.toString(), is); +// builder.addPropertySources(PropertySourceBuilder( +// url.toString(), data.getCombinedProperties())); +// }catch(Exception e){ +// LOGGER.log(Level.INFO, "Failed to read " + url + " with format " + format, e); +// } +// } +// } +// } +// this.config = ConfigurationProvider.createConfiguration(builder.build()); +// LOGGER.info("Meta-Configuration read: " + this.config.getProperties().size() + " entries."); +// } +// +// +// /** +// * Access the system's meta-configuration, initialize if necessary. Normally this class shoulds never be accessed +// * by client code. But it could be useful for extensions that extend the meta-configuration capabilities +// * of tamaya having access to the meta-configuration, so they can read their own meta-entries to +// * setup whatever features they implement. +// * @return the meta-configuration instance used for setting up the Tamaya's application configuration +// * model. +// */ +// public static Configuration getConfiguration(){ +// if(INSTANCE.config==null) { +// INSTANCE.init(null); +// } +// return INSTANCE.config; +// } +// +// /** +// * Access the system's meta-configuration, initialize if necessary. Normally this class shoulds never be accessed +// * by client code. But it could be useful for extensions that extend the meta-configuration capabilities +// * of tamaya having access to the meta-configuration, so they can read their own meta-entries to +// * setup whatever features they implement. +// * +// * @param resourceExpression the resource expression that defines where the metaconfiguration +// * files/resources are located. +// * @param formatNames the formats supported, if null all formats found are tried for each resource(=URL). +// * @return the meta-configuration instance used for setting up the Tamaya's application configuration +// * model. +// */ +// public static Configuration getConfiguration(String resourceExpression, +// String... formatNames){ +// if(INSTANCE.config==null) { +// INSTANCE.init(resourceExpression, formatNames); +// } +// return INSTANCE.config; +// } +// +//} http://git-wip-us.apache.org/repos/asf/incubator-tamaya-sandbox/blob/9f71f2d8/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/ProfileManager.java ---------------------------------------------------------------------- diff --git a/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/ProfileManager.java b/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/ProfileManager.java index 6e95ffe..0d19d9c 100644 --- a/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/ProfileManager.java +++ b/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/ProfileManager.java @@ -1,213 +1,213 @@ -/* - * 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.metamodel.dsl; - -import org.apache.tamaya.ConfigException; -import org.apache.tamaya.Configuration; -import org.apache.tamaya.functions.ConfigurationFunctions; -import org.apache.tamaya.resolver.Resolver; -import org.apache.tamaya.resolver.spi.ExpressionResolver; -import org.apache.tamaya.spi.ServiceContextManager; - -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Component that manages the current setup profiles for this environment/runtime. The profile manager - * reads the profile meta configuration that looks as follows: - * <pre> - * TAMAYA: - * PROFILES-DEF: - * - profiles: DEFAULTS,DEV,TEST,PTA,PROD - * - defaults: DEFAULTS - * - default-active: DEV - * - evaluation: ${sys:ENV}, ${env:ENV} - * </pre> - * Hereby: - * <ul> - * <li><b>profiles</b> defines the available profiles, including implicit default profiles.</li> - * <li><b>defaults</b> defines the profiles that are loaded implicitly first as defaults.</li> - * <li><b>default-active</b> defines the profile(s) activated by default, when no profile setting could be evaluated. - * <li><b>evaluation</b> defines the resolution expressions to be used to evaluate the current profiles active. - * By default {@code ${sys:ENV}, ${env:ENV}} is used, which tries to evaluate {@code ENV} using system and - * environment properties. Refere to the {@code tamaya-resolver} module for further details on resolvers and - * expressions and see {@link Resolver#evaluateExpression(String, boolean)}. - * </ul> - */ -public final class ProfileManager { - - private static final Logger LOG = Logger.getLogger(ProfileManager.class.getName()); - private static final ProfileManager INSTANCE = new ProfileManager(); - - /** The currently active profiles, in order of precedence, the most significant are the last ones. */ - private List<String> activeProfiles = new ArrayList<>(); - /** A set of all defined profiles. */ - private Set<String> profiles = new HashSet<>(); - /** The current used default profiles, loaded initially, before all other profiles are loaded. */ - private List<String> defaultProfiles = new ArrayList<>(); - - - /** - * Get the current instance. - * @return the current profile manager, never null. - */ - public static ProfileManager getInstance(){ - return INSTANCE; - } - - private ProfileManager(){ - Configuration metaConfig = MetaConfiguration.getConfiguration(); - Configuration profileConfig = metaConfig.with( - ConfigurationFunctions.section("TAMAYA.PROFILES-DEF")); - String[] selectables = profileConfig.getOrDefault("profiles","DEFAULT,DEV,TEST,PROD").split(","); - for(String sel:selectables){ - sel = sel.trim(); - if(sel.isEmpty()){ - continue; - } - this.profiles.add(sel); - } - String[] defaults = profileConfig.getOrDefault("defaults","DEFAULT").split(","); - for(String def:defaults){ - def = def.trim(); - if(def.isEmpty()){ - continue; - } - if(!isProfileDefined(def)){ - throw new ConfigException("Invalid profile encountered: " +def + ", valid are: " + profiles); - } - this.defaultProfiles.add(def); - } - String[] expressions = profileConfig.getOrDefault("evaluation","${sys:ENV}, ${env:ENV}").split(","); - String currentEnvironment = null; - for(String exp:expressions){ - exp = exp.trim(); - if(exp.isEmpty()){ - continue; - } - currentEnvironment = evaluateExpression(exp); - if(currentEnvironment!=null){ - currentEnvironment = currentEnvironment.trim(); - if(!currentEnvironment.isEmpty()){ - break; - } - } - } - if(currentEnvironment==null|| currentEnvironment.isEmpty()){ - currentEnvironment = profileConfig.getOrDefault("default-active", "DEV"); - } - this.activeProfiles.addAll(defaultProfiles); - String[] profilesActive = currentEnvironment.split(","); - for(String prof:profilesActive){ - prof = prof.trim(); - if(prof.isEmpty()){ - continue; - } - if(!isProfileDefined(prof)){ - throw new ConfigException("Invalid profile encountered: " +prof + ", valid are: " + profiles); - } - this.activeProfiles.add(prof); - } - } - - /** - * Evaluates the expressions to evaluate the current profile. - * Currently the following expressions are supported - * <pre> - * sys-property:xxx - * env-property:xxx - * </pre> - * {@code xxx} is the corresponding key. - * @param currentProfileExpression the profile expression. - * @return the evaluated String, or null. - */ - private String evaluateExpression(String currentProfileExpression){ - currentProfileExpression = currentProfileExpression.trim(); - List<ExpressionResolver> resolvers = new ArrayList<>(); - for(ExpressionResolver res: ServiceContextManager.getServiceContext().getServices(ExpressionResolver.class)){ - resolvers.add(res); - } - for(ExpressionResolver res:resolvers){ - if(currentProfileExpression.startsWith(res.getResolverPrefix())){ - try{ - return res.evaluate(currentProfileExpression.substring(res.getResolverPrefix().length())); - }catch(Exception e){ - LOG.log(Level.FINEST, "Error evaluating resolver: " + res, e); - } - } - } - return null; - } - - /** - * Allows to check if a profile is currently active. - * @param profileName the profile name, not null. - * @return true, if the profile is active. - */ - public boolean isProfileActive(String profileName){ - return this.activeProfiles.contains(profileName); - } - - /** - * Allows to check if a profile is currently defined. - * @param profileName the profile name, not null. - * @return true, if the profile is defined. - */ - public boolean isProfileDefined(String profileName){ - return this.profiles.contains(profileName); - } - - /** - * Allows to check if a profile is a default profile. - * @param profileName the profile name, not null. - * @return true, if the profile is a default profile. - */ - public boolean isProfileDefault(String profileName){ - return this.defaultProfiles.contains(profileName); - } - - /** - * Get the list of currently active profiles. - * @return the list of currently active profiles, in order of precedence, the most significant - * are the last ones, never null. - */ - public List<String> getActiveProfiles(){ - return Collections.unmodifiableList(activeProfiles); - } - - /** - * Get the list of currently active profiles. - * @return the list of currently active profiles, in order of precedence, the most significant - * are the last ones, never null. - */ - public List<String> getDefaultProfiles(){ - return Collections.unmodifiableList(defaultProfiles); - } - - /** - * Get the list of currently active profiles. - * @return the list of currently active profiles, in order of precedence, the most significant - * are the last ones, never null. - */ - public Set<String> getAllProfiles(){ - return Collections.unmodifiableSet(profiles); - } - -} +///* +// * 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.metamodel.dsl; +// +//import org.apache.tamaya.ConfigException; +//import org.apache.tamaya.Configuration; +//import org.apache.tamaya.functions.ConfigurationFunctions; +//import org.apache.tamaya.resolver.Resolver; +//import org.apache.tamaya.resolver.spi.ExpressionResolver; +//import org.apache.tamaya.spi.ServiceContextManager; +// +//import java.util.*; +//import java.util.logging.Level; +//import java.util.logging.Logger; +// +///** +// * Component that manages the current setup profiles for this environment/runtime. The profile manager +// * reads the profile meta configuration that looks as follows: +// * <pre> +// * TAMAYA: +// * PROFILES-DEF: +// * - profiles: DEFAULTS,DEV,TEST,PTA,PROD +// * - defaults: DEFAULTS +// * - default-active: DEV +// * - evaluation: ${sys:ENV}, ${env:ENV} +// * </pre> +// * Hereby: +// * <ul> +// * <li><b>profiles</b> defines the available profiles, including implicit default profiles.</li> +// * <li><b>defaults</b> defines the profiles that are loaded implicitly first as defaults.</li> +// * <li><b>default-active</b> defines the profile(s) activated by default, when no profile setting could be evaluated. +// * <li><b>evaluation</b> defines the resolution expressions to be used to evaluate the current profiles active. +// * By default {@code ${sys:ENV}, ${env:ENV}} is used, which tries to evaluate {@code ENV} using system and +// * environment properties. Refere to the {@code tamaya-resolver} module for further details on resolvers and +// * expressions and see {@link Resolver#evaluateExpression(String, boolean)}. +// * </ul> +// */ +//public final class ProfileManager { +// +// private static final Logger LOG = Logger.getLogger(ProfileManager.class.getName()); +// private static final ProfileManager INSTANCE = new ProfileManager(); +// +// /** The currently active profiles, in order of precedence, the most significant are the last ones. */ +// private List<String> activeProfiles = new ArrayList<>(); +// /** A set of all defined profiles. */ +// private Set<String> profiles = new HashSet<>(); +// /** The current used default profiles, loaded initially, before all other profiles are loaded. */ +// private List<String> defaultProfiles = new ArrayList<>(); +// +// +// /** +// * Get the current instance. +// * @return the current profile manager, never null. +// */ +// public static ProfileManager getInstance(){ +// return INSTANCE; +// } +// +// private ProfileManager(){ +// Configuration metaConfig = MetaConfiguration.getConfiguration(); +// Configuration profileConfig = metaConfig.with( +// ConfigurationFunctions.section("TAMAYA.PROFILES-DEF")); +// String[] selectables = profileConfig.getOrDefault("profiles","DEFAULT,DEV,TEST,PROD").split(","); +// for(String sel:selectables){ +// sel = sel.trim(); +// if(sel.isEmpty()){ +// continue; +// } +// this.profiles.add(sel); +// } +// String[] defaults = profileConfig.getOrDefault("defaults","DEFAULT").split(","); +// for(String def:defaults){ +// def = def.trim(); +// if(def.isEmpty()){ +// continue; +// } +// if(!isProfileDefined(def)){ +// throw new ConfigException("Invalid profile encountered: " +def + ", valid are: " + profiles); +// } +// this.defaultProfiles.add(def); +// } +// String[] expressions = profileConfig.getOrDefault("evaluation","${sys:ENV}, ${env:ENV}").split(","); +// String currentEnvironment = null; +// for(String exp:expressions){ +// exp = exp.trim(); +// if(exp.isEmpty()){ +// continue; +// } +// currentEnvironment = evaluateExpression(exp); +// if(currentEnvironment!=null){ +// currentEnvironment = currentEnvironment.trim(); +// if(!currentEnvironment.isEmpty()){ +// break; +// } +// } +// } +// if(currentEnvironment==null|| currentEnvironment.isEmpty()){ +// currentEnvironment = profileConfig.getOrDefault("default-active", "DEV"); +// } +// this.activeProfiles.addAll(defaultProfiles); +// String[] profilesActive = currentEnvironment.split(","); +// for(String prof:profilesActive){ +// prof = prof.trim(); +// if(prof.isEmpty()){ +// continue; +// } +// if(!isProfileDefined(prof)){ +// throw new ConfigException("Invalid profile encountered: " +prof + ", valid are: " + profiles); +// } +// this.activeProfiles.add(prof); +// } +// } +// +// /** +// * Evaluates the expressions to evaluate the current profile. +// * Currently the following expressions are supported +// * <pre> +// * sys-property:xxx +// * env-property:xxx +// * </pre> +// * {@code xxx} is the corresponding key. +// * @param currentProfileExpression the profile expression. +// * @return the evaluated String, or null. +// */ +// private String evaluateExpression(String currentProfileExpression){ +// currentProfileExpression = currentProfileExpression.trim(); +// List<ExpressionResolver> resolvers = new ArrayList<>(); +// for(ExpressionResolver res: ServiceContextManager.getServiceContext().getServices(ExpressionResolver.class)){ +// resolvers.add(res); +// } +// for(ExpressionResolver res:resolvers){ +// if(currentProfileExpression.startsWith(res.getResolverPrefix())){ +// try{ +// return res.evaluate(currentProfileExpression.substring(res.getResolverPrefix().length())); +// }catch(Exception e){ +// LOG.log(Level.FINEST, "Error evaluating resolver: " + res, e); +// } +// } +// } +// return null; +// } +// +// /** +// * Allows to check if a profile is currently active. +// * @param profileName the profile name, not null. +// * @return true, if the profile is active. +// */ +// public boolean isProfileActive(String profileName){ +// return this.activeProfiles.contains(profileName); +// } +// +// /** +// * Allows to check if a profile is currently defined. +// * @param profileName the profile name, not null. +// * @return true, if the profile is defined. +// */ +// public boolean isProfileDefined(String profileName){ +// return this.profiles.contains(profileName); +// } +// +// /** +// * Allows to check if a profile is a default profile. +// * @param profileName the profile name, not null. +// * @return true, if the profile is a default profile. +// */ +// public boolean isProfileDefault(String profileName){ +// return this.defaultProfiles.contains(profileName); +// } +// +// /** +// * Get the list of currently active profiles. +// * @return the list of currently active profiles, in order of precedence, the most significant +// * are the last ones, never null. +// */ +// public List<String> getActiveProfiles(){ +// return Collections.unmodifiableList(activeProfiles); +// } +// +// /** +// * Get the list of currently active profiles. +// * @return the list of currently active profiles, in order of precedence, the most significant +// * are the last ones, never null. +// */ +// public List<String> getDefaultProfiles(){ +// return Collections.unmodifiableList(defaultProfiles); +// } +// +// /** +// * Get the list of currently active profiles. +// * @return the list of currently active profiles, in order of precedence, the most significant +// * are the last ones, never null. +// */ +// public Set<String> getAllProfiles(){ +// return Collections.unmodifiableSet(profiles); +// } +// +//} http://git-wip-us.apache.org/repos/asf/incubator-tamaya-sandbox/blob/9f71f2d8/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/TamayaConfigurator.java ---------------------------------------------------------------------- diff --git a/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/TamayaConfigurator.java b/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/TamayaConfigurator.java index f8abf29..c4570d7 100644 --- a/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/TamayaConfigurator.java +++ b/metamodel/src/main/java/org/apache/tamaya/metamodel/dsl/TamayaConfigurator.java @@ -1,234 +1,234 @@ -/* - * 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.metamodel.dsl; - -import org.apache.tamaya.Configuration; -import org.apache.tamaya.ConfigurationProvider; -import org.apache.tamaya.functions.ConfigurationFunctions; -import org.apache.tamaya.spi.*; -import org.apache.tamaya.metamodel.spi.DSLPropertySourceProvider; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.logging.Logger; - -/** - * Configuration class setting up the Tamaya runtime model. - */ -public final class TamayaConfigurator { - - private static final Logger LOGGER = Logger.getLogger(MetaConfiguration.class.getName()); - private static final Comparator<WrappedPropertySource> ORDINAL_COMPARATOR = - new Comparator<WrappedPropertySource>(){ - @Override - public int compare(WrappedPropertySource o1, WrappedPropertySource o2) { - return o1.getOrdinal() - o2.getOrdinal(); - } - }; - - private static final TamayaConfigurator INSTANCE = new TamayaConfigurator(); - - private ConfigurationContext configurationContext; - private Set<String> formats = new HashSet<>(); - private Set<String> suffixes = new HashSet<>(); - private Map<String,DSLPropertySourceProvider> dslResolvers = new HashMap<>(); - - - private TamayaConfigurator(){ - configure(null); - } - - /** - * Get the singleton instance. - * @return the instance, never null. - */ - public static TamayaConfigurator getInstance(){ - return INSTANCE; - } - - /** - * Configures the Tamaya runtime using the metamodel configuration found at the default - * location. - * @see MetaConfiguration - */ - public void configure(){ - configure(null); - } - - /** - * Configures the Tamaya runtime using the given resource location expression and (optionally) - * formats to be used for evaluating the metamodel configuration. - * @param resourceExpression resource expression for resolving the location of the - * meta configuration. - * @param formats the format names to be used, optional, but not null. - * @see MetaConfiguration - */ - public void configure(String resourceExpression, String... formats){ - loadDSLSourceResolvers(); - Configuration metaConfig = MetaConfiguration.getConfiguration(resourceExpression, formats); - Configuration profilesConfig = metaConfig.with( - ConfigurationFunctions.section("TAMAYA.PROFILES.", true)); - Configuration metaProfile = profilesConfig.with( - ConfigurationFunctions.section("<COMMON>.", true)); - System.out.println(metaProfile.getProperties().keySet()); - String[] values = metaProfile.getOrDefault("formats","yaml, properties, xml-properties").split(","); - for(String fmt:values){ - fmt = fmt.trim(); - if(fmt.isEmpty()){ - continue; - } - this.formats.add(fmt); - } - values = metaProfile.getOrDefault("suffixes", "yml, yaml, properties, xml").split(","); - for(String sfx:values){ - sfx = sfx.trim(); - if(sfx.isEmpty()){ - continue; - } - this.suffixes.add(sfx); - } - ConfigurationContextBuilder builder = ConfigurationProvider.getConfigurationContextBuilder(); - Map<String, PropertySource> loadedPropertySources = loadDefaultPropertySources(); - int defaultOrdinal = loadSources(builder, "<COMMON>", metaProfile, loadedPropertySources, 0) + 20; - // Load current profiles - for(String profile:ProfileManager.getInstance().getActiveProfiles()){ - metaProfile = profilesConfig.with( - ConfigurationFunctions.section(profile, true)); - defaultOrdinal = loadSources(builder, profile, metaProfile, loadedPropertySources, defaultOrdinal) + 20; - } - // formats: yaml, properties, xml-properties - // - SUFFIX: yaml, yml, properties, xml - // - sources: - // - "named:env-properties" # provider name, or class name - // - "named:main-args" - // - "named:sys-properties" - // - "resource:classpath:META-INF/config/**/*.SUFFIX" - - } - - /** - * Loads all default registered property sources and providers. - * @return the default property sources available on the system. - */ - private Map<String, PropertySource> loadDefaultPropertySources() { - Map<String, PropertySource> loadedPropertySources = new HashMap<>(); - for(PropertySource ps: ServiceContextManager.getServiceContext().getServices(PropertySource.class)){ - loadedPropertySources.put(ps.getName(), ps); - } - for(PropertySourceProvider prov: ServiceContextManager.getServiceContext().getServices(PropertySourceProvider.class)){ - for(PropertySource ps: prov.getPropertySources()){ - loadedPropertySources.put(ps.getName(), ps); - } - } - return loadedPropertySources; - } - - private int loadSources(ConfigurationContextBuilder builder, String profileId, Configuration metaProfile, Map<String, - PropertySource> defaultPropertySources, int nextOrdinal) { - String[] values; - List<PropertySource> propertySourcesLoaded = new ArrayList<>(); - values = metaProfile.getOrDefault("sources","<default>").split(","); - if(values.length==1 && "<default>".equals(values[0])){ - // load default property sources and providers from config as default. - // additional providers may be added depending on the active profile... - LOGGER.info("Using default configuration setup for "+profileId); - nextOrdinal = addAndGetNextOrdinal(builder, defaultPropertySources.values(), - propertySourcesLoaded, nextOrdinal); - }else { - LOGGER.info("Loading DSL based "+profileId+" configuration context..."); - int count = 0; - for (String source : values) { - source = source.trim(); - if (source.isEmpty()) { - continue; - } - String sourceKey = getSourceKey(source); - LOGGER.info("Loading "+profileId+" configuration source: " + source); - // evaluate DSLSourceResolver and resolve PropertySources, register thm into context - // apply newMaxOrdinal... - DSLPropertySourceProvider resolver = dslResolvers.get(sourceKey); - if(resolver==null){ - LOGGER.warning("DSL error: unresolvable source expression: "+ source); - continue; - } - List<PropertySource> sources = resolver.resolve(source.substring(sourceKey.length()), - defaultPropertySources); - nextOrdinal = addAndGetNextOrdinal(builder, sources, propertySourcesLoaded, nextOrdinal); - } - LOGGER.info("Loaded "+count+" DSL based "+profileId+" configuration contexts."); - } - return nextOrdinal; - } - - private int addAndGetNextOrdinal(ConfigurationContextBuilder builder, Collection<PropertySource> sourcesToAdd, - List<PropertySource> allPropertySources, int nextOrdinal) { - allPropertySources.addAll(wrapOrdinals(nextOrdinal, sourcesToAdd)); - nextOrdinal = Math.max(calculateHighestOrdinal(allPropertySources)+1, nextOrdinal+1); - builder.addPropertySources(allPropertySources); - return nextOrdinal; - } - - private List<WrappedPropertySource> wrapOrdinals(int nextOrdinal, Collection<PropertySource> propertySources) { - List<WrappedPropertySource> result = new ArrayList<>(); - for(PropertySource ps: propertySources){ - result.add(WrappedPropertySource.of(ps)); - } - Collections.sort(result, ORDINAL_COMPARATOR); - for(WrappedPropertySource ps: result){ - ps.setOrdinal(nextOrdinal++); - } - Collections.sort(result, ORDINAL_COMPARATOR); - return result; - } - - private int calculateHighestOrdinal(Collection<PropertySource> sources) { - int maxOrdinal = 0; - for (PropertySource ps : sources) { - if (ps.getOrdinal() > maxOrdinal) { - maxOrdinal = ps.getOrdinal(); - } - } - return maxOrdinal; - } - - private String getSourceKey(String source) { - int index = source.indexOf(':'); - if(index>0){ - return source.substring(0,index); - } - return source; - } - - private void loadDSLSourceResolvers() { - // Load the ConfigurationDSLSourceResolvers on the system - for(DSLPropertySourceProvider res: - ServiceContextManager.getServiceContext().getServices( - DSLPropertySourceProvider.class)){ - this.dslResolvers.put(res.getKey(), res); - } - } - -} +///* +// * 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.metamodel.dsl; +// +//import org.apache.tamaya.Configuration; +//import org.apache.tamaya.ConfigurationProvider; +//import org.apache.tamaya.functions.ConfigurationFunctions; +//import org.apache.tamaya.spi.*; +//import org.apache.tamaya.metamodel.spi.DSLPropertySourceProvider; +// +//import java.util.ArrayList; +//import java.util.Collection; +//import java.util.Collections; +//import java.util.Comparator; +//import java.util.HashMap; +//import java.util.HashSet; +//import java.util.List; +//import java.util.Map; +//import java.util.Set; +//import java.util.logging.Logger; +// +///** +// * Configuration class setting up the Tamaya runtime model. +// */ +//public final class TamayaConfigurator { +// +// private static final Logger LOGGER = Logger.getLogger(MetaConfiguration.class.getName()); +// private static final Comparator<WrappedPropertySource> ORDINAL_COMPARATOR = +// new Comparator<WrappedPropertySource>(){ +// @Override +// public int compare(WrappedPropertySource o1, WrappedPropertySource o2) { +// return o1.getOrdinal() - o2.getOrdinal(); +// } +// }; +// +// private static final TamayaConfigurator INSTANCE = new TamayaConfigurator(); +// +// private ConfigurationContext configurationContext; +// private Set<String> formats = new HashSet<>(); +// private Set<String> suffixes = new HashSet<>(); +// private Map<String,DSLPropertySourceProvider> dslResolvers = new HashMap<>(); +// +// +// private TamayaConfigurator(){ +// configure(null); +// } +// +// /** +// * Get the singleton instance. +// * @return the instance, never null. +// */ +// public static TamayaConfigurator getInstance(){ +// return INSTANCE; +// } +// +// /** +// * Configures the Tamaya runtime using the metamodel configuration found at the default +// * location. +// * @see MetaConfiguration +// */ +// public void configure(){ +// configure(null); +// } +// +// /** +// * Configures the Tamaya runtime using the given resource location expression and (optionally) +// * formats to be used for evaluating the metamodel configuration. +// * @param resourceExpression resource expression for resolving the location of the +// * meta configuration. +// * @param formats the format names to be used, optional, but not null. +// * @see MetaConfiguration +// */ +// public void configure(String resourceExpression, String... formats){ +// loadDSLSourceResolvers(); +// Configuration metaConfig = MetaConfiguration.getConfiguration(resourceExpression, formats); +// Configuration profilesConfig = metaConfig.with( +// ConfigurationFunctions.section("TAMAYA.PROFILES.", true)); +// Configuration metaProfile = profilesConfig.with( +// ConfigurationFunctions.section("<COMMON>.", true)); +// System.out.println(metaProfile.getProperties().keySet()); +// String[] values = metaProfile.getOrDefault("formats","yaml, properties, xml-properties").split(","); +// for(String fmt:values){ +// fmt = fmt.trim(); +// if(fmt.isEmpty()){ +// continue; +// } +// this.formats.add(fmt); +// } +// values = metaProfile.getOrDefault("suffixes", "yml, yaml, properties, xml").split(","); +// for(String sfx:values){ +// sfx = sfx.trim(); +// if(sfx.isEmpty()){ +// continue; +// } +// this.suffixes.add(sfx); +// } +// ConfigurationContextBuilder builder = ConfigurationProvider.getConfigurationContextBuilder(); +// Map<String, PropertySource> loadedPropertySources = loadDefaultPropertySources(); +// int defaultOrdinal = loadSources(builder, "<COMMON>", metaProfile, loadedPropertySources, 0) + 20; +// // Load current profiles +// for(String profile:ProfileManager.getInstance().getActiveProfiles()){ +// metaProfile = profilesConfig.with( +// ConfigurationFunctions.section(profile, true)); +// defaultOrdinal = loadSources(builder, profile, metaProfile, loadedPropertySources, defaultOrdinal) + 20; +// } +// // formats: yaml, properties, xml-properties +// // - SUFFIX: yaml, yml, properties, xml +// // - sources: +// // - "named:env-properties" # provider name, or class name +// // - "named:main-args" +// // - "named:sys-properties" +// // - "resource:classpath:META-INF/config/**/*.SUFFIX" +// +// } +// +// /** +// * Loads all default registered property sources and providers. +// * @return the default property sources available on the system. +// */ +// private Map<String, PropertySource> loadDefaultPropertySources() { +// Map<String, PropertySource> loadedPropertySources = new HashMap<>(); +// for(PropertySource ps: ServiceContextManager.getServiceContext().getServices(PropertySource.class)){ +// loadedPropertySources.put(ps.getName(), ps); +// } +// for(PropertySourceProvider prov: ServiceContextManager.getServiceContext().getServices(PropertySourceProvider.class)){ +// for(PropertySource ps: prov.getPropertySources()){ +// loadedPropertySources.put(ps.getName(), ps); +// } +// } +// return loadedPropertySources; +// } +// +// private int loadSources(ConfigurationContextBuilder builder, String profileId, Configuration metaProfile, Map<String, +// PropertySource> defaultPropertySources, int nextOrdinal) { +// String[] values; +// List<PropertySource> propertySourcesLoaded = new ArrayList<>(); +// values = metaProfile.getOrDefault("sources","<default>").split(","); +// if(values.length==1 && "<default>".equals(values[0])){ +// // load default property sources and providers from config as default. +// // additional providers may be added depending on the active profile... +// LOGGER.info("Using default configuration setup for "+profileId); +// nextOrdinal = addAndGetNextOrdinal(builder, defaultPropertySources.values(), +// propertySourcesLoaded, nextOrdinal); +// }else { +// LOGGER.info("Loading DSL based "+profileId+" configuration context..."); +// int count = 0; +// for (String source : values) { +// source = source.trim(); +// if (source.isEmpty()) { +// continue; +// } +// String sourceKey = getSourceKey(source); +// LOGGER.info("Loading "+profileId+" configuration source: " + source); +// // evaluate DSLSourceResolver and resolve PropertySources, register thm into context +// // apply newMaxOrdinal... +// DSLPropertySourceProvider resolver = dslResolvers.get(sourceKey); +// if(resolver==null){ +// LOGGER.warning("DSL error: unresolvable source expression: "+ source); +// continue; +// } +// List<PropertySource> sources = resolver.resolve(source.substring(sourceKey.length()), +// defaultPropertySources); +// nextOrdinal = addAndGetNextOrdinal(builder, sources, propertySourcesLoaded, nextOrdinal); +// } +// LOGGER.info("Loaded "+count+" DSL based "+profileId+" configuration contexts."); +// } +// return nextOrdinal; +// } +// +// private int addAndGetNextOrdinal(ConfigurationContextBuilder builder, Collection<PropertySource> sourcesToAdd, +// List<PropertySource> allPropertySources, int nextOrdinal) { +// allPropertySources.addAll(wrapOrdinals(nextOrdinal, sourcesToAdd)); +// nextOrdinal = Math.max(calculateHighestOrdinal(allPropertySources)+1, nextOrdinal+1); +// builder.addPropertySources(allPropertySources); +// return nextOrdinal; +// } +// +// private List<WrappedPropertySource> wrapOrdinals(int nextOrdinal, Collection<PropertySource> propertySources) { +// List<WrappedPropertySource> result = new ArrayList<>(); +// for(PropertySource ps: propertySources){ +// result.add(WrappedPropertySource.of(ps)); +// } +// Collections.sort(result, ORDINAL_COMPARATOR); +// for(WrappedPropertySource ps: result){ +// ps.setOrdinal(nextOrdinal++); +// } +// Collections.sort(result, ORDINAL_COMPARATOR); +// return result; +// } +// +// private int calculateHighestOrdinal(Collection<PropertySource> sources) { +// int maxOrdinal = 0; +// for (PropertySource ps : sources) { +// if (ps.getOrdinal() > maxOrdinal) { +// maxOrdinal = ps.getOrdinal(); +// } +// } +// return maxOrdinal; +// } +// +// private String getSourceKey(String source) { +// int index = source.indexOf(':'); +// if(index>0){ +// return source.substring(0,index); +// } +// return source; +// } +// +// private void loadDSLSourceResolvers() { +// // Load the ConfigurationDSLSourceResolvers on the system +// for(DSLPropertySourceProvider res: +// ServiceContextManager.getServiceContext().getServices( +// DSLPropertySourceProvider.class)){ +// this.dslResolvers.put(res.getKey(), res); +// } +// } +// +//}
