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

📄 agentserverconfiggenerator.java

📁 一个类似于openJMS分布在ObjectWeb之下的JMS消息中间件。
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* * Copyright (C) 2000 ScalAgent Distributed Technologies * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or any later version. *  * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU * Lesser General Public License for more details. *  * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 * USA. * */package fr.dyade.aaa.util;import java.io.IOException;import java.io.OutputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.util.Hashtable;import java.util.Properties;import java.util.StringTokenizer;import java.util.Vector;import org.apache.xml.serialize.OutputFormat;import org.apache.xml.serialize.XMLSerializer;import org.apache.xerces.dom.DocumentImpl;import org.apache.xerces.parsers.DOMParser;import org.w3c.dom.*;import org.xml.sax.SAXException;import org.xml.sax.InputSource;// TODO : allow to have only a transient server in a serverSEtpublic class AgentServerConfigGenerator{  public static final String VAR_MARK = "$";  public static final String CONFIG_TAG = "config";  public static final String VAR_TAG = "var";   public static final String SET_TAG = "serverSet";  public static final String PROPERTY_TAG = "property";  public static final String DOMAIN_TAG = "domain";  public static final String NETWORK_TAG = "network";  public static final String SERVER_TAG = "server";  public static final String TRANSIENT_TAG = "transient";  public static final String NAME = "name";  public static final String ID = "id";  public static final String PORT = "port";  public static final String SERVER = "server";  public static final String INFO = "info";  public static final String VALUE = "value";  public static final String TYPE = "type";  public static final String A3_DTD = "a3config.dtd";  private static final String DOMAINS_PREFIX = "D";  private static final String ADMIN_SERVER_NAME = "s0";  private static final String ADMIN_DOMAIN = "D0";  private static final String GLOBALS = "GLOBALS";  private int indent = 2;  private Element templateRoot;  //private Element previousConfigRoot;  private Hashtable defaultValues = new Hashtable();  // to know if default values has been set for a type of block  private Hashtable varsSet = new Hashtable();  private String currentDomain = null;  private boolean merge = false;  /**    * constructor    **/  public AgentServerConfigGenerator(String templateFile)     throws SAXException, IOException{    DOMParser parser = new DOMParser();    parser.parse(templateFile);    init(parser);  }  public AgentServerConfigGenerator(InputStream template)    throws SAXException, IOException{    DOMParser parser = new DOMParser();    parser.parse(new InputSource(template));    init(parser);  }  private void init(DOMParser parser) throws SAXException, IOException {    Document doc = parser.getDocument();    // add specifics variable to template Root    // the port  name of router, no default value    Element routerElement = doc.createElement(VAR_TAG);    routerElement.setAttribute(NAME, "domain.port");    routerElement.setAttribute(TYPE, "java.lang.Integer");    routerElement.setAttribute(INFO,"The port required on admin server to connect to new domain");    // get root element    templateRoot = doc.getDocumentElement();    templateRoot.appendChild(routerElement);  }  /**   * set nb of chars for indentation   */  public void setIndent(int indent){    this.indent = indent;  }  /**   * return the list of all set types defined in template   */  public String[] getServerSetTypes(){    NodeList childs = templateRoot.getChildNodes();    Vector v = new Vector();    for (int i=0; i<childs.getLength(); i++){      Node currentNode = childs.item(i);      if (currentNode.getNodeType() == Node.ELEMENT_NODE &&             currentNode.getNodeName().equals(SET_TAG)){        v.addElement(currentNode.getAttributes().getNamedItem(NAME).getNodeValue());      }    }    String[] res = new String[v.size()];    v.copyInto(res);    return res;  }//   /**//    * This fonction is obsolete, it will be automatically a merge//    * creation of a3config as an xml OutputStream//    *///   public void build(OutputStream os, Properties p) //     throws IOException, A3configException{//     Document currentDoc = new DocumentImpl();//     DocumentType docType = //       ((DocumentImpl)currentDoc).createDocumentType(CONFIG_TAG, null, A3_DTD);//     Element root = currentDoc.createElement(CONFIG_TAG);//     currentDoc.appendChild(docType);//     currentDoc.appendChild(root);//     buildSimpleElement(PROPERTY_TAG, root, p);//     buildSimpleElement(DOMAIN_TAG, root, p);//     instantiateServers((short)0, root, p);//     write(currentDoc, os);//   }  /**   * Generate news a3servers configurations depending of new template,   * new properties and existing configuration.   *    * @param totalConfig The whole configuration including all applications,   *  only known by admin server s0   * @param localConfig The application specific configuration, seen    *  by application servers   * @param previousConfig The name of the previous configuration file    *  (a3servers.xml)   * @param p The properties to instantiate new configuration   */  public void merge(OutputStream totalConfig, OutputStream localConfig,                    Properties p, InputStream previousConfig,                    String instanceName)    throws IOException, A3configException, SAXException{    merge = true;    // parse existing config    DOMParser parser = new DOMParser();    parser.parse(new InputSource(previousConfig));    Document previousDoc = parser.getDocument();    Element previousRoot = previousDoc.getDocumentElement();    // generate new domain name    //currentDomain = newDomain(previousRoot);    currentDomain = instanceName;    DocumentImpl localDoc = new DocumentImpl();    // create local configuration//     localDoc.appendChild(//       localDoc.importNode(previousDoc.getDoctype(), true));    Element localRoot = localDoc.createElement(CONFIG_TAG);    localDoc.appendChild(localRoot);    buildSimpleElement(PROPERTY_TAG, localRoot, p);    buildSimpleElement(DOMAIN_TAG, localRoot, p);    short nextId = getNextId(previousRoot);    nextId = instantiateServers(nextId, localRoot, p);    previousRoot.setAttribute("nextServerId", "" + nextId);    // write configs    updateConfs(localRoot, previousRoot, p);    write(previousDoc, totalConfig);    write(localDoc, localConfig);  }  ////////////////////////  // FIXME this method is defined to workaround a xerces bug : deletes  // attributes on import nodes unless parse attributes of child before  // should be removed later  private void updateImport(Element elem){     NamedNodeMap attrs= elem.getAttributes();    for (int i=0; i<attrs.getLength(); i++){      attrs.item(i).getNodeName();      attrs.item(i).getNodeValue();    }    NodeList childs = elem.getChildNodes();    for (int i=0; i<childs.getLength(); i++){      // recall fonction only for elements      if (childs.item(i).getNodeType() == Node.ELEMENT_NODE){        updateImport((Element)childs.item(i));      }    }  }  //////////////////////    private void write(Document doc, OutputStream out) throws IOException{    OutputFormat format  = new OutputFormat(doc);    format.setIndent(indent);    XMLSerializer  serial = new XMLSerializer(out, format);    serial.asDOMSerializer();    serial.serialize(doc);    out.flush();  }  private static Element getChild(Element parent, String tagName,                            String attrName, String attrValue)     throws A3configException{    NodeList childs = parent.getChildNodes();    Node required = null;    for (int i=0; i<childs.getLength(); i++){      Node currentNode = childs.item(i);      if (currentNode.getNodeType() == Node.ELEMENT_NODE &&           currentNode.getNodeName().equals(tagName)){        Node attr = currentNode.getAttributes().getNamedItem(attrName);        if (attr != null && attr.getNodeValue().equals(attrValue))          return (Element)currentNode;      }    }    throw new A3configException ("Unable to find " + tagName +                                  " element, with attr " + attrName +                                  " = " + attrValue);  }  /**   * returns the list of global variables   */  public ConfigVariable[] getGlobalVariables() throws A3configException{    varsSet.put(GLOBALS, GLOBALS);    return getVariables(templateRoot, true);  }  /**   * return the list of variables for a type   */  public ConfigVariable[] getServerSetVariables(String typeName) throws A3configException{    varsSet.put(typeName, typeName);    Element elm = getChild(templateRoot, SET_TAG, NAME, typeName);    return getVariables(elm, true);  }  private short getNextId(Element elem){    String lastId = elem.getAttribute("nextServerId");    if (lastId == null || lastId.equals("")){      return (short)1;    }else{      return Short.parseShort(lastId);    }//       String lastDomain = existingRoot.getAttribute("domainId");//       if (lastDomain == null || lastDomain.equals(""))//         lastDomain = "0";//       int newDomain = new Integer(lastDomain).intValue() + 1;//       existingRoot.setAttribute("domainId", "" + newDomain);//     NodeList childs = elem.getChildNodes();//     Short maxId = new Short((short)0);//     for (int i=0; i<childs.getLength(); i++){//       Node currentNode = childs.item(i);//       if (currentNode.getNodeType() == Node.ELEMENT_NODE &&//           (currentNode.getNodeName().equals(SERVER_TAG) ||//            currentNode.getNodeName().equals(TRANSIENT_TAG))){//         Short id = new Short(currentNode.getAttributes().//                              getNamedItem(ID).getNodeValue());//         if (maxId.compareTo(id) < 0){//           maxId = id;//         }//       }//     }//     return (short)(maxId.intValue()+1);  }//   private String newDomain(Element existingRoot) throws A3configException{//     // generated domains are of the format D1 D2...//     // if an application define subdomains, they will have format D1.sub//     if (merge){//       // get last generated domain//       String lastDomain = existingRoot.getAttribute("domainId");//       if (lastDomain == null || lastDomain.equals(""))//         lastDomain = "0";//       int newDomain = new Integer(lastDomain).intValue() + 1;//       existingRoot.setAttribute("domainId", "" + newDomain);//       return (DOMAINS_PREFIX + newDomain);//     }else{//       return DOMAINS_PREFIX + "1";//     }//   }  private short instantiateServers(short nextId, Element root, Properties p)    throws A3configException{    NodeList childs = templateRoot.getChildNodes();    for (int i=0; i<childs.getLength(); i++){      Node child = childs.item(i);      if (child.getNodeType() == Node.ELEMENT_NODE &&           child.getNodeName().equals(SET_TAG)){        // get the name of the serverSet        String setName =          child.getAttributes().getNamedItem(NAME).getNodeValue();        // Check if variables have been initialized ?        if (varsSet.get(setName) == null){          getVariables(child, false);        }        // check required instances of this set        String instances = p.getProperty(setName);        if (instances != null){          StringTokenizer st = new StringTokenizer(instances, ",");          while(st.hasMoreElements()){            String instanceName = ((String)st.nextElement()).trim();            nextId = instantiateSet(instanceName, child, root, p, nextId);          }        }      }    }    if (nextId++ == Short.MAX_VALUE)      return (short)1;    return nextId;  }  private short instantiateSet(String instanceName, Node setNode,                                Element root, Properties p,                                short nextId) throws A3configException{    NodeList childs = setNode.getChildNodes();    int serversNb = countChilds(setNode, SERVER_TAG);    // TODO : should be allowed...    if (serversNb == 0)      throw new A3configException(        "A serverSet element must contain at least one server");    int transientNb = countChilds(setNode, TRANSIENT_TAG);    int serverPrefixName = 1;    int transientPrefixName = 1;    Short firstServer = new Short(nextId);    Hashtable relativeIds = new Hashtable();    // instantiate servers at once to know ids when instantiate transients    for (int i=0; i<childs.getLength(); i++){      Node sNode = childs.item(i);      if (sNode.getNodeType() == Node.ELEMENT_NODE &&          sNode.getNodeName().equals(SERVER_TAG)){        Element serverElt = instantiateElement(root.getOwnerDocument(),                                               instanceName, sNode, p);        // check if name have been defined (eg was in a var)        String serverName = null;        ////////////////////////////        if (serverElt.getAttributes().getNamedItem(NAME) != null){          String definedName =             serverElt.getAttributes().getNamedItem(NAME).getNodeValue();          if(! definedName.equals(""))            serverName =  instanceName + "." + definedName;        }        if (serverName == null){          serverName = instanceName;          if (serversNb > 1)            serverName += ("." + serverPrefixName ++);        }        //////////////////////////////         if (serverElt.getAttributes().getNamedItem(NAME) != null){//           serverName = instanceName + "." + //             serverElt.getAttributes().getNamedItem(NAME).getNodeValue();//           System.out.println("-1- " + serverName);//         }

⌨️ 快捷键说明

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