Example usage for org.apache.commons.configuration DefaultConfigurationBuilder getConfiguration

List of usage examples for org.apache.commons.configuration DefaultConfigurationBuilder getConfiguration

Introduction

In this page you can find the example usage for org.apache.commons.configuration DefaultConfigurationBuilder getConfiguration.

Prototype

public CombinedConfiguration getConfiguration(boolean load) throws ConfigurationException 

Source Link

Document

Returns the configuration provided by this builder.

Usage

From source file:edu.usc.pgroup.floe.config.FloeConfig.java

/**
 * To retrieve the config object.//from  w w w  . j a v  a2s  .co m
 * FIXME: This is not a Thread Safe Function (for the first initialization)
 *
 * @return Fully initialized configuration object
 * (instance of Apache Commons Configuration)
 */
public static Configuration getConfig() {
    if (config == null) {
        DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
        builder.setFile(new File("config.xml"));
        try {
            config = builder.getConfiguration(true);
        } catch (ConfigurationException e) {
            throw new RuntimeException("Missing configuration description file.");
        }
    }
    return config;
}

From source file:com.iLabs.spice.common.config.ConfigurationHandler.java

/**
 * This method returns the application configuration to the requesting
 * code.If the configuration is not loaded, it is loaded by this method. In
 * case the configuration is already loaded, it is simple returned to the
 * caller.//www .j a v a2 s.  c  o m
 * 
 * @return ConfigurtaionInerface This application configuration is exposed
 *         via this interface.
 */
public static synchronized ConfigurationInterface getApplicationConfiguration() {
    ConfigurationHandler configHandler = null;
    if (compositeConfig == null) {
        String filePath = System.getProperty(SYS_PROPERTY_COMPOSITE_CONFIGURATION);
        if (filePath == null) {
            filePath = SYS_PROPERTY_COMPOSITE_CONFIGURATION_LOC_DEV;
        }
        DefaultConfigurationBuilder builder = null;
        if (filePath != null && filePath.trim().length() > 0) {
            builder = new DefaultConfigurationBuilder(new File(filePath));
            try {
                Configuration configuration = builder.getConfiguration(true);
                ((HierarchicalConfiguration) configuration).setExpressionEngine(new XPathExpressionEngine());
                compositeConfig = configuration;
                configBasePath = builder.getBasePath();
            } catch (ConfigurationException e) {
                throw new RuntimeException(e);
            }
        } else {
            throw new RuntimeException("Composite Configuration file could not be loaded");
        }
    }
    configHandler = new ConfigurationHandler();
    return configHandler;
}

From source file:com.processpuzzle.application.configuration.domain.PropertyContext.java

@Override
protected void setUpTransientComponents() {
    File resourceFile = null;/*from  w  ww  .ja  va 2  s.c o  m*/
    try {
        log.debug("Trying to load resource: " + configurationDescriptorUrl);
        Resource resource = loader.getResource(configurationDescriptorUrl);
        if (resource != null)
            resourceFile = resource.getFile();
        else
            throw new IOException(
                    "Configuration descriptor: " + configurationDescriptorUrl + " can't be load.");

        DefaultConfigurationBuilder configurationBuilder = new DefaultConfigurationBuilder(resourceFile);
        configuration = configurationBuilder.getConfiguration(true);
        configuration.setExpressionEngine(new DefaultExpressionEngine());
    } catch (ConfigurationException e) {
        log.debug(e.getMessage());
        throw new ConfigurationSetUpException(configurationDescriptorUrl, e);
    } catch (IOException e) {
        throw new UndefinedPropertyDescriptorException(configurationDescriptorUrl, e);
    }
}

From source file:com.verymuchme.appconfig.ConfigurationBuilderCommonsConfiguration.java

/**
 * Load a Configuration Definition file using Apache Commons Configuration DefaultConfigurationBuilder
 * //from www  .j  a  va2 s . c  o m
 * @param configurationDefinition
 * @return CommonConfiguration instance
 */
