⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 confighelper.java

📁 Java 3D Desktop Environment旨在使用Java 3D来创建一个3D桌面环境。功能包括:分布式的应用程序
💻 JAVA
字号:
/* * Copyright (c) 2000, Niklas Mehner  * All rights reserved. *  * Redistribution and use in source and binary forms, with or without  * modification, are permitted provided that the following conditions  * are met: *  *   - Redistributions of source code must retain the above copyright  *     notice, this list of conditions and the following disclaimer. *  *   - 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. *  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  * ``AS IS'' AND ANY EXPRESS 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 REGENTS OR  * 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.  */ package org.j3de.util; 

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;
                          
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Document;     
import org.w3c.dom.Element;

import org.j3de.exception.ExceptionHandler;

public class ConfigHelper {                       
  private Node     root;                              
  private Document nodeFactory;
  private List     components;
  private boolean  configurationChanged;  
   
  public ConfigHelper(Node root, Document nodeFactory, boolean newNode) {
    this.root = root;       
    this.nodeFactory = nodeFactory;
    this.components = new Vector();
    this.configurationChanged = newNode;
  }    
  
  public ConfigHelper(Node root) {  
    this(root, null, false);
  }        
  
  public boolean isConfigurationChanged() { 
    if (configurationChanged)
      return true;
                 
    for (int i=0; i<components.size(); i++) {
      if (((Configurable)components.get(i)).isConfigurationChanged())
        return true;
    }
    
    return false;  
  }              

  public void configurationSaved() {   
    configurationChanged = false;      
    for (int i=0; i<components.size(); i++) {
      if (((Configurable)components.get(i)).isConfigurationChanged())
        ((Configurable)components.get(i)).configurationSaved();
    }
  }
   
  public static Element newComponent(Document nodeFactory, String componentKind, Configurable component) {
    Element element = nodeFactory.createElement("component");
    element.setAttribute("name", componentKind);
    element.setAttribute("classname", component.getClass().getName());  
    
    return element; 
  }  

  public Object getComponent(String      componentName) throws ConfigurationException {  
    return getComponent(componentName, null, null, null); 
  }                                                     
  
  public Object getComponent(String      componentName, 
                             Class       defaultImplementation) throws ConfigurationException  {  
    return getComponent(componentName, 
                        defaultImplementation,
                        null, null); 
  } 
  
  public Object getComponent(String      componentName, 
                             Class       defaultImplementation,
                             Class[]     parameterTypes,
                             Object[]    parameters) throws ConfigurationException {  
    return getComponent(componentName, 
                        defaultImplementation,
                        parameterTypes,
                        parameters,
                        this.getClass().getClassLoader()); 
  }
                                   
