KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > fr > dyade > aaa > util > AgentServerConfigGenerator


1 /*
2  * Copyright (C) 2000 ScalAgent Distributed Technologies
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
17  * USA.
18  *
19  */

20 package fr.dyade.aaa.util;
21
22 import java.io.IOException JavaDoc;
23 import java.io.OutputStream JavaDoc;
24 import java.io.FileOutputStream JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.util.Hashtable JavaDoc;
27 import java.util.Properties JavaDoc;
28 import java.util.StringTokenizer JavaDoc;
29 import java.util.Vector JavaDoc;
30 import org.apache.xml.serialize.OutputFormat;
31 import org.apache.xml.serialize.XMLSerializer;
32 import org.apache.xerces.dom.DocumentImpl;
33 import org.apache.xerces.parsers.DOMParser;
34 import org.w3c.dom.*;
35 import org.xml.sax.SAXException JavaDoc;
36 import org.xml.sax.InputSource JavaDoc;
37
38 // TODO : allow to have only a transient server in a serverSEt
39

40 public class AgentServerConfigGenerator{
41
42   public static final String JavaDoc VAR_MARK = "$";
43   public static final String JavaDoc CONFIG_TAG = "config";
44   public static final String JavaDoc VAR_TAG = "var";
45   public static final String JavaDoc SET_TAG = "serverSet";
46   public static final String JavaDoc PROPERTY_TAG = "property";
47   public static final String JavaDoc DOMAIN_TAG = "domain";
48   public static final String JavaDoc NETWORK_TAG = "network";
49   public static final String JavaDoc SERVER_TAG = "server";
50   public static final String JavaDoc TRANSIENT_TAG = "transient";
51   public static final String JavaDoc NAME = "name";
52   public static final String JavaDoc ID = "id";
53   public static final String JavaDoc PORT = "port";
54   public static final String JavaDoc SERVER = "server";
55   public static final String JavaDoc INFO = "info";
56   public static final String JavaDoc VALUE = "value";
57   public static final String JavaDoc TYPE = "type";
58   public static final String JavaDoc A3_DTD = "a3config.dtd";
59
60   private static final String JavaDoc DOMAINS_PREFIX = "D";
61   private static final String JavaDoc ADMIN_SERVER_NAME = "s0";
62   private static final String JavaDoc ADMIN_DOMAIN = "D0";
63   private static final String JavaDoc GLOBALS = "GLOBALS";
64   private int indent = 2;
65   private Element templateRoot;
66   //private Element previousConfigRoot;
67
private Hashtable JavaDoc defaultValues = new Hashtable JavaDoc();
68   // to know if default values has been set for a type of block
69
private Hashtable JavaDoc varsSet = new Hashtable JavaDoc();
70   private String JavaDoc currentDomain = null;
71   private boolean merge = false;
72
73   /**
74    * constructor
75    **/

76   public AgentServerConfigGenerator(String JavaDoc templateFile)
77     throws SAXException JavaDoc, IOException JavaDoc{
78     DOMParser parser = new DOMParser();
79     parser.parse(templateFile);
80     init(parser);
81   }
82
83   public AgentServerConfigGenerator(InputStream JavaDoc template)
84     throws SAXException JavaDoc, IOException JavaDoc{
85     DOMParser parser = new DOMParser();
86     parser.parse(new InputSource JavaDoc(template));
87     init(parser);
88   }
89
90   private void init(DOMParser parser) throws SAXException JavaDoc, IOException JavaDoc {
91     Document doc = parser.getDocument();
92     // add specifics variable to template Root
93
// the port name of router, no default value
94
Element routerElement = doc.createElement(VAR_TAG);
95     routerElement.setAttribute(NAME, "domain.port");
96     routerElement.setAttribute(TYPE, "java.lang.Integer");
97     routerElement.setAttribute(INFO,"The port required on admin server to connect to new domain");
98     // get root element
99
templateRoot = doc.getDocumentElement();
100     templateRoot.appendChild(routerElement);
101   }
102
103   /**
104    * set nb of chars for indentation
105    */

106   public void setIndent(int indent){
107     this.indent = indent;
108   }
109
110   /**
111    * return the list of all set types defined in template
112    */

113   public String JavaDoc[] getServerSetTypes(){
114     NodeList childs = templateRoot.getChildNodes();
115     Vector JavaDoc v = new Vector JavaDoc();
116     for (int i=0; i<childs.getLength(); i++){
117       Node currentNode = childs.item(i);
118       if (currentNode.getNodeType() == Node.ELEMENT_NODE &&
119             currentNode.getNodeName().equals(SET_TAG)){
120         v.addElement(currentNode.getAttributes().getNamedItem(NAME).getNodeValue());
121       }
122     }
123     String JavaDoc[] res = new String JavaDoc[v.size()];
124     v.copyInto(res);
125     return res;
126   }
127
128
129
130 // /**
131
// * This fonction is obsolete, it will be automatically a merge
132
// * creation of a3config as an xml OutputStream
133
// */
134
// public void build(OutputStream os, Properties p)
135
// throws IOException, A3configException{
136
// Document currentDoc = new DocumentImpl();
137
// DocumentType docType =
138
// ((DocumentImpl)currentDoc).createDocumentType(CONFIG_TAG, null, A3_DTD);
139
// Element root = currentDoc.createElement(CONFIG_TAG);
140
// currentDoc.appendChild(docType);
141
// currentDoc.appendChild(root);
142
// buildSimpleElement(PROPERTY_TAG, root, p);
143
// buildSimpleElement(DOMAIN_TAG, root, p);
144
// instantiateServers((short)0, root, p);
145
// write(currentDoc, os);
146
// }
147

148   /**
149    * Generate news a3servers configurations depending of new template,
150    * new properties and existing configuration.
151    *
152    * @param totalConfig The whole configuration including all applications,
153    * only known by admin server s0
154    * @param localConfig The application specific configuration, seen
155    * by application servers
156    * @param previousConfig The name of the previous configuration file
157    * (a3servers.xml)
158    * @param p The properties to instantiate new configuration
159    */

160   public void merge(OutputStream JavaDoc totalConfig, OutputStream JavaDoc localConfig,
161                     Properties JavaDoc p, InputStream JavaDoc previousConfig,
162                     String JavaDoc instanceName)
163     throws IOException JavaDoc, A3configException, SAXException JavaDoc{
164     merge = true;
165     // parse existing config
166
DOMParser parser = new DOMParser();
167     parser.parse(new InputSource JavaDoc(previousConfig));
168     Document previousDoc = parser.getDocument();
169     Element previousRoot = previousDoc.getDocumentElement();
170     // generate new domain name
171
//currentDomain = newDomain(previousRoot);
172
currentDomain = instanceName;
173     DocumentImpl localDoc = new DocumentImpl();
174     // create local configuration
175
// localDoc.appendChild(
176
// localDoc.importNode(previousDoc.getDoctype(), true));
177
Element localRoot = localDoc.createElement(CONFIG_TAG);
178     localDoc.appendChild(localRoot);
179     buildSimpleElement(PROPERTY_TAG, localRoot, p);
180     buildSimpleElement(DOMAIN_TAG, localRoot, p);
181     short nextId = getNextId(previousRoot);
182     nextId = instantiateServers(nextId, localRoot, p);
183     previousRoot.setAttribute("nextServerId", "" + nextId);
184     // write configs
185
updateConfs(localRoot, previousRoot, p);
186     write(previousDoc, totalConfig);
187     write(localDoc, localConfig);
188   }
189
190   ////////////////////////
191
// FIXME this method is defined to workaround a xerces bug : deletes
192
// attributes on import nodes unless parse attributes of child before
193
// should be removed later
194
private void updateImport(Element elem){
195     NamedNodeMap attrs= elem.getAttributes();
196     for (int i=0; i<attrs.getLength(); i++){
197       attrs.item(i).getNodeName();
198       attrs.item(i).getNodeValue();
199     }
200     NodeList childs = elem.getChildNodes();
201     for (int i=0; i<childs.getLength(); i++){
202       // recall fonction only for elements
203
if (childs.item(i).getNodeType() == Node.ELEMENT_NODE){
204         updateImport((Element)childs.item(i));
205       }
206     }
207   }
208   //////////////////////
209

210   private void write(Document doc, OutputStream JavaDoc out) throws IOException JavaDoc{
211     OutputFormat format = new OutputFormat(doc);
212     format.setIndent(indent);
213     XMLSerializer serial = new XMLSerializer(out, format);
214     serial.asDOMSerializer();
215     serial.serialize(doc);
216     out.flush();
217   }
218
219   private static Element getChild(Element parent, String JavaDoc tagName,
220                            String JavaDoc attrName, String JavaDoc attrValue)
221     throws A3configException{
222     NodeList childs = parent.getChildNodes();
223     Node required = null;
224     for (int i=0; i<childs.getLength(); i++){
225       Node currentNode = childs.item(i);
226       if (currentNode.getNodeType() == Node.ELEMENT_NODE &&
227           currentNode.getNodeName().equals(tagName)){
228         Node attr = currentNode.getAttributes().getNamedItem(attrName);
229         if (attr != null && attr.getNodeValue().equals(attrValue))
230           return (Element)currentNode;
231       }
232     }
233     throw new A3configException ("Unable to find " + tagName +
234                                  " element, with attr " + attrName +
235                                  " = " + attrValue);
236   }
237
238   /**
239    * returns the list of global variables
240    */

241   public ConfigVariable[] getGlobalVariables() throws A3configException{
242     varsSet.put(GLOBALS, GLOBALS);
243     return getVariables(templateRoot, true);
244   }
245
246   /**
247    * return the list of variables for a type
248    */

249   public ConfigVariable[] getServerSetVariables(String JavaDoc typeName) throws A3configException{
250     varsSet.put(typeName, typeName);
251     Element elm = getChild(templateRoot, SET_TAG, NAME, typeName);
252     return getVariables(elm, true);
253   }
254
255   private short getNextId(Element elem){
256     String JavaDoc lastId = elem.getAttribute("nextServerId");
257     if (lastId == null || lastId.equals("")){
258       return (short)1;
259     }else{
260       return Short.parseShort(lastId);
261     }
262 // String lastDomain = existingRoot.getAttribute("domainId");
263
// if (lastDomain == null || lastDomain.equals(""))
264
// lastDomain = "0";
265
// int newDomain = new Integer(lastDomain).intValue() + 1;
266
// existingRoot.setAttribute("domainId", "" + newDomain);
267

268 // NodeList childs = elem.getChildNodes();
269
// Short maxId = new Short((short)0);
270
// for (int i=0; i<childs.getLength(); i++){
271
// Node currentNode = childs.item(i);
272
// if (currentNode.getNodeType() == Node.ELEMENT_NODE &&
273
// (currentNode.getNodeName().equals(SERVER_TAG) ||
274
// currentNode.getNodeName().equals(TRANSIENT_TAG))){
275
// Short id = new Short(currentNode.getAttributes().
276
// getNamedItem(ID).getNodeValue());
277
// if (maxId.compareTo(id) < 0){
278
// maxId = id;
279
// }
280
// }
281
// }
282
// return (short)(maxId.intValue()+1);
283
}
284
285 // private String newDomain(Element existingRoot) throws A3configException{
286
// // generated domains are of the format D1 D2...
287
// // if an application define subdomains, they will have format D1.sub
288
// if (merge){
289
// // get last generated domain
290
// String lastDomain = existingRoot.getAttribute("domainId");
291
// if (lastDomain == null || lastDomain.equals(""))
292
// lastDomain = "0";
293
// int newDomain = new Integer(lastDomain).intValue() + 1;
294
// existingRoot.setAttribute("domainId", "" + newDomain);
295
// return (DOMAINS_PREFIX + newDomain);
296
// }else{
297
// return DOMAINS_PREFIX + "1";
298
// }
299
// }
300

301   private short instantiateServers(short nextId, Element root, Properties JavaDoc p)
302     throws A3configException{
303     NodeList childs = templateRoot.getChildNodes();
304     for (int i=0; i<childs.getLength(); i++){
305       Node child = childs.item(i);
306       if (child.getNodeType() == Node.ELEMENT_NODE &&
307           child.getNodeName().equals(SET_TAG)){
308         // get the name of the serverSet
309
String JavaDoc setName =
310           child.getAttributes().getNamedItem(NAME).getNodeValue();
311         // Check if variables have been initialized ?
312
if (varsSet.get(setName) == null){
313           getVariables(child, false);
314         }
315         // check required instances of this set
316
String JavaDoc instances = p.getProperty(setName);
317         if (instances != null){
318           StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(instances, ",");
319           while(st.hasMoreElements()){
320             String JavaDoc instanceName = ((String JavaDoc)st.nextElement()).trim();
321             nextId = instantiateSet(instanceName, child, root, p, nextId);
322           }
323         }
324       }
325     }
326     if (nextId++ == Short.MAX_VALUE)
327       return (short)1;
328     return nextId;
329   }
330
331
332   private short instantiateSet(String JavaDoc instanceName, Node setNode,
333                                Element root, Properties JavaDoc p,
334                                short nextId) throws A3configException{
335     NodeList childs = setNode.getChildNodes();
336     int serversNb = countChilds(setNode, SERVER_TAG);
337     // TODO : should be allowed...
338
if (serversNb == 0)
339       throw new A3configException(
340         "A serverSet element must contain at least one server");
341     int transientNb = countChilds(setNode, TRANSIENT_TAG);
342     int serverPrefixName = 1;
343     int transientPrefixName = 1;
344     Short JavaDoc firstServer = new Short JavaDoc(nextId);
345     Hashtable JavaDoc relativeIds = new Hashtable JavaDoc();
346     // instantiate servers at once to know ids when instantiate transients
347
for (int i=0; i<childs.getLength(); i++){
348       Node sNode = childs.item(i);
349       if (sNode.getNodeType() == Node.ELEMENT_NODE &&
350           sNode.getNodeName().equals(SERVER_TAG)){
351         Element serverElt = instantiateElement(root.getOwnerDocument(),
352                                                instanceName, sNode, p);
353         // check if name have been defined (eg was in a var)
354
String JavaDoc serverName = null;
355         ////////////////////////////
356
if (serverElt.getAttributes().getNamedItem(NAME) != null){
357           String JavaDoc definedName =
358             serverElt.getAttributes().getNamedItem(NAME).getNodeValue();
359           if(! definedName.equals(""))
360             serverName = instanceName + "." + definedName;
361         }
362         if (serverName == null){
363           serverName = instanceName;
364           if (serversNb > 1)
365             serverName += ("." + serverPrefixName ++);
366         }
367         ////////////////////////////
368
// if (serverElt.getAttributes().getNamedItem(NAME) != null){
369
// serverName = instanceName + "." +
370
// serverElt.getAttributes().getNamedItem(NAME).getNodeValue();
371
// System.out.println("-1- " + serverName);
372
// }
373
// if (serverName == null || serverName.equals("")){
374
// serverName = instanceName;
375
// System.out.println("-2- " + serverName);
376
// if (serversNb > 1)
377
// serverName += ("." + serverPrefixName ++);
378
// System.out.println("-3- " + serverName);
379
// }
380
serverElt.setAttribute(NAME, serverName);
381         Short JavaDoc id = new Short JavaDoc(nextId ++);
382         // does this server have a relativeId ?
383
Node idNode = serverElt.getAttributes().getNamedItem(ID);
384         if (idNode != null){
385           String JavaDoc relId = idNode.getNodeValue();
386           if (relId != null && (! relId.equals("")))
387             relativeIds.put(relId, id);
388         }
389         serverElt.setAttribute(ID, id.toString());
390         NodeList serverChilds = sNode.getChildNodes();
391         for (int j=0; j<serverChilds.getLength(); j++){
392           if (serverChilds.item(j).getNodeType() == Node.ELEMENT_NODE)
393             serverElt.appendChild(instantiateElement(root.getOwnerDocument(),
394                                                      instanceName,
395                                                      serverChilds.item(j),
396                                                      p));
397         }
398         root.appendChild(serverElt);
399       }
400     }
401     for (int i=0; i<childs.getLength(); i++){
402       Node tNode = childs.item(i);
403       if (tNode.getNodeType() == Node.ELEMENT_NODE &&
404           tNode.getNodeName().equals(TRANSIENT_TAG)){
405         Element transientElt = instantiateElement(root.getOwnerDocument(),
406                                                   instanceName, tNode, p);
407         // check if name have been defined (eg was in a var)
408
String JavaDoc transientName =
409           transientElt.getAttributes().getNamedItem(NAME).getNodeValue();
410         if (transientName == null || transientName.equals("")){
411           transientName = instanceName + ".transient";
412           if (transientNb > 1)
413             transientName += ("." + transientPrefixName ++);
414           transientElt.setAttribute(NAME, transientName);
415         }
416         // generate id
417
Short JavaDoc id = new Short JavaDoc(nextId ++);
418         transientElt.setAttribute(ID, id.toString());
419         // associated server
420
Node serverNode = transientElt.getAttributes().getNamedItem(SERVER);
421         String JavaDoc associatedServer = null;
422         Short JavaDoc serverId = null;
423         if (serverNode != null)
424           associatedServer = serverNode.getNodeValue();
425         if (associatedServer == null || associatedServer.equals("")){
426           // this was not a var associate to first server
427
serverId = firstServer;
428         }else{
429           serverId = (Short JavaDoc)relativeIds.get(associatedServer);
430         }
431         if (serverId == null){
432           throw new A3configException("transient " + transientName +
433                                         " has no associated server");
434         }
435         transientElt.setAttribute(SERVER, serverId.toString());
436         NodeList serverChilds = tNode.getChildNodes();
437         for (int j=0; j<serverChilds.getLength(); j++){
438           if (serverChilds.item(j).getNodeType() == Node.ELEMENT_NODE)
439             transientElt.appendChild(
440               instantiateElement(root.getOwnerDocument(),
441                                  instanceName, serverChilds.item(j), p));
442         }
443         root.appendChild(transientElt);
444       }
445     }
446     return nextId;
447   }
448
449
450   private int countChilds(Node currentElt, String JavaDoc tagName){
451     int nb = 0;
452     NodeList childs = currentElt.getChildNodes();
453     for (int i=0; i<childs.getLength(); i++){
454       Node currentNode = childs.item(i);
455       if (currentNode.getNodeType() == Node.ELEMENT_NODE &&
456           currentNode.getNodeName().equals(tagName))
457         nb++;
458     }
459     return nb;
460   }
461
462   private void buildSimpleElement(String JavaDoc tagName, Element root, Properties JavaDoc p)
463     throws A3configException{
464     // check if default values for global vars have been initialized
465
if (varsSet.get(GLOBALS) == null)
466       getVariables(templateRoot, false);
467     NodeList childs = templateRoot.getChildNodes();
468     for (int i=0; i<childs.getLength(); i++){
469       Node currentNode = childs.item(i);
470       if (currentNode.getNodeType() == Node.ELEMENT_NODE &&
471           currentNode.getNodeName().equals(tagName)){
472         root.appendChild(instantiateElement(root.getOwnerDocument(),
473                                             null, currentNode, p));
474       }
475     }
476   }
477
478
479   // only for one level
480
private Element instantiateElement(Document doc,
481                                      String JavaDoc instance,
482                                      Node model,
483                                      Properties JavaDoc p) throws A3configException{
484     Element instanceElt = (Element) doc.importNode(model, false);
485     NamedNodeMap attrs = model.getAttributes();
486     for (int j=0; j<attrs.getLength(); j++){
487       Node attrNode = attrs.item(j);
488       String JavaDoc attr = attrs.item(j).getNodeName();
489       String JavaDoc attrValue = attrs.item(j).getNodeValue();
490       if (attrNode.getNodeValue().startsWith(VAR_MARK)){
491         String JavaDoc varName = attrValue.substring(1, attrValue.length());
492         attrValue = null;
493         // get config in properties
494
if (instance != null)
495           attrValue = p.getProperty(instance + "." + varName);
496         if (attrValue == null)
497           // it may be a global variable
498
attrValue = p.getProperty(varName);
499         if (attrValue == null)
500           // get default
501
attrValue = (String JavaDoc)defaultValues.get(varName);
502         if (attrValue == null)
503           throw new A3configException("Variable " +
504                                       ((instance!=null) ? instance+"." : "")
505                                      + varName +
506                                       " not defined, no defaultValue");
507       }
508       // add domain info if any
509
if (merge && (! attrValue.equals(TRANSIENT_TAG)) &&
510           ((model.getNodeName().equals(NETWORK_TAG)
511             && attr.equals(DOMAIN_TAG)) ||
512            (model.getNodeName().equals(DOMAIN_TAG) && attr.equals(NAME)))){
513         attrValue = currentDomain + "." + attrValue;
514       }
515       instanceElt.setAttribute(attr, attrValue);
516     }
517     return instanceElt;
518   }
519
520
521   private ConfigVariable[] getVariables(Node node, boolean type)
522     throws A3configException{
523     NodeList childs = node.getChildNodes();
524     Vector JavaDoc v = new Vector JavaDoc();
525     for (int i=0; i<childs.getLength(); i++){
526       Node currentNode = childs.item(i);
527       if (currentNode.getNodeType() == Node.ELEMENT_NODE &&
528             currentNode.getNodeName().equals(VAR_TAG)){
529         NamedNodeMap attrs = currentNode.getAttributes();
530         String JavaDoc name = attrs.getNamedItem(NAME).getNodeValue();
531         Node valueNode = attrs.getNamedItem(VALUE);
532         String JavaDoc defaultValue = null;
533         if (valueNode != null){
534           defaultValue = valueNode.getNodeValue();
535           defaultValues.put(name, defaultValue);
536         }
537         if (!type)
538           continue;
539         Node infoNode = attrs.getNamedItem(INFO);
540         String JavaDoc info = null;
541         if (infoNode != null)
542         info = infoNode.getNodeValue();
543         try{
544           Class JavaDoc c = ConfigVariable.getClass(
545             attrs.getNamedItem(TYPE).getNodeValue());
546           Object JavaDoc defaultObject = null;
547           if (defaultValue != null){
548             defaultObject = ConfigVariable.getObject(c, defaultValue);
549           }
550           v.addElement(new ConfigVariable(name, c, defaultObject, info));
551         }catch(Exception JavaDoc e){
552           throw new A3configException("Error parsing variable type, variable "
553                                       + name + " has not a valid type");
554         }
555       }
556     }
557     ConfigVariable[] res = new ConfigVariable[v.size()];
558     v.copyInto(res);
559     return res;
560   }
561
562
563   
564   private void updateConfs(Element localRoot,Element previousRoot, Properties JavaDoc p)
565     throws A3configException{
566     // add general previous config properties to new config if not re-defined
567
NodeList childs = previousRoot.getChildNodes();
568     for (int i=0; i<childs.getLength(); i++){
569       Node currentNode = childs.item(i);
570       if (currentNode.getNodeType() == Node.ELEMENT_NODE &&
571             currentNode.getNodeName().equals(PROPERTY_TAG)){
572         try{
573           Element oldPropr = getChild(localRoot, PROPERTY_TAG, NAME,
574                                       ((Element)currentNode).getAttribute(NAME));
575         }catch(Exception JavaDoc e){
576           // this property is not redefined in new conf -> redefine it
577
updateImport((Element)currentNode);
578           localRoot.insertBefore(
579             localRoot.getOwnerDocument().importNode(currentNode, true),
580             localRoot.getFirstChild());
581         }
582       }
583     }
584     // get main domain from D0
585
Element D0Domain = getChild(previousRoot, DOMAIN_TAG, NAME, ADMIN_DOMAIN);
586     updateImport(D0Domain);
587     // get s0 server
588
Element s0server =
589       getChild(previousRoot, SERVER_TAG, NAME, ADMIN_SERVER_NAME);
590     updateImport(s0server);
591     // get first domain, common to admin an this appli
592
Element newDomain = null;
593     childs = localRoot.getChildNodes();
594     for (int i=0; i<childs.getLength(); i++){
595       Node currentNode = childs.item(i);
596       if (currentNode.getNodeType() == Node.ELEMENT_NODE &&
597           currentNode.getNodeName().equals(DOMAIN_TAG)){
598         newDomain = (Element)currentNode;
599         break;
600       }
601     }
602     if (newDomain == null)
603       throw new A3configException("No domain defined");
604     String JavaDoc newDomainName = newDomain.getAttribute(NAME);
605     // get port for s0 to route new domain
606
String JavaDoc routePort = p.getProperty("domain.port");
607     if (routePort == null || Integer.parseInt(routePort)<1)
608       throw new A3configException(
609         "No port defined for admin server to route new application");
610     //check this port is not already defined for a router
611
// (appends when deploy 2 instances with same values
612
checkRouterValid(previousRoot, routePort);
613     // update s0server
614
Element newDomainNetwork =
615       previousRoot.getOwnerDocument().createElement(NETWORK_TAG);
616     newDomainNetwork.setAttribute(DOMAIN_TAG, newDomainName);
617     newDomainNetwork.setAttribute(PORT, routePort);
618     s0server.insertBefore(newDomainNetwork, s0server.getFirstChild());
619     // add new servers to previousconfig
620
Element firstNewServer = null;
621     for (int i=0; i<childs.getLength(); i++){
622       Node currentNode = childs.item(i);
623       if (currentNode.getNodeType() == Node.ELEMENT_NODE &&
624           currentNode.getNodeName().equals(SERVER_TAG) ||
625           currentNode.getNodeName().equals(TRANSIENT_TAG)){
626         if (firstNewServer == null)
627           firstNewServer = (Element)currentNode;
628         updateImport((Element)currentNode);
629         previousRoot.appendChild(
630           previousRoot.getOwnerDocument().importNode(currentNode, true));
631       }
632     }
633     // add domain element to previous config
634
updateImport(newDomain);
635     previousRoot.insertBefore(
636       previousRoot.getOwnerDocument().importNode(newDomain, true), s0server);
637     // import s0server in local config and remove useless domains
638
updateImport(s0server);
639     Element localS0server =
640       (Element)(localRoot.getOwnerDocument().importNode(s0server, true));
641     childs = localS0server.getChildNodes();
642     for (int i=0; i<childs.getLength(); i++){
643       Node currentNode = childs.item(i);
644        if (currentNode.getNodeType() == Node.ELEMENT_NODE &&
645            currentNode.getNodeName().equals(NETWORK_TAG) &&
646            ! currentNode.getAttributes().getNamedItem(DOMAIN_TAG).
647            getNodeValue().equals(ADMIN_DOMAIN) &&
648            ! currentNode.getAttributes().getNamedItem(DOMAIN_TAG).
649                getNodeValue().equals(newDomainName)){
650          localS0server.removeChild(currentNode);
651        }
652     }
653     localRoot.insertBefore(localS0server, firstNewServer);
654     updateImport(D0Domain);
655     localRoot.insertBefore(
656       localRoot.getOwnerDocument().importNode(D0Domain, true), localS0server);
657   }
658
659   private void checkRouterValid(Element previousRoot, String JavaDoc port)
660     throws A3configException{
661     Element s0elt = getChild(previousRoot, "server", "id", "0");
662     NodeList childs = s0elt.getChildNodes();
663     for (int i=0; i<childs.getLength(); i++){
664       Node currentNode = childs.item(i);
665       if (currentNode.getNodeType() == Node.ELEMENT_NODE &&
666           currentNode.getNodeName().equals(NETWORK_TAG) &&
667           currentNode.getAttributes().getNamedItem(PORT).getNodeValue().
668           equals(port))
669         throw new A3configException(
670           "The port " + port + " is already defined for domain " +
671           currentNode.getAttributes().getNamedItem(DOMAIN_TAG).getNodeValue());
672     }
673   }
674
675
676   public static void deleteApplicationConfig(InputStream JavaDoc totalConfig,
677                                              InputStream JavaDoc localConfig,
678                                              String JavaDoc res)
679     throws Exception JavaDoc{
680     DOMParser parser = new DOMParser();
681     parser.parse(new InputSource JavaDoc(totalConfig));
682     Document resDoc = parser.getDocument();
683     Element totalRoot = resDoc.getDocumentElement();
684     parser.parse(new InputSource JavaDoc(localConfig));
685     Element localRoot = parser.getDocument().getDocumentElement();
686     // get s0 server of old config
687
Element s0server = getChild(totalRoot, SERVER, NAME, ADMIN_SERVER_NAME);
688     // parse local Element
689
NodeList childs = localRoot.getChildNodes();
690     for (int i=0; i<childs.getLength(); i++){
691       Node child = childs.item(i);
692       if (child.getNodeType() == Node.ELEMENT_NODE){
693         if (child.getNodeName().equals(DOMAIN_TAG)){
694           String JavaDoc domainName =
695             child.getAttributes().getNamedItem(NAME).getNodeValue();
696           if (! domainName.equals(ADMIN_DOMAIN)){
697             // remove domain from total config
698
removeChild(totalRoot, DOMAIN_TAG, NAME, domainName);
699             // remove network from s0server
700
removeChild(s0server, NETWORK_TAG, DOMAIN_TAG, domainName);
701           }
702         }else if (child.getNodeName().equals(SERVER_TAG)
703                   || child.getNodeName().equals(TRANSIENT_TAG)){
704           //remove this server from total config
705
String JavaDoc sid = child.getAttributes().getNamedItem(ID).getNodeValue();
706           if (! sid.equals("0"))
707             removeChild(totalRoot, child.getNodeName(), ID, sid);
708         }
709       }
710     }
711     // write new config
712
OutputFormat format = new OutputFormat(resDoc);
713     //format.setIndent(indent);
714
FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(res);
715     XMLSerializer serial = new XMLSerializer(fos, format);
716     serial.asDOMSerializer();
717     serial.serialize(resDoc);
718     fos.flush();
719     fos.close();
720   }
721
722   private static void removeChild(Element parent, String JavaDoc tagName,
723                                   String JavaDoc attrName, String JavaDoc attrValue)
724     throws Exception JavaDoc{
725     NodeList childs = parent.getChildNodes();
726     for (int i=0; i<childs.getLength(); i++){
727       Node child = childs.item(i);
728       if (child.getNodeType() == Node.ELEMENT_NODE &&
729             child.getNodeName().equals(tagName)){
730         // check attributes
731
if (child.getAttributes().getNamedItem(attrName).
732             getNodeValue().equals(attrValue)){
733           parent.removeChild(child);
734           return;
735         }
736       }
737     }
738     throw new Exception JavaDoc("Unable to find tag " + tagName + " with attr " +
739                         attrName + "=" + attrValue);
740   }
741
742 }
743
Popular Tags