Package org.jconfig

Source Code of org.jconfig.DefaultConfiguration$MyCategoryListener

/*
* Configuration.java
*
* Created on 19. November 2002, 22:27
*/

package org.jconfig;

import java.io.Serializable;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.SortedMap;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.Vector;
import javax.swing.event.EventListenerList;

import org.jconfig.event.CategoryChangedEvent;
import org.jconfig.event.CategoryListener;
import org.jconfig.event.ConfigurationChangedEvent;
import org.jconfig.event.ConfigurationChangedEventImpl;
import org.jconfig.event.ConfigurationListener;
import org.jconfig.event.PropertyChangedEvent;
import org.jconfig.event.PropertyListener;
import org.jconfig.utils.IncludeEntry;
/**
* This class is the configuration itself. The Configuration is
* useful if one wants to manage multiple configurations. A single
* instance of the Configuration may contain, for example, information
* for one application or user.
*
* @author Andreas Mecky andreas.mecky@xcom.de
* @author Terry Dye terry.dye@xcom.de
*/
public class DefaultConfiguration implements Serializable,Configuration {
    private static boolean debug = false;
   
    protected static final VariableManager vm = VariableManager.getInstance();
    // the name of the configuration
    protected String configName;
    // a map containing all properties for each category
    protected HashMap categories;
    // the name of the default category
    protected String mainCategory;
    // The List of ConfigurationListeners
    private EventListenerList configurationListenerList = new EventListenerList();
    // flag to determine if this is a newly created configuration
    private boolean created = true;
   
    private String encoding;
   
    protected String baseConfigName;
   
    private boolean dirtyFlag = false;
   
    private Vector includes = new Vector();
   
    protected DefaultConfiguration() {
    }
    /**
     * The constructor that creates a new configuration
     * with one empty category called "general". This
     * category is also the default category.
     *
     * @param configName the name of the configuration
     */
    public DefaultConfiguration(String configName) {
        categories = new HashMap();
        this.configName = configName;
        setCategory("general", true);
        created = true;
    }
   
    /**
     * This method sets a category but it does not set
     * this category as default.
     *
     * @param name the name of the category
     */
    public void setCategory(String name) {
        setCategory(name, false);
    }
   
    public void renameCategory(String newName,String oldName) {
      Category c = getCategory(oldName);
      if ( mainCategory.equals(c.getCategoryName())) {
        mainCategory = newName;
      }
      categories.remove(oldName);
      c.renameCategory(newName);
      categories.put(newName,c);
      markDirty();
    }
    /**
     * Besides setting the category, it will also set this
     * category as default category if main is true. It will
     * only set (ie create) the category if it does not exist. If you
     * want delete a category then use @see #removeCategory(String)
     *
     * @param categoryName the name of the category
     * @param main if true then this category is the default category
     */
    public void setCategory(String categoryName, boolean main) {
        if (categoryName != null) {
            if (main) {
                mainCategory = categoryName;
            }
            if (!categories.containsKey(categoryName)) {
//              System.err.println("setCategory(): creating DefaultCategory " + categoryName + " in " + configName + " configuration");
                Category category = new DefaultCategory(categoryName);
                category.setConfigurationName(configName);
                category.addCategoryListener(new MyCategoryListener());
                categories.put(categoryName, category);
                markDirty();
                category.fireCategoryChangedEvent(
                    new ConfigurationChangedEventImpl(ConfigurationChangedEvent.CATEGORY_ADDED, category, null, null, null ));
                fireConfigurationChangedEvent(
                    new ConfigurationChangedEventImpl(ConfigurationChangedEvent.CATEGORY_ADDED, category, null, null, null ));
            }
        }
    }
   
    /* (non-Javadoc)
     * @see org.jconfig.Configuration#setCategory(org.jconfig.Category)
     */
    public void setCategory(Category category) {
        if (!categories.containsKey(category.getCategoryName())) {
            category.setConfigurationName(configName);
            category.addCategoryListener(new MyCategoryListener());
            categories.put(category.getCategoryName(), category);
            category.fireCategoryChangedEvent(
                new ConfigurationChangedEventImpl(ConfigurationChangedEvent.CATEGORY_ADDED, category, null, null, null ));
            fireConfigurationChangedEvent(
                new ConfigurationChangedEventImpl(ConfigurationChangedEvent.CATEGORY_ADDED, category, null, null, null ));
        }
    }
    /**
     * This method returns the name of the
     * default category
     *
     * @return name of the default category
     */
    public String getMainCategoryName() {
        return mainCategory;
    }
   
    /**
     * This method returns a string array with all
     * category names.
     *
     * @return a string array with all category names
     */
    public String[] getCategoryNames() {
        return getCategoryNames(true);
    }
   
    /**
     * A convenience method that returns the key set in the
     * form or a String Array.
     *
     * @param includeParent true will check for a base configuration
     * and include those category names as well.
     * @return the String Array as described
     */
    protected String[] getCategoryNames(boolean includeParent) {
        Set allCategories = categories.keySet();
        Vector all = new Vector(allCategories);       
        if ( baseConfigName != null && includeParent ) {
            Configuration cfg = ConfigurationManager.getConfiguration(baseConfigName);
            String[] parentCategories = cfg.getCategoryNames();
            for ( int i = 0 ; i < parentCategories.length ; i++) {
                if ( all.indexOf(parentCategories[i]) == -1 ) {
                    all.add(parentCategories[i]);
                }
            }
        }       
        return (String[]) all.toArray(new String[0]);
    }
   
    /**
     * This method returns the String value based on the given key.
     *
     * Implementation details: It calls getProperty(name,null,null).
     * It searches inside the default category for the property.
     *
     * @param key the name of the property
     * @return the value as String if it is found or null
     */
    public String getProperty(String key) {
        return getProperty(key, null, null);
    }
   
    /**
     * This method is the same as getProperty(key) but it
     * returns the defaultValue if the property cannot be found.
     *
     * Implementation details: It calls getProperty(key,defaultValue,null).
     *
     * @param key the name of the property
     * @param defaultValue the defaultValue that will be returned if the property cannot be found
     * @return the value as String
     */
    public String getProperty(String key, String defaultValue) {
        return getProperty(key, defaultValue, null);
    }
   
    /**
     * This is the real implementation. It will return the value of the property
     * with the specific name. First of all, it checks if the name of the category
     * exists. If not, then it will use the name of the default category.
     * The next step is that it will look for the property. If it is not found in
     * the category, it will look inside the default category (inheritance). If
     * it still cannot find the property, it will return the defaultValue
     *
     * @param key the name of the property
     * @param defaultValue the default value
     * @param categoryName the name of the category
     * @return the value as String
     */
    public String getProperty(String key,String defaultValue,String categoryName) {
      if ( categoryName == null ) {
        categoryName = mainCategory;
      }
        boolean isMainCat = false;
        if (key == null) {
            return defaultValue;
        }
        if (!categories.containsKey(categoryName)) {
            isMainCat = true;
//            categoryName = mainCategory;
        }
        Category category = getCategory(categoryName);
        if ( category.getCategoryName().equals(mainCategory)) {
            isMainCat = true;
        }
        String tmp = category.getProperty(key);
        // property not found so look in mainCategory
        // if it is not already the mainCategory
        if ( tmp == null && !isMainCat) {
            category = getCategory(mainCategory);
            tmp = category.getProperty(key);
        }
        if ( tmp == null ) {
            if ( baseConfigName != null ) {
                Configuration cfg = ConfigurationManager.getConfiguration(baseConfigName);
                tmp = cfg.getProperty(key,defaultValue,categoryName);           
            }
            else {
                tmp = defaultValue;
            }
        }
        return tmp;
    }
   
