source: axis/ParseTopdl.java @ a3bbb4a

compt_changesinfo-ops
Last change on this file since a3bbb4a was 31aa1ee, checked in by Ted Faber <faber@…>, 13 years ago

Cleaner parsing tests

  • Property mode set to 100644
File size: 17.2 KB
Line 
1// WSDL generated classes
2import edu.isi.www.fedd_types.*;
3import edu.isi.www.topdl.*;
4
5import java.io.*;
6
7import java.util.*;
8
9import javax.xml.parsers.*;
10
11import org.xml.sax.*;
12import org.xml.sax.helpers.*;
13
14public class ParseTopdl {
15    /** Parser instance */
16    protected XMLReader xr;
17    /** Handler that parses topdl file */
18    protected TopdlHandler h;
19
20    /**
21     * This class encapsulates the state of an XML parse of a topdl file.  It
22     * contains abunch of parsing state and is called from the standard SAX
23     * parser at 3 places: when an XML element starts (&lt;element&gt;) when
24     * one ends (&lt;element/&gt;) and whenever characters inside an element
25     * are encountered.  It mostly initializes fileds as elements are exited,
26     * collecting other parsed fields into objects that are finally attached to
27     * the topology itself.
28     */
29    protected class TopdlHandler extends DefaultHandler {
30        /** The name of the outermost element, "experiment" by default */
31        protected String topName;
32
33        // Topology parameters
34        /** The current topology being built */
35        protected TopologyType topo;
36        /** The current element being built */
37        protected ElementType element;
38        /** The current computer being built */
39        protected ComputerType comp;
40        /** The current testbed being built */
41        protected TestbedType tb;
42        /** The current segment being built */
43        protected SegmentType seg;
44        /** The current other element being built */
45        protected OtherType other;
46
47        // Many elements have a name
48        /** the most recent name element parsed */
49        protected String name;
50
51        // CPU parameters
52        /** current cpu type */
53        protected String type;
54        /** current number of cpus */
55        protected int ncpus;
56
57        // Operatingsystem parameters
58        /** Current OS version */
59        protected String version;
60        /** Current OS distro */
61        protected String distribution;
62        /** Current OS distro version */
63        protected String distributionversion;
64
65        // Software parameters
66        /** Current software installation point */
67        protected String install;
68        /** Current software location */
69        protected String location;
70
71        // Storage parameters
72        /** Current storage amount */
73        protected double amount;
74        /** Current storage persistence */
75        protected PersistenceType persistence;
76
77        // Interface Parameters
78        /** Vector of substrate names the current interface is attached to */
79        protected Vector<String> ifsubs;
80        /** Current interface capacity */
81        protected edu.isi.www.topdl.CapacityType cap;
82        /** Current interface latency */
83        protected LatencyType lat;
84
85        // Capacity parameters
86        /** Current capacity rate (bandwidth) */
87        protected double rate;
88        /** Current capacity kind (max, peak)*/
89        protected edu.isi.www.topdl.KindType kind;
90
91        // Latency parameters (shares kind)
92        /** Current latency time */
93        protected double time;
94
95        // Testbed parameters (shares interfaces, type)
96        /** Current URI */
97        protected String uri;
98
99        // Segment parameters (shares interfaces, type, uri)
100        /** Current segment ID */
101        protected IDType id;
102        // IDType parameters
103        /** Current ID uuid (if any) */
104        protected byte[] uuid;
105        /** Current ID fedid (if any) */
106        protected byte[] fedid;
107        /** Current ID uri (if any) */
108        protected String id_uri;
109        /** Current ID localname (if any) */
110        protected String localname;
111        /** Current ID kerberosUsername (if any) */
112        protected String kerberosUsername;
113        /** True when we are parsing an ID (so URIs are stored in id_uri) */
114        protected boolean inID;
115
116        // Attribute parameters
117        /** Current attribute name */
118        protected String aname;
119        /** Current attribute value */
120        protected String aval;
121
122        /** Elements seen so far */
123        protected Vector<ElementType> elements;
124        /** Substrates seen so far */
125        protected Vector<SubstrateType> subs;
126        /** Attributes seen so far */
127        protected Vector<AttributeType> attrs;
128        /** CPUs seen so far */
129        protected Vector<CpuType> cpus;
130        /** Operating Systems seen so far */
131        protected Vector<OperatingsystemType> oses;
132        /** Software seen so far */
133        protected Vector<SoftwareType> software;
134        /** Storage seen so far */
135        protected Vector<StorageType> storage;
136        /** Interfaces seen so far */
137        protected Vector<InterfaceType> interfaces;
138
139        /**
140         * Attributes appear in many elements, some of which can appear inside
141         * the definition of others.  We keep a stack of live attributes so
142         * that a sub-element does not overwrite a super-element's attributes.
143         * attrElements is a set of element names that should start a new set
144         * of recorded attributes, and attrStack keeps the contexts stacked.
145         */
146        protected Set<String> attrElements;
147        /**
148         * The stack of attribute contexts.
149         */
150        protected Stack<Vector<AttributeType>> attrStack;
151        /**
152         * Analogous to attrElements for names.
153         */
154        protected Set<String> nameElements;
155        /**
156         * Analogous to attrStack for names.
157         */
158        protected Stack<String> nameStack;
159        /**
160         * The current buffer of characters collected.
161         */
162        protected char[] c;
163
164        /**
165         * Print parsing info if true
166         */
167        protected boolean debug;
168
169        /**
170         * Initialize the internal data structures.  Top is the outer element
171         * name.  If d is true, debugging info is printed.
172         * @param top a String containing the outer element name
173         * @param d a boolean, if true pring debugging info
174         */
175        TopdlHandler(String top, boolean d) {
176            debug = d;
177            topName = top;
178            topo = null;
179            element = null;
180            comp = null;
181            tb = null;
182            seg = null;
183            other = null;
184
185            type = null;
186            name = null;
187            ncpus = 1;
188
189            version = distribution = distributionversion = null;
190
191            install = location = null;
192
193            amount = 0.0;
194            persistence = null;
195
196            ifsubs = new Vector<String>();
197            cap = null;
198            lat = null;
199
200            rate = 0.0;
201            kind = null;
202
203            time = 0.0;
204
205            uri = null;
206
207            id = null;
208
209            uuid = fedid = null;
210            id_uri = localname = kerberosUsername = null;
211            inID = false;
212
213            aname = aval = null;
214
215            elements = new Vector<ElementType>();
216            cpus = new Vector<CpuType>();
217            subs = new Vector<SubstrateType>();
218            oses = new Vector<OperatingsystemType>();
219            software = new Vector<SoftwareType>();
220            storage = new Vector<StorageType>();
221            interfaces = new Vector<InterfaceType>();
222            attrs = new Vector<AttributeType>();
223
224            attrElements = new TreeSet<String>();
225            for (String e : new String[] {
226                topName, "computer", "cpu", "os", "software", "storage",
227                "interface", "segment", "testbed", "other", "substrates" 
228            }) attrElements.add(e);
229
230            attrStack = new Stack<Vector<AttributeType>>();
231
232            nameElements = new TreeSet<String>();
233            for (String e : new String[] {
234                "computer", "os", "interface", "substrates" 
235            }) nameElements.add(e);
236            nameStack = new Stack<String>();
237            c = new char[0];
238        }
239
240        /**
241         * Called when an element begins.  qn is the element and a has
242         * attributes assigned in the element.  This starts new name or
243         * attribute contexts, if necessary as well as noting the start of an
244         * id (which is a lightweight uri context).  The parameter definitions
245         * below are from org.xml.sax.helpers.DefaultHandler
246         * @param u - The Namespace URI, or the empty string if the element has
247         * no Namespace URI or if Namespace processing is not being performed.
248         * @param l - The local name (without prefix), or the empty string if
249         * Namespace processing is not being performed.
250         * @param qn - The qualified name (with prefix), or the empty string if
251         * qualified names are not available.
252         * @param a - The attributes attached to the element. If there are no
253         * attributes, it shall be an empty Attributes object.
254         */
255        public void startElement(String u, String l, String qn, Attributes a) 
256                throws SAXException {
257
258            if (debug) System.err.println("<" + qn + ">");
259            c = new char[0];
260            if ( attrElements.contains(qn) ) {
261                attrStack.push(attrs);
262                attrs = new Vector<AttributeType>();
263            }
264            if ( nameElements.contains(qn) ) {
265                nameStack.push(name);
266                name = null;
267            }
268            if (qn.equals("id")) inID = true;
269            if (qn.equals("cpu")) {
270                String n = a.getValue("count");
271                if ( n != null) ncpus = Integer.valueOf(n);
272                else ncpus = 1;
273            }
274        }
275
276        /**
277         * Collect the data from each element and stash it where any containing
278         * elent can find it when it is time to construct that thing.  Clear
279         * any fields used.  This is long but straightforward parsing.
280         * @param u - The Namespace URI, or the empty string if the element has
281         * no Namespace URI or if Namespace processing is not being performed.
282         * @param l - The local name (without prefix), or the empty string if
283         * Namespace processing is not being performed.
284         * @param qn - The qualified name (with prefix), or the empty string if
285         * qualified names are not available.
286         */
287        public void endElement(String u, String l, String qn) 
288                throws SAXException {
289
290            if (debug) System.err.println("<" + qn + "/>");
291
292            // Each branch parses the data from the given element, e.g,
293            // "computer" parses the fields collected for </computer>.  In that
294            // case the data stashed by trips through here for
295            // <operatingsystem>, <name>, etc.
296            //
297            // The vector.toArray(new Type[vector.size()], idiom just returns
298            // the contents of the vector as a java array of the vector's type.
299            if (qn.equals(topName)) {
300                topo = new TopologyType("1.0",
301                        subs.toArray(new SubstrateType[subs.size()]), 
302                        elements.toArray(new ElementType[elements.size()]), 
303                        attrs.toArray(new AttributeType[attrs.size()]));
304                elements = new Vector<ElementType>();
305                subs = new Vector<SubstrateType>();
306                attrs = attrStack.pop();
307            }
308            else if (qn.equals("elements")) {
309                elements.add(new ElementType(comp, tb, seg, other));
310                comp = null;
311                tb = null;
312                seg = null;
313                other = null;
314            }
315            else if (qn.equals("computer")) {
316                comp = new ComputerType(name, 
317                        cpus.toArray(new CpuType[cpus.size()]), 
318                        oses.toArray(new OperatingsystemType[oses.size()]), 
319                        software.toArray(new SoftwareType[software.size()]), 
320                        storage.toArray(new StorageType[storage.size()]), 
321                        interfaces.toArray(
322                            new InterfaceType[interfaces.size()]),
323                        attrs.toArray(new AttributeType[attrs.size()]));
324                name = nameStack.pop();
325                cpus = new Vector<CpuType>();
326                oses = new Vector<OperatingsystemType>();
327                software = new Vector<SoftwareType>();
328                storage = new Vector<StorageType>();
329                interfaces = new Vector<InterfaceType>();
330                attrs = attrStack.pop();
331            }
332            else if (qn.equals("cpu")) {
333                cpus.add(new CpuType(type, 
334                        attrs.toArray(new AttributeType[attrs.size()]), ncpus));
335                type = null;
336                attrs = attrStack.pop();
337                ncpus = 1;
338            }
339            else if (qn.equals("type")) { type = new String(c).trim(); }
340            else if (qn.equals("os")) {
341                oses.add(new OperatingsystemType(name, version, 
342                        distribution, distributionversion, 
343                        attrs.toArray(new AttributeType[attrs.size()])));
344                name = nameStack.pop();
345                version = distribution = distributionversion = null;
346                attrs = attrStack.pop();
347            }
348            else if ( qn.equals("version")) { version = new String(c).trim(); }
349            else if ( qn.equals("distribution")) {
350                distribution = new String(c).trim();
351            }
352            else if ( qn.equals("distributionversion")) {
353                distributionversion = new String(c).trim();
354            }
355            else if (qn.equals("software")) {
356                software.add(new SoftwareType(location, install, 
357                            attrs.toArray(new AttributeType[attrs.size()])));
358                location = install = null;
359                attrs = attrStack.pop();
360            }
361            else if ( qn.equals("location")) { 
362                location = new String(c).trim();
363            }
364            else if ( qn.equals("install")) { install = new String(c).trim(); }
365            else if (qn.equals("storage")) {
366                storage.add(new StorageType(amount, persistence, 
367                            attrs.toArray(new AttributeType[attrs.size()])));
368                amount = 0.0;
369                persistence = null;
370                attrs = attrStack.pop();
371            }
372            else if ( qn.equals("amount")) { 
373                amount = Double.valueOf(new String(c));
374            }
375            else if ( qn.equals("persistence")) { 
376                persistence = PersistenceType.fromValue(new String(c));
377            }
378            else if (qn.equals("interface")) {
379                interfaces.add(new InterfaceType(
380                            ifsubs.toArray(new String[ifsubs.size()]),
381                            name,
382                            cap, lat,
383                            attrs.toArray(new AttributeType[attrs.size()])));
384                ifsubs = new Vector<String>();
385                name = nameStack.pop();
386                cap = null;
387                lat = null;
388                attrs = attrStack.pop();
389            }
390            else if (qn.equals("substrate")) {
391                ifsubs.add(new String(c).trim());
392            }
393            else if (qn.equals("capacity")) {
394                cap = new edu.isi.www.topdl.CapacityType(rate, kind);
395                rate = 0.0;
396                kind = null;
397            }
398            else if ( qn.equals("rate")) { 
399                rate = Double.valueOf(new String(c));
400            }
401            else if ( qn.equals("kind")) { 
402                kind = edu.isi.www.topdl.KindType.fromValue(new String(c));
403            }
404            else if (qn.equals("latency")) {
405                lat = new LatencyType(time, kind);
406                time = 0.0;
407                kind = null;
408            }
409            else if ( qn.equals("time")) { 
410                time = Double.valueOf(new String(c));
411            }
412            else if (qn.equals("testbed")) {
413                tb = new TestbedType(uri, type, 
414                        interfaces.toArray(
415                            new InterfaceType[interfaces.size()]),
416                        attrs.toArray(new AttributeType[attrs.size()]));
417                uri = type = null;
418                interfaces = new Vector<InterfaceType>();
419                attrs = attrStack.pop();
420            }
421            else if (qn.equals("uri")) { 
422                if (inID) id_uri = new String(c).trim();
423                else uri = new String(c).trim();
424            }
425            else if (qn.equals("segment")) {
426                seg = new SegmentType(id, type, uri,
427                        interfaces.toArray(
428                            new InterfaceType[interfaces.size()]),
429                        attrs.toArray(new AttributeType[attrs.size()]));
430                id = null;
431                type = uri = null;
432                interfaces = new Vector<InterfaceType>();
433                attrs = attrStack.pop();
434            }
435            else if (qn.equals("id")) { 
436                id = new IDType(uuid, fedid, id_uri, localname, 
437                        kerberosUsername);
438                uuid = null;
439                fedid = null;
440                id_uri = null;
441                localname = null;
442                kerberosUsername = null;
443                inID = false;
444            }
445            else if (qn.equals("uuid")) {
446                uuid = new String(c).trim().getBytes();
447            }
448            else if (qn.equals("fedid")) {
449                fedid = new String(c).trim().getBytes();
450            }
451            else if (qn.equals("localname")) {
452                localname = new String(c).trim();
453            }
454            else if (qn.equals("kerberosUsername")) { 
455                kerberosUsername = new String(c).trim();
456            }
457            else if (qn.equals("other")) { 
458                other = new OtherType(
459                        interfaces.toArray(
460                            new InterfaceType[interfaces.size()]),
461                        attrs.toArray(new AttributeType[attrs.size()]));
462                interfaces = new Vector<InterfaceType>();
463                attrs = attrStack.pop();
464            }
465            else if (qn.equals("substrates")) {
466                subs.add(new SubstrateType(name, cap, lat, 
467                        attrs.toArray(new AttributeType[attrs.size()])));
468                name = nameStack.pop();
469                cap = null;
470                lat = null;
471                attrs = attrStack.pop();
472            }
473            else if (qn.equals("attribute")) {
474                if ( aname != null && aval != null ) {
475                    attrs.add(new AttributeType(aname, aval));
476                    aname = aval = null;
477                }
478                else { aname = new String(c).trim(); }
479            }
480            else if ( qn.equals("value")) { aval = new String(c).trim(); }
481            else if ( qn.equals("name")) { name = new String(c).trim(); }
482
483            // Always clear any accumulated characters
484            c = new char[0];
485        }
486
487        /**
488         * Collect text.
489         */
490        public void characters(char[] ch, int s, int l) {
491            char[] nc = new char[c.length + l];
492            System.arraycopy(c, 0, nc, 0, c.length);
493            System.arraycopy(ch, s, nc, c.length, l);
494            c = nc;
495        }
496        /**
497         * Return the parsed topology
498         * @return the parsed topology
499         */
500        public TopologyType getTopology() { return topo; }
501    }
502
503    /**
504     * Main constructor.  Parse the given stream assuming that the outermost
505     * element is in topName (defaults to "experiment" if topName is null).  If
506     * debug is true, print extra debugging information to the standard error
507     * stream.
508     * @param s the InputStream to parse
509     * @param topName a String with the outer element name
510     * @param debug a boolean, true for extra debugging output
511     * @throws IOException if the stream cannot be read
512     * @throws SAXException if the parsing fails
513     * @throws ParserConfigurationException if the parser creation fails
514     */
515    public ParseTopdl(InputStream s, String topName, boolean debug) 
516        throws IOException, SAXException, ParserConfigurationException {
517        h = new TopdlHandler(topName != null ? topName: "experiment", debug);
518
519        xr = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
520        xr.setContentHandler(h);
521        xr.parse(new InputSource(s));
522    }
523
524    /**
525     * Equivalent to ParseTopdl(s, topName, false)
526     * @param s the InputStream to parse
527     * @param topName a String with the outer element name
528     * @throws IOException if the stream cannot be read
529     * @throws SAXException if the parsing fails
530     * @throws ParserConfigurationException if the parser creation fails
531     */
532    public ParseTopdl(InputStream s, String topName)
533        throws IOException, SAXException, ParserConfigurationException {
534        this(s, topName, false);
535    }
536
537    /**
538     * Return the parsed topology
539     * @return the parsed topology
540     */
541    public TopologyType getTopology() { return h.getTopology(); }
542
543    /**
544     * Test code.  Shouldn't really be called.
545     */
546    static public void main(String args[]) {
547        ParseTopdl p = null;
548
549        System.out.println("Checking file: " + args[0]);
550        try {
551            p = new ParseTopdl(new FileInputStream(new File(args[0])),
552                    "experiment", false);
553            System.out.println("Parse OK");
554        }
555        catch (ParserConfigurationException e) {
556            System.err.println("Parse failed: " + e);
557        }
558        catch (SAXException e) {
559            System.err.println("Parse failed: " + e);
560        }
561        catch (IOException e) {
562            System.err.println("Parse failed: " + e);
563        }
564    }
565}
Note: See TracBrowser for help on using the repository browser.