1 |
pjm2 |
1.3 |
import java.io.*; |
2 |
|
|
import java.util.ArrayList; |
3 |
|
|
|
4 |
|
|
import org.xml.sax.*; |
5 |
|
|
|
6 |
pjm2 |
1.7 |
import javax.xml.parsers.SAXParserFactory; |
7 |
|
|
import javax.xml.parsers.ParserConfigurationException; |
8 |
|
|
import javax.xml.parsers.SAXParser; |
9 |
pjm2 |
1.3 |
|
10 |
pjm2 |
1.7 |
// Paul Mutton, pjm2@ukc.ac.uk |
11 |
pjm2 |
1.3 |
|
12 |
pjm2 |
1.7 |
// XMLPacketMaker - Creates an XMLPacket object. |
13 |
pjm2 |
1.3 |
public class XMLPacketMaker extends HandlerBase { |
14 |
pjm2 |
1.5 |
|
15 |
pjm2 |
1.10 |
// No-args constructor. Generally not used. |
16 |
pjm2 |
1.5 |
public XMLPacketMaker () { |
17 |
pjm2 |
1.10 |
this.xml = "<packet></packet>"; |
18 |
pjm2 |
1.5 |
} |
19 |
|
|
|
20 |
pjm2 |
1.10 |
// Constructor for accepting XML input. |
21 |
|
|
public XMLPacketMaker (String xml) { |
22 |
|
|
this.xml = xml; |
23 |
pjm2 |
1.5 |
} |
24 |
|
|
|
25 |
pjm2 |
1.10 |
public XMLPacket createXMLPacket() { |
26 |
|
|
|
27 |
|
|
// Create the XMLPacket to store values in. |
28 |
|
|
XMLPacket packet = new XMLPacket(); |
29 |
pjm2 |
1.3 |
|
30 |
|
|
// Use the default (non-validating) parser |
31 |
|
|
SAXParserFactory factory = SAXParserFactory.newInstance(); |
32 |
|
|
try { |
33 |
pjm2 |
1.5 |
|
34 |
pjm2 |
1.3 |
// Parse the input |
35 |
|
|
SAXParser saxParser = factory.newSAXParser(); |
36 |
pjm2 |
1.10 |
saxParser.parse(xml, new XMLPacketParser(packet)); |
37 |
pjm2 |
1.5 |
|
38 |
pjm2 |
1.8 |
// Print out the entire contents of the packet's HashMap. |
39 |
|
|
System.out.println("XMLPacket contents: -"); |
40 |
pjm2 |
1.7 |
packet.printAll(); |
41 |
pjm2 |
1.3 |
|
42 |
pjm2 |
1.10 |
} |
43 |
|
|
catch (Throwable t) { |
44 |
pjm2 |
1.9 |
System.out.println("The recieved packet did not contain valid XML, so I'm gonna reject it."); |
45 |
|
|
//t.printStackTrace (); |
46 |
pjm2 |
1.3 |
} |
47 |
pjm2 |
1.10 |
|
48 |
|
|
return packet; |
49 |
pjm2 |
1.3 |
} |
50 |
pjm2 |
1.8 |
|
51 |
pjm2 |
1.10 |
String xml; |
52 |
pjm2 |
1.3 |
} |