private CombinedConfiguration loadConfigurationDefinition(String configurationDefinition) {

    InputStream configurationDefinitionIs = null;
    CombinedConfiguration combinedConfiguration = null;

    try {
        configurationDefinitionIs = new ByteArrayInputStream(configurationDefinition.getBytes("UTF-8"));
        // Load configuration definition
        DefaultConfigurationBuilder defaultConfigurationBuilder = new DefaultConfigurationBuilder();
        defaultConfigurationBuilder.load(configurationDefinitionIs);
        logger.trace(String.format(
                "AppConfig.ConfigurationDefinitionBuilder.loadConfigurationDefinition configuration definition loaded"));
        combinedConfiguration = defaultConfigurationBuilder.getConfiguration(false);
        logger.trace(String.format(
                "AppConfig.ConfigurationDefinitionBuilder.loadConfigurationDefinition configuration generated successfully"));
    } catch (Exception e) {
        String errorMessage = "AppConfig.ConfigurationDefinitionBuilder.loadConfigurationDefinition failed to load configuration definition file";
        logger.error(errorMessage, e);
        throw new AppConfigException(errorMessage, e);
    } finally {
        try {
            // Delete the temporary file
            configurationDefinitionIs.close();
        } catch (Exception ee) {
            // Ignore
        }
    }
    return combinedConfiguration;
}

From source file:com.legstar.config.commons.LegStarConfigCommons.java

/**
 * Loads an XML configuration from file.
 * //from w w  w  . j  a  va  2s  . c o m
 * @param configFileName the configuration file name
 * @return the in-memory XML configuration
 * @throws LegStarConfigurationException if configuration failed to load
 */
protected HierarchicalConfiguration loadGeneralConfig(final String configFileName)
        throws LegStarConfigurationException {
    try {
        if (_log.isDebugEnabled()) {
            _log.debug("Loading configuration file: " + configFileName);
        }
        /* First try as if it is a single configuration file */
        HierarchicalConfiguration generalConfig = new XMLConfiguration(configFileName);
        /*
         * If the first tag is additional, then this is a combined
         * configuration
         * that needs to be loaded in a specific way.
         */
        if (generalConfig.configurationsAt("additional").size() > 0) {
            DefaultConfigurationBuilder dcb = new DefaultConfigurationBuilder();
            dcb.setFileName(configFileName);
            generalConfig = (HierarchicalConfiguration) dcb.getConfiguration(true)
                    .getConfiguration(DefaultConfigurationBuilder.ADDITIONAL_NAME);
        }
        generalConfig.setExpressionEngine(new XPathExpressionEngine());
        return generalConfig;
    } catch (ConfigurationException e) {
        throw new LegStarConfigurationException(e);
    }
}

From source file:com.dm.estore.common.config.Cfg.java

private Configuration createConfiguration() {
    try {//from ww w . j  av  a  2  s .  c  o  m
        final CompositeConfiguration compositeConfig = new CompositeConfiguration();

        String configuredHome = null;
        if (overrideProperties != null) {
            MapConfiguration initialConfig = new MapConfiguration(overrideProperties);
            compositeConfig.addConfiguration(initialConfig);

            if (overrideProperties.containsKey(CommonConstants.Cfg.CFG_HOME_FOLDER)) {
                configuredHome = overrideProperties.getProperty(CommonConstants.Cfg.CFG_HOME_FOLDER);
            }
        }

        configurationHome = getOrCreateHomeFolder(configuredHome);

        final DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder(
                configurationHome + File.separator + ROOT_CONFIG_NAME);
        final CombinedConfiguration reloadableConfig = builder.getConfiguration(true);
        ConfigurationLogListener listener = new ConfigurationLogListener();
        reloadableConfig.addConfigurationListener(listener);
        reloadableConfig.addErrorListener(listener);
        // reloadableConfig.setForceReloadCheck(true);
        compositeConfig.addConfiguration(reloadableConfig);

        lastReloadTime = new Date();
        return compositeConfig;
    } catch (ConfigurationException e) {
        LOG.error("Unable to load configuration", e);
    }

    return null;
}

From source file:eu.scape_project.planning.utils.ConfigurationLoader.java

/**
 * Loads the configuration with the provided name.
 * //ww w .j  a  v  a  2  s . c  o m
 * @param name
 *            the configuration name
 * @param ignoreBuffer
 *            true to ignore the internal buffer, false otherwise
 * @return the configuration
 */
public Configuration load(String name, boolean ignoreBuffer) {
    CombinedConfiguration config = null;

    if (!ignoreBuffer) {
        config = buffer.get(name);
        if (config != null) {
            return config;
        }
    }

    try {
        DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder(name);
        builder.clearErrorListeners();
        builder.addErrorListener(new ConfigurationErrorListener() {
            @Override
            public void configurationError(ConfigurationErrorEvent event) {
                if (event.getType() == DefaultConfigurationBuilder.EVENT_ERR_LOAD_OPTIONAL) {
                    LOG.debug("Could not load optional configuration file {}", event.getPropertyName(),
                            event.getCause());
                } else {
                    LOG.warn("Configuration error on {}", event.getPropertyName(), event.getCause());
                }
            }
        });
        config = builder.getConfiguration(true);
        buffer.put(name, config);
    } catch (ConfigurationException e) {
        LOG.error("Cannot load configuration {}", e, name);
    }
    return config;
}