  public Object getComponent(String      componentName, 
                             Class       defaultImplementation,
                             Class[]     parameterTypes,
                             Object[]    parameters,
                             ClassLoader loader) throws ConfigurationException {
    String classname = null;

    try {
      Object result = null;
    
      NodeList nodes = root.getChildNodes();
      for (int i=0; i<nodes.getLength(); i++) {
        Node node = nodes.item(i);       
        
        // If this node defines a component search the attributes
        // for its name and classname
        if (node.getNodeName().equals("component")) {     
          String name = null;
          String attrname;
          
          NamedNodeMap attributes = node.getAttributes();
          
          for (int attrnr=0; attrnr<attributes.getLength(); attrnr++) {    
            attrname = attributes.item(attrnr).getNodeName(); 
            if (attrname.equals("name")) {
              name = attributes.item(attrnr).getNodeValue();
            } else if (attrname.equals("classname")) {
              classname = attributes.item(attrnr).getNodeValue();
            }                                            
       
          }                                              
          
          // seems we have found, what we are looking for.
          // instantiate this component
          if ((classname != null) && 
              ((componentName == null) || ((name != null) && name.equals(componentName)))) {  
            
            if (parameterTypes != null) {  
              
              Constructor constructor;
              try {
                constructor= loader.loadClass(classname.trim()).getConstructor(parameterTypes);
              } catch (NoSuchMethodException e) {
                ExceptionHandler.handleException(e);
                String parameterString = "(";
                for (int j=0; j<parameterTypes.length; j++)
                  parameterString += parameterTypes[j].getName() + " ";
                parameterString += ")";
                throw new ConfigurationException("Class " + classname + " has no constructor" + parameterString);
              }
              
              result = constructor.newInstance(parameters);
              
            } else { 
              result = loader.loadClass(classname.trim()).newInstance();    
            }
            
          } 
          
          if (result instanceof Configurable)
            ((Configurable)result).configure(node, nodeFactory);
        }
      }
      
      // we did not find any suitable component : create default component
      // and configure it.         
      if ((result == null) && (defaultImplementation != null)){    
        configurationChanged = true;
        if (parameterTypes != null) {   
          Constructor constructor;
          try {
            constructor = defaultImplementation.getConstructor(parameterTypes);
          } catch (NoSuchMethodException e) {
            ExceptionHandler.handleException(e);
            String parameterString = "(";
            for (int j=0; j<parameterTypes.length; j++)
              parameterString += parameterTypes[j].getName() + " ";
            parameterString += ")";
            throw new ConfigurationException("Class " + defaultImplementation + " has no constructor" + parameterString);
          }

          result =  (Configurable)constructor.newInstance(parameters);
        } else { 
          result = (Configurable)defaultImplementation.newInstance();        
        }
        
        root.appendChild(((Configurable)result).configure(nodeFactory, componentName));    
      }
      
      if ((result != null) && (result instanceof Configurable))                   
        components.add(result);
    
      return result;
    } catch (ClassNotFoundException e) {
      ExceptionHandler.handleException(e);
      throw new ConfigurationException("Class " + classname + " could not be found while loading component : " + componentName);
    } catch (IllegalAccessException e) {
      ExceptionHandler.handleException(e);
      throw new ConfigurationException("No access to constructor of class " + classname + " while loading component : " + componentName);
    } catch (InstantiationException e) {
      ExceptionHandler.handleException(e);
      throw new ConfigurationException("Exception while instantiating  " + classname + " while loading component : " + componentName);
    } catch (InvocationTargetException e) {
      ExceptionHandler.handleException(e);
      throw new ConfigurationException("Exception thrown by constructor of class  " + classname + " while loading component : " + componentName);
    }   
  }             
  
  public void newProperty(String name, String value) { 
    configurationChanged = true;

    Element element = nodeFactory.createElement("property");
    element.setAttribute("name",  name);
    element.setAttribute("value", value);  
    
    root.appendChild(element);
  }
  
  public String getPropertyValue(String name) { 
    NodeList childNodes = root.getChildNodes();   
    
    for (int i=0; i<childNodes.getLength(); i++) {
      Node node = childNodes.item(i);
      if (node.getNodeName().equals("property")) {
        NamedNodeMap attributes = node.getAttributes();  
        Node attrib = attributes.getNamedItem("name");
        
        if ((attrib != null) && (attrib.getNodeValue().equals(name)))
          return attributes.getNamedItem("value").getNodeValue();
      }
    }
    
    return null;
  }    
  
  public String getPropertyValue(String name, String defaultValue, boolean warn) {
    String value = getPropertyValue(name);
    
    if (value != null)
      return value;
      
    if (warn)
      ExceptionHandler.handleWarning(
        "Property not found : " + name + 
        " in Node " + root.getNodeName() + " ["+ root.getNodeValue() + "]"); 
        
    return defaultValue;
  }                                             
    
  public int getPropertyValue(String name, int defaultValue, boolean warn) {
    return Integer.parseInt(getPropertyValue(name, new Integer(defaultValue).toString(), warn));
  }