    /**
     * This method sets a property with the name and the value
     * in the default category. It calls setProperty(name.value,null).
     *
     * @param name the name of the property
     * @param value the value as String
     */
    public void setProperty(String name, String value) {
        setProperty(name, value, null);
    }
   
    /**
     * This method sets the value for a property for the given
     * category. It also raises a PropertyEvent. If the category
     * is null then it uses the default category.
     *
     * @param name the name of the property
     * @param value the value as String
     * @param categoryName the name of the category
     */
    public void setProperty(String name, String value, String categoryName) {
//      System.err.println("DefaultConfiguration.setProperty category=" + categoryName + ", propertyName="+name + ", propertyValue="+value);
        if (name != null) {
            if (categoryName == null) {
                categoryName = mainCategory;
            }
            Category category = getCategory(categoryName);
            category.setProperty(name, value);
            markDirty();
            fireConfigurationChangedEvent(
                new ConfigurationChangedEventImpl(ConfigurationChangedEvent.PROPERTY_CHANGED, category, name, value,null ));
        }
    }
   
    /**
     * This method deletes a property from the default category.
     * It calls removeProperty(name,null).
     *
     * @param name the name of the property
     */
    public void removeProperty(String name) {
        if (name != null) {
            removeProperty(name, null);           
        }
    }
   
    /**
     * This method deletes a property with the given name
     * from the specific category. If the category is null
     * then it will delete the property from the default category.
     *
     * @param name the name of the property
     * @param category the name of the category
     */
    public void removeProperty(String name, String category) {
        if (category == null) {
            category = mainCategory;
        }
        if (name != null) {
            //if (categories.containsKey(category)) {
            Category cat = getCategory(category);
            String tmp = cat.getProperty(name,null);
            cat.setProperty(name, null);
            fireConfigurationChangedEvent(
                new ConfigurationChangedEventImpl(ConfigurationChangedEvent.PROPERTY_REMOVED,cat, name, tmp,null ));
            markDirty();
        }
       
    }
   
    /**
     * The method returns the number of categories inside this configuration.
     *
     * @return the number of categories
     */
    public int getNumberOfCategories() {
        return getCategoryNames().length;
    }
   
    /**
     * This method deletes a category with all its properties
     *
     * @param category the name of the category
     */
    public void removeCategory(String category) {
        if (categories.containsKey(category)) {
            Category cat = getCategory(category);
            categories.remove(category);
            cat.fireCategoryChangedEvent(
                new ConfigurationChangedEventImpl(ConfigurationChangedEvent.CATEGORY_REMOVED, cat, null, null, null));
            fireConfigurationChangedEvent(
                new ConfigurationChangedEventImpl(ConfigurationChangedEvent.CATEGORY_REMOVED,cat, null, null,null ));
            cat = null;
            markDirty();           
        }
    }
   
    /* (non-Javadoc)
     * @see org.jconfig.Configuration#getProperties(java.lang.String)
     */
    public Properties getProperties(String category) {             
        return getProperties(category,true);
    }
   
    /* (non-Javadoc)
     * @see org.jconfig.Configuration#getProperties()
     */
    public Properties getProperties() {
        return getProperties(mainCategory,true);
    }
   
    /**
     * @param category
     * @param includeParent
     * @return
     */
    protected Properties getProperties(String category,boolean includeParent) {
      println("configname = " + configName + ", baseConfigname = " + baseConfigName+", category="+category);
        Category cat = getCategory(category);
        Properties props = new Properties();
        if ( cat != null ) {           
            props = (Properties)cat.getProperties().clone();
            println("+-+ " + cat.getCategoryName());
            if ( debug) props.list(System.err);
            println("+-+ " + cat.getCategoryName());
        }
        if ( baseConfigName != null && includeParent ) {      
            Configuration cfg = ConfigurationManager.getConfiguration(baseConfigName);
            Properties parentProps = cfg.getProperties(category);
            println("!!!!!");
            if ( debug ) parentProps.list(System.err);
            println("!!!!!");
            Enumeration num = parentProps.keys();
            while ( num.hasMoreElements() ) {
                String name = (String)num.nextElement();
                println("lookin for " + name);
                if ( !props.containsKey(name) ) {
                  println("adding " + name);
                    props.setProperty(name, (String)parentProps.get(name));
                }
            }
        }  
        return props;
    }
   