From source file:org.apache.metron.api.ConfigurationManager.java

/**
 * Common method to load content of all configuration resources defined in
 * 'config-definition.xml'.// www . j ava  2s.c  om
 * 
 * @param configDefFilePath
 *          the config def file path
 * @return Configuration
 */
public static Configuration getConfiguration(String configDefFilePath) {
    if (configurationsCache.containsKey(configDefFilePath)) {
        return configurationsCache.get(configDefFilePath);
    }
    CombinedConfiguration configuration = null;
    synchronized (configurationsCache) {
        if (configurationsCache.containsKey(configDefFilePath)) {
            return configurationsCache.get(configDefFilePath);
        }
        DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
        String fielPath = getConfigDefFilePath(configDefFilePath);
        LOGGER.info("loading from 'configDefFilePath' :" + fielPath);
        builder.setFile(new File(fielPath));
        try {
            configuration = builder.getConfiguration(true);
            configurationsCache.put(fielPath, configuration);
        } catch (ConfigurationException | ConfigurationRuntimeException e) {
            LOGGER.info("Exception in loading property files.", e);
        }
    }
    return configuration;
}

From source file:org.apache.metron.configuration.ConfigurationManager.java

/**
 * Common method to load content of all configuration resources defined in
 * 'config-definition.xml'.//from  w w  w . j a va2  s .c  o m
 * 
 * @param configDefFilePath
 *          the config def file path
 * @return Configuration
 */
public static Configuration getConfiguration(String configDefFilePath) {
    if (configurationsCache.containsKey(configDefFilePath)) {
        return configurationsCache.get(configDefFilePath);
    }
    CombinedConfiguration configuration = null;
    synchronized (configurationsCache) {
        if (configurationsCache.containsKey(configDefFilePath)) {
            return configurationsCache.get(configDefFilePath);
        }
        DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
        String fielPath = getConfigDefFilePath(configDefFilePath);
        LOGGER.info("loading from 'configDefFilePath' :" + fielPath);
        builder.setFile(new File(fielPath));
        try {
            configuration = builder.getConfiguration(true);
            configurationsCache.put(fielPath, configuration);
        } catch (ConfigurationException e) {
            LOGGER.info("Exception in loading property files.", e);
        }
    }
    return configuration;
}

From source file:org.j2free.config.ConfigurationListener.java

/**
 *
 * @param event//from   www.ja  v  a 2s .  c  o m
 */