  public double getPropertyValue(String name, double defaultValue, boolean warn) {
    return Double.parseDouble(getPropertyValue(name, new Double(defaultValue).toString(), warn));
  }
  
  public List getList(String name, EntryFactory factory) {
    List result = new Vector();
    NodeList childNodes = root.getChildNodes();   
    
    for (int i=0; i<childNodes.getLength(); i++) {
      Node node = childNodes.item(i);    
      
      if (node.getNodeName().equals("list")) {  
        NamedNodeMap attributes = node.getAttributes();  
        Node attrib = attributes.getNamedItem("name");      
        
        if ((attrib != null) && (attrib.getNodeValue().equals(name))) {
          NodeList itemList = node.getChildNodes();           
         
          for (int j=0; j<itemList.getLength(); j++) { 
            Node item = itemList.item(j);
            
            if (item.getNodeName().equals("listitem")) { 
              try {
                result.add(factory.createEntry(item));   
              } catch (Exception e) {
                ExceptionHandler.handleException(new ConfigurationException("Got null-value for map. Skipping Entry."));
              } 
            }
          }
        }
      }
    }
    
    return result;
  } 
  
  public Map getMap(String name, EntryFactory factory) {
    Map result = new Hashtable();
    NodeList childNodes = root.getChildNodes();   
    
    for (int i=0; i<childNodes.getLength(); i++) {
      Node node = childNodes.item(i);    
      
      if (node.getNodeName().equals("map")) {  
        NamedNodeMap attributes = node.getAttributes();  
        Node attrib = attributes.getNamedItem("name");      
        
        if ((attrib != null) && (attrib.getNodeValue().equals(name))) {
          NodeList itemList = node.getChildNodes();           
         
          for (int j=0; j<itemList.getLength(); j++) { 
            Node item = itemList.item(j);
            
            if (item.getNodeName().equals("mapitem")) { 
              NamedNodeMap itemattributes = item.getAttributes(); 
              Node itemname = itemattributes.getNamedItem("name"); 
              try {      
                result.put(itemname.getNodeValue(), factory.createEntry(item));
              } catch (NullPointerException e) {    
                 ExceptionHandler.handleException(e);
                ExceptionHandler.handleException(new ConfigurationException("Got null-value for map. Skipping Entry."));
              }   
            }
          }
        }
      }
    }
    
    return result;
  } 
  
  public List getComponentList(String name) {
    return getList(name, new ComponentFactory());
  }
    
  public Map getComponentMap(String name, ClassLoader loader) {  
    return getMap(name, new ComponentFactory(loader));
  }
  
  public Map getComponentMap(String name) { 
    return getMap(name, new ComponentFactory());
  }      
  
  public Map getStringMap(String name) {
    return getMap(name, new EntryFactory() { 
      public Object createEntry(Node node) {
        try {
          NamedNodeMap attributes = node.getAttributes();  
          return attributes.getNamedItem("value").getNodeValue();
        } catch (Exception e) {
          ExceptionHandler.handleException(e);
          return null;
        }
      }
    });
  }    

  public List getIntList(String name) {
    return getList(name, new EntryFactory() { 
      public Object createEntry(Node node) {
        try {
          NamedNodeMap attributes = node.getAttributes();  
          return new Integer(attributes.getNamedItem("name").getNodeValue());
        } catch (Exception e) {
          ExceptionHandler.handleException(e);
          return null;
        }
      }
    });
  }    

  private class ComponentFactory implements EntryFactory {
    private ClassLoader classloader;                      
    
    public ComponentFactory() {              
      this.classloader = this.getClass().getClassLoader();
    }

    public ComponentFactory(ClassLoader classloader) {              
      this.classloader = classloader;
    }
      
    public Object createEntry(Node node) {  
      try {                             
        return new ConfigHelper(node, nodeFactory, false).getComponent(null,  null, null, null, classloader);
      } catch (Exception e) {
        ExceptionHandler.handleException(e);
      }
        
      return null;
    }
  }  
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -