KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jgroups > conf > XmlConfigurator


1 // $Id: XmlConfigurator.java,v 1.12 2004/09/23 16:29:14 belaban Exp $
2

3 package org.jgroups.conf;
4
5 /**
6  * Uses XML to configure a protocol stack
7  * @author Filip Hanik (<a HREF="mailto:filip@filip.net">filip@filip.net)
8  * @version 1.0
9  */

10
11 import org.apache.commons.logging.Log;
12 import org.apache.commons.logging.LogFactory;
13 import org.jgroups.util.Util;
14 import org.w3c.dom.*;
15
16 import javax.xml.parsers.DocumentBuilder JavaDoc;
17 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
18 import java.io.File JavaDoc;
19 import java.io.FileInputStream JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.io.InputStream JavaDoc;
22 import java.net.URL JavaDoc;
23 import java.util.*;
24
25
26 public class XmlConfigurator implements ProtocolStackConfigurator {
27     private static boolean xml_debug=true;
28
29     public static final String JavaDoc ATTR_NAME="name";
30     public static final String JavaDoc ATTR_VALUE="value";
31     public static final String JavaDoc ATTR_INHERIT="inherit";
32     public static final String JavaDoc ELMT_PROT_OVERRIDE="protocol-override";
33     public static final String JavaDoc ELMT_PROT="protocol";
34     public static final String JavaDoc ELMT_PROT_NAME="protocol-name";
35     public static final String JavaDoc ELMT_CLASS="class-name";
36     public static final String JavaDoc ELMT_DESCRIPTION="description";
37     public static final String JavaDoc ELMT_PROT_PARAMS="protocol-params";
38
39     private final ArrayList mProtocolStack=new ArrayList();
40     private final String JavaDoc mStackName;
41     protected static final Log log=LogFactory.getLog(XmlConfigurator.class);
42
43     protected XmlConfigurator(String JavaDoc stackName, ProtocolData[] protocols) {
44         mStackName=stackName;
45         for(int i=0; i < protocols.length; i++)
46             mProtocolStack.add(protocols[i]);
47     }
48
49     protected XmlConfigurator(String JavaDoc stackName) {
50         this(stackName, new ProtocolData[0]);
51     }
52
53
54     public static XmlConfigurator getInstance(URL JavaDoc url) throws java.io.IOException JavaDoc {
55         return getInstance(url.openStream());
56     }
57
58     public static XmlConfigurator getInstanceOldFormat(URL JavaDoc url) throws java.io.IOException JavaDoc {
59         return getInstanceOldFormat(url.openStream());
60     }
61
62     public static XmlConfigurator getInstance(InputStream JavaDoc stream) throws java.io.IOException JavaDoc {
63         return parse(stream);
64     }
65
66     public static XmlConfigurator getInstanceOldFormat(InputStream JavaDoc stream) throws java.io.IOException JavaDoc {
67         return parseOldFormat(stream);
68     }
69
70
71     public static XmlConfigurator getInstance(Element el) throws java.io.IOException JavaDoc {
72         return parse(el);
73     }
74
75
76     /**
77      *
78      * @param convert If false: print old plain output, else print new XML format
79      * @return
80      */

81     public String JavaDoc getProtocolStackString(boolean convert) {
82         StringBuffer JavaDoc buf=new StringBuffer JavaDoc();
83         Iterator it=mProtocolStack.iterator();
84         if(convert) buf.append("<config>\n");
85         while(it.hasNext()) {
86             ProtocolData d=(ProtocolData)it.next();
87             if(convert) buf.append(" <");
88             buf.append(d.getProtocolString(convert));
89             if(convert) buf.append("/>");
90             if(it.hasNext()) {
91                 if(convert)
92                     buf.append('\n');
93                 else
94                     buf.append(':');
95             }
96         }
97         if(convert) buf.append("\n</config>");
98         return buf.toString();
99     }
100
101
102     public String JavaDoc getProtocolStackString() {
103         return getProtocolStackString(false);
104     }
105
106
107     public ProtocolData[] getProtocolStack() {
108         return (ProtocolData[])mProtocolStack.toArray(new ProtocolData[mProtocolStack.size()]);
109     }
110
111     public String JavaDoc getName() {
112         return mStackName;
113     }
114
115     public void override(ProtocolData data)
116             throws IOException JavaDoc {
117         int index=mProtocolStack.indexOf(data);
118         if(index < 0) throw new IOException JavaDoc("You can not override a protocol that doesn't exist");
119         ProtocolData source=(ProtocolData)mProtocolStack.get(index);
120         source.override(data.getParametersAsArray());
121     }
122
123     public void add(ProtocolData data) {
124         mProtocolStack.add(data);
125     }
126
127
128 // protected static XmlConfigurator parse(InputStream stream) throws java.io.IOException {
129
// XmlConfigurator configurator=null;
130
// try {
131
// DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
132
// factory.setValidating(false); //for now
133
// DocumentBuilder builder=factory.newDocumentBuilder();
134
// builder.setEntityResolver(new ClassPathEntityResolver());
135
// Document document=builder.parse(stream);
136
// Element root=(Element)document.getElementsByTagName("protocol-stack").item(0);
137
// root.normalize();
138
// //print("",new PrintWriter(System.out),root);
139
// String stackname=root.getAttribute(ATTR_NAME);
140
// String inherit=root.getAttribute(ATTR_INHERIT);
141
// boolean isinherited=(inherit != null && inherit.length() > 0);
142
// NodeList protocol_list=document.getElementsByTagName(isinherited ? ELMT_PROT_OVERRIDE : ELMT_PROT);
143
// Vector v=new Vector();
144
// for(int i=0; i < protocol_list.getLength(); i++) {
145
// if(protocol_list.item(i).getNodeType() == Node.ELEMENT_NODE) {
146
// v.addElement(parseProtocolData(protocol_list.item(i)));
147
// }
148
// }
149
// ProtocolData[] protocols=new ProtocolData[v.size()];
150
// v.copyInto(protocols);
151
//
152
// if(isinherited) {
153
// URL inheritURL=new URL(inherit);
154
// configurator=XmlConfigurator.getInstance(inheritURL);
155
// for(int i=0; i < protocols.length; i++)
156
// configurator.override(protocols[i]);
157
// }
158
// else {
159
// configurator=new XmlConfigurator(stackname, protocols);
160
// }//end if
161
//
162
// }
163
// catch(Exception x) {
164
// if(x instanceof java.io.IOException)
165
// throw (java.io.IOException)x;
166
// else {
167
// if(xml_debug) x.printStackTrace();
168
// String error=Util.getStackTrace(x);
169
// if(log.isErrorEnabled()) log.error(error);
170
// throw new java.io.IOException(x.getMessage());
171
// }
172
// }
173
// return configurator;
174
// }
175

176
177         protected static XmlConfigurator parseOldFormat(InputStream JavaDoc stream) throws java.io.IOException JavaDoc {
178         XmlConfigurator configurator=null;
179         try {
180             DocumentBuilderFactory JavaDoc factory=DocumentBuilderFactory.newInstance();
181             factory.setValidating(false); //for now
182
DocumentBuilder JavaDoc builder=factory.newDocumentBuilder();
183             builder.setEntityResolver(new ClassPathEntityResolver());
184             Document document=builder.parse(stream);
185             Element root=(Element)document.getElementsByTagName("protocol-stack").item(0);
186             root.normalize();
187             //print("",new PrintWriter(System.out),root);
188
String JavaDoc stackname=root.getAttribute(ATTR_NAME);
189             String JavaDoc inherit=root.getAttribute(ATTR_INHERIT);
190             boolean isinherited=(inherit != null && inherit.length() > 0);
191             NodeList protocol_list=document.getElementsByTagName(isinherited ? ELMT_PROT_OVERRIDE : ELMT_PROT);
192             Vector v=new Vector();
193             for(int i=0; i < protocol_list.getLength(); i++) {
194                 if(protocol_list.item(i).getNodeType() == Node.ELEMENT_NODE) {
195                     v.addElement(parseProtocolData(protocol_list.item(i)));
196                 }
197             }
198             ProtocolData[] protocols=new ProtocolData[v.size()];
199             v.copyInto(protocols);
200
201             if(isinherited) {
202                 URL JavaDoc inheritURL=new URL JavaDoc(inherit);
203                 configurator=XmlConfigurator.getInstance(inheritURL);
204                 for(int i=0; i < protocols.length; i++)
205                     configurator.override(protocols[i]);
206             }
207             else {
208                 configurator=new XmlConfigurator(stackname, protocols);
209             }//end if
210

211         }
212         catch(Exception JavaDoc x) {
213             if(x instanceof java.io.IOException JavaDoc)
214                 throw (java.io.IOException JavaDoc)x;
215             else {
216                 if(xml_debug) x.printStackTrace();
217                 String JavaDoc error=Util.getStackTrace(x);
218                 if(log.isErrorEnabled()) log.error(error);
219                 throw new java.io.IOException JavaDoc(x.getMessage());
220             }
221         }
222         return configurator;
223     }
224
225
226
227
228     protected static XmlConfigurator parse(InputStream JavaDoc stream) throws java.io.IOException JavaDoc {
229         /**
230          * CAUTION: crappy code ahead ! I (bela) am not an XML expert, so the code below is pretty amateurish...
231          * But it seems to work, and it is executed only on startup, so no perf loss on the critical path.
232          * If somebody wants to improve this, please be my guest.
233          */

234         try {
235             DocumentBuilderFactory JavaDoc factory=DocumentBuilderFactory.newInstance();
236             factory.setValidating(false); //for now
237
DocumentBuilder JavaDoc builder=factory.newDocumentBuilder();
238             builder.setEntityResolver(new ClassPathEntityResolver());
239             Document document=builder.parse(stream);
240
241             // The root element of the document should be the "config" element,
242
// but the parser(Element) method checks this so a check is not
243
// needed here.
244
Element configElement = document.getDocumentElement();
245             return parse(configElement);
246         }
247         catch(Exception JavaDoc x) {
248             if(x instanceof java.io.IOException JavaDoc)
249                 throw (java.io.IOException JavaDoc)x;
250             else {
251                 if(xml_debug) x.printStackTrace();
252                 String JavaDoc error=Util.getStackTrace(x);
253                 if(log.isErrorEnabled()) log.error(error);
254                 throw new java.io.IOException JavaDoc(x.getMessage());
255             }
256         }
257     }
258
259
260
261
262     protected static XmlConfigurator parse(Element root_element) throws java.io.IOException JavaDoc {
263         XmlConfigurator configurator=null;
264
265         /** LinkedList<ProtocolData> */
266         LinkedList prot_data=new LinkedList();
267
268
269         /**
270          * CAUTION: crappy code ahead ! I (bela) am not an XML expert, so the code below is pretty amateurish...
271          * But it seems to work, and it is executed only on startup, so no perf loss on the critical path.
272          * If somebody wants to improve this, please be my guest.
273          */

274         try {
275             Node root=root_element;
276 // NodeList roots=root_element.getChildNodes();
277
// for(int i =0; i < roots.getLength(); i++) {
278
// root=roots.item(i);
279
// if(root.getNodeType() != Node.ELEMENT_NODE)
280
// continue;
281
// }
282

283             String JavaDoc root_name=root.getNodeName();
284             if(!"config".equals(root_name.trim().toLowerCase())) {
285                 log.fatal("XML protocol stack configuration does not start with a '<config>' element; " +
286                         "maybe the XML configuration needs to be converted to the new format ?\n" +
287                         "use 'java org.jgroups.conf.XmlConfigurator <old XML file> -new_format' to do so");
288                 throw new IOException JavaDoc("invalid XML configuration");
289             }
290
291             NodeList prots=root.getChildNodes();
292             for(int i=0; i < prots.getLength(); i++) {
293                 Node node = prots.item(i);
294                 if( node.getNodeType() != Node.ELEMENT_NODE )
295                     continue;
296
297                 Element tag = (Element) node;
298                 String JavaDoc protocol = tag.getTagName();
299                 // System.out.println("protocol: " + protocol);
300
LinkedList tmp=new LinkedList();
301
302                 NamedNodeMap attrs = tag.getAttributes();
303                 int attrLength = attrs.getLength();
304                 for(int a = 0; a < attrLength; a ++) {
305                     Attr attr = (Attr) attrs.item(a);
306                     String JavaDoc name = attr.getName();
307                     String JavaDoc value = attr.getValue();
308                     // System.out.println(" name=" + name + ", value=" + value);
309
tmp.add(new ProtocolParameter(name, value));
310                 }
311                 ProtocolParameter[] params=new ProtocolParameter[tmp.size()];
312                 for(int j=0; j < tmp.size(); j++)
313                     params[j]=(ProtocolParameter)tmp.get(j);
314                 ProtocolData data=new ProtocolData(protocol, "bla", "" + protocol, params);
315                 prot_data.add(data);
316             }
317
318             ProtocolData[] data=new ProtocolData[(prot_data.size())];
319             for(int k=0; k < prot_data.size(); k++)
320                 data[k]=(ProtocolData)prot_data.get(k);
321             configurator=new XmlConfigurator("bla", data);
322         }
323         catch(Exception JavaDoc x) {
324             if(x instanceof java.io.IOException JavaDoc)
325                 throw (java.io.IOException JavaDoc)x;
326             else {
327                 if(xml_debug) x.printStackTrace();
328                 String JavaDoc error=Util.getStackTrace(x);
329                 if(log.isErrorEnabled()) log.error(error);
330                 throw new java.io.IOException JavaDoc(x.getMessage());
331             }
332         }
333         return configurator;
334     }
335
336
337     protected static ProtocolData parseProtocolData(Node protocol)
338             throws java.io.IOException JavaDoc {
339         try {
340             protocol.normalize();
341             boolean isOverride=ELMT_PROT_OVERRIDE.equals(protocol.getNodeName());
342             int pos=0;
343             NodeList children=protocol.getChildNodes();
344             /**
345              * there should be 4 Element Nodes if we are not overriding
346              * 1. protocol-name
347              * 2. description
348              * 3. class-name
349              * 4. protocol-params
350              *
351              * If we are overriding we should have
352              * 1. protocol-name
353              * 2. protocol-params
354              */

355
356             //
357

358             String JavaDoc name=null;
359             String JavaDoc clazzname=null;
360             String JavaDoc desc=null;
361             ProtocolParameter[] plist=null;
362
363             for(int i=0; i < children.getLength(); i++) {
364                 if(children.item(i).getNodeType() == Node.ELEMENT_NODE) {
365                     pos++;
366                     if(isOverride && (pos == 2)) pos=4;
367                     switch(pos) {
368                         case 1:
369                             name=children.item(i).getFirstChild().getNodeValue();
370                             break;
371                         case 2:
372                             desc=children.item(i).getFirstChild().getNodeValue();
373                             break;
374                         case 3:
375                             clazzname=children.item(i).getFirstChild().getNodeValue();
376                             break;
377                         case 4:
378                             plist=parseProtocolParameters((Element)children.item(i));
379                             break;
380                     }//switch
381
}//end if
382
}//for
383

384             if(isOverride)
385                 return new ProtocolData(name, plist);
386             else
387                 return new ProtocolData(name, desc, clazzname, plist);
388         }
389         catch(Exception JavaDoc x) {
390             if(x instanceof java.io.IOException JavaDoc)
391                 throw (java.io.IOException JavaDoc)x;
392             else {
393
394                 if(xml_debug) x.printStackTrace();
395                 String JavaDoc error=Util.getStackTrace(x);
396                 if(log.isErrorEnabled()) log.error(error);
397                 throw new java.io.IOException JavaDoc(x.getMessage());
398             }//end if
399
}//catch
400
}
401
402     protected static ProtocolParameter[] parseProtocolParameters(Element protparams)
403             throws IOException JavaDoc {
404
405         try {
406             Vector v=new Vector();
407             protparams.normalize();
408             NodeList parameters=protparams.getChildNodes();
409             for(int i=0; i < parameters.getLength(); i++) {
410                 if(parameters.item(i).getNodeType() == Node.ELEMENT_NODE) {
411                     String JavaDoc pname=parameters.item(i).getAttributes().getNamedItem(ATTR_NAME).getNodeValue();
412                     String JavaDoc pvalue=parameters.item(i).getAttributes().getNamedItem(ATTR_VALUE).getNodeValue();
413                     ProtocolParameter p=new ProtocolParameter(pname, pvalue);
414                     v.addElement(p);
415                 }//end if
416
}//for
417
ProtocolParameter[] result=new ProtocolParameter[v.size()];
418             v.copyInto(result);
419             return result;
420         }
421         catch(Exception JavaDoc x) {
422             if(x instanceof java.io.IOException JavaDoc)
423                 throw (java.io.IOException JavaDoc)x;
424             else {
425
426                 if(xml_debug) x.printStackTrace();
427                 String JavaDoc error=Util.getStackTrace(x);
428                 if(log.isErrorEnabled()) log.error(error);
429                 throw new java.io.IOException JavaDoc(x.getMessage());
430             }//end if
431
}//catch
432
}
433
434     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
435         String JavaDoc input_file=null, output=null;
436         XmlConfigurator conf;
437         boolean new_format=false;
438
439         if(args.length == 0) {
440             help();
441             return;
442         }
443
444         input_file=args[0];
445
446         for(int i=1; i < args.length; i++) {
447             if("-new_format".equals(args[i])) {
448                 new_format=true;
449                 continue;
450             }
451             help();
452             return;
453         }
454
455         xml_debug=true;
456         if(input_file != null) {
457             InputStream JavaDoc input=null;
458
459             try {
460                 input=new FileInputStream JavaDoc(new File JavaDoc(input_file));
461             }
462             catch(Throwable JavaDoc t) {
463             }
464             if(input == null) {
465                 try {
466                     input=new URL JavaDoc(input_file).openStream();
467                 }
468                 catch(Throwable JavaDoc t) {
469                 }
470             }
471
472             conf=XmlConfigurator.getInstanceOldFormat(input);
473             output=conf.getProtocolStackString(new_format);
474             output=replace(output, "org.jgroups.protocols.", "");
475             if(new_format)
476                 System.out.println(getTitle(input_file));
477             System.out.println('\n' + output);
478         }
479         else {
480             System.err.println("no input file given");
481         }
482     }
483
484     private static String JavaDoc getTitle(String JavaDoc input) {
485         StringBuffer JavaDoc sb=new StringBuffer JavaDoc();
486         sb.append("\n\n<!-- ************ JGroups Protocol Stack Configuration ************** -->\n");
487         sb.append("<!-- generated by XmlConfigurator on " + new Date() + " -->\n");
488         sb.append("<!-- input file: " + input + " -->");
489         return sb.toString();
490     }
491
492
493     public static String JavaDoc replace(String JavaDoc input, final String JavaDoc expr, String JavaDoc replacement) {
494         StringBuffer JavaDoc sb=new StringBuffer JavaDoc();
495         int new_index=0, index=0, len=expr.length(), input_len=input.length();
496
497         while(true) {
498             new_index=input.indexOf(expr, index);
499             if(new_index == -1) {
500                 sb.append(input.substring(index, input_len));
501                 break;
502             }
503             sb.append(input.substring(index, new_index));
504             sb.append(replacement);
505             index=new_index + len;
506         }
507
508
509         return sb.toString();
510     }
511
512
513     static void help() {
514         System.out.println("XmlConfigurator <input XML file> [-new_format]");
515         System.out.println("(-new_format: converts old XML format into new format)");
516     }
517 }
518
Popular Tags