Repository: incubator-tamaya Updated Branches: refs/heads/master 87569d293 -> 9f0e1ddc4
TAMAYA-289: Revisit code Remove unused methods, fix Eclipse warnings. Fix typos in Javadoc, minor refactorings. Project: http://git-wip-us.apache.org/repos/asf/incubator-tamaya/repo Commit: http://git-wip-us.apache.org/repos/asf/incubator-tamaya/commit/9f0e1ddc Tree: http://git-wip-us.apache.org/repos/asf/incubator-tamaya/tree/9f0e1ddc Diff: http://git-wip-us.apache.org/repos/asf/incubator-tamaya/diff/9f0e1ddc Branch: refs/heads/master Commit: 9f0e1ddc47a2faa6d9119c1a3440172ee70e3c1a Parents: 87569d2 Author: Phil Ottlinger <[email protected]> Authored: Tue Oct 24 00:02:21 2017 +0200 Committer: Phil Ottlinger <[email protected]> Committed: Tue Oct 24 00:02:21 2017 +0200 ---------------------------------------------------------------------- .../core/internal/ConfigValueEvaluator.java | 2 - .../core/internal/DefaultConfiguration.java | 6 +- .../internal/DefaultConfigurationContext.java | 17 +- .../DefaultConfigurationContextBuilder.java | 35 +- .../core/internal/DefaultServiceContext.java | 19 +- .../core/internal/OSGIServiceComparator.java | 15 +- .../core/internal/OSGIServiceContext.java | 6 +- .../tamaya/core/internal/OSGIServiceLoader.java | 450 +++++++++---------- .../internal/PriorityServiceComparator.java | 13 +- .../core/internal/PropertyConverterManager.java | 25 +- .../core/internal/PropertySourceComparator.java | 58 +-- .../core/internal/WrappedPropertySource.java | 3 - 12 files changed, 280 insertions(+), 369 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9f0e1ddc/code/core/src/main/java/org/apache/tamaya/core/internal/ConfigValueEvaluator.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/ConfigValueEvaluator.java b/code/core/src/main/java/org/apache/tamaya/core/internal/ConfigValueEvaluator.java index 368d763..f1c8bf2 100644 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/ConfigValueEvaluator.java +++ b/code/core/src/main/java/org/apache/tamaya/core/internal/ConfigValueEvaluator.java @@ -21,10 +21,8 @@ package org.apache.tamaya.core.internal; import org.apache.tamaya.spi.ConfigurationContext; import org.apache.tamaya.spi.PropertyValue; -import java.util.HashMap; import java.util.Map; - /** * Component SPI which encapsulates the evaluation of a single or full <b>raw</b>value * for a {@link ConfigurationContext}. http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9f0e1ddc/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfiguration.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfiguration.java b/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfiguration.java index 2011133..1c22e44 100644 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfiguration.java +++ b/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfiguration.java @@ -153,7 +153,8 @@ public class DefaultConfiguration implements Configuration { * @param <T> the value type * @return the converted value, never {@code null}. */ - @Override + @SuppressWarnings("unchecked") + @Override public <T> T get(String key, Class<T> type) { Objects.requireNonNull(key, "Key must not be null."); Objects.requireNonNull(type, "Target type must not be null"); @@ -180,7 +181,8 @@ public class DefaultConfiguration implements Configuration { return convertValue(key, get(key), type); } - protected <T> T convertValue(String key, String value, TypeLiteral<T> type) { + @SuppressWarnings("unchecked") + protected <T> T convertValue(String key, String value, TypeLiteral<T> type) { if (value != null) { List<PropertyConverter<T>> converters = configurationContext.getPropertyConverters(type); ConversionContext context = new ConversionContext.Builder(this, this.configurationContext, key, type) http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9f0e1ddc/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationContext.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationContext.java b/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationContext.java index f3126af..9645681 100644 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationContext.java +++ b/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationContext.java @@ -29,8 +29,6 @@ import org.apache.tamaya.spi.PropertyValue; import org.apache.tamaya.spi.PropertyValueCombinationPolicy; import org.apache.tamaya.spi.ServiceContextManager; -import javax.annotation.Priority; -import java.io.Serializable; import java.util.*; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; @@ -45,7 +43,7 @@ public class DefaultConfigurationContext implements ConfigurationContext { private final static Logger LOG = Logger.getLogger(DefaultConfigurationContext.class.getName()); /** - * Cubcomponent handling {@link org.apache.tamaya.spi.PropertyConverter} instances. + * Subcomponent handling {@link org.apache.tamaya.spi.PropertyConverter} instances. */ private final PropertyConverterManager propertyConverterManager = new PropertyConverterManager(); @@ -70,13 +68,8 @@ public class DefaultConfigurationContext implements ConfigurationContext { */ private final ReentrantReadWriteLock propertySourceLock = new ReentrantReadWriteLock(); - /** - * Lock for internal synchronization. - */ - private final ReentrantReadWriteLock propertyFilterLock = new ReentrantReadWriteLock(); - - - DefaultConfigurationContext(DefaultConfigurationContextBuilder builder) { + @SuppressWarnings("unchecked") + DefaultConfigurationContext(DefaultConfigurationContextBuilder builder) { List<PropertySource> propertySources = new ArrayList<>(); // first we load all PropertySources which got registered via java.util.ServiceLoader propertySources.addAll(builder.propertySources); @@ -89,7 +82,7 @@ public class DefaultConfigurationContext implements ConfigurationContext { // Finally add the converters for(Map.Entry<TypeLiteral<?>, Collection<PropertyConverter<?>>> en:builder.getPropertyConverter().entrySet()) { - for (PropertyConverter converter : en.getValue()) { + for (@SuppressWarnings("rawtypes") PropertyConverter converter : en.getValue()) { this.propertyConverterManager.register(en.getKey(), converter); } } @@ -195,7 +188,7 @@ public class DefaultConfigurationContext implements ConfigurationContext { b.append(" -------------------\n"); b.append(" CLASS TYPE INFO\n\n"); for(Map.Entry<TypeLiteral<?>, List<PropertyConverter<?>>> converterEntry:getPropertyConverters().entrySet()){ - for(PropertyConverter converter: converterEntry.getValue()){ + for(PropertyConverter<?> converter: converterEntry.getValue()){ b.append(" "); appendFormatted(b, converter.getClass().getSimpleName(), 30); appendFormatted(b, converterEntry.getKey().getRawType().getSimpleName(), 30); http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9f0e1ddc/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationContextBuilder.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationContextBuilder.java b/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationContextBuilder.java index 8d4dda4..2ddade6 100644 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationContextBuilder.java +++ b/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultConfigurationContextBuilder.java @@ -64,8 +64,6 @@ public class DefaultConfigurationContextBuilder implements ConfigurationContextB */ private boolean built; - - /** * Creates a new builder instance. */ @@ -103,7 +101,6 @@ public class DefaultConfigurationContextBuilder implements ConfigurationContextB return this; } - @Override public ConfigurationContextBuilder setContext(ConfigurationContext context) { checkBuilderState(); @@ -162,8 +159,8 @@ public class DefaultConfigurationContextBuilder implements ConfigurationContextB return this; } - - @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override public DefaultConfigurationContextBuilder addDefaultPropertyConverters() { checkBuilderState(); addCorePropertyConverters(); @@ -175,7 +172,8 @@ public class DefaultConfigurationContextBuilder implements ConfigurationContextB return this; } - private void addCorePropertyConverters() { + @SuppressWarnings("unchecked") + private 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()); @@ -207,15 +205,6 @@ public class DefaultConfigurationContextBuilder implements ConfigurationContextB return this; } - private PropertySource getPropertySource(String name) { - for(PropertySource ps:propertySources){ - if(ps.getName().equals(name)){ - return ps; - } - } - throw new IllegalArgumentException("No such PropertySource: "+name); - } - @Override public List<PropertySource> getPropertySources() { return this.propertySources; @@ -308,7 +297,7 @@ public class DefaultConfigurationContextBuilder implements ConfigurationContextB @Override public <T> ConfigurationContextBuilder removePropertyConverters(TypeLiteral<T> typeToConvert, - PropertyConverter<T>... converters) { + @SuppressWarnings("unchecked") PropertyConverter<T>... converters) { return removePropertyConverters(typeToConvert, Arrays.asList(converters)); } @@ -328,7 +317,6 @@ public class DefaultConfigurationContextBuilder implements ConfigurationContextB return this; } - @Override public ConfigurationContextBuilder setPropertyValueCombinationPolicy(PropertyValueCombinationPolicy combinationPolicy){ checkBuilderState(); @@ -336,9 +324,8 @@ public class DefaultConfigurationContextBuilder implements ConfigurationContextB return this; } - @Override - public <T> ConfigurationContextBuilder addPropertyConverters(TypeLiteral<T> type, PropertyConverter<T>... propertyConverters){ + public <T> ConfigurationContextBuilder addPropertyConverters(TypeLiteral<T> type, @SuppressWarnings("unchecked") PropertyConverter<T>... propertyConverters){ checkBuilderState(); Objects.requireNonNull(type); Objects.requireNonNull(propertyConverters); @@ -377,11 +364,6 @@ public class DefaultConfigurationContextBuilder implements ConfigurationContextB return this; } - private WrappedPropertySource getWrappedPropertySource(PropertySource delegate) { - PropertySource ps = getPropertySource(delegate.getName()); - return WrappedPropertySource.of(ps); - } - protected ConfigurationContextBuilder loadDefaults() { checkBuilderState(); this.combinationPolicy = PropertyValueCombinationPolicy.DEFAULT_OVERRIDING_POLICY; @@ -391,8 +373,8 @@ public class DefaultConfigurationContextBuilder implements ConfigurationContextB return this; } - - private Map<TypeLiteral, Collection<PropertyConverter>> getDefaultPropertyConverters() { + @SuppressWarnings("rawtypes") + private Map<TypeLiteral, Collection<PropertyConverter>> getDefaultPropertyConverters() { Map<TypeLiteral, Collection<PropertyConverter>> result = new HashMap<>(); for (PropertyConverter conv : ServiceContextManager.getServiceContext().getServices( PropertyConverter.class)) { @@ -408,7 +390,6 @@ public class DefaultConfigurationContextBuilder implements ConfigurationContextB return result; } - /** * Builds a new configuration based on the configuration of this builder instance. * http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9f0e1ddc/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultServiceContext.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultServiceContext.java b/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultServiceContext.java index 7146ccf..04377e2 100644 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultServiceContext.java +++ b/code/core/src/main/java/org/apache/tamaya/core/internal/DefaultServiceContext.java @@ -44,7 +44,8 @@ public final class DefaultServiceContext implements ServiceContext { * Singletons. */ private final Map<Class<?>, Object> singletons = new ConcurrentHashMap<>(); - private Map<Class, Class> factoryTypes = new ConcurrentHashMap<>(); + @SuppressWarnings("rawtypes") + private Map<Class, Class> factoryTypes = new ConcurrentHashMap<>(); @Override public <T> T getService(Class<T> serviceType) { @@ -60,7 +61,8 @@ public final class DefaultServiceContext implements ServiceContext { @Override public <T> T create(Class<T> serviceType) { - Class<? extends T> implType = factoryTypes.get(serviceType); + @SuppressWarnings("unchecked") + Class<? extends T> implType = factoryTypes.get(serviceType); if(implType==null) { Collection<T> services = getServices(serviceType); if (services.isEmpty()) { @@ -72,7 +74,7 @@ public final class DefaultServiceContext implements ServiceContext { try { return implType.newInstance(); } catch (Exception e) { - LOG.log(Level.SEVERE, "Failed to create instabce of " + implType.getName(), e); + LOG.log(Level.SEVERE, "Failed to create instance of " + implType.getName(), e); return null; } } @@ -86,7 +88,8 @@ public final class DefaultServiceContext implements ServiceContext { */ @Override public <T> List<T> getServices(final Class<T> serviceType) { - List<T> found = (List<T>) servicesLoaded.get(serviceType); + @SuppressWarnings("unchecked") + List<T> found = (List<T>) servicesLoaded.get(serviceType); if (found != null) { return found; } @@ -109,13 +112,14 @@ public final class DefaultServiceContext implements ServiceContext { services = Collections.emptyList(); } } - final List<T> previousServices = List.class.cast(servicesLoaded.putIfAbsent(serviceType, (List<Object>) services)); + @SuppressWarnings("unchecked") + final List<T> previousServices = List.class.cast(servicesLoaded.putIfAbsent(serviceType, (List<Object>) services)); return previousServices != null ? previousServices : services; } /** - * Checks the given instance for a @Priority annotation. If present the annotation's value s evaluated. If no such - * annotation is present, a default priority is returned (1); + * 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 of {@code 1} is returned. * @param o the instance, not {@code null}. * @return a priority, by default 1. */ @@ -197,5 +201,4 @@ public final class DefaultServiceContext implements ServiceContext { return cl.getResource(resource); } - } http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9f0e1ddc/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 index a1a99b6..c9815cf 100644 --- 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 @@ -24,8 +24,9 @@ import javax.annotation.Priority; import java.util.Comparator; /** - * Comparator implementation for odering services loaded based on their increasing priority values. + * Comparator implementation for ordering services loaded based on their increasing priority values. */ +@SuppressWarnings("rawtypes") class OSGIServiceComparator implements Comparator<ServiceReference> { @Override @@ -41,8 +42,8 @@ class OSGIServiceComparator implements Comparator<ServiceReference> { } /** - * Checks the given instance for a @Priority annotation. If present the annotation's value s evaluated. If no such - * annotation is present, a default priority is returned (1); + * 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. @@ -52,15 +53,15 @@ class OSGIServiceComparator implements Comparator<ServiceReference> { } /** - * Checks the given type optionally annotated with a @Priority. If present the annotation's value s evaluated. - * If no such annotation is present, a default priority is returned (1); + * 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 type) { + public static int getPriority(Class<? extends Object> type) { int prio = 1; - Priority priority = (Priority)type.getAnnotation(Priority.class); + Priority priority = type.getAnnotation(Priority.class); if (priority != null) { prio = priority.value(); } http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9f0e1ddc/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 index d17650b..ddbf692 100644 --- 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 @@ -61,7 +61,8 @@ public class OSGIServiceContext implements ServiceContext{ return this.osgiServiceLoader.getBundleContext().getService(ref); } if(ConfigurationProviderSpi.class==serviceType){ - T service = (T)new DefaultConfigurationProvider(); + @SuppressWarnings("unchecked") + T service = (T)new DefaultConfigurationProvider(); this.osgiServiceLoader.getBundleContext().registerService( serviceType.getName(), service, @@ -71,7 +72,8 @@ public class OSGIServiceContext implements ServiceContext{ return null; } - @Override + @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); http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9f0e1ddc/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 index dae7bea..3bf0291 100644 --- 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 @@ -23,247 +23,231 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.*; -import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import org.osgi.framework.*; -import org.osgi.util.tracker.ServiceTracker; /** - * An bundle listener that registers services defined in META-INF/services, when a bundle is starting. + * A bundle listener that registers services defined in META-INF/services, when + * a bundle is starting. * * @author [email protected] */ +@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()); - 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 assignble 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(); - } - br.close(); - } - 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 assignble 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) { - } - } + // 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/9f0e1ddc/code/core/src/main/java/org/apache/tamaya/core/internal/PriorityServiceComparator.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/PriorityServiceComparator.java b/code/core/src/main/java/org/apache/tamaya/core/internal/PriorityServiceComparator.java index d94f0d4..3b2ff5a 100644 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/PriorityServiceComparator.java +++ b/code/core/src/main/java/org/apache/tamaya/core/internal/PriorityServiceComparator.java @@ -22,7 +22,7 @@ import javax.annotation.Priority; import java.util.Comparator; /** - * Comparator implementation for odering services loaded based on their increasing priority values. + * Comparator implementation for ordering services loaded based on their increasing priority values. */ public class PriorityServiceComparator implements Comparator<Object> { @@ -52,8 +52,8 @@ public class PriorityServiceComparator implements Comparator<Object> { } /** - * Checks the given instance for a @Priority annotation. If present the annotation's value s evaluated. If no such - * annotation is present, a default priority is returned (1); + * 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. @@ -63,15 +63,16 @@ public class PriorityServiceComparator implements Comparator<Object> { } /** - * Checks the given type optionally annotated with a @Priority. If present the annotation's value s evaluated. - * If no such annotation is present, a default priority is returned (1); + * 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. */ + @SuppressWarnings({ "rawtypes", "unchecked" }) public static int getPriority(Class type) { int prio = 1; - Priority priority = (Priority)type.getAnnotation(Priority.class); + Priority priority = (Priority)type.getAnnotation(Priority.class); if (priority != null) { prio = priority.value(); } http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9f0e1ddc/code/core/src/main/java/org/apache/tamaya/core/internal/PropertyConverterManager.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/PropertyConverterManager.java b/code/core/src/main/java/org/apache/tamaya/core/internal/PropertyConverterManager.java index 867553a..eb5fa92 100644 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/PropertyConverterManager.java +++ b/code/core/src/main/java/org/apache/tamaya/core/internal/PropertyConverterManager.java @@ -92,26 +92,28 @@ public class PropertyConverterManager { /** * Registers the default converters provided out of the box. */ + @SuppressWarnings({ "rawtypes", "unchecked" }) protected void initConverters() { - for (PropertyConverter conv : ServiceContextManager.getServiceContext().getServices(PropertyConverter.class)) { + for ( PropertyConverter conv : ServiceContextManager.getServiceContext().getServices(PropertyConverter.class)) { Type type = TypeLiteral.getGenericInterfaceTypeParameters(conv.getClass(), PropertyConverter.class)[0]; register(TypeLiteral.of(type), conv); } } /** - * Registers a ew converter instance. + * Registers a new converter instance. * * @param targetType the target type, not {@code null}. * @param converter the converter, not {@code null}. * @param <T> the type. */ + @SuppressWarnings("unchecked") public <T> void register(TypeLiteral<T> targetType, PropertyConverter<T> converter) { Objects.requireNonNull(converter); Lock writeLock = lock.writeLock(); try { writeLock.lock(); - List converters = List.class.cast(this.converters.get(targetType)); + List<PropertyConverter<?>> converters = List.class.cast(this.converters.get(targetType)); if(converters!=null && converters.contains(converter)){ return; } @@ -194,12 +196,12 @@ public class PropertyConverterManager { /** * Get the list of all current registered converters for the given target type. * If not converters are registered, they component tries to create and register a dynamic - * converter based on String costructor or static factory methods available. + * converter based on String constructor or static factory methods available. * The converters provided are of the following type and returned in the following order: * <ul> * <li>Converters mapped explicitly to the required target type are returned first, ordered * by decreasing priority. This means, if explicit converters are registered these are used - * primarly for converting a value.</li> + * primarily for converting a value.</li> * <li>The target type of each explicitly registered converter also can be transitively mapped to * 1) all directly implemented interfaces, 2) all its superclasses (except Object), 3) all the interfaces * implemented by its superclasses. These groups of transitive converters is returned similarly in the @@ -219,10 +221,10 @@ public class PropertyConverterManager { * @return the ordered list of converters (may be empty for not convertible types). * @see #createDefaultPropertyConverter(org.apache.tamaya.TypeLiteral) */ - public <T> List<PropertyConverter<T>> getPropertyConverters(TypeLiteral<T> targetType) { + @SuppressWarnings("unchecked") + public <T> List<PropertyConverter<T>> getPropertyConverters(TypeLiteral<T> targetType) { Lock readLock = lock.readLock(); List<PropertyConverter<T>> converterList = new ArrayList<>(); - List<PropertyConverter<T>> converters; // direct mapped converters try { readLock.lock(); @@ -285,7 +287,8 @@ public class PropertyConverterManager { * @param <T> the type * @return the boxed type, or null. */ - private <T> TypeLiteral<T> mapBoxedType(TypeLiteral<T> targetType) { + @SuppressWarnings("unchecked") + private <T> TypeLiteral<T> mapBoxedType(TypeLiteral<T> targetType) { Type parameterType = targetType.getType(); if (parameterType == int.class) { return TypeLiteral.class.cast(TypeLiteral.of(Integer.class)); @@ -359,7 +362,7 @@ public class PropertyConverterManager { try { constr = targetType.getRawType().getDeclaredConstructor(String.class); } catch (NoSuchMethodException e) { - LOG.log(Level.FINEST, "No matching constrctor for " + targetType, e); + LOG.log(Level.FINEST, "No matching constructor for " + targetType, e); return null; } converter = new PropertyConverter<T>() { @@ -418,7 +421,6 @@ public class PropertyConverterManager { PropertyConverterManager that = (PropertyConverterManager) o; return converters.equals(that.converters); - } @Override @@ -442,8 +444,7 @@ public class PropertyConverterManager { if (!Modifier.isStatic(factoryMethod.getModifiers())) { throw new ConfigException(factoryMethod.toGenericString() + - " is not a static method. Only static " + - "methods can be used as factory methods."); + " is not a static method. Only static methods can be used as factory methods."); } try { AccessController.doPrivileged(new PrivilegedAction<Object>() { http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9f0e1ddc/code/core/src/main/java/org/apache/tamaya/core/internal/PropertySourceComparator.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/PropertySourceComparator.java b/code/core/src/main/java/org/apache/tamaya/core/internal/PropertySourceComparator.java index 64e245d..20ca097 100644 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/PropertySourceComparator.java +++ b/code/core/src/main/java/org/apache/tamaya/core/internal/PropertySourceComparator.java @@ -19,17 +19,10 @@ package org.apache.tamaya.core.internal; import org.apache.tamaya.spi.PropertySource; -import org.apache.tamaya.spi.PropertyValue; import javax.annotation.Priority; import java.io.Serializable; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; import java.util.Comparator; -import java.util.logging.Level; -import java.util.logging.Logger; /** * Comparator for ordering of PropertySources based on their ordinal method and class name. @@ -38,8 +31,6 @@ public class PropertySourceComparator implements Comparator<PropertySource>, Ser private static final long serialVersionUID = 1L; - private static final Logger LOG = Logger.getLogger(PropertySourceComparator.class.getName()); - private static final PropertySourceComparator INSTANCE = new PropertySourceComparator(); /** Singleton constructor. */ @@ -54,7 +45,7 @@ public class PropertySourceComparator implements Comparator<PropertySource>, Ser } /** - * Order property source reversely, the most important come first. + * Order property source reversely, the most important comes first. * * @param source1 the first PropertySource * @param source2 the second PropertySource @@ -71,63 +62,20 @@ public class PropertySourceComparator implements Comparator<PropertySource>, Ser } /** - * Evaluates an ordinal value from a {@link PropertySource}, Herey the ordinal of type {@code int} + * Evaluates an ordinal value from a {@link PropertySource}, Hereby the ordinal of type {@code int} * is evaluated as follows: * <ol> * <li>It evaluates the {@code String} value for {@link PropertySource#TAMAYA_ORDINAL} and tries * to convert it to an {@code int} value, using {@link Integer#parseInt(String)}.</li> * <li>It tries to find and evaluate a method {@code int getOrdinal()}.</li> * <li>It tries to find and evaluate a static field {@code int ORDINAL}.</li> - * <li>It tries to find an d evaluate a class level {@link Priority} annotation.</li> + * <li>It tries to find and evaluate a class level {@link Priority} annotation.</li> * <li>It uses the default priority ({@code 0}.</li> * </ol> * @param propertySource the property source, not {@code null}. * @return the ordinal value to compare the property source. */ public static int getOrdinal(PropertySource propertySource) { -// PropertyValue ordinalValue = propertySource.get(PropertySource.TAMAYA_ORDINAL); -// if(ordinalValue!=null){ -// try{ -// return Integer.parseInt(ordinalValue.getProperty().trim()); -// }catch(Exception e){ -// LOG.finest("Failed to parse ordinal from " + PropertySource.TAMAYA_ORDINAL + -// " in " + propertySource.getName()+": "+ordinalValue.getProperty()); -// } -// } -// try { -// Method method = propertySource.getClass().getMethod("getOrdinal"); -// if(int.class.equals(method.getReturnType())){ -// if(!method.isAccessible()){ -// method.setAccessible(true); -// } -// try { -// return (int)method.invoke(propertySource); -// } catch (Exception e) { -// LOG.log(Level.FINEST, "Error calling 'int getOrdinal()' on " + propertySource.getName(), e); -// } -// } -// } catch (NoSuchMethodException e) { -// LOG.finest("No 'int getOrdinal()' method found in " + propertySource.getName()); -// } -// try { -// Field field = propertySource.getClass().getField("ORDINAL"); -// if(int.class.equals(field.getType()) && Modifier.isStatic(field.getModifiers())){ -// if(!field.isAccessible()){ -// field.setAccessible(true); -// } -// try { -// return (int)field.get(propertySource); -// } catch (Exception e) { -// LOG.log(Level.FINEST, "Error evaluating 'int ORDINAL' on " + propertySource.getName(), e); -// } -// } -// } catch (NoSuchFieldException e) { -// LOG.finest("No 'int ORDINAL' field found in " + propertySource.getName()); -// } -// Priority prio = propertySource.getClass().getAnnotation(Priority.class); -// if(prio!=null){ -// return prio.value(); -// } return propertySource.getOrdinal(); } http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/9f0e1ddc/code/core/src/main/java/org/apache/tamaya/core/internal/WrappedPropertySource.java ---------------------------------------------------------------------- diff --git a/code/core/src/main/java/org/apache/tamaya/core/internal/WrappedPropertySource.java b/code/core/src/main/java/org/apache/tamaya/core/internal/WrappedPropertySource.java index 32bb12b..34f4361 100644 --- a/code/core/src/main/java/org/apache/tamaya/core/internal/WrappedPropertySource.java +++ b/code/core/src/main/java/org/apache/tamaya/core/internal/WrappedPropertySource.java @@ -105,7 +105,6 @@ class WrappedPropertySource implements PropertySource{ WrappedPropertySource that = (WrappedPropertySource) o; return getDelegate().getName().equals(that.getDelegate().getName()); - } @Override @@ -123,6 +122,4 @@ class WrappedPropertySource implements PropertySource{ ", delegate-class=" + delegate.getClass().getName() + '}'; } - - }
