From a7fec2fe722ac668f4c1a06633423eb46e3c3e84 Mon Sep 17 00:00:00 2001 From: Emerson Oliveira Date: Mon, 1 Apr 2013 14:02:01 -0300 Subject: [PATCH] Início da refatoração do ConfigurationLoader --- impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/ConfigurationLoader.java | 430 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- impl/core/src/test/java/br/gov/frameworkdemoiselle/configuration/field/basic/ConfigurationBasicFieldTest.java | 2 +- 2 files changed, 76 insertions(+), 356 deletions(-) diff --git a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/ConfigurationLoader.java b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/ConfigurationLoader.java index 6781b98..5e5ef47 100644 --- a/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/ConfigurationLoader.java +++ b/impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/ConfigurationLoader.java @@ -37,37 +37,26 @@ */ package br.gov.frameworkdemoiselle.internal.configuration; +import static br.gov.frameworkdemoiselle.configuration.ConfigType.SYSTEM; + import java.io.FileNotFoundException; import java.io.Serializable; import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.net.URL; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.validation.constraints.NotNull; - -import org.apache.commons.configuration.DataConfiguration; + +import org.apache.commons.configuration.AbstractConfiguration; +import org.apache.commons.configuration.FileConfiguration; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.commons.configuration.SystemConfiguration; import org.apache.commons.configuration.XMLConfiguration; -import org.slf4j.Logger; import br.gov.frameworkdemoiselle.annotation.Ignore; import br.gov.frameworkdemoiselle.annotation.Name; import br.gov.frameworkdemoiselle.configuration.ConfigType; import br.gov.frameworkdemoiselle.configuration.Configuration; import br.gov.frameworkdemoiselle.configuration.ConfigurationException; -import br.gov.frameworkdemoiselle.internal.producer.LoggerProducer; -import br.gov.frameworkdemoiselle.internal.producer.ResourceBundleProducer; import br.gov.frameworkdemoiselle.util.Reflections; -import br.gov.frameworkdemoiselle.util.ResourceBundle; import br.gov.frameworkdemoiselle.util.Strings; /** @@ -80,391 +69,122 @@ public class ConfigurationLoader implements Serializable { private static final long serialVersionUID = 1L; - private ResourceBundle bundle; + private ConfigType type; - private Logger logger; - - /** - * Loads a config class filling it with the corresponding values. - * - * @param object - * config object - * @throws ConfigurationException - */ - public void load(Object object) throws ConfigurationException { - Class config = object.getClass(); + private String resource; - getLogger().debug(getBundle().getString("loading-configuration-class", config.getName())); + private String prefix; - for (Field field : Reflections.getNonStaticFields(config)) { - loadField(field, object, config); - } - } + private org.apache.commons.configuration.Configuration configuration; - private void loadField(Field field, Object object, Class clazz) { - if (!field.isAnnotationPresent(Ignore.class) && clazz.isAnnotationPresent(Configuration.class)) { - String resource = clazz.getAnnotation(Configuration.class).resource(); - ConfigType type = clazz.getAnnotation(Configuration.class).type(); - org.apache.commons.configuration.Configuration config = getConfiguration(resource, type); - - if (config != null) { - Key key = new Key(field, clazz, config); - Object value = getValue(key, field, config); - validate(field, key, value, resource); - setValue(field, key, object, value); - } - } - } - - private void setValue(Field field, Key key, Object object, Object value) { - if (value != null) { - Reflections.setFieldValue(field, object, value); - getLogger().debug( - getBundle().getString("configuration-field-loaded", key.toString(), field.getName(), value)); - } + public void load(Object object) throws ConfigurationException { + loadType(object); + loadResource(object); + loadPrefix(object); + loadConfiguration(); + loadFields(object); } - private void validate(Field field, Key key, Object value, String resource) { - if (field.isAnnotationPresent(NotNull.class) && value == null) { - throw new ConfigurationException(getBundle().getString("configuration-attribute-is-mandatory", - key.toString(), resource)); - } + private void loadType(Object object) { + this.type = object.getClass().getAnnotation(Configuration.class).type(); } - /** - * Returns the configuration class according to specified resource name and configuration type. - * - * @param resource - * @param type - * @return a configuration - */ - private org.apache.commons.configuration.Configuration getConfiguration(String resource, ConfigType type) { - org.apache.commons.configuration.Configuration result = null; - + private void loadConfiguration() { try { - URL url; + AbstractConfiguration conf; - switch (type) { + switch (this.type) { case SYSTEM: - result = new SystemConfiguration(); - break; - - case PROPERTIES: - url = getResourceAsURL(resource + ".properties"); - - if (url != null) { - result = new DataConfiguration(new PropertiesConfiguration(url)); - } else { - getLogger().warn(getBundle().getString("resource-not-found", resource + ".properties")); - } - + conf = new SystemConfiguration(); break; case XML: - url = getResourceAsURL(resource + ".xml"); - - if (url != null) { - result = new DataConfiguration(new XMLConfiguration(url)); - } else { - getLogger().warn(getBundle().getString("resource-not-found", resource + ".xml")); - } - + conf = new XMLConfiguration(); break; default: - throw new ConfigurationException(getBundle().getString("configuration-type-not-implemented-yet", - type.name())); + conf = new PropertiesConfiguration(); + break; } - } catch (Exception cause) { - throw new ConfigurationException(getBundle().getString("error-creating-configuration-from-resource", - resource), cause); - } - - return result; - } - - @SuppressWarnings("unchecked") - private T getValue(Key key, Field field, org.apache.commons.configuration.Configuration config) { - Object value; - - Class fieldClass = (Class) field.getType(); - - if (fieldClass.isArray()) { - value = getArray(key, field, config); - - } else if (fieldClass.equals(Map.class)) { - value = getMap(key, field, config); + conf.setDelimiterParsingDisabled(true); - } else if (fieldClass.equals(Properties.class)) { - value = getProperty(key, config); - - } else if (fieldClass.equals(Class.class)) { - value = getClass(key, field, config); - - } else { - value = getBasic(key, field, config); - } - - return (T) value; - } - - @SuppressWarnings("unchecked") - private Object getMap(Key key, Field field, org.apache.commons.configuration.Configuration config) { - Map value = null; - - String regexp = "^(" + key.getPrefix() + ")((.+)\\.)?(" + key.getName() + ")$"; - Pattern pattern = Pattern.compile(regexp); - Matcher matcher; - - String iterKey; - String mapKey; - String confKey; - - for (Iterator iter = config.getKeys(); iter.hasNext();) { - iterKey = iter.next(); - matcher = pattern.matcher(iterKey); - - if (matcher.matches()) { - confKey = matcher.group(1) + (matcher.group(2) == null ? "" : matcher.group(2)) + matcher.group(4); - - if (value == null) { - value = new HashMap(); - } - - mapKey = matcher.group(3) == null ? "default" : matcher.group(3); - value.put(mapKey, config.getProperty(confKey)); + if (conf instanceof FileConfiguration) { + ((FileConfiguration) conf).setURL(Reflections.getResourceAsURL(this.resource)); + ((FileConfiguration) conf).load(); } - } - - return value; - } - private Object getArray(Key key, Field field, org.apache.commons.configuration.Configuration config) { - Object value = null; + this.configuration = conf; - Class fieldClass = (Class) field.getType(); - - try { - Method method; - String methodName = "get"; - - methodName += Strings.firstToUpper(fieldClass.getSimpleName()); - methodName = Strings.removeChars(methodName, '[', ']'); - - methodName += "Array"; - - method = config.getClass().getMethod(methodName, String.class); - value = method.invoke(config, key.toString()); - - } catch (Throwable cause) { - throw new ConfigurationException(getBundle().getString("error-converting-to-type", fieldClass.getName()), - cause); + } catch (FileNotFoundException cause) { + cause.printStackTrace(); + } catch (org.apache.commons.configuration.ConfigurationException e) { + e.printStackTrace(); } - - return value; } - private Object getBasic(Key key, Field field, org.apache.commons.configuration.Configuration config) { - Object value = null; - - Class fieldClass = (Class) field.getType(); - - try { - Method method; - String methodName = "get"; - - methodName += discoveryGenericType(field); - methodName += Strings.firstToUpper(fieldClass.getSimpleName()); - - if (!fieldClass.isPrimitive()) { - method = config.getClass().getMethod(methodName, String.class, fieldClass); - value = method.invoke(config, key.toString(), null); - - } else if (config.containsKey(key.toString())) { - method = config.getClass().getMethod(methodName, String.class); - value = method.invoke(config, key.toString()); - } + private void loadResource(Object object) { + if (this.type != SYSTEM) { + String name = object.getClass().getAnnotation(Configuration.class).resource(); + String extension = this.type.toString().toLowerCase(); - } catch (Throwable cause) { - throw new ConfigurationException(getBundle().getString("error-converting-to-type", fieldClass.getName()), - cause); + this.resource = name + "." + extension; } - - return value; } - private Object getClass(Key key, Field field, org.apache.commons.configuration.Configuration config) { - Object value = null; - - try { - String canonicalName = config.getString(key.toString()); - - if (canonicalName != null) { - ClassLoader classLoader = getClassLoaderForClass(canonicalName); - value = Class.forName(canonicalName, true, classLoader); - } - - } catch (Exception cause) { - // TODO Lançar a mensagem correta - throw new ConfigurationException(null, cause); - } - - return value; + private void loadPrefix(Object object) { + this.prefix = object.getClass().getAnnotation(Configuration.class).prefix(); } - /** - * Discovery the Generic's type. for example: the generic's type of List list is an Integer type - * - * @param field - * @return - */ - private String discoveryGenericType(Field field) { - - Type genericFieldType = field.getGenericType(); - - if (genericFieldType instanceof ParameterizedType) { - ParameterizedType type = (ParameterizedType) genericFieldType; - Type[] fieldArgumentTypes = type.getActualTypeArguments(); - for (Type fieldArgumentType : fieldArgumentTypes) { - @SuppressWarnings("rawtypes") - Class fieldArgumentClass = (Class) fieldArgumentType; - - if ("String".equals(fieldArgumentClass.getSimpleName())) { - return ""; - } - - return fieldArgumentClass.getSimpleName(); - } + private void loadFields(Object object) { + for (Field field : Reflections.getNonStaticFields(object.getClass())) { + loadField(field, object); } - - return ""; } - private Object getProperty(Key key, org.apache.commons.configuration.Configuration config) { - Object value = null; - - @SuppressWarnings("unchecked") - Iterator iterator = config.getKeys(key.toString()); - if (iterator.hasNext()) { - Properties props = new Properties(); - - while (iterator.hasNext()) { - String fullKey = iterator.next(); - String prefix = key.toString() + "."; - String unprefixedKey = fullKey.substring(prefix.length()); - props.put(unprefixedKey, config.getString(fullKey)); - } - - value = props; + private void loadField(Field field, Object object) { + if (hasIgnore(field)) { + return; } - return value; - } - - public static ClassLoader getClassLoaderForClass(final String canonicalName) throws FileNotFoundException { - return getClassLoaderForResource(canonicalName.replaceAll("\\.", "/") + ".class"); - } - - public static ClassLoader getClassLoaderForResource(final String resource) throws FileNotFoundException { - final String stripped = resource.startsWith("/") ? resource.substring(1) : resource; - - URL url = null; - ClassLoader result = Thread.currentThread().getContextClassLoader(); + try { + String key = getKey(field); + Class fieldType = field.getType(); + String methodName = "get" + Strings.firstToUpper(fieldType.getSimpleName()); - if (result != null) { - url = result.getResource(stripped); - } + Method method = configuration.getClass().getMethod(methodName, String.class, fieldType); + Object value = method.invoke(configuration, key, Reflections.getFieldValue(field, object)); + // TODO Se não achar no arquivo de configuração vai dar a falsa sensação que o valor padrão foi carregado de + // lá. Corrigir isso! - if (url == null) { - result = ConfigurationLoader.class.getClassLoader(); - url = ConfigurationLoader.class.getClassLoader().getResource(stripped); - } + Reflections.setFieldValue(field, object, value); - if (url == null) { - result = null; + } catch (SecurityException cause) { + cause.printStackTrace(); + } catch (NoSuchMethodException cause) { + cause.printStackTrace(); + } catch (IllegalArgumentException cause) { + cause.printStackTrace(); + } catch (IllegalAccessException cause) { + cause.printStackTrace(); + } catch (InvocationTargetException cause) { + cause.printStackTrace(); } - - return result; - } - - public static URL getResourceAsURL(final String resource) throws FileNotFoundException { - ClassLoader classLoader = getClassLoaderForResource(resource); - return classLoader != null ? classLoader.getResource(resource) : null; } - private ResourceBundle getBundle() { - if (bundle == null) { - bundle = ResourceBundleProducer.create("demoiselle-core-bundle"); - } - - return bundle; - } + private String getKey(Field field) { + String key = this.prefix; - private Logger getLogger() { - if (logger == null) { - logger = LoggerProducer.create(ConfigurationLoader.class); + if (field.isAnnotationPresent(Name.class)) { + key += field.getAnnotation(Name.class).value(); + }else{ + key += field.getName(); } - return logger; + return key; } - private final class Key { - - private String prefix; - - private String name; - - private String key; - - private Key(final Field field, final Class type, final org.apache.commons.configuration.Configuration config) { - - this.prefix = type.getAnnotation(Configuration.class).prefix(); - if (this.prefix == null) { - this.prefix = ""; - } - - if (field.isAnnotationPresent(Name.class)) { - this.name = getNameByAnnotation(field); - } else { - this.name = getNameByField(field); - } - - this.key = this.prefix + this.name; - - if (!config.containsKey(this.key)) { - getLogger().debug(getBundle().getString("key-not-found", this.key)); - } - } - - private String getNameByAnnotation(Field field) { - String result; - - Name nameAnnotation = field.getAnnotation(Name.class); - if (Strings.isEmpty(nameAnnotation.value())) { - throw new ConfigurationException(getBundle().getString("configuration-name-attribute-cant-be-empty")); - } else { - result = nameAnnotation.value(); - } - - return result; - } - - private String getNameByField(Field field) { - return field.getName(); - } - - public String getPrefix() { - return prefix; - } - - public String getName() { - return name; - } - - @Override - public String toString() { - return this.key; - } + private boolean hasIgnore(Field field) { + return field.isAnnotationPresent(Ignore.class); } } diff --git a/impl/core/src/test/java/br/gov/frameworkdemoiselle/configuration/field/basic/ConfigurationBasicFieldTest.java b/impl/core/src/test/java/br/gov/frameworkdemoiselle/configuration/field/basic/ConfigurationBasicFieldTest.java index 59c5421..7719157 100644 --- a/impl/core/src/test/java/br/gov/frameworkdemoiselle/configuration/field/basic/ConfigurationBasicFieldTest.java +++ b/impl/core/src/test/java/br/gov/frameworkdemoiselle/configuration/field/basic/ConfigurationBasicFieldTest.java @@ -113,7 +113,7 @@ public class ConfigurationBasicFieldTest extends AbstractConfigurationTest { assertEquals(expected, xmlConfig.getStringWithSpace()); } - // @Test + @Test public void loadStringWithComma() { String expected = "demoiselle,framework"; -- libgit2 0.21.2