He is an implementation of the reloadable decorator suggested by Eric. I have also added a set/getRefreshDelay method.

Emmanuel Bourg


Eric Galluzzo wrote:

Alternatively, it might be nice to introduce a FileConfiguration interface that just has a java.io.File getFile() method. Both DOM4JConfiguration and PropertiesConfiguration would implement this. Then one could repackage your existing ReloadablePropertiesConfiguration as a ReloadableConfiguration that implements Configuration but delegates to another FileConfiguration and checks the file every so often. Thus:

Configuration config = new ReloadableConfiguration(
   new DOM4JConfiguration( myXMLFile ) );

or

Configuration config = new ReloadableConfiguration(
   new PropertiesConfiguration( myPropFile ) );

This is a Decorator design reminiscent of FilteredOutputStream and FilteredInputStream.

- Eric



---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



Index: src/java/org/apache/commons/configuration/BaseConfiguration.java
===================================================================
RCS file: 
/home/cvspublic/jakarta-commons-sandbox/configuration/src/java/org/apache/commons/configuration/BaseConfiguration.java,v
retrieving revision 1.16
diff -u -r1.16 BaseConfiguration.java
--- src/java/org/apache/commons/configuration/BaseConfiguration.java    17 Oct 2003 
08:11:52 -0000      1.16
+++ src/java/org/apache/commons/configuration/BaseConfiguration.java    16 Dec 2003 
14:33:18 -0000
@@ -55,6 +55,7 @@
  */
 
 import java.util.Iterator;
+import java.util.Map;
 
 import org.apache.commons.collections.SequencedHashMap;
 
@@ -86,7 +87,7 @@
 public class BaseConfiguration extends AbstractConfiguration
 {
     /** stores the configuration key-value pairs */
-    private SequencedHashMap store = new SequencedHashMap();
+    private Map store = new SequencedHashMap();
     
     /**
      * Empty constructor.  You must add all the values to this configuration.
@@ -200,6 +201,10 @@
         }
     }
 
+    public void clear() {
+        store.clear();
+    }
+
     /**
      * Get the list of the keys contained in the configuration
      * repository.
@@ -208,6 +213,6 @@
      */
     public Iterator getKeys()
     {
-        return store.iterator();
+        return store.keySet().iterator();
     }
 }
Index: src/java/org/apache/commons/configuration/Configuration.java
===================================================================
RCS file: 
/home/cvspublic/jakarta-commons-sandbox/configuration/src/java/org/apache/commons/configuration/Configuration.java,v
retrieving revision 1.6
diff -u -r1.6 Configuration.java
--- src/java/org/apache/commons/configuration/Configuration.java        12 Nov 2003 
08:12:33 -0000      1.6
+++ src/java/org/apache/commons/configuration/Configuration.java        16 Dec 2003 
14:33:18 -0000
@@ -131,6 +131,11 @@
     void clearProperty(String key);
 
     /**
+     * Clear all properties in the configuration.
+     */
+    void clear();
+
+    /**
      *  Gets a property from the configuration.
      *
      *  @param key property to retrieve
Index: src/java/org/apache/commons/configuration/DOM4JConfiguration.java
===================================================================
RCS file: 
/home/cvspublic/jakarta-commons-sandbox/configuration/src/java/org/apache/commons/configuration/DOM4JConfiguration.java,v
retrieving revision 1.7
diff -u -r1.7 DOM4JConfiguration.java
--- src/java/org/apache/commons/configuration/DOM4JConfiguration.java   11 Nov 2003 
15:02:07 -0000      1.7
+++ src/java/org/apache/commons/configuration/DOM4JConfiguration.java   16 Dec 2003 
14:33:20 -0000
@@ -87,7 +87,7 @@
  * @author <a href="mailto:[EMAIL PROTECTED]">Daniel Rall</a>
  * @since 0.8.1
  */
