http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/base/src/main/java/org/apache/tamaya/spi/StandaloneConfigContext.java ---------------------------------------------------------------------- diff --git a/code/base/src/main/java/org/apache/tamaya/spi/StandaloneConfigContext.java b/code/base/src/main/java/org/apache/tamaya/spi/StandaloneConfigContext.java new file mode 100644 index 0000000..43eba5c --- /dev/null +++ b/code/base/src/main/java/org/apache/tamaya/spi/StandaloneConfigContext.java @@ -0,0 +1,292 @@ +///* +// * 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.base.configsource.ConfigSourceComparator; +//import org.apache.tamaya.base.convert.ConverterManager; +// +//import javax.config.spi.ConfigSource; +//import javax.config.spi.Converter; +//import java.lang.reflect.ParameterizedType; +//import java.lang.reflect.Type; +//import java.util.*; +//import java.util.concurrent.locks.ReentrantReadWriteLock; +//import java.util.logging.Logger; +// +///** +// * Central SPI for programmatically dealing with the setup of the configuration system. +// * This includes adding and enlisting {@link ConfigSource}s, +// * managing {@link Converter}s, ConfigFilters, etc. +// */ +//public final class StandaloneConfigContext implements ConfigContext{ +// +// private static final Logger LOG = Logger.getLogger(StandaloneConfigContext.class.getName()); +// +// /** +// * Subcomponent handling {@link Converter} instances. +// */ +// private final ConverterManager converterManager = new ConverterManager(); +// +// +// +// /** +// * The current unmodifiable list of loaded {@link Filter} instances. +// */ +// private final List<Filter> immutableFilters; +// +// /** +// * The current unmodifiable list of loaded {@link ConfigSource} instances. +// */ +// @Override +// public List<ConfigSource> getSources(){ +// return immutableConfigSources; +// } +// +// /** +// * The current unmodifiable list of loaded {@link Filter} instances. +// */ +// @Override +// public List<Filter> getFilters(){ +// return immutableFilters; +// } +// +// +// /** +// * Lock for internal synchronization. +// */ +// final ReentrantReadWriteLock propertySourceLock = new ReentrantReadWriteLock(); +// +// @SuppressWarnings("unchecked") +// StandaloneConfigContext(StandaloneConfigContextBuilder builder) { +// List<ConfigSource> propertySources = new ArrayList<>(); +// // first we load all PropertySources which got registered via java.util.ServiceLoader +// propertySources.addAll(builder.propertySources); +// // now sort them according to their ordinal values +// immutableConfigSources = Collections.unmodifiableList(propertySources); +// +// // as next step we pick up the PropertyFilters pretty much the same way +// List<Filter> filters = new ArrayList<>(builder.getFilters()); +// immutableFilters = Collections.unmodifiableList(filters); +// +// // Finally add the converters +// for(Map.Entry<Type, Collection<Converter>> en:builder.getConverter().entrySet()) { +// for (@SuppressWarnings("rawtypes") Converter converter : en.getValue()) { +// this.converterManager.addSources(en.getKey(), converter); +// } +// } +// LOG.info("Registered " + converterManager.getConverters().size() + " property converters: " + +// converterManager.getConverters()); +// +// configValueCombinationPolicy = builder.combinationPolicy; +// +// } +// +// +// @Override +// public boolean equals(Object o) { +// if (this == o) { +// return true; +// } +// if (!(o instanceof StandaloneConfigContext)){ +// return false; +// } +// +// StandaloneConfigContext that = (StandaloneConfigContext) o; +// +// if (!converterManager.equals(that.converterManager)) { +// return false; +// } +// if (!immutableConfigSources.equals(that.immutableConfigSources)) { +// return false; +// } +// if (!immutableFilters.equals(that.immutableFilters)) { +// return false; +// } +// return getConfigValueCombinationPolicy().equals(that.getConfigValueCombinationPolicy()); +// +// } +// +// @Override +// public int hashCode() { +// int result = converterManager.hashCode(); +// result = 31 * result + immutableConfigSources.hashCode(); +// result = 31 * result + immutableFilters.hashCode(); +// result = 31 * result + getConfigValueCombinationPolicy().hashCode(); +// return result; +// } +// +// @Override +// public String toString() { +// StringBuilder b = new StringBuilder("ConfigurationContext{\n"); +// b.append(" Property Sources\n"); +// b.append(" ----------------\n"); +// if(immutableConfigSources.isEmpty()){ +// b.append(" No property sources loaded.\n\n"); +// }else { +// b.append(" CLASS NAME ORDINAL SCANNABLE SIZE STATE ERROR\n\n"); +// for (ConfigSource ps : immutableConfigSources) { +// b.append(" "); +// appendFormatted(b, ps.getClass().getSimpleName(), 30); +// appendFormatted(b, ps.getName(), 70); +// appendFormatted(b, String.valueOf(ConfigSourceComparator.getOrdinal(ps)), 8); +// String state = ps.getValue("_state"); +// if(state==null){ +// appendFormatted(b, "OK", 10); +// }else { +// appendFormatted(b, state, 10); +// if("ERROR".equals(state)){ +// String val = ps.getValue("_exception"); +// if(val!=null) { +// appendFormatted(b, val, 30); +// } +// } +// } +// b.append('\n'); +// } +// b.append("\n"); +// } +// b.append(" Property Filters\n"); +// b.append(" ----------------\n"); +// if(immutableFilters.isEmpty()){ +// b.append(" No property filters loaded.\n\n"); +// }else { +// b.append(" CLASS INFO\n\n"); +// for (Filter filter : getPropertyFilters()) { +// b.append(" "); +// appendFormatted(b, filter.getClass().getSimpleName(), 30); +// b.append(removeNewLines(filter.toString())); +// b.append('\n'); +// } +// b.append("\n\n"); +// } +// b.append(" Property Converters\n"); +// b.append(" -------------------\n"); +// b.append(" CLASS TYPE INFO\n\n"); +// for(Map.Entry<Type, List<Converter>> converterEntry: getConverters().entrySet()){ +// for(Converter converter: converterEntry.getValue()){ +// b.append(" "); +// appendFormatted(b, converter.getClass().getSimpleName(), 30); +// if(converterEntry.getKey() instanceof ParameterizedType){ +// ParameterizedType pt = (ParameterizedType)converterEntry.getKey(); +// appendFormatted(b, pt.getRawType().getTypeName(), 30); +// }else{ +// appendFormatted(b, converterEntry.getKey().getTypeName(), 30); +// } +// b.append(removeNewLines(converter.toString())); +// b.append('\n'); +// } +// } +// b.append("\n\n"); +// b.append(" PropertyValueCombinationPolicy: " + getConfigValueCombinationPolicy().getClass().getName()).append('\n'); +// b.append('}'); +// return b.toString(); +// } +// +// +// +// +// +// /** +// * <p> +// * This method returns the Map of registered PropertyConverters +// * per type. +// * The List for each type is ordered via their {@link javax.annotation.Priority} and +// * cladd name. +// * </p> +// * +// * <p>A simplified scenario could be like:</p> +// * <pre> +// * { +// * Date.class -> {StandardDateConverter, TimezoneDateConverter, MyCustomDateConverter } +// * Boolean.class -> {StandardBooleanConverter, FrenchBooleanConverter} +// * Integer.class -> {DynamicDefaultConverter} +// * } +// * </pre> +// * +// * @return map with sorted list of registered PropertySources per type. +// */ +// public Map<Type, List<Converter>> getConverters() { +// return converterManager.getConverters(); +// } +// +// /** +// * <p> +// * This method returns the registered PropertyConverters for a given type. +// * The List for each type is ordered via their {@link javax.annotation.Priority}. +// * </p> +// * +// * <p> +// * PropertyConverters with a higher Priority come first. The PropertyConverter with the +// * lowest Priority comes last. +// * If two PropertyConverter have the same ordinal number they will get sorted +// * using their class name just to ensure the user at least gets the same ordering +// * after a JVM restart. +// * </p> +// * +// * <p> +// * Additionally if a PropertyProvider is accessed, which is not registered the implementation +// * should try to figure out, if there could be a default implementation as follows:</p> +// * <ol> +// * <li>Look for static factory methods: {@code of(String), valueOf(String), getInstance(String), +// * instanceOf(String), fomr(String)}</li> +// * <li>Look for a matching constructor: {@code T(String)}.</li> +// * </ol> +// * +// * <p> +// * If a correspoding factory method or constructor could be found, a corresponding +// * PropertyConverter should be created and registered automatically for the given +// * type. +// * </p> +// * +// * <p> The scenario could be like:</p> +// * +// * <pre> +// * { +// * Date.class -> {MyCustomDateConverter,StandardDateConverter, TimezoneDateConverter} +// * Boolean.class -> {StandardBooleanConverter, FrenchBooleanConverter} +// * Integer.class -> {DynamicDefaultConverter} +// * } +// * </pre> +// * +// * <p> +// * The converters returned for a type should be used as a chain, whereas the result of the +// * first converters that is able to convert the configured value, is taken as the chain's result. +// * No more converters are called after a converters has successfully converted the input into +// * the required target type. +// * </p> +// * +// * @param type type of the desired converters +// * @return a sorted list of registered PropertySources per type. +// */ +// public List<Converter> getConverters(Type type) { +// return converterManager.getConverters(type); +// } +// +// /** +// * Access the current PropertyFilter instances. +// * @return the list of registered PropertyFilters, never null. +// */ +// public List<Filter> getPropertyFilters() { +// return immutableFilters; +// } +// +// +// +//} +//
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/core/bnd.bnd ---------------------------------------------------------------------- diff --git a/code/core/bnd.bnd b/code/core/bnd.bnd index b611eb1..7c85414 100644 --- a/code/core/bnd.bnd +++ b/code/core/bnd.bnd @@ -12,7 +12,7 @@ javac.target: 1.8 Bundle-Version: ${version}.${tstamp} Bundle-Name: Apache Tamaya - Core Bundle-SymbolicName: org.apache.tamaya.core -Bundle-Description: Apacha Tamaya Configuration Java Core Implementation +Bundle-Description: Apacha Tamaya Configuration Core Implementation Bundle-Category: Implementation Bundle-Copyright: (C) Apache Foundation Bundle-License: Apache Licence version 2 @@ -23,21 +23,23 @@ Bundle-Activator: org.apache.tamaya.core.OSGIActivator Export-Package: \ org.apache.tamaya.core Import-Package: \ - org.apache.tamaya,\ - org.apache.tamaya.spi,\ - org.apache.tamaya.spisupport,\ - org.apache.tamaya.spisupport.propertysource,\ + javax.config,\ + javax.config.spi,\ + org.apache.tamaya.base,\ + org.apache.tamaya.base.configsource,\ + org.apache.tamaya.base.convert,\ + org.apache.tamaya.base.filter,\ + org.apache.tamaya.spi,\ org.osgi.framework,\ javax.annotation Private-Package: \ - org.apache.tamaya.core.internal,\ - org.apache.tamaya.core.internal.converters + org.apache.tamaya.core,\ + org.apache.tamaya.core.converters Export-Service: \ - org.apache.tamaya.Configuration,\ - org.apache.tamaya.core.internal.ConfigValueEvaluator,\ - org.apache.tamaya.spi.ConfigurationContextBuilder,\ - org.apache.tamaya.spi.ConfigurationProviderSpi,\ - org.apache.tamaya.spi.PropertyConverter,\ - org.apache.tamaya.spi.PropertySource,\ + javax.config.Config,\ + javax.config.spi.ConfigBuilder,\ + javax.config.spi.ConfigProviderResolver,\ + javax.config.spi.Converter,\ + javax.config.spi.ConfigSource,\ org.apache.tamaya.spi.ServiceContext \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/core/pom.xml ---------------------------------------------------------------------- diff --git a/code/core/pom.xml b/code/core/pom.xml index 2d98631..6250ea7 100644 --- a/code/core/pom.xml +++ b/code/core/pom.xml @@ -31,18 +31,13 @@ under the License. <dependencies> <dependency> - <groupId>org.assertj</groupId> - <artifactId>assertj-core</artifactId> - </dependency> - <dependency> <groupId>org.apache.tamaya</groupId> - <artifactId>tamaya-api</artifactId> + <artifactId>tamaya-base</artifactId> <version>${project.version}</version> </dependency> <dependency> - <groupId>org.apache.tamaya</groupId> - <artifactId>tamaya-spisupport</artifactId> - <version>${project.version}</version> + <groupId>org.assertj</groupId> + <artifactId>assertj-core</artifactId> </dependency> <dependency> <groupId>junit</groupId> http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/core/src/main/java/org/apache/tamaya/core/OSGIActivator.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/OSGIActivator.java b/code/core/src/main/java/org/apache/tamaya/core/OSGIActivator.java index 2ca51db..3e0fdba 100644 --- a/code/core/src/main/java/org/apache/tamaya/core/OSGIActivator.java +++ b/code/core/src/main/java/org/apache/tamaya/core/OSGIActivator.java @@ -18,17 +18,15 @@ */ package org.apache.tamaya.core; - - -import org.apache.tamaya.ConfigurationProvider; -import org.apache.tamaya.core.internal.*; +import org.apache.tamaya.base.DefaultConfigBuilder; +import org.apache.tamaya.base.configsource.ConfigSourceComparator; +import org.apache.tamaya.base.filter.FilterComparator; +import org.apache.tamaya.spi.ServiceContext; import org.apache.tamaya.spi.ServiceContextManager; -import org.apache.tamaya.spisupport.DefaultConfiguration; -import org.apache.tamaya.spisupport.PropertyFilterComparator; -import org.apache.tamaya.spisupport.PropertySourceComparator; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; +import javax.config.spi.ConfigProviderResolver; import java.util.logging.Logger; /** @@ -47,14 +45,15 @@ public class OSGIActivator implements BundleActivator { context.addBundleListener(serviceLoader); ServiceContextManager.set(new OSGIServiceContext(serviceLoader)); LOG.info("Registered Tamaya OSGI ServiceContext..."); - ConfigurationProvider.setConfiguration( - new CoreConfigurationBuilder() - .addDefaultPropertyConverters() - .addDefaultPropertyFilters() - .addDefaultPropertySources() - .sortPropertyFilter(PropertyFilterComparator.getInstance()) - .sortPropertySources(PropertySourceComparator.getInstance()) - .build() + ConfigProviderResolver.instance().registerConfig( + new DefaultConfigBuilder() + .addDiscoveredConverters() + .addDiscoveredFilters() + .addDiscoveredSources() + .sortFilter(FilterComparator.getInstance()) + .sortSources(ConfigSourceComparator.getInstance()) + .build(), + ServiceContext.defaultClassLoader() ); LOG.info("Loaded default configuration from OSGI."); } http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/core/src/main/java/org/apache/tamaya/core/internal/BannerManager.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/BannerManager.java b/code/core/src/main/java/org/apache/tamaya/core/internal/BannerManager.java deleted file mode 100644 index 52247c9..0000000 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/BannerManager.java +++ /dev/null @@ -1,165 +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.core.internal; - -import org.apache.tamaya.ConfigurationProvider; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Locale; -import java.util.Objects; -import java.util.logging.Level; -import java.util.logging.Logger; - -import static org.apache.tamaya.core.internal.BannerManager.BANNER_RESOURCE_PATH; - -/** - * Controls the output of the banner of Tamaya. - * - * <p>This class controls if and how the banner of Tamaya is presented the user. - * The banner is provided by the Tamaya Core under the resource path - * {@value BANNER_RESOURCE_PATH}.</p> - * - * <p>The behavior of the banner manager can be controlled by - * specifying the configuration key {@code tamaya.banner} with one of - * the three folowing values: - * - * <dl> - * <dt>OFF</dt> - * <dd>Banner will not be shown</dd> - * <dt>CONSOLE</dt> - * <dd>The banner will be printed on STDOUT</dd> - * <dt>LOGGER</dt> - * <dd>The banner will be logged</dd> - * </dl> - * - * In case of any other value the banner will not be shown. - * </p> - * - * - * - * @see BannerTarget - */ -class BannerManager { - /** - * The resouce path to the file containing the banner of Tamaya. - */ - protected final static String BANNER_RESOURCE_PATH = "/tamaya-banner.txt"; - - enum BannerTarget { - OFF, CONSOLE, LOGGER - } - - private BannerTarget bannerTarget; - - public BannerManager(String value) { - value = Objects.requireNonNull(value).toUpperCase(Locale.getDefault()); - - try { - bannerTarget = BannerTarget.valueOf(value); - } catch (NullPointerException | IllegalArgumentException e) { - bannerTarget = BannerTarget.OFF; - } - } - - public void outputBanner() { - BannerPrinter bp = new SilentBannerPrinter(); - - switch (bannerTarget) { - case CONSOLE: - bp = new ConsoleBannerPrinter(); - break; - case LOGGER: - bp = new LoggingBannerPrinter(); - break; - case OFF: - default: - break; - } - - bp.outputBanner(); - } -} - -abstract class AbstractBannerPrinter implements BannerPrinter { - private static final Logger log = Logger.getLogger(AbstractBannerPrinter.class.getName()); - - @Override - public void outputBanner() { - try (InputStream in = ConfigurationProvider.class.getResourceAsStream(BANNER_RESOURCE_PATH)) { - BufferedReader reader = new BufferedReader(new InputStreamReader(in)); - String line; - - while ((line = reader.readLine()) != null) { - outputSingleLine(line); - } - } catch (Exception e) { - log.log(Level.WARNING, "Failed to output the banner of tamaya.", e); - } - } - - abstract void outputSingleLine(String line); -} - - -/** - * Outputs the Tamaya banner to an implementation specific output channel - * as STDOUT or the logging system. - */ -interface BannerPrinter { - /** - * Outputs the banner to the output channel - * used by the implementation. - */ - void outputBanner(); -} - -/** - * Silent implementation of a {@link BannerPrinter}. - */ -class SilentBannerPrinter implements BannerPrinter { - @Override - public void outputBanner() { - } -} - -/** - * Logs the banner via JUL at level {@link java.util.logging.Level#INFO}. - */ -class LoggingBannerPrinter extends AbstractBannerPrinter { - private static final Logger log = Logger.getLogger(LoggingBannerPrinter.class.getName()); - - @Override - void outputSingleLine(String line) { - log.log(Level.INFO, line); - } -} - -/** - * Prints the banner to the console. - */ -class ConsoleBannerPrinter extends AbstractBannerPrinter { - @Override - void outputSingleLine(String line) { - System.out.println(line); - } -} - - http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/core/src/main/java/org/apache/tamaya/core/internal/CoreConfiguration.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/CoreConfiguration.java b/code/core/src/main/java/org/apache/tamaya/core/internal/CoreConfiguration.java deleted file mode 100644 index 5363b76..0000000 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/CoreConfiguration.java +++ /dev/null @@ -1,43 +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.core.internal; - -import org.apache.tamaya.spi.ConfigurationBuilder; -import org.apache.tamaya.spi.ConfigurationContext; -import org.apache.tamaya.spisupport.DefaultConfiguration; -import org.apache.tamaya.spisupport.DefaultConfigurationContext; -import org.apache.tamaya.spisupport.DefaultConfigurationContextBuilder; - -/** - * Default implementation of {@link ConfigurationBuilder}. - */ -public final class CoreConfiguration extends DefaultConfiguration { - - /** - * Creates a new builder instance. - */ - public CoreConfiguration(ConfigurationContext context) { - super(context); - } - - @Override - public ConfigurationBuilder toBuilder() { - return new CoreConfigurationBuilder(this); - } -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/core/src/main/java/org/apache/tamaya/core/internal/CoreConfigurationBuilder.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/CoreConfigurationBuilder.java b/code/core/src/main/java/org/apache/tamaya/core/internal/CoreConfigurationBuilder.java deleted file mode 100644 index 4daacdf..0000000 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/CoreConfigurationBuilder.java +++ /dev/null @@ -1,91 +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.core.internal; - -import org.apache.tamaya.Configuration; -import org.apache.tamaya.TypeLiteral; -import org.apache.tamaya.spi.ConfigurationContext; -import org.apache.tamaya.spi.ConfigurationBuilder; -import org.apache.tamaya.core.internal.converters.*; -import org.apache.tamaya.spisupport.DefaultConfigurationBuilder; -import org.apache.tamaya.spisupport.DefaultConfigurationContext; -import org.apache.tamaya.spisupport.DefaultConfigurationContextBuilder; - -import java.io.File; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.net.URI; -import java.net.URL; -import java.nio.file.Path; -import java.util.*; - -/** - * Default implementation of {@link ConfigurationBuilder}. - */ -public final class CoreConfigurationBuilder extends DefaultConfigurationBuilder { - - /** - * Creates a new builder instance. - */ - public CoreConfigurationBuilder() { - super(); - } - - /** - * Creates a new builder instance. - */ - public CoreConfigurationBuilder(Configuration config) { - super(config); - } - - /** - * Creates a new builder instance initializing it with the given context. - * @param context the context to be used, not null. - */ - public CoreConfigurationBuilder(ConfigurationContext context) { - super(context); - } - - @SuppressWarnings("unchecked") - protected void addCorePropertyConverters() { - addPropertyConverters(TypeLiteral.<BigDecimal>of(BigDecimal.class), new BigDecimalConverter()); - addPropertyConverters(TypeLiteral.<BigInteger>of(BigInteger.class), new BigIntegerConverter()); - addPropertyConverters(TypeLiteral.<Boolean>of(Boolean.class), new BooleanConverter()); - addPropertyConverters(TypeLiteral.<Byte>of(Byte.class), new ByteConverter()); - addPropertyConverters(TypeLiteral.<Character>of(Character.class), new CharConverter()); - addPropertyConverters(TypeLiteral.<Class<?>>of(Class.class), new ClassConverter()); - addPropertyConverters(TypeLiteral.<Currency>of(Currency.class), new CurrencyConverter()); - addPropertyConverters(TypeLiteral.<Double>of(Double.class), new DoubleConverter()); - addPropertyConverters(TypeLiteral.<File>of(File.class), new FileConverter()); - addPropertyConverters(TypeLiteral.<Float>of(Float.class), new FloatConverter()); - addPropertyConverters(TypeLiteral.<Integer>of(Integer.class), new IntegerConverter()); - addPropertyConverters(TypeLiteral.<Long>of(Long.class), new LongConverter()); - addPropertyConverters(TypeLiteral.<Number>of(Number.class), new NumberConverter()); - addPropertyConverters(TypeLiteral.<Path>of(Path.class), new PathConverter()); - addPropertyConverters(TypeLiteral.<Short>of(Short.class), new ShortConverter()); - addPropertyConverters(TypeLiteral.<URI>of(URI.class), new URIConverter()); - addPropertyConverters(TypeLiteral.<URL>of(URL.class), new URLConverter()); - } - - @Override - public Configuration build() { - return new CoreConfiguration(contextBuilder.build()); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/core/src/main/java/org/apache/tamaya/core/internal/CoreConfigurationProvider.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/CoreConfigurationProvider.java b/code/core/src/main/java/org/apache/tamaya/core/internal/CoreConfigurationProvider.java deleted file mode 100644 index caf7fbb..0000000 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/CoreConfigurationProvider.java +++ /dev/null @@ -1,101 +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.core.internal; - -import org.apache.tamaya.Configuration; -import org.apache.tamaya.spi.ConfigurationContext; -import org.apache.tamaya.spi.ConfigurationBuilder; -import org.apache.tamaya.spi.ConfigurationContextBuilder; -import org.apache.tamaya.spi.ConfigurationProviderSpi; -import org.apache.tamaya.spisupport.DefaultConfiguration; -import org.apache.tamaya.spisupport.DefaultConfigurationContextBuilder; -import org.osgi.service.component.annotations.Component; - -import java.util.Objects; - -/** - * Implementation of the Configuration API. This class uses the current {@link org.apache.tamaya.spi.ConfigurationContext} to evaluate the - * chain of {@link org.apache.tamaya.spi.PropertySource} and {@link org.apache.tamaya.spi.PropertyFilter} - * instance to evaluate the current Configuration. - */ -@Component(service = ConfigurationProviderSpi.class) -public class CoreConfigurationProvider implements ConfigurationProviderSpi { - - private Configuration config = new CoreConfigurationBuilder() - .addDefaultPropertyConverters() - .addDefaultPropertyFilters() - .addDefaultPropertySources() - .build(); - { - String bannerConfig = config.getOrDefault("tamaya.banner", "OFF"); - - BannerManager bm = new BannerManager(bannerConfig); - bm.outputBanner(); - } - - @Override - public Configuration getConfiguration() { - return config; - } - - @Override - public Configuration createConfiguration(ConfigurationContext context) { - return new CoreConfiguration(context); - } - - @Override - public ConfigurationBuilder getConfigurationBuilder() { - return new CoreConfigurationBuilder(); - } - - @Override - public ConfigurationContextBuilder getConfigurationContextBuilder() { - return new DefaultConfigurationContextBuilder(); - } - - @Override - public void setConfiguration(Configuration config) { - Objects.requireNonNull(config.getContext()); - this.config = Objects.requireNonNull(config); - } - - @Override - public boolean isConfigurationSettable() { - return true; - } - - /** - * @deprecated use {@link Configuration#getContext()} instead. - */ - @Deprecated - @Override - public ConfigurationContext getConfigurationContext() { - return this.config.getContext(); - } - - /** - * @deprecated the context should be given upon creation of the {@link Configuration} - */ - @Deprecated - @Override - public void setConfigurationContext(ConfigurationContext context){ - this.config = new CoreConfigurationBuilder(context).build(); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceComparator.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceComparator.java b/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceComparator.java deleted file mode 100644 index c9815cf..0000000 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceComparator.java +++ /dev/null @@ -1,70 +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.core.internal; - -import org.osgi.framework.ServiceReference; - -import javax.annotation.Priority; -import java.util.Comparator; - -/** - * Comparator implementation for ordering services loaded based on their increasing priority values. - */ -@SuppressWarnings("rawtypes") -class OSGIServiceComparator implements Comparator<ServiceReference> { - - @Override - public int compare(ServiceReference o1, ServiceReference o2) { - int prio = getPriority(o1) - getPriority(o2); - if (prio < 0) { - return 1; - } else if (prio > 0) { - return -1; - } else { - return 0; //o1.getClass().getSimpleName().compareTo(o2.getClass().getSimpleName()); - } - } - - /** - * Checks the given instance for a @Priority annotation. If present the annotation's value is evaluated. If no such - * annotation is present, a default priority {@code 1} is returned. - * - * @param o the instance, not {@code null}. - * @return a priority, by default 1. - */ - public static int getPriority(Object o) { - return getPriority(o.getClass()); - } - - /** - * Checks the given type optionally annotated with a @Priority. If present the annotation's value is evaluated. - * If no such annotation is present, a default priority {@code 1} is returned. - * - * @param type the type, not {@code null}. - * @return a priority, by default 1. - */ - public static int getPriority(Class<? extends Object> type) { - int prio = 1; - Priority priority = type.getAnnotation(Priority.class); - if (priority != null) { - prio = priority.value(); - } - return prio; - } -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceContext.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceContext.java b/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceContext.java deleted file mode 100644 index b7328d9..0000000 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceContext.java +++ /dev/null @@ -1,172 +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.core.internal; - -import org.apache.tamaya.spi.ConfigurationProviderSpi; -import org.apache.tamaya.spi.ServiceContext; -import org.osgi.framework.Bundle; -import org.osgi.framework.InvalidSyntaxException; -import org.osgi.framework.ServiceReference; - -import java.io.IOException; -import java.net.URL; -import java.util.*; -import java.util.logging.Logger; - -/** - * ServiceContext implementation based on OSGI Service mechanisms. - */ -public class OSGIServiceContext implements ServiceContext{ - - private static final Logger LOG = Logger.getLogger(OSGIServiceContext.class.getName()); - private static final OSGIServiceComparator REF_COMPARATOR = new OSGIServiceComparator(); - - private final OSGIServiceLoader osgiServiceLoader; - - public OSGIServiceContext(OSGIServiceLoader osgiServiceLoader){ - this.osgiServiceLoader = Objects.requireNonNull(osgiServiceLoader); - } - - public boolean isInitialized(){ - return osgiServiceLoader != null; - } - - - @Override - public int ordinal() { - return 10; - } - - @Override - public <T> T getService(Class<T> serviceType) { - LOG.finest("TAMAYA Loading service: " + serviceType.getName()); - ServiceReference<T> ref = this.osgiServiceLoader.getBundleContext().getServiceReference(serviceType); - if(ref!=null){ - return this.osgiServiceLoader.getBundleContext().getService(ref); - } - if(ConfigurationProviderSpi.class==serviceType){ - @SuppressWarnings("unchecked") - T service = (T)new CoreConfigurationProvider(); - this.osgiServiceLoader.getBundleContext().registerService( - serviceType.getName(), - service, - new Hashtable<String, Object>()); - return service; - } - return null; - } - - @SuppressWarnings("unchecked") - @Override - public <T> T create(Class<T> serviceType) { - LOG.finest("TAMAYA Creating service: " + serviceType.getName()); - ServiceReference<T> ref = this.osgiServiceLoader.getBundleContext().getServiceReference(serviceType); - if(ref!=null){ - try { - return (T)this.osgiServiceLoader.getBundleContext().getService(ref).getClass().newInstance(); - } catch (Exception e) { - return null; - } - } - return null; - } - - @Override - public <T> List<T> getServices(Class<T> serviceType) { - LOG.finest("TAMAYA Loading services: " + serviceType.getName()); - List<ServiceReference<T>> refs = new ArrayList<>(); - List<T> services = new ArrayList<>(refs.size()); - try { - refs.addAll(this.osgiServiceLoader.getBundleContext().getServiceReferences(serviceType, null)); - Collections.sort(refs, REF_COMPARATOR); - for(ServiceReference<T> ref:refs){ - T service = osgiServiceLoader.getBundleContext().getService(ref); - if(service!=null) { - services.add(service); - } - } - } catch (InvalidSyntaxException e) { - e.printStackTrace(); - } - try{ - for(T service:ServiceLoader.load(serviceType)){ - services.add(service); - } - return services; - } catch (Exception e) { - e.printStackTrace(); - } - return services; - } - - @Override - public Enumeration<URL> getResources(String resource, ClassLoader cl) throws IOException{ - LOG.finest("TAMAYA Loading resources: " + resource); - List<URL> result = new ArrayList<>(); - URL url = osgiServiceLoader.getBundleContext().getBundle() - .getEntry(resource); - if(url != null) { - LOG.finest("TAMAYA Resource: " + resource + " found in unregistered bundle " + - osgiServiceLoader.getBundleContext().getBundle().getSymbolicName()); - result.add(url); - } - for(Bundle bundle: osgiServiceLoader.getResourceBundles()) { - url = bundle.getEntry(resource); - if (url != null && !result.contains(url)) { - LOG.finest("TAMAYA Resource: " + resource + " found in registered bundle " + bundle.getSymbolicName()); - result.add(url); - } - } - for(Bundle bundle: osgiServiceLoader.getBundleContext().getBundles()) { - url = bundle.getEntry(resource); - if (url != null && !result.contains(url)) { - LOG.finest("TAMAYA Resource: " + resource + " found in unregistered bundle " + bundle.getSymbolicName()); - result.add(url); - } - } - return Collections.enumeration(result); - } - - @Override - public URL getResource(String resource, ClassLoader cl){ - LOG.finest("TAMAYA Loading resource: " + resource); - URL url = osgiServiceLoader.getBundleContext().getBundle() - .getEntry(resource); - if(url!=null){ - LOG.finest("TAMAYA Resource: " + resource + " found in bundle " + - osgiServiceLoader.getBundleContext().getBundle().getSymbolicName()); - return url; - } - for(Bundle bundle: osgiServiceLoader.getResourceBundles()) { - url = bundle.getEntry(resource); - if(url != null){ - LOG.finest("TAMAYA Resource: " + resource + " found in registered bundle " + bundle.getSymbolicName()); - return url; - } - } - for(Bundle bundle: osgiServiceLoader.getBundleContext().getBundles()) { - url = bundle.getEntry(resource); - if(url != null){ - LOG.finest("TAMAYA Resource: " + resource + " found in unregistered bundle " + bundle.getSymbolicName()); - return url; - } - } - return null; - } -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceLoader.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceLoader.java b/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceLoader.java deleted file mode 100644 index b973d5f..0000000 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/OSGIServiceLoader.java +++ /dev/null @@ -1,254 +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.core.internal; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.apache.tamaya.spisupport.PriorityServiceComparator; -import org.osgi.framework.*; - -/** - * A bundle listener that registers services defined in META-INF/services, when - * a bundle is starting. - * - * @author anat...@apache.org - */ -@SuppressWarnings("rawtypes") -public class OSGIServiceLoader implements BundleListener { - // Provide logging - private static final Logger log = Logger.getLogger(OSGIServiceLoader.class.getName()); - private static final String META_INF_SERVICES = "META-INF/services/"; - - private BundleContext context; - - private Set<Bundle> resourceBundles = Collections.synchronizedSet(new HashSet<Bundle>()); - - public OSGIServiceLoader(BundleContext context) { - this.context = Objects.requireNonNull(context); - // Check for matching bundles already installed... - for (Bundle bundle : context.getBundles()) { - switch (bundle.getState()) { - case Bundle.ACTIVE: - checkAndLoadBundle(bundle); - } - } - } - - public BundleContext getBundleContext() { - return context; - } - - public Set<Bundle> getResourceBundles() { - synchronized (resourceBundles) { - return new HashSet<>(resourceBundles); - } - } - - @Override - public void bundleChanged(BundleEvent bundleEvent) { - // Parse and create metadata when installed - if (bundleEvent.getType() == BundleEvent.STARTED) { - Bundle bundle = bundleEvent.getBundle(); - checkAndLoadBundle(bundle); - } else if (bundleEvent.getType() == BundleEvent.STOPPED) { - Bundle bundle = bundleEvent.getBundle(); - checkAndUnloadBundle(bundle); - } - } - - private void checkAndUnloadBundle(Bundle bundle) { - if (bundle.getEntry(META_INF_SERVICES) == null) { - return; - } - synchronized (resourceBundles) { - resourceBundles.remove(bundle); - log.fine("Unregistered ServiceLoader bundle: " + bundle.getSymbolicName()); - } - Enumeration<String> entryPaths = bundle.getEntryPaths(META_INF_SERVICES); - while (entryPaths.hasMoreElements()) { - String entryPath = entryPaths.nextElement(); - if (!entryPath.endsWith("/")) { - removeEntryPath(bundle, entryPath); - } - } - } - - private void checkAndLoadBundle(Bundle bundle) { - if (bundle.getEntry(META_INF_SERVICES) == null) { - return; - } - synchronized (resourceBundles) { - resourceBundles.add(bundle); - log.info("Registered ServiceLoader bundle: " + bundle.getSymbolicName()); - } - Enumeration<String> entryPaths = bundle.getEntryPaths(META_INF_SERVICES); - while (entryPaths.hasMoreElements()) { - String entryPath = entryPaths.nextElement(); - if (!entryPath.endsWith("/")) { - processEntryPath(bundle, entryPath); - } - } - } - - private void processEntryPath(Bundle bundle, String entryPath) { - try { - String serviceName = entryPath.substring(META_INF_SERVICES.length()); - if (!serviceName.startsWith("org.apache.tamaya")) { - // Ignore non Tamaya entries... - return; - } - Class<?> serviceClass = bundle.loadClass(serviceName); - URL child = bundle.getEntry(entryPath); - InputStream inStream = child.openStream(); - log.info("Loading Services " + serviceClass.getName() + " from bundle...: " + bundle.getSymbolicName()); - try (BufferedReader br = new BufferedReader(new InputStreamReader(inStream, "UTF-8"))) { - String implClassName = br.readLine(); - while (implClassName != null) { - int hashIndex = implClassName.indexOf("#"); - if (hashIndex > 0) { - implClassName = implClassName.substring(0, hashIndex - 1); - } else if (hashIndex == 0) { - implClassName = ""; - } - implClassName = implClassName.trim(); - if (implClassName.length() > 0) { - try { - // Load the service class - log.fine("Loading Class " + implClassName + " from bundle...: " + bundle.getSymbolicName()); - Class<?> implClass = bundle.loadClass(implClassName); - if (!serviceClass.isAssignableFrom(implClass)) { - log.warning("Configured service: " + implClassName + " is not assignable to " - + serviceClass.getName()); - continue; - } - log.info("Loaded Service Factory (" + serviceName + "): " + implClassName); - // Provide service properties - Hashtable<String, String> props = new Hashtable<>(); - props.put(Constants.VERSION_ATTRIBUTE, bundle.getVersion().toString()); - String vendor = bundle.getHeaders().get(Constants.BUNDLE_VENDOR); - props.put(Constants.SERVICE_VENDOR, (vendor != null ? vendor : "anonymous")); - // Translate annotated @Priority into a service ranking - props.put(Constants.SERVICE_RANKING, - String.valueOf(PriorityServiceComparator.getPriority(implClass))); - - // Register the service factory on behalf of the intercepted bundle - JDKUtilServiceFactory factory = new JDKUtilServiceFactory(implClass); - BundleContext bundleContext = bundle.getBundleContext(); - bundleContext.registerService(serviceName, factory, props); - log.info("Registered Tamaya service class: " + implClassName + "(" + serviceName + ")"); - } catch (Exception e) { - log.log(Level.SEVERE, "Failed to load service: " + implClassName, e); - } catch (NoClassDefFoundError err) { - log.log(Level.SEVERE, "Failed to load service: " + implClassName, err); - } - } - implClassName = br.readLine(); - } - } - } catch (RuntimeException rte) { - throw rte; - } catch (Exception e) { - log.log(Level.SEVERE, "Failed to read services from: " + entryPath, e); - } - } - - private void removeEntryPath(Bundle bundle, String entryPath) { - try { - String serviceName = entryPath.substring(META_INF_SERVICES.length()); - if (!serviceName.startsWith("org.apache.tamaya")) { - // Ignore non Tamaya entries... - return; - } - Class<?> serviceClass = bundle.loadClass(serviceName); - - URL child = bundle.getEntry(entryPath); - InputStream inStream = child.openStream(); - - BufferedReader br = new BufferedReader(new InputStreamReader(inStream, "UTF-8")); - String implClassName = br.readLine(); - while (implClassName != null) { - int hashIndex = implClassName.indexOf("#"); - if (hashIndex > 0) { - implClassName = implClassName.substring(0, hashIndex - 1); - } else if (hashIndex == 0) { - implClassName = ""; - } - implClassName = implClassName.trim(); - if (implClassName.length() > 0) { - log.fine("Unloading Service (" + serviceName + "): " + implClassName); - try { - // Load the service class - Class<?> implClass = bundle.loadClass(implClassName); - if (!serviceClass.isAssignableFrom(implClass)) { - log.warning("Configured service: " + implClassName + " is not assignable to " - + serviceClass.getName()); - continue; - } - ServiceReference<?> ref = bundle.getBundleContext().getServiceReference(implClass); - if (ref != null) { - bundle.getBundleContext().ungetService(ref); - } - } catch (Exception e) { - log.log(Level.SEVERE, "Failed to unload service: " + implClassName, e); - } catch (NoClassDefFoundError err) { - log.log(Level.SEVERE, "Failed to unload service: " + implClassName, err); - } - } - implClassName = br.readLine(); - } - br.close(); - } catch (RuntimeException rte) { - throw rte; - } catch (Exception e) { - log.log(Level.SEVERE, "Failed to read services from: " + entryPath, e); - } - } - - /** - * Service factory simply instantiating the configured service. - */ - static class JDKUtilServiceFactory implements ServiceFactory { - private final Class<?> serviceClass; - - public JDKUtilServiceFactory(Class<?> serviceClass) { - this.serviceClass = serviceClass; - } - - @Override - public Object getService(Bundle bundle, ServiceRegistration registration) { - try { - log.fine("Creating Service...:" + serviceClass.getName()); - return serviceClass.newInstance(); - } catch (Exception ex) { - ex.printStackTrace(); - throw new IllegalStateException("Failed to create service: " + serviceClass.getName(), ex); - } - } - - @Override - public void ungetService(Bundle bundle, ServiceRegistration registration, Object service) { - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/core/src/main/java/org/apache/tamaya/core/internal/converters/BigDecimalConverter.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/BigDecimalConverter.java b/code/core/src/main/java/org/apache/tamaya/core/internal/converters/BigDecimalConverter.java deleted file mode 100644 index 7e71b7e..0000000 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/BigDecimalConverter.java +++ /dev/null @@ -1,76 +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.core.internal.converters; - -import org.apache.tamaya.spi.ConversionContext; -import org.apache.tamaya.spi.PropertyConverter; -import org.osgi.service.component.annotations.Component; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.Objects; -import java.util.logging.Logger; - -/** - * Converter, converting from String to BigDecimal, the supported format is one of the following: - * <ul> - * <li>232573527352.76352753</li> - * <li>-23257352.735276352753</li> - * <li>-0xFFFFFF (integral numbers only)</li> - * <li>-0XFFFFAC (integral numbers only)</li> - * <li>0xFFFFFF (integral numbers only)</li> - * <li>0XFFFFAC (integral numbers only)</li> - * </ul> - */ -@Component(service = PropertyConverter.class) -public class BigDecimalConverter implements PropertyConverter<BigDecimal>{ - - /** The logger. */ - private static final Logger LOG = Logger.getLogger(BigDecimalConverter.class.getName()); - /** Converter to be used if the format is not directly supported by BigDecimal, e.g. for integral hex values. */ - private final BigIntegerConverter integerConverter = new BigIntegerConverter(); - - @Override - public BigDecimal convert(String value, ConversionContext context) { - context.addSupportedFormats(getClass(), "<bigDecimal> -> new BigDecimal(String)"); - - String trimmed = Objects.requireNonNull(value).trim(); - try{ - return new BigDecimal(trimmed); - } catch(Exception e){ - LOG.finest("Parsing BigDecimal failed, trying BigInteger for: " + value); - BigInteger bigInt = integerConverter.convert(value, context); - if(bigInt!=null){ - return new BigDecimal(bigInt); - } - LOG.finest("Failed to parse BigDecimal from: " + value); - return null; - } - } - - @Override - public boolean equals(Object o){ - return getClass().equals(o.getClass()); - } - - @Override - public int hashCode(){ - return getClass().hashCode(); - } -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/core/src/main/java/org/apache/tamaya/core/internal/converters/BigIntegerConverter.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/BigIntegerConverter.java b/code/core/src/main/java/org/apache/tamaya/core/internal/converters/BigIntegerConverter.java deleted file mode 100644 index edca14a..0000000 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/BigIntegerConverter.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.tamaya.core.internal.converters; - -import org.apache.tamaya.spi.ConversionContext; -import org.apache.tamaya.spi.PropertyConverter; -import org.osgi.service.component.annotations.Component; - -import java.math.BigInteger; -import java.util.Objects; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Converter, converting from String to BigInteger, the supported format is one of the following: - * <ul> - * <li>0xFFFFFF</li> - * <li>0XFFFFAC</li> - * <li>23257352735276352753</li> - * <li>-0xFFFFFF</li> - * <li>-0XFFFFAC</li> - * <li>-23257352735276352753</li> - * </ul> - */ -@Component(service = PropertyConverter.class) -public class BigIntegerConverter implements PropertyConverter<BigInteger>{ - - /** The logger. */ - private static final Logger LOG = Logger.getLogger(BigIntegerConverter.class.getName()); - /** Converter used to decode hex, octal values. */ - private final ByteConverter byteConverter = new ByteConverter(); - - @Override - public BigInteger convert(String value, ConversionContext context) { - context.addSupportedFormats(getClass(), "[-]0X.. (hex)", "[-]0x... (hex)", "<bigint> -> new BigInteger(bigint)"); - String trimmed = Objects.requireNonNull(value).trim(); - if(trimmed.startsWith("0x") || trimmed.startsWith("0X")){ - LOG.finest("Parsing Hex value to BigInteger: " + value); - trimmed = trimmed.substring(2); - StringBuilder decimal = new StringBuilder(); - for(int offset = 0;offset < trimmed.length();offset+=2){ - if(offset==trimmed.length()-1){ - LOG.finest("Invalid Hex-Byte-String: " + value); - return null; - } - byte val = byteConverter.convert("0x" + trimmed.substring(offset, offset + 2), context); - if(val<10){ - decimal.append('0').append(val); - } else{ - decimal.append(val); - } - } - return new BigInteger(decimal.toString()); - } else if(trimmed.startsWith("-0x") || trimmed.startsWith("-0X")){ - LOG.finest("Parsing Hex value to BigInteger: " + value); - trimmed = trimmed.substring(3); - StringBuilder decimal = new StringBuilder(); - for(int offset = 0;offset < trimmed.length();offset+=2){ - if(offset==trimmed.length()-1){ - LOG.finest("Invalid Hex-Byte-String: " + trimmed); - return null; - } - byte val = byteConverter.convert("0x" + trimmed.substring(offset, offset + 2), context); - if(val<10){ - decimal.append('0').append(val); - } else{ - decimal.append(val); - } - } - return new BigInteger('-' + decimal.toString()); - } - try{ - return new BigInteger(trimmed); - } catch(Exception e){ - LOG.log(Level.FINEST, "Failed to parse BigInteger from: " + value, e); - return null; - } - } - - @Override - public boolean equals(Object o){ - return getClass().equals(o.getClass()); - } - - @Override - public int hashCode(){ - return getClass().hashCode(); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/core/src/main/java/org/apache/tamaya/core/internal/converters/BooleanConverter.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/BooleanConverter.java b/code/core/src/main/java/org/apache/tamaya/core/internal/converters/BooleanConverter.java deleted file mode 100644 index 7e61140..0000000 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/BooleanConverter.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.tamaya.core.internal.converters; - -import org.apache.tamaya.spi.ConversionContext; -import org.apache.tamaya.spi.PropertyConverter; -import org.osgi.service.component.annotations.Component; - -import java.util.Locale; -import java.util.Objects; -import java.util.logging.Logger; - -/** - * Converter, converting from String to Boolean. - */ -@Component(service = PropertyConverter.class) -public class BooleanConverter implements PropertyConverter<Boolean> { - - private final Logger LOG = Logger.getLogger(getClass().getName()); - - @Override - public Boolean convert(String value, ConversionContext context) { - context.addSupportedFormats(getClass(), "yes (ignore case)", "y (ignore case)", "true (ignore case)", "t (ignore case)", "1", "no (ignore case)", "n (ignore case)", "false (ignore case)", "f (ignore case)", "0"); - String ignoreCaseValue = Objects.requireNonNull(value) - .trim() - .toLowerCase(Locale.ENGLISH); - switch(ignoreCaseValue) { - case "1": - case "yes": - case "y": - case "true": - case "t": - case "on": - return Boolean.TRUE; - case "no": - case "n": - case "false": - case "f": - case "0": - case "off": - return Boolean.FALSE; - default: - LOG.finest("Unknown boolean value encountered: " + value); - } - return null; - } - - @Override - public boolean equals(Object o){ - return getClass().equals(o.getClass()); - } - - @Override - public int hashCode(){ - return getClass().hashCode(); - } -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/core/src/main/java/org/apache/tamaya/core/internal/converters/ByteConverter.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/ByteConverter.java b/code/core/src/main/java/org/apache/tamaya/core/internal/converters/ByteConverter.java deleted file mode 100644 index 9b213cf..0000000 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/ByteConverter.java +++ /dev/null @@ -1,83 +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.core.internal.converters; - -import org.apache.tamaya.spi.ConversionContext; -import org.apache.tamaya.spi.PropertyConverter; -import org.osgi.service.component.annotations.Component; - -import java.util.Locale; -import java.util.Objects; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Converter, converting from String to Byte, the supported format is one of the following: - * <ul> - * <li>123 (byte value)</li> - * <li>0xFF (byte value)</li> - * <li>0XDF (byte value)</li> - * <li>0D1 (byte value)</li> - * <li>-123 (byte value)</li> - * <li>-0xFF (byte value)</li> - * <li>-0XDF (byte value)</li> - * <li>-0D1 (byte value)</li> - * <li>MIN_VALUE (ignoring case)</li> - * <li>MIN (ignoring case)</li> - * <li>MAX_VALUE (ignoring case)</li> - * <li>MAX (ignoring case)</li> - * </ul> - */ -@Component(service = PropertyConverter.class) -public class ByteConverter implements PropertyConverter<Byte>{ - - private final Logger LOG = Logger.getLogger(getClass().getName()); - - @Override - public Byte convert(String value, ConversionContext context) { - context.addSupportedFormats(getClass(),"<byte>", "MIN_VALUE", "MIN", "MAX_VALUE", "MAX"); - String trimmed = Objects.requireNonNull(value).trim(); - switch(trimmed.toUpperCase(Locale.ENGLISH)){ - case "MIN_VALUE": - case "MIN": - return Byte.MIN_VALUE; - case "MAX_VALUE": - case "MAX": - return Byte.MAX_VALUE; - default: - try{ - return Byte.decode(trimmed); - } - catch(Exception e){ - LOG.log(Level.FINEST, "Unparseable Byte: " + value); - return null; - } - } - } - - @Override - public boolean equals(Object o){ - return getClass().equals(o.getClass()); - } - - @Override - public int hashCode(){ - return getClass().hashCode(); - } -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/core/src/main/java/org/apache/tamaya/core/internal/converters/CharConverter.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/CharConverter.java b/code/core/src/main/java/org/apache/tamaya/core/internal/converters/CharConverter.java deleted file mode 100644 index 3895969..0000000 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/CharConverter.java +++ /dev/null @@ -1,80 +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.core.internal.converters; - -import org.apache.tamaya.spi.ConversionContext; -import org.apache.tamaya.spi.PropertyConverter; -import org.osgi.service.component.annotations.Component; - -import java.util.Objects; -import java.util.logging.Logger; - -/** - * Converter, converting from String to Character, the supported format is one of the following: - * <ul> - * <li>'a'</li> - * <li>123 (byte value)</li> - * <li>0xFF (byte value)</li> - * <li>0XDF (byte value)</li> - * <li>0D1 (byte value)</li> - * </ul> - */ -@Component(service = PropertyConverter.class) -public class CharConverter implements PropertyConverter<Character>{ - - private static final Logger LOG = Logger.getLogger(CharConverter.class.getName()); - - @Override - public Character convert(String value, ConversionContext context) { - context.addSupportedFormats(getClass(),"\\'<char>\\'", "<char>", "<charNum>"); - String trimmed = Objects.requireNonNull(value).trim(); - if(trimmed.isEmpty()){ - return null; - } - if(trimmed.startsWith("'")) { - try { - trimmed = trimmed.substring(1, trimmed.length() - 1); - if (trimmed.isEmpty()) { - return null; - } - return trimmed.charAt(0); - } catch (Exception e) { - LOG.finest("Invalid character format encountered: '" + value + "', valid formats are 'a', 101 and a."); - return null; - } - } - try { - Integer val = Integer.parseInt(trimmed); - return (char) val.shortValue(); - } catch (Exception e) { - LOG.finest("Character format is not numeric: '" + value + "', using first character."); - return trimmed.charAt(0); - } - } - - @Override - public boolean equals(Object o){ - return getClass().equals(o.getClass()); - } - - @Override - public int hashCode(){ - return getClass().hashCode(); - } -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/core/src/main/java/org/apache/tamaya/core/internal/converters/ClassConverter.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/ClassConverter.java b/code/core/src/main/java/org/apache/tamaya/core/internal/converters/ClassConverter.java deleted file mode 100644 index b29bc15..0000000 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/ClassConverter.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.tamaya.core.internal.converters; - -import org.apache.tamaya.spi.ConversionContext; -import org.apache.tamaya.spi.PropertyConverter; -import org.osgi.service.component.annotations.Component; - -import java.util.Objects; -import java.util.logging.Logger; - -/** - * Converter, converting from String to Class, hereby using the following classloaders: - * <ul> - * <li>The current ThreadContext ClassLoader</li> - * <li>The Classloader of this class</li> - * <li>The system Classloader</li> - * </ul> - */ -@Component(service = PropertyConverter.class) -public class ClassConverter implements PropertyConverter<Class<?>>{ - - private final Logger LOG = Logger.getLogger(getClass().getName()); - - @Override - public Class<?> convert(String value, ConversionContext context) { - if(value==null){ - return null; - } - context.addSupportedFormats(getClass(),"<fullyQualifiedClassName>"); - String trimmed = Objects.requireNonNull(value).trim(); - try{ - return Class.forName(trimmed, false, Thread.currentThread().getContextClassLoader()); - } - catch(Exception e){ - LOG.finest("Class not found in context CL: " + trimmed); - } - try{ - return Class.forName(trimmed, false, ClassConverter.class.getClassLoader()); - } - catch(Exception e){ - LOG.finest("Class not found in ClassConverter's CL: " + trimmed); - } - try{ - return Class.forName(trimmed, false, ClassLoader.getSystemClassLoader()); - } - catch(Exception e){ - LOG.finest("Class not found in System CL (giving up): " + trimmed); - return null; - } - } - - @Override - public boolean equals(Object o){ - return getClass().equals(o.getClass()); - } - - @Override - public int hashCode(){ - return getClass().hashCode(); - } -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/core/src/main/java/org/apache/tamaya/core/internal/converters/ConvertQuery.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/ConvertQuery.java b/code/core/src/main/java/org/apache/tamaya/core/internal/converters/ConvertQuery.java deleted file mode 100644 index 6fb31c6..0000000 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/ConvertQuery.java +++ /dev/null @@ -1,68 +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.core.internal.converters; - -import org.apache.tamaya.ConfigQuery; -import org.apache.tamaya.Configuration; -import org.apache.tamaya.TypeLiteral; -import org.apache.tamaya.spi.ConversionContext; -import org.apache.tamaya.spi.PropertyConverter; - -import java.util.List; -import java.util.Objects; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Query to convert a String value. - * @param <T> the target type. - */ -final class ConvertQuery<T> implements ConfigQuery<T> { - - private static final Logger LOG = Logger.getLogger(ConvertQuery.class.getName()); - - private String rawValue; - private TypeLiteral<T> type; - - public ConvertQuery(String rawValue, TypeLiteral<T> type) { - this.rawValue = Objects.requireNonNull(rawValue); - this.type = Objects.requireNonNull(type); - } - - @Override - public T query(Configuration config) { - List<PropertyConverter<T>> converters = config.getContext().getPropertyConverters(type); - ConversionContext context = new ConversionContext.Builder(type).setConfigurationContext(config.getContext()) - .setConfiguration(config).setKey(ConvertQuery.class.getName()).build(); - for(PropertyConverter<?> conv: converters) { - try{ - if(conv instanceof OptionalConverter){ - continue; - } - T result = (T)conv.convert(rawValue, context); - if(result!=null){ - return result; - } - }catch(Exception e){ - LOG.log(Level.FINEST, e, () -> "Converter "+ conv +" failed to convert to " + type); - } - } - return null; - } -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/core/src/main/java/org/apache/tamaya/core/internal/converters/CurrencyConverter.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/CurrencyConverter.java b/code/core/src/main/java/org/apache/tamaya/core/internal/converters/CurrencyConverter.java deleted file mode 100644 index b769d06..0000000 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/CurrencyConverter.java +++ /dev/null @@ -1,102 +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.core.internal.converters; - -import org.apache.tamaya.spi.ConversionContext; -import org.apache.tamaya.spi.PropertyConverter; -import org.osgi.service.component.annotations.Component; - -import java.util.Currency; -import java.util.Locale; -import java.util.Objects; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Converter, converting from String to Currency, the supported format is one of the following: - * <ul> - * <li>CHF (currency code)</li> - * <li>123 (numeric currency value > - * = 0)</li> - * <li>DE (ISO 2-digit country)</li> - * <li>de_DE, de_DE_123 (Locale)</li> - * </ul> - */ -@Component(service = PropertyConverter.class) -public class CurrencyConverter implements PropertyConverter<Currency> { - - private static final Logger LOG = Logger.getLogger(CurrencyConverter.class.getName()); - - @Override - public Currency convert(String value, ConversionContext context) { - context.addSupportedFormats(getClass(), "<currencyCode>, using Locale.ENGLISH", "<numericValue>", "<locale>"); - String trimmed = Objects.requireNonNull(value).trim(); - try { - return Currency.getInstance(trimmed.toUpperCase(Locale.ENGLISH)); - } catch (Exception e) { - LOG.log(Level.FINEST, "Not a valid textual currency code: " + trimmed + ", checking for numeric...", e); - } - try { - // Check for numeric code - Integer numCode = Integer.parseInt(trimmed); - for (Currency currency : Currency.getAvailableCurrencies()) { - if (currency.getNumericCode() == numCode) { - return currency; - } - } - } catch (Exception e) { - LOG.log(Level.FINEST, "Not a valid numeric currency code: " + trimmed + ", checking for locale...", e); - } - try { - // Check for numeric code - String[] parts = trimmed.split("\\_"); - Locale locale; - switch (parts.length) { - case 1: - locale = new Locale("", parts[0]); - break; - case 2: - locale = new Locale(parts[0], parts[1]); - break; - case 3: - locale = new Locale(parts[0], parts[1], parts[2]); - break; - default: - locale = null; - } - if (locale != null) { - return Currency.getInstance(locale); - } - LOG.finest("Not a valid currency: " + trimmed + ", giving up..."); - } catch (Exception e) { - LOG.log(Level.FINEST, "Not a valid country locale for currency: " + trimmed + ", giving up...", e); - } - return null; - } - - @Override - public boolean equals(Object o){ - return getClass().equals(o.getClass()); - } - - @Override - public int hashCode(){ - return getClass().hashCode(); - } -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9bc56a38/code/core/src/main/java/org/apache/tamaya/core/internal/converters/DoubleConverter.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/DoubleConverter.java b/code/core/src/main/java/org/apache/tamaya/core/internal/converters/DoubleConverter.java deleted file mode 100644 index e527756..0000000 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/converters/DoubleConverter.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.tamaya.core.internal.converters; - -import org.apache.tamaya.spi.ConversionContext; -import org.apache.tamaya.spi.PropertyConverter; -import org.osgi.service.component.annotations.Component; - -import java.util.Locale; -import java.util.Objects; -import java.util.logging.Logger; - -/** - * Converter, converting from String to Double, using the Java number syntax: - * (-)?[0-9]*\.[0-9]*. In case of error the value given also is tried being parsed as integral number using - * {@link LongConverter}. Additionally the following values are supported: - * <ul> - * <li>NaN (ignoring case)</li> - * <li>POSITIVE_INFINITY (ignoring case)</li> - * <li>NEGATIVE_INFINITY (ignoring case)</li> - * </ul> - */ -@Component(service = PropertyConverter.class) -public class DoubleConverter implements PropertyConverter<Double> { - /** - * The logger. - */ - private static final Logger LOG = Logger.getLogger(DoubleConverter.class.getName()); - /** - * The converter used, when floating point parse failed. - */ - private final LongConverter integerConverter = new LongConverter(); - - @Override - public Double convert(String value, ConversionContext context) { - context.addSupportedFormats(getClass(), "<double>", "MIN", "MIN_VALUE", "MAX", "MAX_VALUE", "POSITIVE_INFINITY", "NEGATIVE_INFINITY", "NAN"); - String trimmed = Objects.requireNonNull(value).trim(); - switch (trimmed.toUpperCase(Locale.ENGLISH)) { - case "POSITIVE_INFINITY": - return Double.POSITIVE_INFINITY; - case "NEGATIVE_INFINITY": - return Double.NEGATIVE_INFINITY; - case "NAN": - return Double.NaN; - case "MIN_VALUE": - case "MIN": - return Double.MIN_VALUE; - case "MAX_VALUE": - case "MAX": - return Double.MAX_VALUE; - default: - try { - return Double.valueOf(trimmed); - } catch (Exception e) { - // OK perhaps we have an integral number that must be converted to the double type... - LOG.finest("Parsing of double as floating number failed, trying parsing integral" + - " number/hex instead..."); - } - Long val = integerConverter.convert(trimmed, context); - if(val!=null){ - return val.doubleValue(); - } - return null; - } - - } - - @Override - public boolean equals(Object o){ - return getClass().equals(o.getClass()); - } - - @Override - public int hashCode(){ - return getClass().hashCode(); - } -}