The purpose of this project is to use the adapter mode to fit the Documenthandler interface into a Java.util.Properties interface. The adapter mode of the object is used. Xmlproperties is an object that inherits from Java.util.Properties and delegates an object of type Documenthandler.
This project requires two classes: the Xmlproperties class and the Xmlparser class, the former is the Java.util.Properties type, and the latter is the Documenthandler type.
The source code is as follows, the adapter class Xmlproperties:
Import Java.io.bufferedinputstream;import Java.io.file;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.ioexception;import Java.io.inputstream;import Java.io.OutputStream; Import Java.io.printwriter;import Java.util.enumeration;import Java.util.properties;import Org.xml.sax.saxexception;public class Xmlproperties extends properties{xmlparser p=null;/* * Read XML from an input stream * */public synchronized void Load (InputStream in) throws Ioexception{try {p=new xmlparser (in,this);} catch (Saxexception e) {//TODO Auto-generated catch Blockthrow New IOException (E.getmessage ());}} /* * Read XML file into * */public synchronized void load (file file) throws FileNotFoundException, Saxexception{inputstream in=new B Ufferedinputstream (new FileInputStream); try {p=new xmlparser (in, this);} catch (Saxexception e) {//TODO Auto-generated catch BlockSystem.out.println (e); throw e;}} /* Call the following store () method */public synchronized void Save (OutputStream out,string header) {store (out, header);} /* * Apply this PThe Roperty list is written to the output stream * */public synchronized void Store (OutputStream out,string header) {PrintWriter wout=new printwriter ( Wout.println ("<?xml version= ' 1.0 ' >"), if (header!=null) {wout.println ("<!--" +header+ "--");} Wout.print ("<properties>"); for (enumeration E=keys (); e.hasmoreelements ();) {string key= (string) e.nextelement (); String val= (String) get (key), Wout.print ("\n<key name=\" "+key+" \ ">"), Wout.print (Encode (Val)); Wout.print (" </key> ");} Wout.print ("\n</properties>"); Wout.flush ();} Protected StringBuffer Encode (string string) {int len=string.length (); StringBuffer buffer=new StringBuffer (len), char c;for (int i=0;i<len;i++) {switch (C=string.charat (i)) {case ' & ': Buffer.append ("&"); Break;case ' x ': Buffer.append ("<"); Break;case ': Buffer.append (">"); Break;default: Buffer.append (c);}} return buffer;} Public xmlproperties () {super ();} Public Xmlproperties (properties) {Super (properties);}}
xmlparser Source code:
Import Javax.management.runtimeerrorexception;import Org.junit.runner.computer;import org.xml.sax.AttributeList; Import Org.xml.sax.documenthandler;import Org.xml.sax.inputsource;import Org.xml.sax.locator;import Org.xml.sax.parser;import Org.xml.sax.saxexception;public class Xmlparser implements documenthandler{private static F inal int in_nothing=0; private static final int in_document=1; private static final int in_key=2; private int state=in_nothing; Private String key; private StringBuffer value; Private Parser Parser; Private Class Parser_class=null; Private Properties Xmlprop=null; public static final String parser_p= "Org.apache.xerces.parsers.SAXParser"; Private Class Getparserclass () throws ClassNotFoundException {if (parser_class==null) parser_class=class.forname (P Arser_p); return parser_class; Private Parser Getparser () {try {return (Parser) Getparserclass (). newinstance ();} catch (Exception e) {//TODO auto-generated CAtch blockthrow New RuntimeException ("Unable to intantiate" +parser_p); } public Xmlparser (InputStream in,xmlproperties xmlprop) throws Saxexception {//TODO auto-generated constructor s Tub This.xmlprop=xmlprop; this.state=in_nothing; This.value=new StringBuffer (); try {parser=getparser ();p Arser.setdocumenthandler (this);p the Arser.parse (new InputSource (in));} catch (Exception e) {// Todo:handle Exceptione.printstacktrace (); throw new Saxexception ("can ' t create parser");}} @Overridepublic void Setdocumentlocator (Locator Locator) {//TODO auto-generated method stub} @Overridepublic void Startdocument () throws Saxexception {//TODO auto-generated method stub} @Overridepublic void Enddocument () throws Saxexce ption {//TODO auto-generated method stub} @Overridepublic void Startelement (String name, AttributeList atts) throws Saxexc eption {//TODO auto-generated method stubif (state==in_nothing) {if (Name.equals ("Properties")) {state=in_document;} else {throw new Saxexception ("AttemP to find Properties ");}} else if (state==in_document) {if (Name.equals ("PropertyList")) {State=in_document;key=atts.getvalue ("name"); if (key= =null) {throw new Saxexception ("No Name for key" +atts);}} else if (name.equals ("property")) {State=in_key;key=atts.getvalue ("name"), if (key==null) {throw new Saxexception ("No Name for key "+atts);}} Else{throw new Saxexception ("Attemp to find Keys");} Else{throw new Saxexception ("Invalid element" +name);} @Overridepublic void EndElement (String name) throws Saxexception {//TODO auto-generated method stubif (State==in_key) { Xmlprop.setproperty (Key, value.tostring ()); System.out.println ("<key name=\" "+key+" \ ">"); System.out.println (value.tostring () + "</key>\n"); state=in_document;name=null;value=new StringBuffer ();} else if (state==in_document) {state=in_nothing;}} @Overridepublic void characters (char[] ch, int start, int length) throws Saxexception {//TODO auto-generated method stubif (State==in_key) {Compute (ch,start,length);}} public void Compute (char[] Ch,iNT Start,int length) {int St=start;int len=length-1;while (st<length && ((ch[st]== ' \ n ') | | (ch[st]== ' \ t ') | | (ch[st]== ") | | (ch[st]== ' \ R '))) St++;while (len>0 && (ch[len]== ' \ n ') | | (ch[len]== ' \ t ') | | (ch[len]== ") | | (ch[len]== ' \ R '))) Len--;while (St<=len) {value.append (ch[st]); st++;}} @Overridepublic void Ignorablewhitespace (char[] ch, int start, int length) throws Saxexception {//TODO auto-generated Meth OD stub} @Overridepublic void ProcessingInstruction (string target, String data) throws Saxexception {//TODO auto-generated method Stub}}
Test the class source code:
Import Java.io.file;import java.io.fileoutputstream;import Java.io.ioexception;import Java.io.OutputStream;import Java.util.enumeration;import Org.xml.sax.saxexception;public class Testxml {public static void main (string[] args) Throws IOException, Saxexception{xmlproperties xml=new xmlproperties (); Xml.load (New File ("D:\\data\\testxml.xml")); Enumeration Keyenumeration=xml.keys (); Enumeration valueenumeration=xml.elements (); while (Keyenumeration.hasmoreelements ()) {string key= (String) Keyenumeration.nextelement (); String value= (String) valueenumeration.nextelement (); System.out.println (key+ "=" +value) outputstream out=new fileoutputstream (New File ("D:\\data\\out.xml")); Xml.save ( Out, "test");}}}
To test the required XML file:
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE Properties SYSTEM "D:\data\xmlproperties.dtd" ><!--XML Wrapper for properties--><properties> <propertylist name= "MyList" ><property name= "name" >webendshaere</property><property name= " Website ">www.webendshaere.com</property><property name=" email ">[email protected]</property> <property name= "TechSupport" >[email protected]</property></propertylist></properties>
Test the required Xmlproperties.dtd file
<?xml version= "1.0" encoding= "UTF-8"?> <! ELEMENT properties (#PCDATA |property) *> <! ELEMENT key (#PCDATA) > <! Attlist Key Name CDATA #IMPLIED >
Application of convert XML file to properties type----Adapter mode