    private void println(String string) {
      if ( debug ) {
        System.err.println( string );
      }
  }
  /**
     * This method returns all the names of the properties
     * for the specific category
     *
     * @param category the name of the category
     * @return the names as string array
     */
    public String[] getPropertyNames(String category) {
        if ( containsCategory(category) ) {
            // FIXME: include parent properties
            Properties properties = getProperties(category);           
            if (properties != null) {               
                Enumeration en = properties.propertyNames();
                Vector keys = new Vector();
                while ( en.hasMoreElements() ) {
                    String nm = (String)en.nextElement();                   
                    keys.add(nm);
                }
                /*
                Set keys = properties.keySet();
                 */
                return (String[]) keys.toArray(new String[0]);
            }           
        }
        return null;
    }
   
    /**
     * This method sets a variable inside the configuration.
     *
     * @param name the name of the variable
     * @param value the value of the variable
     */
    public void setVariable(String name, String value) {
        if (name != null && value != null) {
            vm.addVariable(name, value,configName);
        }
    }
   
    /**
     * It returns a HashMap with all variables with the
     * variable name as key
     *
     * @return a HashMap with all variables
     */
    public HashMap getVariables() {
        return vm.getVariables(configName);
    }
   
    public String getVariable(String name) {
        return vm.getVariable(configName, name);
    }
   
   
    /**
     * @param name
     * @param defaultValue
     * @return
     */
    public int getIntProperty(String name, int defaultValue) {
        return getIntProperty(name, defaultValue, mainCategory);
    }
   
    /**
     * @param name
     * @param defaultValue
     * @param category
     * @return
     */
    public int getIntProperty(String name, int defaultValue, String category) {
        String value = getProperty(name,null,category);
        if (value == null) {
            return defaultValue;
        } else {
            try {
                return Integer.parseInt(vm.replaceVariables(value,configName));
            } catch (NumberFormatException nfe) {
                return defaultValue;
            }
        }       
    }
   
    /**
     * Wrapper method to keep API simple
     *
     * @see Category#getBooleanProperty(String, boolean)
     * @param name
     * @param defaultValue
     * @return
     */
    public boolean getBooleanProperty(String name, boolean defaultValue) {
        return getBooleanProperty(name, defaultValue, mainCategory);
    }
   
    /**
     * Wrapper method to Category method
     *
     * @param defaultValue
     * @param categoryName
     * @return
     */
    public boolean getBooleanProperty(String name,boolean defaultValue,String categoryName) {
        String value = getProperty(name,null,categoryName);
        if ( value == null ) {
            return defaultValue;
        } else {
            try {
                return Boolean.valueOf(vm.replaceVariables(value,configName)).booleanValue();
            } catch (Exception e) {
                return defaultValue;
            }
        }
    }
   
    /**
     * Wrapper method to Category method
     *
     * @param key
     * @param value
     */
    public void setBooleanProperty(String key, boolean value) {
        getCategory().setBooleanProperty(key, value);
       
    }
   
    /**
     * Wrapper method to Category method
     *
     * @param key
     * @param value
     * @param category
     */
    public void setBooleanProperty(String key, boolean value, String category) {
        getCategory(category).setBooleanProperty(key, value);
    }
   
    /**
     * Wrapper method to Category method
     *
     * @param name
     * @param defaultValue
     * @return
     */
    public long getLongProperty(String name, long defaultValue) {
        return getLongProperty(name, defaultValue, mainCategory);
    }
   
    /**
     * Wrapper method to Category method
     *
     * @param name
     * @param defaultValue
     * @param categoryName
     * @return
     */
    public long getLongProperty(String name,long defaultValue,String categoryName) {
        String value = getProperty(name,null,categoryName);
        if (value == null) {
            return defaultValue;
        } else {
            try {
                return Long.parseLong(vm.replaceVariables(value,configName));
            } catch (NumberFormatException nfe) {
                return defaultValue;
            }
        }    
    }
   
    /**
     * Wrapper method to Category method
     *
     * @param name
     * @param defaultValue
     * @return
     */
    public double getDoubleProperty(String name, double defaultValue) {
        return getDoubleProperty(name, defaultValue, mainCategory);
    }
   
    /**
     * Wrapper method to Category method
     *
     * @param name
     * @param defaultValue
     * @param category
     * @return
     */
    public double getDoubleProperty(String name,double defaultValue,String category) {
        String value = getProperty(name,null,category);
        if (value == null) {
            return defaultValue;
        } else {
            try {
                return Double.parseDouble(vm.replaceVariables(value,configName));
            } catch (Exception e) {
                return defaultValue;
            }
        }       
    }
   
    /**
     * Wrapper method to Category method
     *
     * @param name
     * @param defaultValue
     * @return
     */
    public char getCharProperty(String name, char defaultValue) {
        return getCharProperty(name, defaultValue, mainCategory);
    }
   
    /**
     * Wrapper method to Category method
     *
     * @param name
     * @param defaultValue
     * @param category
     * @return
     */
    public char getCharProperty(
    String name,
    char defaultValue,
    String category) {
        Category cat = getCategory(category);
        return cat.getCharProperty(name, defaultValue);
    }
   