-public class DOM4JConfiguration extends XMLConfiguration
+public class DOM4JConfiguration extends XMLConfiguration implements FileConfiguration
 {
     // For conformance with xpath
     private static final char ATTRIB_MARKER = '@';
Index: src/java/org/apache/commons/configuration/PropertiesConfiguration.java
===================================================================
RCS file: 
/home/cvspublic/jakarta-commons-sandbox/configuration/src/java/org/apache/commons/configuration/PropertiesConfiguration.java,v
retrieving revision 1.12
diff -u -r1.12 PropertiesConfiguration.java
--- src/java/org/apache/commons/configuration/PropertiesConfiguration.java      11 Nov 
2003 15:02:07 -0000      1.12
+++ src/java/org/apache/commons/configuration/PropertiesConfiguration.java      16 Dec 
2003 14:33:20 -0000
@@ -95,7 +95,7 @@
  */
 public class PropertiesConfiguration
         extends BasePropertiesConfiguration
-        implements Configuration
+        implements FileConfiguration
 {
     /** Static logger */
     Log log = LogFactory.getLog(PropertiesConfiguration.class);
@@ -166,6 +166,16 @@
     public void load(String fileName) throws IOException
     {
         load(getPropertyStream(fileName));
+    }
+
+    /**
+     * Save the properties to the fileName set by setFileName
+     *
+     * @throws IOException
+     */
+    public void save() throws IOException
+    {
+        save(getFileName());
     }
 
     /**
package org.apache.commons.configuration;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2003 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowledgement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgement may appear in the software itself,
 *    if and wherever such third-party acknowledgements normally appear.
 *
 * 4. The names "The Jakarta Project", "Commons", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact [EMAIL PROTECTED]
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

import java.io.IOException;

/**
 * A file based configuration.
 *
 * @author Emmanuel Bourg
 * @author Eric Galluzo
 * @version $Revision$, $Date$
 */
public interface FileConfiguration extends Configuration {

    /**
     * Save the properties to the fileName set by setFileName.
     *
     * @throws IOException
     */
    void save() throws IOException;

    /**
     * Load the properties from the fileName set by setFileName
     *
     * @throws IOException
     */    
    void load() throws Exception;

    /**
     * Return the name of the file.
     */
    String getFileName();

}
package org.apache.commons.configuration;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2003 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowledgement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgement may appear in the software itself,
 *    if and wherever such third-party acknowledgements normally appear.
 *
 * 4. The names "The Jakarta Project", "Commons", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact [EMAIL PROTECTED]
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

import java.io.IOException;
import java.io.File;
import java.util.Iterator;
import java.util.Properties;
import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * A decorator around a [EMAIL PROTECTED] FileConfiguration} that will reload the
 * properties everytime the configuration file is changed. The file is checked
 * every time a property is accessed. The file is not reloaded more than once
 * every 5 seconds by default, this time can be changed by setting the refresh
 * delay. The automatic reloading can be disabled by calling
 * <code>setAutoReload(false)</code>, it's enabled by default. When the file
 * is reloaded the configuration is cleared
 *
 * @author Emmanuel Bourg
 * @author Eric Galluzo
 * @version $Revision$, $Date$
 */
public class ReloadableConfiguration implements Configuration {

    /** Logger */
    private Log log = LogFactory.getLog(this.getClass());

    private FileConfiguration configuration;

    /** Should the configuration be reloaded on file changes ? */
    protected boolean autoReload = true;

    /** The last time the configuration file was modified. */
    protected long lastModified;

    /** The last time the file was checked for changes. */
    protected long lastChecked;

    /** The minimum delay in milliseconds between checks. */
    protected long refreshDelay = 5000;

    /** The lock to block read access while reloading */
    private Object reloadLock = new Object();

    /**
     * Creates a reloadable configuration.
     *
     * @param configuration
     */
    public ReloadableConfiguration(FileConfiguration configuration) {
        this.configuration = configuration;

        File file = new File(configuration.getFileName());
        lastModified = file.lastModified();
    }

    /**
     * Tell if the auto reload mode is enabled or disabled.
     */
    public boolean isAutoReload() {
        return autoReload;
    }

    /**
     * Enable or disable the automatic reloading of the configuration
     * when the file is changed.
     */
    public void setAutoReload(boolean autoReload) {
        this.autoReload = autoReload;
    }

    public long getRefreshDelay() {
        return refreshDelay;
    }

    /**
     * Set the minimal time between two reloadings.
     *
     * @param refreshDelay refresh delay in milliseconds
     */
    public void setRefreshDelay(long refreshDelay) {
        this.refreshDelay = refreshDelay;
    }

    /**
     * Check if the configuration has changed since the last
     * time it was loaded.
     */
    protected boolean hasChanged() {
        if (configuration.getFileName() == null) {
            return false;
        }

        File file = new File(configuration.getFileName());
        return (file.lastModified() > lastModified);
    }

    /**
     * Reload the configuration if the file has been modified. The
     * configuration will not be reloaded more than once every 5 seconds.
     */
    protected void reload() {
        long now = System.currentTimeMillis();
        if (autoReload) {
            synchronized (reloadLock) {
                if ((now > lastChecked + refreshDelay) && hasChanged()) {

                    lastChecked = now;
                    
                    log.debug("Reloading configuration " + 
configuration.getFileName());

                    try {
                        configuration.clear();
                        configuration.load();
                    } catch (Exception e) {
                        log.warn("Unable to reload configuration", e);
                    }
                }
            }
        }
    }


    public void save(String filename) throws IOException {
        configuration.save();
        lastModified = System.currentTimeMillis();
    }

    public Properties getProperties(String key) {
        reload();
        return configuration.getProperties(key);
    }

    public Object getProperty(String key) {
        reload();
        return configuration.getProperty(key);
    }

    public boolean getBoolean(String key) {
        reload();
        return configuration.getBoolean(key);
    }

    public boolean getBoolean(String key, boolean defaultValue) {
        reload();
        return configuration.getBoolean(key, defaultValue);
    }

    public Boolean getBoolean(String key, Boolean defaultValue) {
        reload();
        return configuration.getBoolean(key, defaultValue);
    }

    public byte getByte(String key) {
        reload();
        return configuration.getByte(key);
    }

    public byte getByte(String key, byte defaultValue) {
        reload();
        return configuration.getByte(key, defaultValue);
    }

    public Byte getByte(String key, Byte defaultValue) {
        reload();
        return configuration.getByte(key, defaultValue);
    }

    public double getDouble(String key) {
        reload();
        return configuration.getDouble(key);
    }

    public double getDouble(String key, double defaultValue) {
        reload();
        return configuration.getDouble(key, defaultValue);
    }

    public Double getDouble(String key, Double defaultValue) {
        reload();
        return configuration.getDouble(key, defaultValue);
    }

    public float getFloat(String key) {
        reload();
        return configuration.getFloat(key);
    }

    public float getFloat(String key, float defaultValue) {
        reload();
        return configuration.getFloat(key, defaultValue);
    }

    public Float getFloat(String key, Float defaultValue) {
        reload();
        return configuration.getFloat(key, defaultValue);
    }

    public int getInt(String key) {
        reload();
        return configuration.getInt(key);
    }

    public int getInt(String key, int defaultValue) {
        reload();
        return configuration.getInt(key, defaultValue);
    }

    public Integer getInteger(String key, Integer defaultValue) {
        reload();
        return configuration.getInteger(key, defaultValue);
    }

    public long getLong(String key) {
        reload();
        return configuration.getLong(key);
    }

    public long getLong(String key, long defaultValue) {
        reload();
        return configuration.getLong(key, defaultValue);
    }

    public Long getLong(String key, Long defaultValue) {
        reload();
        return configuration.getLong(key, defaultValue);
    }

    public short getShort(String key) {
        reload();
        return configuration.getShort(key);
    }

    public short getShort(String key, short defaultValue) {
        reload();
        return configuration.getShort(key, defaultValue);
    }

    public Short getShort(String key, Short defaultValue) {
        reload();
        return configuration.getShort(key, defaultValue);
    }

    public String getString(String key) {
        reload();
        return configuration.getString(key);
    }

    public String getString(String key, String defaultValue) {
        reload();
        return configuration.getString(key, defaultValue);
    }

    public String[] getStringArray(String key) {
        reload();
        return configuration.getStringArray(key);
    }

    public Vector getVector(String key) {
        reload();
        return configuration.getVector(key);
    }

    public Vector getVector(String key, Vector defaultValue) {
        reload();
        return configuration.getVector(key, defaultValue);
    }

    public Configuration subset(String prefix) {
        reload();
        return configuration.subset(prefix);
    }

    public Iterator getKeys() {
        reload();
        return configuration.getKeys();
    }

    public Iterator getKeys(String prefix) {
        reload();
        return configuration.getKeys(prefix);
    }

    public boolean isEmpty() {
        return configuration.isEmpty();
    }

    public boolean containsKey(String key) {
        return configuration.containsKey(key);
    }

    public void addProperty(String key, Object value) {
        configuration.addProperty(key, value);
    }

    public void setProperty(String key, Object value) {
        configuration.setProperty(key, value);
    }

    public void clearProperty(String key) {
        configuration.clearProperty(key);
    }

    public void clear() {
        configuration.clear();
    }

}
package org.apache.commons.configuration;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2003 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowledgement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgement may appear in the software itself,
 *    if and wherever such third-party acknowledgements normally appear.
 *
 * 4. The names "The Jakarta Project", "Commons", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact [EMAIL PROTECTED]
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

import java.io.File;
import java.io.FileWriter;

import junit.framework.TestCase;

/**
 * Test case for the ReloadableConfiguration class.
 *
 * @author Emmanuel Bourg
 * @version $Revision$, $Date$
 */
public class TestReloadableConfiguration extends TestCase {

    public void testAutomaticReloading() throws Exception {

        // create a new configuration
        File file = new File("testReload.properties");

        try {
            FileWriter out = new FileWriter(file);
            out.write("string=value1");
            out.flush();
            out.close();

            // load the configuration
            PropertiesConfiguration pc = new 
PropertiesConfiguration("testReload.properties");
            pc.setFileName("testReload.properties");

            ReloadableConfiguration rc = new ReloadableConfiguration(pc);
            rc.setAutoReload(false);
            assertEquals("Initial value", "value1", rc.getString("string"));

            Thread.sleep(500);

            // change the file
            out = new FileWriter(file);
            out.write("string=value2");
            out.flush();
            out.close();

            // test the automatic reloading
            assertEquals("Modified value with disabled reloading", "value1", 
rc.getString("string"));
            rc.setAutoReload(true);
            assertEquals("Modified value with enabled reloading", "value2", 
rc.getString("string"));
        } finally {
            // delete the test file
            file.delete();
        }
    }

}

Attachment: smime.p7s
Description: S/MIME Cryptographic Signature

Reply via email to