http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/b56817f7/dormant/core/src/main/java/org/apache/tamaya/core/internal/inject/ConfiguredType.java ---------------------------------------------------------------------- diff --git a/dormant/core/src/main/java/org/apache/tamaya/core/internal/inject/ConfiguredType.java b/dormant/core/src/main/java/org/apache/tamaya/core/internal/inject/ConfiguredType.java deleted file mode 100644 index 879d54a..0000000 --- a/dormant/core/src/main/java/org/apache/tamaya/core/internal/inject/ConfiguredType.java +++ /dev/null @@ -1,222 +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.inject; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.*; - -import org.apache.tamaya.core.properties.PropertyChangeSet; -import org.apache.tamaya.ConfigException; -import org.apache.tamaya.Configuration; -import org.apache.tamaya.PropertySource; -import org.apache.tamaya.annotation.*; -import org.apache.tamaya.core.internal.Utils; - -/** - * Structure that contains and manages configuration related things for a configured type registered. - * Created by Anatole on 03.10.2014. - */ -@SuppressWarnings({"rawtypes", "unchecked"}) -public class ConfiguredType { - /** - * A list with all annotated instance variables. - */ - private List<ConfiguredField> configuredFields = new ArrayList<>(); - /** - * A list with all annotated methods (templates). - */ - private List<ConfiguredSetterMethod> configuredSetterMethods = new ArrayList<>(); - /** - * A list with all callback methods listening to config changes. - */ - private List<ConfigChangeCallbackMethod> callbackMethods = new ArrayList<>(); - /** - * The basic type. - */ - private Class type; - - /** - * Creates an instance of this class hereby evaluating the config annotations given for later effective - * injection (configuration) of instances. - * - * @param type the instance type. - */ - - public ConfiguredType(Class type) { - this.type = Objects.requireNonNull(type); - initFields(type); - initMethods(type); - } - - private void initFields(Class type) { - for (Field f : type.getDeclaredFields()) { - if (f.isAnnotationPresent(NoConfig.class)) { - continue; - } - try { - ConfiguredField configuredField = new ConfiguredField(f); - configuredFields.add(configuredField); - } catch (Exception e) { - throw new ConfigException("Failed to initialized configured field: " + - f.getDeclaringClass().getName() + '.' + f.getName(), e); - } - } - } - - private void initMethods(Class type) { - // TODO revisit this logic here... - for (Method m : type.getDeclaredMethods()) { - if (m.isAnnotationPresent(NoConfig.class)) { - continue; - } - ObservesConfigChange mAnnot = m.getAnnotation(ObservesConfigChange.class); - Collection<ConfiguredProperty> propertiesAnnots = Utils.getAnnotations(m, ConfiguredProperty.class, ConfiguredProperties.class); - if (type.isInterface()) { - // it is a template - if (mAnnot != null) { - if (m.isDefault()) { - addObserverMethod(m); - } - } else { - if (m.isDefault()) { - addPropertySetter(m, propertiesAnnots); - } - } - } else { - if (mAnnot != null) { - addObserverMethod(m); - } else { - addPropertySetter(m, propertiesAnnots); - } - } - } - } - - private boolean addPropertySetter(Method m, Collection<ConfiguredProperty> propertiesAnnots) { - if (!propertiesAnnots.isEmpty()) { - if (m.getParameterTypes().length == 0) { - // getter method - Class<?> returnType = m.getReturnType(); - if (!void.class.equals(returnType)) { - try { - configuredSetterMethods.add(new ConfiguredSetterMethod(m)); - return true; - } catch (Exception e) { - throw new ConfigException("Failed to initialized configured setter method: " + - m.getDeclaringClass().getName() + '.' + m.getName(), e); - } - } - } - } - return false; - } - - - - private void addObserverMethod(Method m) { - if (m.getParameterTypes().length != 1) { - return; - } - if (!m.getParameterTypes()[0].equals(PropertyChangeSet.class)) { - return; - } - if (!void.class.equals(m.getReturnType())) { - return; - } - try { - this.callbackMethods.add(new ConfigChangeCallbackMethod(m)); - } catch (Exception e) { - throw new ConfigException("Failed to initialized configured callback method: " + - m.getDeclaringClass().getName() + '.' + m.getName(), e); - } - } - - - /** - * Method called to configure an instance. - * - * @param instance The instance to be configured. - * @param configurations Configuration instances that replace configuration served by services. This allows - * more easily testing and adaption. - */ - public void configure(Object instance, Configuration... configurations) { - for (ConfiguredField field : configuredFields) { - field.applyInitialValue(instance, configurations); - } - for (ConfiguredSetterMethod method : configuredSetterMethods) { - method.applyInitialValue(instance, configurations); - // TODO, if method should be recalled on changes, corresponding callbacks could be registered here - WeakConfigListenerManager.of().registerConsumer(instance, method.createConsumer(instance, configurations)); - } - // Register callbacks for this intance (weakly) - for (ConfigChangeCallbackMethod callback : callbackMethods) { - WeakConfigListenerManager.of().registerConsumer(instance, callback.createConsumer(instance, configurations)); - } - } - - - private String getName(Object source) { - if (source instanceof PropertySource) { - PropertySource ps = (PropertySource) source; - return ps.getName(); - } - return "N/A"; - } - - - public boolean isConfiguredBy(Configuration configuration) { - // TODO implement this - return true; - } - - public static boolean isConfigured(Class type) { - if (type.getAnnotation(DefaultAreas.class) != null) { - return true; - } - // if no class level annotation is there we might have field level annotations only - for (Field field : type.getDeclaredFields()) { - if (field.isAnnotationPresent(ConfiguredProperties.class)) { - return true; - } - } - // if no class level annotation is there we might have method level annotations only - for (Method method : type.getDeclaredMethods()) { - if (method.isAnnotationPresent(ConfiguredProperties.class)) { - return true; - } - } - for (Field field : type.getDeclaredFields()) { - if (field.isAnnotationPresent(ConfiguredProperty.class)) { - return true; - } - } - // if no class level annotation is there we might have method level annotations only - for (Method method : type.getDeclaredMethods()) { - if (method.isAnnotationPresent(ConfiguredProperty.class)) { - return true; - } - } - return false; - } - - public Class getType() { - return this.type; - } -}
http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/b56817f7/dormant/core/src/main/java/org/apache/tamaya/core/internal/inject/InjectionUtils.java ---------------------------------------------------------------------- diff --git a/dormant/core/src/main/java/org/apache/tamaya/core/internal/inject/InjectionUtils.java b/dormant/core/src/main/java/org/apache/tamaya/core/internal/inject/InjectionUtils.java deleted file mode 100644 index d80ee80..0000000 --- a/dormant/core/src/main/java/org/apache/tamaya/core/internal/inject/InjectionUtils.java +++ /dev/null @@ -1,221 +0,0 @@ -package org.apache.tamaya.core.internal.inject; - -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.Field; -import java.lang.reflect.Member; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.ListIterator; - -import org.apache.tamaya.ConfigException; -import org.apache.tamaya.Configuration; -import org.apache.tamaya.PropertyAdapter; -import org.apache.tamaya.annotation.*; -import org.apache.tamaya.annotation.WithPropertyAdapter; -import org.apache.tamaya.core.internal.Utils; -import org.apache.tamaya.spi.PropertyAdapterSpi; - -/** - * Created by Anatole on 19.12.2014. - */ -@SuppressWarnings("unchecked") -final class InjectionUtils { - - private InjectionUtils(){} - - /** - * This method evaluates the {@link org.apache.tamaya.Configuration} that currently is valid for the given target field/method. - * - * @return the {@link org.apache.tamaya.Configuration} instance to be used, never null. - */ - public static Configuration getConfiguration(ConfiguredProperty prop, Configuration... configuration) { - String name = prop.config(); - if (name != null && !name.trim().isEmpty()) { - return Configuration.current(name.trim()); - } - return Configuration.current(); - } - - /** - * Evaluates all absolute configuration key based on the annotations found on a class. - * - * @param areasAnnot the (optional) annotation definining areas to be looked up. - * @param propertyAnnotation the annotation on field/method level that may defined one or - * several keys to be looked up (in absolute or relative form). - * @return the list current keys in order how they should be processed/looked up. - */ - public static List<String> evaluateKeys(Member member, DefaultAreas areasAnnot, ConfiguredProperty propertyAnnotation) { - List<String> keys = new ArrayList<>(Arrays.asList(propertyAnnotation.keys())); - if (keys.isEmpty()) //noinspection UnusedAssignment - keys.add(member.getName()); - ListIterator<String> iterator = keys.listIterator(); - while (iterator.hasNext()) { - String next = iterator.next(); - if (next.startsWith("[") && next.endsWith("]")) { - // absolute key, strip away brackets, take key as is - iterator.set(next.substring(1, next.length() - 1)); - } else { - if (areasAnnot != null) { - // Remove original entry, since it will be replaced with prefixed entries - iterator.remove(); - // Add prefixed entries, including absolute (root) entry for "" area keys. - for (String area : areasAnnot.value()) { - iterator.add(area.isEmpty() ? next : area + '.' + next); - } - } - } - } - return keys; - } - - /** - * Evaluates all absolute configuration key based on the member name found. - * - * @param areasAnnot the (optional) annotation definining areas to be looked up. - * @return the list current keys in order how they should be processed/looked up. - */ - public static List<String> evaluateKeys(Member member, DefaultAreas areasAnnot) { - List<String> keys = new ArrayList<>(); - String name = member.getName(); - String mainKey; - if(name.startsWith("get") || name.startsWith("set")){ - mainKey = Character.toLowerCase(name.charAt(3)) + name.substring(4); - } - else{ - mainKey = Character.toLowerCase(name.charAt(0)) + name.substring(1); - } - keys.add(mainKey); - if (areasAnnot != null) { - // Add prefixed entries, including absolute (root) entry for "" area keys. - for (String area : areasAnnot.value()) { - if(!area.isEmpty()) { - keys.add(area + '.' + mainKey); - } - } - } - else{ // add package name - keys.add(member.getDeclaringClass().getName()+'.'+mainKey); - } - return keys; - } - - /** - * Internally evaluated the current valid configuration keys based on the given annotations present. - * - * @return the keys to be returned, or null. - */ - public static String getConfigValue(Method method, Configuration... configurations) { - DefaultAreas areasAnnot = method.getDeclaringClass().getAnnotation(DefaultAreas.class); - WithLoadPolicy loadPolicy = Utils.getAnnotation(WithLoadPolicy.class, method, method.getDeclaringClass()); - return getConfigValueInternal(method, areasAnnot, loadPolicy, configurations); - } - - - /** - * Internally evaluated the current valid configuration keys based on the given annotations present. - * - * @return the keys to be returned, or null. - */ - public static String getConfigValue(Field field, Configuration... configurations) { - DefaultAreas areasAnnot = field.getDeclaringClass().getAnnotation(DefaultAreas.class); - WithLoadPolicy loadPolicy = Utils.getAnnotation(WithLoadPolicy.class, field, field.getDeclaringClass()); - return getConfigValueInternal(field, areasAnnot, loadPolicy, configurations); - } - - /** - * Internally evaluated the current valid configuration keys based on the given annotations present. - * - * @return the keys to be returned, or null. - */ - private static String getConfigValueInternal(AnnotatedElement element, DefaultAreas areasAnnot, WithLoadPolicy loadPolicy, Configuration... configurations) { - Collection<ConfiguredProperty> configuredProperties = Utils.getAnnotations( - element, ConfiguredProperty.class, ConfiguredProperties.class); - DefaultValue defaultAnnot = element.getAnnotation(DefaultValue.class); - String configValue = null; - if(configuredProperties.isEmpty()){ - List<String> keys = InjectionUtils.evaluateKeys((Member)element, areasAnnot); - Configuration config = InjectionUtils.getConfiguration("default", configurations); - configValue = evaluteConfigValue(configValue, keys, config); - } - else { - for (ConfiguredProperty prop : configuredProperties) { - List<String> keys = InjectionUtils.evaluateKeys((Member) element, areasAnnot, prop); - Configuration config = InjectionUtils.getConfiguration(prop, configurations); - configValue = evaluteConfigValue(configValue, keys, config); - } - } - if (configValue == null && defaultAnnot != null) { - return defaultAnnot.value(); - } - return configValue; - } - - private static String evaluteConfigValue(String configValue, List<String> keys, Configuration config) { - for (String key : keys) { - configValue = config.get(key).orElse(null); - if (configValue != null) { - break; - } - } - if (configValue != null) { - // net step perform expression resolution, if any - configValue = Configuration.evaluateValue(configValue, config); - } - return configValue; - } - - - @SuppressWarnings("rawtypes") - public static <T> T adaptValue(AnnotatedElement element, Class<T> targetType, String configValue){ - try { - // Check for adapter/filter -// T adaptedValue = null; - WithPropertyAdapter codecAnnot = element.getAnnotation(WithPropertyAdapter.class); - Class<? extends PropertyAdapter> codecType; - if (codecAnnot != null) { - codecType = codecAnnot.value(); - if (!codecType.equals(PropertyAdapter.class)) { - // TODO cache here... -// Codec<String> codec = codecType.newInstance(); -// adaptedValue = (T) codec.adapt(configValue); - } - } - if (String.class.equals(targetType)) { - return (T)configValue; - } else { - PropertyAdapter<?> adapter = PropertyAdapter.getInstance(targetType); - return (T)adapter.adapt(configValue); - } - } catch (Exception e) { - throw new ConfigException("Failed to annotate configured member: " + element, e); - } - } - - /** - * This method evaluates the {@link Configuration} that currently is valid for the given target field/method. - * @param configurations Configuration instances that replace configuration served by services. This allows - * more easily testing and adaption. - * @return the {@link Configuration} instance to be used, never null. - */ - public static Configuration getConfiguration(String name, Configuration... configurations) { - if(name!=null) { - for(Configuration conf: configurations){ - if(name.equals(conf.getName())){ - return conf; - } - } - return Configuration.current(name); - } - else{ - for(Configuration conf: configurations){ - if("default".equals(conf.getName())){ - return conf; - } - } - } - return Configuration.current(); - } -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/b56817f7/dormant/core/src/main/java/org/apache/tamaya/core/internal/inject/WeakConfigListenerManager.java ---------------------------------------------------------------------- diff --git a/dormant/core/src/main/java/org/apache/tamaya/core/internal/inject/WeakConfigListenerManager.java b/dormant/core/src/main/java/org/apache/tamaya/core/internal/inject/WeakConfigListenerManager.java deleted file mode 100644 index e9b9ec3..0000000 --- a/dormant/core/src/main/java/org/apache/tamaya/core/internal/inject/WeakConfigListenerManager.java +++ /dev/null @@ -1,117 +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.inject; - -import org.apache.tamaya.core.properties.PropertyChangeSet; - -import java.util.Map; -import java.util.WeakHashMap; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.StampedLock; -import java.util.function.Consumer; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Simple listener container that only holds weak references on the listeners. - */ -public final class WeakConfigListenerManager{ - - private static final WeakConfigListenerManager INSTANCE = new WeakConfigListenerManager(); - - private static final Logger LOG = Logger.getLogger(WeakConfigListenerManager.class.getName()); - private StampedLock lock = new StampedLock(); - private Map<Object,Consumer<PropertyChangeSet>> listenerReferences = new WeakHashMap<>(); - - /** Private singleton constructor. */ - private WeakConfigListenerManager(){} - - public static WeakConfigListenerManager of(){ - return INSTANCE; - } - - /** - * Registers the given consumer for the instance. If a consumer already exists for this instance the given - * consumer is appended. - * @param instance the instance, not null. - * @param listener the consumer. - */ - public void registerConsumer(Object instance, Consumer<PropertyChangeSet> listener){ - Lock writeLock = lock.asWriteLock(); - try { - writeLock.lock(); - Consumer<PropertyChangeSet> l = listenerReferences.get(instance); - if (l == null) { - listenerReferences.put(instance, listener); - } else { - listenerReferences.put(instance, l.andThen(listener)); - } - } - finally{ - writeLock.unlock(); - } - } - - /** - * Unregisters all consumers for the given instance. - * @param instance the instance, not null. - */ - public void unregisterConsumer(Object instance) { - Lock writeLock = lock.asWriteLock(); - try { - writeLock.lock(); - listenerReferences.remove(instance); - } - finally{ - writeLock.unlock(); - } - } - - /** - * Publishes a change event to all consumers registered. - * @param change the change event, not null. - */ - public void publishChangeEvent(PropertyChangeSet change){ - Lock readLock = lock.asReadLock(); - try{ - readLock.lock(); - listenerReferences.values().parallelStream().forEach(l -> { - try{ - l.accept(change); - } - catch(Exception e){ - LOG.log(Level.SEVERE, "ConfigChangeListener failed: " + l.getClass().getName(), e); - } - }); - } - finally{ - readLock.unlock(); - } - } - - - @Override - public String toString(){ - return "WeakConfigListenerManager{" + - "listenerReferences=" + listenerReferences + - '}'; - } - - -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/b56817f7/dormant/core/src/main/java/org/apache/tamaya/core/internal/logging/AbstractDelegatingLogger.java ---------------------------------------------------------------------- diff --git a/dormant/core/src/main/java/org/apache/tamaya/core/internal/logging/AbstractDelegatingLogger.java b/dormant/core/src/main/java/org/apache/tamaya/core/internal/logging/AbstractDelegatingLogger.java deleted file mode 100644 index cc0ac45..0000000 --- a/dormant/core/src/main/java/org/apache/tamaya/core/internal/logging/AbstractDelegatingLogger.java +++ /dev/null @@ -1,411 +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.logging; - -import java.text.MessageFormat; -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.ResourceBundle; -import java.util.logging.*; - -/** - * java.util.logging.Logger implementation delegating to another framework. - * All methods can be used except: - * setLevel - * addHandler / getHandlers - * setParent / getParent - * setUseParentHandlers / getUseParentHandlers - * - * @author gnodet - */ -public abstract class AbstractDelegatingLogger extends Logger { - - protected AbstractDelegatingLogger(final String name, final String resourceBundleName) { - super(name, resourceBundleName); - } - - public void log(final LogRecord record) { - if (isLoggable(record.getLevel())) { - doLog(record); - } - } - - public void log(final Level level, final String msg) { - if (isLoggable(level)) { - final LogRecord lr = new LogRecord(level, msg); - doLog(lr); - } - } - - public void log(final Level level, final String msg, final Object param1) { - if (isLoggable(level)) { - final LogRecord lr = new LogRecord(level, msg); - final Object[] params = {param1}; - lr.setParameters(params); - doLog(lr); - } - } - - public void log(final Level level, final String msg, final Object[] params) { - if (isLoggable(level)) { - final LogRecord lr = new LogRecord(level, msg); - lr.setParameters(params); - doLog(lr); - } - } - - public void log(final Level level, final String msg, final Throwable thrown) { - if (isLoggable(level)) { - final LogRecord lr = new LogRecord(level, msg); - lr.setThrown(thrown); - doLog(lr); - } - } - - public void logp(final Level level, final String sourceClass, final String sourceMethod, final String msg) { - if (isLoggable(level)) { - final LogRecord lr = new LogRecord(level, msg); - lr.setSourceClassName(sourceClass); - lr.setSourceMethodName(sourceMethod); - doLog(lr); - } - } - - public void logp(final Level level, final String sourceClass, final String sourceMethod, final String msg, final Object param1) { - if (isLoggable(level)) { - final LogRecord lr = new LogRecord(level, msg); - lr.setSourceClassName(sourceClass); - lr.setSourceMethodName(sourceMethod); - final Object[] params = {param1}; - lr.setParameters(params); - doLog(lr); - } - } - - public void logp(final Level level, final String sourceClass, final String sourceMethod, final String msg, final Object[] params) { - if (isLoggable(level)) { - final LogRecord lr = new LogRecord(level, msg); - lr.setSourceClassName(sourceClass); - lr.setSourceMethodName(sourceMethod); - lr.setParameters(params); - doLog(lr); - } - } - - public void logp(final Level level, final String sourceClass, final String sourceMethod, final String msg, final Throwable thrown) { - if (isLoggable(level)) { - final LogRecord lr = new LogRecord(level, msg); - lr.setSourceClassName(sourceClass); - lr.setSourceMethodName(sourceMethod); - lr.setThrown(thrown); - doLog(lr); - } - } - - public void logrb(final Level level, final String sourceClass, final String sourceMethod, final String bundleName, final String msg) { - if (isLoggable(level)) { - final LogRecord lr = new LogRecord(level, msg); - lr.setSourceClassName(sourceClass); - lr.setSourceMethodName(sourceMethod); - doLog(lr, bundleName); - } - } - - public void logrb(final Level level, final String sourceClass, final String sourceMethod, - final String bundleName, final String msg, final Object param1) { - if (isLoggable(level)) { - final LogRecord lr = new LogRecord(level, msg); - lr.setSourceClassName(sourceClass); - lr.setSourceMethodName(sourceMethod); - final Object[] params = {param1}; - lr.setParameters(params); - doLog(lr, bundleName); - } - } - - public void logrb(final Level level, final String sourceClass, final String sourceMethod, - final String bundleName, final String msg, final Object[] params) { - if (isLoggable(level)) { - final LogRecord lr = new LogRecord(level, msg); - lr.setSourceClassName(sourceClass); - lr.setSourceMethodName(sourceMethod); - lr.setParameters(params); - doLog(lr, bundleName); - } - } - - public void logrb(final Level level, final String sourceClass, final String sourceMethod, - final String bundleName, final String msg, final Throwable thrown) { - if (isLoggable(level)) { - final LogRecord lr = new LogRecord(level, msg); - lr.setSourceClassName(sourceClass); - lr.setSourceMethodName(sourceMethod); - lr.setThrown(thrown); - doLog(lr, bundleName); - } - } - - public void entering(final String sourceClass, final String sourceMethod) { - if (isLoggable(Level.FINER)) { - logp(Level.FINER, sourceClass, sourceMethod, "ENTRY"); - } - } - - public void entering(final String sourceClass, final String sourceMethod, final Object param1) { - if (isLoggable(Level.FINER)) { - final Object[] params = {param1}; - logp(Level.FINER, sourceClass, sourceMethod, "ENTRY {0}", params); - } - } - - public void entering(final String sourceClass, final String sourceMethod, final Object[] params) { - if (isLoggable(Level.FINER)) { - final String msg = "ENTRY"; - if (params == null) { - logp(Level.FINER, sourceClass, sourceMethod, msg); - return; - } - final StringBuilder builder = new StringBuilder(msg); - for (int i = 0; i < params.length; i++) { - builder.append(" {"); - builder.append(Integer.toString(i)); - builder.append("}"); - } - logp(Level.FINER, sourceClass, sourceMethod, builder.toString(), params); - } - } - - public void exiting(final String sourceClass, final String sourceMethod) { - if (isLoggable(Level.FINER)) { - logp(Level.FINER, sourceClass, sourceMethod, "RETURN"); - } - } - - public void exiting(final String sourceClass, final String sourceMethod, final Object result) { - if (isLoggable(Level.FINER)) { - final Object[] params = {result}; - logp(Level.FINER, sourceClass, sourceMethod, "RETURN {0}", params); - } - } - - public void throwing(final String sourceClass, final String sourceMethod, final Throwable thrown) { - if (isLoggable(Level.FINER)) { - final LogRecord lr = new LogRecord(Level.FINER, "THROW"); - lr.setSourceClassName(sourceClass); - lr.setSourceMethodName(sourceMethod); - lr.setThrown(thrown); - doLog(lr); - } - } - - public void severe(final String msg) { - if (isLoggable(Level.SEVERE)) { - final LogRecord lr = new LogRecord(Level.SEVERE, msg); - doLog(lr); - } - } - - public void warning(final String msg) { - if (isLoggable(Level.WARNING)) { - final LogRecord lr = new LogRecord(Level.WARNING, msg); - doLog(lr); - } - } - - public void info(final String msg) { - if (isLoggable(Level.INFO)) { - final LogRecord lr = new LogRecord(Level.INFO, msg); - doLog(lr); - } - } - - public void config(final String msg) { - if (isLoggable(Level.CONFIG)) { - final LogRecord lr = new LogRecord(Level.CONFIG, msg); - doLog(lr); - } - } - - public void fine(final String msg) { - if (isLoggable(Level.FINE)) { - final LogRecord lr = new LogRecord(Level.FINE, msg); - doLog(lr); - } - } - - public void finer(final String msg) { - if (isLoggable(Level.FINER)) { - final LogRecord lr = new LogRecord(Level.FINER, msg); - doLog(lr); - } - } - - public void finest(final String msg) { - if (isLoggable(Level.FINEST)) { - final LogRecord lr = new LogRecord(Level.FINEST, msg); - doLog(lr); - } - } - - public void setLevel(final Level newLevel) throws SecurityException { - throw new UnsupportedOperationException(); - } - - public abstract Level getLevel(); - - public boolean isLoggable(final Level level) { - final Level l = getLevel(); - return level.intValue() >= l.intValue() && l != Level.OFF; - } - - protected boolean supportsHandlers() { - return false; - } - - public synchronized void addHandler(final Handler handler) throws SecurityException { - if (supportsHandlers()) { - super.addHandler(handler); - return; - } - throw new UnsupportedOperationException(); - } - - public synchronized void removeHandler(final Handler handler) throws SecurityException { - if (supportsHandlers()) { - super.removeHandler(handler); - return; - } - throw new UnsupportedOperationException(); - } - - public synchronized Handler[] getHandlers() { - if (supportsHandlers()) { - return super.getHandlers(); - } - throw new UnsupportedOperationException(); - } - - public synchronized void setUseParentHandlers(final boolean useParentHandlers) { - if (supportsHandlers()) { - super.setUseParentHandlers(useParentHandlers); - return; - } - throw new UnsupportedOperationException(); - } - - public synchronized boolean getUseParentHandlers() { - if (supportsHandlers()) { - return super.getUseParentHandlers(); - } - throw new UnsupportedOperationException(); - } - - public Logger getParent() { - return null; - } - - public void setParent(final Logger parent) { - throw new UnsupportedOperationException(); - } - - protected void doLog(final LogRecord lr) { - lr.setLoggerName(getName()); - final String rbname = getResourceBundleName(); - if (rbname != null) { - lr.setResourceBundleName(rbname); - lr.setResourceBundle(getResourceBundle()); - } - internalLog(lr); - } - - protected void doLog(final LogRecord lr, final String rbname) { - lr.setLoggerName(getName()); - if (rbname != null) { - lr.setResourceBundleName(rbname); - lr.setResourceBundle(loadResourceBundle(rbname)); - } - internalLog(lr); - } - - protected void internalLog(final LogRecord record) { - final Filter filter = getFilter(); - if (filter != null && !filter.isLoggable(record)) { - return; - } - final String msg = formatMessage(record); - internalLogFormatted(msg, record); - } - - protected abstract void internalLogFormatted(String msg, LogRecord record); - - protected String formatMessage(final LogRecord record) { - String format = record.getMessage(); - final ResourceBundle catalog = record.getResourceBundle(); - if (catalog != null) { - try { - format = catalog.getString(record.getMessage()); - } catch (final MissingResourceException ex) { - format = record.getMessage(); - } - } - try { - final Object[] parameters = record.getParameters(); - if (parameters == null || parameters.length == 0) { - return format; - } - if (format.contains("{0") || format.contains("{1") - || format.contains("{2") || format.contains("{3")) { - return MessageFormat.format(format, parameters); - } - return format; - } catch (final Exception ex) { - return format; - } - } - - /** - * Load the specified resource bundle - * - * @param resourceBundleName the name current the resource bundle to load, cannot be null - * @return the loaded resource bundle. - * @throws MissingResourceException If the specified resource bundle can not be loaded. - */ - static ResourceBundle loadResourceBundle(final String resourceBundleName) { - // try context class loader to load the resource - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - if (null != cl) { - try { - return ResourceBundle.getBundle(resourceBundleName, Locale.getDefault(), cl); - } catch (final MissingResourceException e) { - // Failed to load using context classloader, ignore - } - } - // try system class loader to load the resource - cl = ClassLoader.getSystemClassLoader(); - if (null != cl) { - try { - return ResourceBundle.getBundle(resourceBundleName, Locale.getDefault(), cl); - } catch (final MissingResourceException e) { - // Failed to load using system classloader, ignore - } - } - return null; - } - -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/b56817f7/dormant/core/src/main/java/org/apache/tamaya/core/internal/logging/Log4j2Logger.java ---------------------------------------------------------------------- diff --git a/dormant/core/src/main/java/org/apache/tamaya/core/internal/logging/Log4j2Logger.java b/dormant/core/src/main/java/org/apache/tamaya/core/internal/logging/Log4j2Logger.java deleted file mode 100644 index 35ae4ab..0000000 --- a/dormant/core/src/main/java/org/apache/tamaya/core/internal/logging/Log4j2Logger.java +++ /dev/null @@ -1,97 +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.logging; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.LogRecord; - -public class Log4j2Logger extends AbstractDelegatingLogger { - private static final Map<Level, org.apache.logging.log4j.Level> TO_LOG4J = new HashMap<>(); - - private final Logger log; - - static { - //older versions current log4j don't have TRACE, use debug -// org.apache.logging.log4j.Level t = org.apache.logging.log4j.Level.DEBUG; - - TO_LOG4J.put(Level.ALL, org.apache.logging.log4j.Level.ALL); - TO_LOG4J.put(Level.SEVERE, org.apache.logging.log4j.Level.ERROR); - TO_LOG4J.put(Level.WARNING, org.apache.logging.log4j.Level.WARN); - TO_LOG4J.put(Level.INFO, org.apache.logging.log4j.Level.INFO); - TO_LOG4J.put(Level.CONFIG, org.apache.logging.log4j.Level.DEBUG); - TO_LOG4J.put(Level.FINE, org.apache.logging.log4j.Level.DEBUG); - TO_LOG4J.put(Level.FINER, org.apache.logging.log4j.Level.TRACE); - TO_LOG4J.put(Level.FINEST, org.apache.logging.log4j.Level.TRACE); - TO_LOG4J.put(Level.OFF, org.apache.logging.log4j.Level.OFF); - } - - public Log4j2Logger(final String name, final String resourceBundleName) { - super(name, resourceBundleName); - log = LogManager.getLogger(name); - } - - public Level getLevel() { - final org.apache.logging.log4j.Level l = log.getLevel(); - if (l != null) { - return fromL4J(l); - } - return null; - } - - protected void internalLogFormatted(final String msg, final LogRecord record) { - log.log(TO_LOG4J.get(record.getLevel()), msg, record.getThrown()); - } - - - private Level fromL4J(final org.apache.logging.log4j.Level l) { - Level l2 = null; - switch (l.getStandardLevel()) { - case ALL: - l2 = Level.ALL; - break; - case FATAL: - l2 = Level.SEVERE; - break; - case ERROR: - l2 = Level.SEVERE; - break; - case WARN: - l2 = Level.WARNING; - break; - case INFO: - l2 = Level.INFO; - break; - case DEBUG: - l2 = Level.FINE; - break; - case OFF: - l2 = Level.OFF; - break; - case TRACE: - l2 = Level.FINEST; - break; - default: - l2 = Level.FINE; - } - return l2; - } -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/b56817f7/dormant/core/src/main/java/org/apache/tamaya/core/internal/logging/Log4jLogger.java ---------------------------------------------------------------------- diff --git a/dormant/core/src/main/java/org/apache/tamaya/core/internal/logging/Log4jLogger.java b/dormant/core/src/main/java/org/apache/tamaya/core/internal/logging/Log4jLogger.java deleted file mode 100644 index 224378c..0000000 --- a/dormant/core/src/main/java/org/apache/tamaya/core/internal/logging/Log4jLogger.java +++ /dev/null @@ -1,200 +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.logging; - -import org.apache.log4j.Appender; -import org.apache.log4j.AppenderSkeleton; -import org.apache.log4j.LogManager; -import org.apache.log4j.Logger; -import org.apache.log4j.Priority; -import org.apache.log4j.spi.LoggingEvent; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogRecord; - -/** - * java.util.logging.Logger implementation delegating to Log4j. - * All methods can be used except: - * setLevel - * addHandler / getHandlers - * setParent / getParent - * setUseParentHandlers / getUseParentHandlers - * - * @author gnodet - */ -public class Log4jLogger extends AbstractDelegatingLogger { - private static final Map<Level, org.apache.log4j.Level> TO_LOG4J = new HashMap<>(); - private static final org.apache.log4j.Level TRACE; - - private final Logger log; - - static { - //older versions current log4j don't have TRACE, use debug - org.apache.log4j.Level t = org.apache.log4j.Level.DEBUG; - try { - final Field f = org.apache.log4j.Level.class.getField("TRACE"); - t = (org.apache.log4j.Level) f.get(null); - } catch (final Throwable ex) { - //ignore, assume old version current log4j - } - TRACE = t; - - TO_LOG4J.put(Level.ALL, org.apache.log4j.Level.ALL); - TO_LOG4J.put(Level.SEVERE, org.apache.log4j.Level.ERROR); - TO_LOG4J.put(Level.WARNING, org.apache.log4j.Level.WARN); - TO_LOG4J.put(Level.INFO, org.apache.log4j.Level.INFO); - TO_LOG4J.put(Level.CONFIG, org.apache.log4j.Level.DEBUG); - TO_LOG4J.put(Level.FINE, org.apache.log4j.Level.DEBUG); - TO_LOG4J.put(Level.FINER, TRACE); - TO_LOG4J.put(Level.FINEST, TRACE); - TO_LOG4J.put(Level.OFF, org.apache.log4j.Level.OFF); - } - - public Log4jLogger(final String name, final String resourceBundleName) { - super(name, resourceBundleName); - log = LogManager.getLogger(name); - } - - public Level getLevel() { - final org.apache.log4j.Level l = log.getEffectiveLevel(); - if (l != null) { - return fromL4J(l); - } - return null; - } - - public void setLevel(final Level newLevel) throws SecurityException { - log.setLevel(TO_LOG4J.get(newLevel)); - } - - public synchronized void addHandler(final Handler handler) throws SecurityException { - log.addAppender(new HandlerWrapper(handler)); - } - - public synchronized void removeHandler(final Handler handler) throws SecurityException { - log.removeAppender("HandlerWrapper-" + handler.hashCode()); - } - - public synchronized Handler[] getHandlers() { - final List<Handler> ret = new ArrayList<>(); - final Enumeration<?> en = log.getAllAppenders(); - while (en.hasMoreElements()) { - final Appender ap = (Appender) en.nextElement(); - if (ap instanceof HandlerWrapper) { - ret.add(((HandlerWrapper) ap).getHandler()); - } - } - return ret.toArray(new Handler[ret.size()]); - } - - protected void internalLogFormatted(final String msg, final LogRecord record) { - log.log(AbstractDelegatingLogger.class.getName(), - TO_LOG4J.get(record.getLevel()), - msg, - record.getThrown()); - } - - - private Level fromL4J(final org.apache.log4j.Level l) { - Level l2 = null; - switch (l.toInt()) { - case org.apache.log4j.Level.ALL_INT: - l2 = Level.ALL; - break; - case org.apache.log4j.Level.FATAL_INT: - l2 = Level.SEVERE; - break; - case org.apache.log4j.Level.ERROR_INT: - l2 = Level.SEVERE; - break; - case org.apache.log4j.Level.WARN_INT: - l2 = Level.WARNING; - break; - case org.apache.log4j.Level.INFO_INT: - l2 = Level.INFO; - break; - case org.apache.log4j.Level.DEBUG_INT: - l2 = Level.FINE; - break; - case org.apache.log4j.Level.OFF_INT: - l2 = Level.OFF; - break; - default: - if (l.toInt() == TRACE.toInt()) { - l2 = Level.FINEST; - } - } - return l2; - } - - - private class HandlerWrapper extends AppenderSkeleton { - Handler handler; - - public HandlerWrapper(final Handler h) { - handler = h; - name = "HandlerWrapper-" + h.hashCode(); - } - - public Handler getHandler() { - return handler; - } - - @Override - protected void append(final LoggingEvent event) { - final LogRecord lr = new LogRecord(fromL4J(event.getLevel()), - event.getMessage().toString()); - lr.setLoggerName(event.getLoggerName()); - if (event.getThrowableInformation() != null) { - lr.setThrown(event.getThrowableInformation().getThrowable()); - } - final String rbname = getResourceBundleName(); - if (rbname != null) { - lr.setResourceBundleName(rbname); - lr.setResourceBundle(getResourceBundle()); - } - handler.publish(lr); - } - - public void close() { - handler.close(); - closed = true; - } - - public boolean requiresLayout() { - return false; - } - - @Override - public Priority getThreshold() { - return TO_LOG4J.get(handler.getLevel()); - } - - @Override - public boolean isAsSevereAsThreshold(final Priority priority) { - final Priority p = getThreshold(); - return p == null || priority.isGreaterOrEqual(p); - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/b56817f7/dormant/core/src/main/java/org/apache/tamaya/core/internal/logging/Slf4jLogger.java ---------------------------------------------------------------------- diff --git a/dormant/core/src/main/java/org/apache/tamaya/core/internal/logging/Slf4jLogger.java b/dormant/core/src/main/java/org/apache/tamaya/core/internal/logging/Slf4jLogger.java deleted file mode 100644 index a580128..0000000 --- a/dormant/core/src/main/java/org/apache/tamaya/core/internal/logging/Slf4jLogger.java +++ /dev/null @@ -1,181 +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.logging; - -import org.slf4j.spi.LocationAwareLogger; - -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogRecord; - -/** - * <p> - * java.util.logging.Logger implementation delegating to SLF4J. - * </p> - * <p> - * Methods {@link java.util.logging.Logger#setParent(Logger)}, {@link java.util.logging.Logger#getParent()}, - * {@link java.util.logging.Logger#setUseParentHandlers(boolean)} and - * {@link java.util.logging.Logger#getUseParentHandlers()} are not overrriden. - * </p> - * <p> - * Level annotation inspired by {@link org.slf4j.bridge.SLF4JBridgeHandler}: - * </p> - * <p/> - * <pre> - * FINEST -> TRACE - * FINER -> DEBUG - * FINE -> DEBUG - * CONFIG -> DEBUG - * INFO -> INFO - * WARN ING -> WARN - * SEVER -> ERROR - * </pre> - */ -public class Slf4jLogger extends AbstractDelegatingLogger { - - private static final String FQCN = AbstractDelegatingLogger.class.getName(); - - private final org.slf4j.Logger logger; - private LocationAwareLogger locationAwareLogger; - - - public Slf4jLogger(final String name, final String resourceBundleName) { - super(name, resourceBundleName); - logger = org.slf4j.LoggerFactory.getLogger(name); - if (logger instanceof LocationAwareLogger) { - locationAwareLogger = (LocationAwareLogger) logger; - } - } - - @Override - protected boolean supportsHandlers() { - return true; - } - - @Override - public Level getLevel() { - final Level level; - // Verify fromMap the wider (trace) to the narrower (error) - if (logger.isTraceEnabled()) { - level = Level.FINEST; - } else if (logger.isDebugEnabled()) { - // map to the lowest between FINER, FINE and CONFIG - level = Level.FINER; - } else if (logger.isInfoEnabled()) { - level = Level.INFO; - } else if (logger.isWarnEnabled()) { - level = Level.WARNING; - } else if (logger.isErrorEnabled()) { - level = Level.SEVERE; - } else { - level = Level.OFF; - } - return level; - } - - @Override - public boolean isLoggable(final Level level) { - final int i = level.intValue(); - if (i == Level.OFF.intValue()) { - return false; - } else if (i >= Level.SEVERE.intValue()) { - return logger.isErrorEnabled(); - } else if (i >= Level.WARNING.intValue()) { - return logger.isWarnEnabled(); - } else if (i >= Level.INFO.intValue()) { - return logger.isInfoEnabled(); - } else if (i >= Level.FINER.intValue()) { - return logger.isDebugEnabled(); - } - return logger.isTraceEnabled(); - } - - - @Override - protected void internalLogFormatted(final String msg, final LogRecord record) { - - final Level level = record.getLevel(); - final Throwable t = record.getThrown(); - - final Handler[] targets = getHandlers(); - if (targets != null) { - for (final Handler h : targets) { - h.publish(record); - } - } - if (!getUseParentHandlers()) { - return; - } - - /* - * As we can not use a "switch ... case" block but only a "if ... else if ..." block, the order current the - * comparisons is important. We first try log level FINE then INFO, WARN, FINER, etc - */ - if (Level.FINE.equals(level)) { - if (locationAwareLogger == null) { - logger.debug(msg, t); - } else { - locationAwareLogger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, t); - } - } else if (Level.INFO.equals(level)) { - if (locationAwareLogger == null) { - logger.info(msg, t); - } else { - locationAwareLogger.log(null, FQCN, LocationAwareLogger.INFO_INT, msg, null, t); - } - } else if (Level.WARNING.equals(level)) { - if (locationAwareLogger == null) { - logger.warn(msg, t); - } else { - locationAwareLogger.log(null, FQCN, LocationAwareLogger.WARN_INT, msg, null, t); - } - } else if (Level.FINER.equals(level)) { - if (locationAwareLogger == null) { - logger.trace(msg, t); - } else { - locationAwareLogger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, t); - } - } else if (Level.FINEST.equals(level)) { - if (locationAwareLogger == null) { - logger.trace(msg, t); - } else { - locationAwareLogger.log(null, FQCN, LocationAwareLogger.TRACE_INT, msg, null, t); - } - } else if (Level.ALL.equals(level)) { - // should never occur, all is used to configure java.util.logging - // but not accessible by the API Logger.xxx() API - if (locationAwareLogger == null) { - logger.error(msg, t); - } else { - locationAwareLogger.log(null, FQCN, LocationAwareLogger.ERROR_INT, msg, null, t); - } - } else if (Level.SEVERE.equals(level)) { - if (locationAwareLogger == null) { - logger.error(msg, t); - } else { - locationAwareLogger.log(null, FQCN, LocationAwareLogger.ERROR_INT, msg, null, t); - } - } else if (Level.CONFIG.equals(level)) { - if (locationAwareLogger == null) { - logger.debug(msg, t); - } else { - locationAwareLogger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, t); - } - } - // don't log if Level.OFF - } -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/b56817f7/dormant/core/src/main/java/org/apache/tamaya/core/internal/resources/io/AbstractFileResolvingResource.java ---------------------------------------------------------------------- diff --git a/dormant/core/src/main/java/org/apache/tamaya/core/internal/resources/io/AbstractFileResolvingResource.java b/dormant/core/src/main/java/org/apache/tamaya/core/internal/resources/io/AbstractFileResolvingResource.java deleted file mode 100644 index ff35687..0000000 --- a/dormant/core/src/main/java/org/apache/tamaya/core/internal/resources/io/AbstractFileResolvingResource.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright 2002-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.tamaya.core.internal.resources.io; - -import org.apache.tamaya.core.resource.Resource; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URL; -import java.net.URLConnection; - -/** - * Abstract base class for resources which resolve URLs into File references, - * such as {@code UrlResource} or {@link ClassPathResource}. - * - * <p>Detects the "file" protocol as well as the JBoss "vfs" protocol in URLs, - * resolving file system references accordingly. - * - * @author Juergen Hoeller - * @since 3.0 - */ -abstract class AbstractFileResolvingResource extends AbstractResource { - - /** - * This implementation returns a File reference for the underlying class path - * resource, provided that it refers to a file in the file system. - */ - @Override - public File getFile() throws IOException { - URL url = getURL(); - if (url.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) { - return VfsResourceDelegate.getResource(url).getFile(); - } - return ResourceUtils.getFile(url, getDescription()); - } - - /** - * This implementation determines the underlying File - * (or jar file, in case current a resource in a jar/zip). - */ - @Override - protected File getFileForLastModifiedCheck() throws IOException { - URL url = getURL(); - if (ResourceUtils.isJarURL(url)) { - URL actualUrl = ResourceUtils.extractJarFileURL(url); - if (actualUrl.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) { - return VfsResourceDelegate.getResource(actualUrl).getFile(); - } - return ResourceUtils.getFile(actualUrl, "Jar URL"); - } - else { - return getFile(); - } - } - - /** - * This implementation returns a File reference for the underlying class path - * resource, provided that it refers to a file in the file system. - * @see ResourceUtils#getFile(java.net.URI, String) - */ - protected File getFile(URI uri) throws IOException { - if (uri.getScheme().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) { - return VfsResourceDelegate.getResource(uri).getFile(); - } - return ResourceUtils.getFile(uri, getDescription()); - } - - - @Override - public boolean exists() { - try { - URL url = getURL(); - if (ResourceUtils.isFileURL(url)) { - // Proceed with file system resolution... - return getFile().exists(); - } - else { - // Try a URL connection content-length header... - URLConnection con = url.openConnection(); - customizeConnection(con); - HttpURLConnection httpCon = - (con instanceof HttpURLConnection ? (HttpURLConnection) con : null); - if (httpCon != null) { - int code = httpCon.getResponseCode(); - if (code == HttpURLConnection.HTTP_OK) { - return true; - } - else if (code == HttpURLConnection.HTTP_NOT_FOUND) { - return false; - } - } - if (con.getContentLength() >= 0) { - return true; - } - if (httpCon != null) { - // no HTTP OK status, and no content-length header: give up - httpCon.disconnect(); - return false; - } - else { - // Fall back to stream existence: can we open the stream? - InputStream is = getInputStream(); - is.close(); - return true; - } - } - } - catch (IOException ex) { - return false; - } - } - - @Override - public boolean isReadable() { - try { - URL url = getURL(); - if (ResourceUtils.isFileURL(url)) { - // Proceed with file system resolution... - File file = getFile(); - return (file.canRead() && !file.isDirectory()); - } - else { - return true; - } - } - catch (IOException ex) { - return false; - } - } - - @Override - public long contentLength() throws IOException { - URL url = getURL(); - if (ResourceUtils.isFileURL(url)) { - // Proceed with file system resolution... - return getFile().length(); - } - else { - // Try a URL connection content-length header... - URLConnection con = url.openConnection(); - customizeConnection(con); - return con.getContentLength(); - } - } - - @Override - public long lastModified() throws IOException { - URL url = getURL(); - if (ResourceUtils.isFileURL(url) || ResourceUtils.isJarURL(url)) { - // Proceed with file system resolution... - return super.lastModified(); - } - else { - // Try a URL connection last-modified header... - URLConnection con = url.openConnection(); - customizeConnection(con); - return con.getLastModified(); - } - } - - - /** - * Customize the given {@link URLConnection}, obtained in the course current an - * {@link #exists()}, {@link #contentLength()} or {@link #lastModified()} call. - * <p>Calls {@link ResourceUtils#useCachesIfNecessary(URLConnection)} and - * delegates to {@link #customizeConnection(HttpURLConnection)} if possible. - * Can be overridden in subclasses. - * @param con the URLConnection to customize - * @throws IOException if thrown from URLConnection methods - */ - protected void customizeConnection(URLConnection con) throws IOException { - ResourceUtils.useCachesIfNecessary(con); - if (con instanceof HttpURLConnection) { - customizeConnection((HttpURLConnection) con); - } - } - - /** - * Customize the given {@link HttpURLConnection}, obtained in the course current an - * {@link #exists()}, {@link #contentLength()} or {@link #lastModified()} call. - * <p>Sets request method "HEAD" by default. Can be overridden in subclasses. - * @param con the HttpURLConnection to customize - * @throws IOException if thrown from HttpURLConnection methods - */ - protected void customizeConnection(HttpURLConnection con) throws IOException { - con.setRequestMethod("HEAD"); - } - - - /** - * Inner delegate class, avoiding a hard JBoss VFS API dependency at runtime. - */ - private static class VfsResourceDelegate { - - public static Resource getResource(URL url) throws IOException { - return new VfsResource(VfsUtils.getRoot(url)); - } - - public static Resource getResource(URI uri) throws IOException { - return new VfsResource(VfsUtils.getRoot(uri)); - } - } - -} http://git-wip-us.apache.org/repos/asf/incubator-tamaya/blob/b56817f7/dormant/core/src/main/java/org/apache/tamaya/core/internal/resources/io/AbstractResource.java ---------------------------------------------------------------------- diff --git a/dormant/core/src/main/java/org/apache/tamaya/core/internal/resources/io/AbstractResource.java b/dormant/core/src/main/java/org/apache/tamaya/core/internal/resources/io/AbstractResource.java deleted file mode 100644 index a1c91a5..0000000 --- a/dormant/core/src/main/java/org/apache/tamaya/core/internal/resources/io/AbstractResource.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Copyright 2002-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.tamaya.core.internal.resources.io; - -import org.apache.tamaya.core.resource.Resource; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.Objects; - - -/** - * Convenience base class for {@link org.apache.tamaya.core.resource.Resource} implementations, - * pre-implementing typical behavior. - * - * <p>The "exists" method will check whether a File or InputStream can - * be opened; "isOpen" will always return false; "getURL" and "getFile" - * throw an exception; and "toString" will return the description. - * - * @author Juergen Hoeller - * @since 28.12.2003 - */ -public abstract class AbstractResource implements Resource { - - /** - * This implementation checks whether a File can be opened, - * falling back to whether an InputStream can be opened. - * This will cover both directories and content resources. - */ - @Override - public boolean exists() { - // Try file existence: can we find the file in the file system? - try { - return getFile().exists(); - } - catch (IOException ex) { - // Fall back to stream existence: can we open the stream? - try { - InputStream is = getInputStream(); - is.close(); - return true; - } - catch (Throwable isEx) { - return false; - } - } - } - - /** - * This implementation always returns {@code true}. - */ - @Override - public boolean isReadable() { - return true; - } - - /** - * This implementation always returns {@code false}. - */ - @Override - public boolean isOpen() { - return false; - } - - /** - * This implementation throws a FileNotFoundException, assuming - * that the resource cannot be resolved to a URL. - */ - @Override - public URL getURL() throws IOException { - throw new FileNotFoundException(getDescription() + " cannot be resolved to URL"); - } - - /** - * This implementation builds a URI based on the URL returned - * by {@link #getURL()}. - */ - @Override - public URI getURI() throws IOException { - URL url = getURL(); - try { - return ResourceUtils.toURI(url); - } - catch (URISyntaxException ex) { - throw new IllegalStateException("Invalid URI [" + url + "]", ex); - } - } - - /** - * This implementation throws a FileNotFoundException, assuming - * that the resource cannot be resolved to an absolute file path. - */ - @Override - public File getFile() throws IOException { - throw new FileNotFoundException(getDescription() + " cannot be resolved to absolute file path"); - } - - /** - * This implementation reads the entire InputStream to calculate the - * content length. Subclasses will almost always be able to provide - * a more optimal version current this, e.g. checking a File length. - * @throws IllegalStateException if {@code #getInputStreamSupplier()} returns null. - */ - @Override - public long contentLength() throws IOException { - InputStream is = this.getInputStream(); - Objects.requireNonNull(is, "resource input stream must not be null"); - try { - long size = 0; - byte[] buf = new byte[255]; - int read; - while ((read = is.read(buf)) != -1) { - size += read; - } - return size; - } - finally { - try { - is.close(); - } - catch (IOException ex) { - } - } - } - - /** - * This implementation checks the timestamp current the underlying File, - * if available. - * @see #getFileForLastModifiedCheck() - */ - @Override - public long lastModified() throws IOException { - long lastModified = getFileForLastModifiedCheck().lastModified(); - if (lastModified == 0L) { - throw new FileNotFoundException(getDescription() + - " cannot be resolved in the file system for resolving its last-modified timestamp"); - } - return lastModified; - } - - /** - * Determine the File to use for timestamp checking. - * <p>The default implementation delegates to {@link #getFile()}. - * @return the File to use for timestamp checking (never {@code null}) - * @throws IOException if the resource cannot be resolved as absolute - * file path, i.e. if the resource is not available in a file system - */ - protected File getFileForLastModifiedCheck() throws IOException { - return getFile(); - } - - /** - * This implementation throws a FileNotFoundException, assuming - * that relative resources cannot be created for this resource. - */ - @Override - public Resource createRelative(String relativePath) throws IOException { - throw new FileNotFoundException("Cannot of a relative resource for " + getDescription()); - } - - /** - * This implementation always returns {@code null}, - * assuming that this resource type does not have a filename. - */ - @Override - public String getFilename() { - return null; - } - - - /** - * This implementation returns the description current this resource. - * @see #getDescription() - */ - @Override - public String toString() { - return getDescription(); - } - - /** - * This implementation compares description strings. - * @see #getDescription() - */ - @Override - public boolean equals(Object obj) { - return (obj == this || - (obj instanceof Resource && ((Resource) obj).getDescription().equals(getDescription()))); - } - - /** - * This implementation returns the description's hash code. - * @see #getDescription() - */ - @Override - public int hashCode() { - return getDescription().hashCode(); - } - -}