public synchronized void contextInitialized(ServletContextEvent event) {
    context = event.getServletContext();

    // Get the configuration file
    String configPathTemp = (String) context.getInitParameter(INIT_PARAM_CONFIG_PATH);

    // Use the default path if it wasn't specified
    if (StringUtils.isBlank(configPathTemp))
        configPathTemp = DEFAULT_CONFIG_PATH;

    // Finalize the config path (needs to be final for inner-Runnable below)
    final String configPath = configPathTemp;
    context.setAttribute(CONTEXT_ATTR_CONFIG_PATH, configPath);

    try {
        // Load the configuration
        DefaultConfigurationBuilder configBuilder = new DefaultConfigurationBuilder();
        configBuilder.setFileName(configPath);

        final CombinedConfiguration config = configBuilder.getConfiguration(true);

        // Save the config where we can get at it later
        context.setAttribute(CONTEXT_ATTR_CONFIG, config);
        Global.put(CONTEXT_ATTR_CONFIG, config);

        // Determine the localhost
        String localhost = config.getString(PROP_LOCALHOST, "ip");
        if (localhost.equalsIgnoreCase("ip")) {
            try {
                localhost = InetAddress.getLocalHost().getHostAddress();
                log.info("Using localhost: " + localhost);
            } catch (Exception e) {
                log.warn("Error determining localhost", e);
                localhost = "localhost";
            }
        }

        context.setAttribute(CONTEXT_ATTR_LOCALHOST, localhost);
        Global.put(CONTEXT_ATTR_LOCALHOST, localhost);
        loadedConfigPropKeys.add(CONTEXT_ATTR_LOCALHOST);

        // Set application context attributes for all config properties
        String prop, value;
        Iterator itr = config.getKeys();
        while (itr.hasNext()) {
            prop = (String) itr.next();
            value = config.getString(prop);

            // Anything with the value "localhost" will be set to the IP if possible
            value = (value.equals("localhost") ? localhost : value);

            log.debug("Config: " + prop + " = " + value);
            context.setAttribute(prop, value);
            loadedConfigPropKeys.add(prop);
        }

        // Run Mode configuration
        String runMode = config.getString(PROP_RUNMODE);
        try {
            RUN_MODE = RunMode.valueOf(runMode);
        } catch (Exception e) {
            log.warn("Error setting runmode, invalid value: " + runMode);
        }

        context.setAttribute("devMode", RUN_MODE != RunMode.PRODUCTION);
        loadedConfigPropKeys.add("devMode");

        // Fragment Cache Configuration
        if (config.getBoolean(FragmentCache.Properties.ENABLED, false)) {
            log.info("Enabling fragment caching...");
            FragmentCacheTag.enable();

            // This is expected to be in seconds
            long temp = config.getLong(FragmentCache.Properties.REQUEST_TIMEOUT, -1l);
            if (temp != -1) {
                log.info("Setting FragmentCacheTag request timeout: " + temp);
                FragmentCacheTag.setRequestTimeout(temp);
            }

            // The property is in seconds, but WARNING_COMPUTE_DURATION does NOT use a TimeUnit, so it's in ms
            temp = config.getLong(FragmentCache.Properties.WARNING_DURATION, -1l);
            if (temp != -1) {
                log.info("Setting FragmentCacheTag warning duration: " + temp);
                FragmentCacheTag.setWarningComputeDuration(temp * 1000);
            }

            // Get the fragment cache names
            String[] cacheNames = config.getStringArray(FragmentCache.Properties.ENGINE_NAMES);
            for (String cacheName : cacheNames) {
                String cacheClassName = config
                        .getString(String.format(FragmentCache.Properties.ENGINE_CLASS_TEMPLATE, cacheName));
                try {
                    // Load up the class
                    Class<? extends FragmentCache> cacheClass = (Class<? extends FragmentCache>) Class
                            .forName(cacheClassName);

                    // Look for a constructor that takes a config
                    Constructor<? extends FragmentCache> constructor = null;
                    try {
                        constructor = cacheClass.getConstructor(Configuration.class);
                    } catch (Exception e) {
                    }

                    FragmentCache cache;

                    // If we found the configuration constructor, use it
                    if (constructor != null)
                        cache = constructor.newInstance(config);
                    else {
                        // otherwise use a default no-args constructor
                        log.warn("Could not find a " + cacheClass.getSimpleName()
                                + " constructor that takes a Configuration, defaulting to no-args constructor");
                        cache = cacheClass.newInstance();
                    }

                    // register the cache with the FragmentCacheTag using the config strategy-name, or the engineName
                    // if a strategy-name is not specified
                    log.info("Registering FragmentCache strategy: [name=" + cacheName + ", class="
                            + cacheClass.getName() + "]");
                    FragmentCacheTag.registerStrategy(cacheName, cache);
                } catch (Exception e) {
                    log.error("Error enabling FragmentCache engine: " + cacheName, e);
                }
            }

        } else {
            // Have to call this here, because reconfiguration could turn
            // the cache off after it was previously enabled.
            FragmentCacheTag.disable();
        }

        // For Task execution
        ScheduledExecutorService taskExecutor;

        if (config.getBoolean(PROP_TASK_EXECUTOR_ON, false)) {
            int threads = config.getInt(PROP_TASK_EXECUTOR_THREADS, DEFAULT_TASK_EXECUTOR_THREADS);

            if (threads == 1)
                taskExecutor = Executors.newSingleThreadScheduledExecutor();
            else
                taskExecutor = Executors.newScheduledThreadPool(threads);

            context.setAttribute(CONTEXT_ATTR_TASK_MANAGER, taskExecutor);
            loadedConfigPropKeys.add(CONTEXT_ATTR_TASK_MANAGER);

            Global.put(CONTEXT_ATTR_TASK_MANAGER, taskExecutor);
        } else {
            // Not allowed to shutdown the taskExecutor if dynamic reconfig is enabled
            if (reconfigTask == null) {
                // Shutdown and remove references to the taskManager previously created
                taskExecutor = (ScheduledExecutorService) Global.get(CONTEXT_ATTR_TASK_MANAGER);
                if (taskExecutor != null) {
                    taskExecutor.shutdown(); // will block until all tasks complete
                    taskExecutor = null;
                    Global.remove(CONTEXT_ATTR_TASK_MANAGER);
                }
            } else {
                // We could just log a warning that you can't do this, but the user
                // might not see that, so we're going to refuse to reset a configuration
                // that cannot be loaded in whole successfully.
                throw new ConfigurationException(
                        "Cannot disable task execution service, dynamic reconfiguration is enabled!");
            }
        }

        // Email Service
        if (config.getBoolean(PROP_MAIL_SERVICE_ON, false)) {
            if (!SimpleEmailService.isEnabled()) {
                // Get the SMTP properties
                Properties props = System.getProperties();
                props.put(PROP_SMTP_HOST, config.getString(PROP_SMTP_HOST));
                props.put(PROP_SMTP_PORT, config.getString(PROP_SMTP_PORT));
                props.put(PROP_SMTP_AUTH, config.getString(PROP_SMTP_AUTH));

                Session session;

                if (config.getBoolean(PROP_SMTP_AUTH)) {
                    final String user = config.getString(PROP_SMTP_USER);
                    final String pass = config.getString(PROP_SMTP_PASS);

                    Authenticator auth = new Authenticator() {
                        @Override
                        public PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(user, pass);
                        }
                    };
                    session = Session.getInstance(props, auth);

                } else {
                    session = Session.getInstance(props);
                }

                // Get the global headers
                Iterator headerNames = config.getKeys(PROP_MAIL_HEADER_PREFIX);
                List<KeyValuePair<String, String>> headers = new LinkedList<KeyValuePair<String, String>>();

                String headerName;
                while (headerNames.hasNext()) {
                    headerName = (String) headerNames.next();
                    headers.add(new KeyValuePair<String, String>(headerName, config.getString(headerName)));
                }

                // Initialize the service
                SimpleEmailService.init(session);
                SimpleEmailService.setGlobalHeaders(headers);

                // Set whether we actually send the e-mails
                SimpleEmailService.setDummyMode(config.getBoolean(PROP_MAIL_DUMMY_MODE, false));

                // Set the failure policy
                String policy = config.getString(PROP_MAIL_ERROR_POLICY);
                if (policy != null) {
                    if (policy.equals(VALUE_MAIL_POLICY_DISCARD)) {
                        SimpleEmailService.setErrorPolicy(new SimpleEmailService.DiscardPolicy());
                    } else if (policy.equals(VALUE_MAIL_POLICY_REQUEUE)) {
                        Priority priority = null;
                        try {
                            priority = Priority.valueOf(config.getString(PROP_MAIL_REQUEUE_PRIORITY));
                        } catch (Exception e) {
                            log.warn("Error reading requeue policy priority: "
                                    + config.getString(PROP_MAIL_REQUEUE_PRIORITY, "") + ", using default");
                        }

                        if (priority == null)
                            SimpleEmailService.setErrorPolicy(new SimpleEmailService.RequeuePolicy());
                        else
                            SimpleEmailService.setErrorPolicy(new SimpleEmailService.RequeuePolicy(priority));
                    }
                }

                // Parse templates
                String emailTemplateDir = config.getString(PROP_MAIL_TEMPLATE_DIR);

                // If the template
                if (StringUtils.isBlank(emailTemplateDir))
                    emailTemplateDir = DEFAULT_EMAIL_TEMPLATE_DIR;

                log.debug("Looking for e-mail templates in: " + emailTemplateDir);
                Set<String> templates = context.getResourcePaths(emailTemplateDir);

                // E-mail templates
                if (templates != null && !templates.isEmpty()) {
                    log.debug("Found " + templates.size() + " templates");

                    String key;
                    String defaultTemplate = config.getString(PROP_MAIL_DEFAULT_TEMPLATE, EMPTY);

                    InputStream in;
                    StringBuilder builder;
                    Scanner scanner;

                    try {
                        Template template;
                        String[] parts;

                        ContentType contentType;

                        for (String path : templates) {
                            path = path.trim();
                            parts = path.split("\\.");

                            contentType = ContentType.valueOfExt(parts[1]);

                            try {
                                in = context.getResourceAsStream(path.trim());

                                if (in != null && in.available() > 0) {
                                    scanner = new Scanner(in);
                                    builder = new StringBuilder();

                                    while (scanner.hasNextLine()) {
                                        builder.append(scanner.nextLine());
                                        if (contentType == ContentType.PLAIN) {
                                            builder.append("\n");
                                        }
                                    }

                                    template = new Template(builder.toString(), contentType);

                                    key = parts[0].replace(emailTemplateDir, EMPTY);
                                    SimpleEmailService.registerTemplate(key, template,
                                            key.equals(defaultTemplate));
                                }
                            } catch (IOException ioe) {
                                log.error("Error loading e-mail template: " + path, ioe);
                            }
                        }
                    } catch (Exception e) {
                        log.error("Error loading e-mail templates", e);
                    }
                } else
                    log.debug("No e-mail templates found.");
            }
        } else if (SimpleEmailService.isEnabled()) {
            boolean shutdown = false;
            try {
                shutdown = SimpleEmailService.shutdown(30, TimeUnit.SECONDS);
            } catch (InterruptedException ie) {
                log.warn("Interrupted while shutting down SimpleEmailService");
            }

            if (!shutdown)
                SimpleEmailService.shutdown();
        }

        // QueuedHttpCallService
        if (config.getBoolean(PROP_HTTP_SRVC_ON, false)) {
            if (!SimpleHttpService.isEnabled()) // Don't double init...
            {
                int defaultThreadCount = Runtime.getRuntime().availableProcessors() + 1; // threads to use if unspecified
                SimpleHttpService.init(config.getInt(PROP_HTTP_SRVC_CORE_POOL, defaultThreadCount),
                        config.getInt(PROP_HTTP_SRVC_MAX_POOL, defaultThreadCount),
                        config.getLong(PROP_HTTP_SRVC_POOL_IDLE, DEFAULT_HTTP_SRVC_THREAD_IDLE),
                        config.getInt(PROP_HTTP_SRVC_CONNECT_TOUT, DEFAULT_HTTP_SRVC_CONNECT_TOUT),
                        config.getInt(PROP_HTTP_SRVE_SOCKET_TOUT, DEFAULT_HTTP_SRVE_SOCKET_TOUT));
            }
        } else if (SimpleHttpService.isEnabled()) {
            boolean shutdown = false;
            try {
                // Try to shutdown the service while letting currently waiting tasks complete
                shutdown = SimpleHttpService.shutdown(30, TimeUnit.SECONDS);
            } catch (InterruptedException ie) {
                log.warn("Interrupted while waiting for SimpleHttpService to shutdown");
            }
            if (!shutdown) {
                // But if that doesn't finish in 60 seconds, just cut it off
                int count = SimpleHttpService.shutdown().size();
                log.warn("SimpleHttpService failed to shutdown in 60 seconds, so it was terminated with "
                        + count + " tasks waiting");
            }
        }

        // Spymemcached Client
        if (config.getBoolean(PROP_SPYMEMCACHED_ON, false)) {
            String addresses = config.getString(PROP_SPYMEMCACHED_ADDRESSES);
            if (addresses == null) {
                log.error("Error configuring spymemcached; enabled but no addresses!");
            } else {
                try {
                    // Reflect our way to the constructor, this is all so that the
                    // spymemcached jar does not need to be included in a J2Free app
                    // unless it is actually to be used.
                    Class klass = Class.forName("net.spy.memcached.MemcachedClient");
                    Constructor constructor = klass.getConstructor(List.class);

                    klass = Class.forName("net.spy.memcached.AddrUtil");
                    Method method = klass.getMethod("getAddresses", String.class);

                    Object client = constructor.newInstance(method.invoke(null, addresses));

                    context.setAttribute(CONTEXT_ATTR_SPYMEMCACHED, client);
                    loadedConfigPropKeys.add(CONTEXT_ATTR_SPYMEMCACHED);

                    Global.put(CONTEXT_ATTR_SPYMEMCACHED, client);

                    log.info("Spymemcached client created, connected to " + addresses);
                } catch (Exception e) {
                    log.error("Error creating memcached client [addresses=" + addresses + "]", e);
                }
            }
        } else {
            // If a spymemcached client was previous created
            Object client = Global.get(CONTEXT_ATTR_SPYMEMCACHED);
            if (client != null) {
                try {
                    // Reflect our way to the shutdown method
                    Class klass = Class.forName("net.spy.memcached.MemcachedClient");
                    Method method = klass.getMethod("shutdown");

                    method.invoke(null, client); // and shut it down

                    log.info("Spymemcached client shutdown");
                } catch (Exception e) {
                    log.error("Error shutting down spymemcached client", e);
                }

                // Then remove any references
                Global.remove(CONTEXT_ATTR_SPYMEMCACHED);
                client = null;
            }
        }
    } catch (ConfigurationException ce) {
        log.error("Error configuring app", ce);
    }
}