    /**
     * This method creates a string representation of the configuration.
     *
     * @return a string with the configuration
     */
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        String[] cats = getCategoryNames(false);
        for (int i = 0; i < cats.length; i++) {
            buffer.append("Category=");
            buffer.append(cats[i]);
            Properties props = getProperties(cats[i],false);
            if (props != null) {
                buffer.append("\n");
                Iterator nit = props.keySet().iterator();
                while (nit.hasNext()) {
                    String name = (String) nit.next();
                    String value = props.getProperty(name);
                    buffer.append("  ");
                    buffer.append(name);
                    buffer.append("=");
                    buffer.append(value);
                    buffer.append("\n");
                }
            }
        }
        return buffer.toString();
    }
   
    /**
     * This method converts the Configuration into a String
     * which looks like XML.
     *
     * @return the Configuration as String in XML format
     */
    public String getXMLAsString() {
        StringBuffer buffer = new StringBuffer();       
        // first we will write out the variable block
        // if we have some
        buffer.append("<?xml version=\"1.0\"");
        if ( getEncoding() != null ) {
            buffer.append(" encoding=\""+getEncoding()+"\"");
        }
        buffer.append(" ?>\n");
        buffer.append("<properties");
        if ( baseConfigName != null ) {
            buffer.append(" extends=\"");
            buffer.append(baseConfigName);
            buffer.append("\"");
        }
        buffer.append(">\n");
        addIncludeBlock(buffer);       
        addVariableBlock(buffer);
        // now we are writing out all categories with
        // their properties
        String[] cats = getCategoryNames(false);
        for (int i = 0; i < cats.length; i++) {
            buffer.append("  <category name=\"");
            buffer.append(escapeForXML(cats[i]));
            buffer.append("\">\n");           
            SortedMap sm = getSortedProperties(cats[i],false);
            if (sm != null) {
                Iterator nit = sm.keySet().iterator();
                while (nit.hasNext()) {
                    String name = (String) nit.next();
                    String value = (String)sm.get(name);
                    buffer.append("    <property name=\"");
                    buffer.append(escapeForXML(name));
                    buffer.append("\" value=\"");
                    // do not convert the value
                    buffer.append(escapeForXML(value));
                    buffer.append("\"/>\n");
                }
                buffer.append("  </category>\n");
            }
        }
        buffer.append("</properties>\n");
        return buffer.toString();
    }
   
    protected SortedMap getSortedProperties(String categoryName,boolean includeParent) {
        Properties props = getProperties(categoryName,includeParent);
        SortedMap sm = new TreeMap();
        if (props != null) {
            Iterator nit = props.keySet().iterator();
            while (nit.hasNext()) {
                String name = (String) nit.next();
                String value = props.getProperty(name);
                sm.put(name,value);
            }
            return sm;
        }
        return null;
    }
   
    protected void addIncludeBlock(StringBuffer buffer) {
        if ( includes.size() > 0 ) {
            for ( int i = 0; i < includes.size();i++) {
                IncludeEntry ie = (IncludeEntry)includes.get(i);
                buffer.append("  <include ");
                if ( ie.getType() == IncludeEntry.PROPERTIES ) {
                    buffer.append("properties=\"");
                    buffer.append(ie.getName());
                    buffer.append("\"/>\n");
                }
            }
        }
    }
   
    protected void addVariableBlock(StringBuffer buffer) {
        Iterator it = vm.getVariables(configName).keySet().iterator();
        boolean vars = false;
        if (it.hasNext()) {
            buffer.append("  <variables>\n");
            vars = true;
        }
        while (it.hasNext()) {
            String varName = (String) it.next();
            String varText = (String) vm.getVariables(configName).get(varName);
            buffer.append("    <variable name=\"");
            buffer.append(escapeForXML(varName));
            buffer.append("\" value=\"");
            buffer.append(escapeForXML(varText));
            buffer.append("\"/>\n");
        }
        if (vars) {
            buffer.append("  </variables>\n");
        }
    }
   
    protected String escapeForXML(String text) {       
        StringBuffer result = new StringBuffer();
        for ( int i = 0; i < text.length();i++) {
            char character = text.charAt(i);
            if (character == '<') {
                result.append("&lt;");
              }
              else if (character == '>') {
                result.append("&gt;");
              }
              else if (character == '\"') {
                result.append("&quot;");
              }
              else if (character == '\'') {
                result.append("&#039;");
              }
              else if (character == '\\') {
                 result.append("&#092;");
              }
              else if (character == '&') {
                 result.append("&amp;");
              }
              else {               
                result.append(character);
              }
        }       
        return result.toString();
    }
   
    /**
     * Adds the PropertyListener to the main category.
     *
     * If the main category changes after the listener has
     * already been added, the listener is still registered,
     * but not to the main category any longer. One way to
     * handle this behavior is to remove the listener from
     * the old main category and add it to the new main
     * category.
     *
     * @param listener
     */
    public void addPropertyListener(PropertyListener listener) {
        addPropertyListener(listener, mainCategory);
    }
   
    /**
     * Adds the PropertyListener to the given category.
     */
    public void addPropertyListener(PropertyListener listener, String categoryName) {
        getCategory(categoryName).addPropertyListener(listener);
    }
   
    public void addCategoryListener(CategoryListener listener) {
      addCategoryListener(listener,mainCategory);
    }
   
    public void addCategoryListener(CategoryListener listener,String categoryName) {
      getCategory(categoryName).addCategoryListener(listener);
    }
    /**
     * Return the name of the current configuration.
     * @return
     */
    public String getConfigName() {
        return configName;
    }
   
    public void setConfigName(String configName) {
        this.configName = configName;
    }
   
    /**
     * Adds the specified configuration listener to receive configuration
     * changed events from this configuration.
     *
     * @param listener The ConfigurationListener
     */
    public void addConfigurationListener(ConfigurationListener listener) {
        configurationListenerList.add(ConfigurationListener.class, listener);
    }
   
    /**
     * Removes the specified configuration listener from the configuration
     * change events from this configuration.
     *
     * @param listener The ConfigurationListener
     */
    public void removeConfigurationListener(ConfigurationListener listener) {
        configurationListenerList.remove(ConfigurationListener.class, listener);
    }
   
    /**
     * Deliver configuration changed event to all listeners that are registered
     * with our listener list.
     *
     * @param event The ConfigurationChangedEvent
     */
    public void fireConfigurationChangedEvent(ConfigurationChangedEvent event) {
        // Guaranteed to return a non-null array
        Object[] listeners = configurationListenerList.getListenerList();
        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length - 2; i >= 0; i -= 2) {
            if (listeners[i] == ConfigurationListener.class) {
                // Lazily create the event:
                ((ConfigurationListener) listeners[i + 1]).configurationChanged(event);
            }
        }
    }
   
    /**
     * Returns the main category for this configuration
     *
     * @return The main category
     */
    public Category getCategory() {
        return getCategory(mainCategory);
    }
   
    /**
     * Returns a category based on the name provided.
     *
     * This implementation has an interesting twist now inside. We need to check
     * if the parent's configuration has a category of the same name. The normal
     * case is that we override a value in a parent configuration, but we still want
     * the values from the parent configuration if they aren't overridden.
     *
     * Example. parentConfiguration has category A and has property key AKey
     * childConfiguration extends parentConfiguration has category and has property key BKey
     *
     * childConfiguration.getCategory("A").getProperty("AKey"); // didn't work, works with this implementation
     * childConfiguration.getCategory("A").getProperty("BKey"); // always worked
     *
     * The reason for this change is that the category objects don't know anything about
     * brother, sister, parent or any other relations. This method handles the logic to
     * gather the information about brother, sister, parent, cousin or whatever.
     *
     * @param categoryName The name of the category (if null, main category will be used)
     * @return The category object (new instance if necessary)
     */
    public Category getCategory(String categoryName) {
//      System.err.println("retrieving category "+categoryName);
        if(categoryName == null) {
            categoryName = mainCategory;
        }
       
        Category category = (Category)categories.get(categoryName);
        // the value might be in the base config, so we need to check that too.
        if( category == null ) { // category not found, but could be in baseConfig defined
            if ( baseConfigName != null ) {
//              System.err.println("!!looking in base config " +baseConfigName + " for category");
              Configuration cfg = ConfigurationManager.getConfiguration(baseConfigName);
              return cfg.getCategory(categoryName);
            }
//            System.err.println("getCategory(): creating DefaultCategory " + categoryName + " in " + configName + " configuration");
            category = new DefaultCategory(categoryName);
            categories.put(categoryName, category);
        } else { // category found, but we still need to see if the parent config has a matching category
          if ( baseConfigName != null && !"base".equals(baseConfigName) ) { // "base" needs to checked, otherwise endless loop!
//            System.err.println("have a baseConfigName:"+baseConfigName);
            Configuration parentCfg = ConfigurationManager.getConfiguration(baseConfigName);
            Category parentCategory = parentCfg.getCategory(categoryName);
            Properties props = parentCategory.getProperties();
            // TODO: needs to be investigated, whether or not we should clone the categories
            // when we rewrite them. This might cost a little bit, but we should have an
            // easier time if we need to save the values back to the property/xml/database/etc.
            // I think the save configuration might produce false results.
            for (Iterator iter = props.keySet().iterator(); iter.hasNext();) {
          String element = (String) iter.next();
          if ( category.getProperty(element) == null) { // we don't want to overwrite the child value, if it exists
                                                      // in the parent config's category too!
//            System.err.println("## ##");
            category.setProperty(element, parentCategory.getProperty(element));
          }
        }
          }
        }
        return category;
    }
   
   
    /**
     * Wrapper method to Category method
     *
     * @param key
     * @param value
     */
    public void setLongProperty(String key, long value) {
        getCategory().setLongProperty(key, value);
    }
   
   
    /**
     * Wrapper method to Category method
     *
     * @param key
     * @param value
     */
    public void setIntProperty(String key, int value) {
        getCategory().setIntProperty(key, value);
       
    }
   
   
    /**
     * Wrapper method to Category method
     *
     * @param key
     * @param value
     */
    public void setCharProperty(String key, char value) {
        getCategory().setCharProperty(key, value);
    }
   
    /**
     * Wrapper method to Category method
     *
     * @param key
     * @param value
     * @param category
     */
    public void setCharProperty(String key, char value, String category) {
        getCategory(category).setCharProperty(key, value);
    }
   
    /**
     * Wrapper method to Category method
     *
     * @param key
     * @param value
     */
    public void setDoubleProperty(String key, double value) {
        getCategory().setDoubleProperty(key, value);
       
    }
   
    /**
     * Wrapper method to Category method
     *
     * @param key
     * @param value
     * @param category
     */
    public void setLongProperty(String key, long value, String category) {
        getCategory(category).setLongProperty(key, value);
    }
   
    /**
     * Wrapper method to Category method
     *
     * @param key
     * @param value
     * @param category
     */
    public void setIntProperty(String key, int value, String category) {
        getCategory(category).setIntProperty(key, value);
    }
   
    /**
     * Wrapper method to Category method
     *
     * @param key
     * @param value
     * @param category
     */
    public void setDoubleProperty(String key, double value, String category) {
        getCategory(category).setDoubleProperty(key, value);
    }
   
    public boolean hasChanged() {
        return dirtyFlag;
    }
   
    public String[] getArray(String key) {
        return getArray(key,null);       
    }
   
    public String[] getArray(String key, String[] defaultValue) {
        return getArray(key,defaultValue,mainCategory);
    }
   
    public String[] getArray(String key, String[] defaultValue, String category) {
      return getArray(key,defaultValue,category,",");
    }
   
    public String[] getArray(String key, String[] defaultValue, String category,String separator) {
        String value = getProperty(key,null,category);
        if ( value == null ) {
            return defaultValue;
        }
        Vector all = new Vector();
        StringTokenizer sto = new StringTokenizer(value,separator);
        while ( sto.hasMoreElements() ) {
            String val = (String)sto.nextElement();
            val = vm.replaceVariables(val,configName);
            all.add(val);
        }
        return (String[])all.toArray(new String[0]);       
    }
   
    public boolean isNew() {
        return created;
    }
   
    public void resetCreated() {
        created = false;
    }
   
    public String getEncoding() {
        return encoding;
    }
   
    protected void markDirty() {
      dirtyFlag = true;
    }
   
    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }
   
    public boolean containsCategory(String categoryName) {
        if(categoryName == null) {
            return false;
        }
        Category category = (Category)categories.get(categoryName);
        if( category != null ) {
            return true;
        }
        return false;
    }
   
    public void addInclude(int type, String name) {
        IncludeEntry ie = new IncludeEntry(name,type);
        includes.add(ie);
    }
   
    public Vector getIncludes() {
        return includes;
    }   
   
    public void setBaseConfiguration(String name) {
        baseConfigName = name;
        VariableManager.getInstance().setInheritance(configName,name);
    }   
 
  public String getBaseConfiguration() {
    return baseConfigName;
  }
           
    protected class MyCategoryListener implements CategoryListener {
       
                /* (non-Javadoc)
                 * @see org.jconfig.event.CategoryListener#categoryChanged(org.jconfig.event.CategoryChangedEvent)
                 */
        public void categoryChanged(CategoryChangedEvent event) {
            fireConfigurationChangedEvent((ConfigurationChangedEvent)event);
           
        }
       
                /* (non-Javadoc)
                 * @see org.jconfig.event.PropertyListener#propertyChanged(org.jconfig.event.PropertyChangedEvent)
                 */
        public void propertyChanged(PropertyChangedEvent e) {
        }
       
    }
   
}
TOP

Related Classes of org.jconfig.DefaultConfiguration$MyCategoryListener

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.