XML application and Xgen combat

Source: Internet
Author: User
Tags format config ini print object socket tostring xmlns
XML now seems that any software development can not be separated from the XML technology support, in graphics, databases, encryption security, software engineering, network Education, E-commerce, voice technology has a place where XML, the tide of XML application has come.

XML Working Group founder member C.M. Sperberg-mcqueen that: "The biggest impact of XML is the rise of XML software: XML parsers, XML programming language libraries, XSLT processors, XSL FO processors, database acceptance xml-not only that, There are also Web browsers that accept XML. "It is also because of this, IBM, Microsoft, SUN, HP, Oracle and other large companies have entered the market."

In learned the Xgen and other object binding tools, I believe that we have been eager to use xgen to combat, to experience the advantages of XML object binding. Here's a look at some of the XML apps I use a lot.

1. XML configuration file
Each system may require a large or small configuration file, the configuration file to initialize the parameters of the system, the benefits are not described in detail. The general configuration file has the following formats:

1. Window System INI format file and the properties file used in the Java language

2. XML-formatted files

3. Other format documents

The first type of configuration file is a plain text file, the basic use of "key = value" format to record a variety of parameters, easy to write and read manually.

XML Schemas based XML files are easy to read, and they can show the hierarchical relationship and constraint relationship among different elements very well. A configuration file that uses XML format relative to the INI file format has the following advantages:

1.1. Configuration with Hierarchy

1.2. Check the validity of the value

1.3. Support linked lists, enumerations, complex data types

1.4. Configuration files can be nested

1.5. XML editing tools, such as XML Spy, are very handy to edit configuration files

1.6. There are a large number of Third-party XML object binding tools, and powerful, easy to develop. such as the Java language version of the Xgen, jaxb,c++ version of the tool Xbind

Now let's start to practice using XML as a configuration file for your program.

1.1. Design xsd files (XML Schema)
Xgen need to compile an XSD file, which is an outline file that describes the XML file of the specified type, and is a plain text file. The editing tool allows you to create and edit XSD files manually, but with some XML editing tools you can do the work of XSD writing with less effort. I've also used some XML editing tools, but only XML spy is the most powerful and easy to use.

Some features of XML Spy:

l have prompt input when editing XML, XSD files and so on, which is very convenient for you to choose.

L also have the validation function of XML file, which can determine whether the value of element value conforms to the definition of schema.

L Support DTD and XSD interchange

L provides sample XML instance file functionality for XSD

L also support java,c++,c# XML binding, can generate java,c++ and C # code, not too strong Oh!

Writing alertserver.xsd files through XML spy

<?xml version= "1.0"?>

<xsd:schema targetnamespace= "urn:com:lianchuang:smartsecurer:alert:config:configfile.xsd" xmlns:xsd= "http:// Www.w3.org/2001/XMLSchema "xmlns=" urn:com:lianchuang:smartsecurer:alert:config:configfile.xsd " elementformdefault= "qualified" attributeformdefault= "unqualified" >

<xsd:element name= "Config" type= "Conifgtype"/>

<xsd:complextype name= "Conifgtype" >

<xsd:sequence>

<xsd:element ref= "Globe"/>

</xsd:sequence>

</xsd:complexType>

<xsd:element name= "Globe" type= "Globetype"/>

<xsd:complextype name= "Globetype" >

<xsd:sequence>

<xsd:element ref= "Alertserver"/>

<xsd:element ref= "Vomanager" maxoccurs= "unbounded"/>

</xsd:sequence>

</xsd:complexType>

<xsd:element name= "Alertserver" type= "Alertservertype"/>

<xsd:complextype name= "Alertservertype" >

<xsd:sequence>

<xsd:element name= "ID" type= "Xsd:int"/>

<xsd:element name= "Address" type= "xsd:string" default= "127.0.0.1" minoccurs= "0"/>

<xsd:element name= "Port" type= "Xsd:int" default= "1099" minoccurs= "0"/>

<xsd:element name= "Alertservername" type= "xsd:string" minoccurs= "0"/>

<xsd:element name= "Registerinterval" type= "Xsd:int" default= "1000" minoccurs= "0"/>

<xsd:element name= "CacheSize" type= "Xsd:int" default= "10000" minoccurs= "0"/>

<xsd:element name= "Deliverthreadnum" type= "Xsd:int" default= "2" minoccurs= "0"/>

<xsd:element ref= "Dbopermode" default= "default" minoccurs= "0"/>

<xsd:element name= "batchdbinsertsize" type= "Xsd:int" default= "1000" minoccurs= "0"/>

<xsd:element name= "Statisticsinterval" type= "Xsd:int" default= "1000" minoccurs= "0"/>

</xsd:sequence>

</xsd:complexType>

<xsd:element name= "Vomanager" type= "Vomanagertype"/>

<xsd:complextype name= "Vomanagertype" >

<xsd:sequence>

<xsd:element name= "Address" type= "xsd:string"/>

<xsd:element name= "Port" type= "Xsd:int" default= "1099" minoccurs= "0"/>

</xsd:sequence>

</xsd:complexType>

<xsd:element name= "Dbopermode" >

<xsd:simpleType>

<xsd:restriction base= "Xsd:string" >

<xsd:enumeration value= "Default"/>

<xsd:enumeration value= "Native"/>

</xsd:restriction>

</xsd:simpleType>

</xsd:element>

</xsd:schema>



Note <xsd:schema> settings

elementformdefault= "qualified" attributeformdefault= "unqualified" property

, otherwise there will be an exception in the Unmarshal (InputStream, valid) method invocation. This setting represents the restriction of local elements and attributes, that is, to prefix each local element.

When elementFormDefault is set to qualified, it represents that in the instance of the syntax, all elements must be explicitly qualified with a prefix or by setting the {default namespace}. The unqualified setting means that only elements that are globally declared must be explicitly qualified, while elements of a locally declared element may not be qualified. In this case, it is an error to qualify a local declaration. Similarly, when you set attributeFormDefault to qualified, you must explicitly qualify all attributes in the instance document with a prefix.

1.2. Create Java Objects
Enter the Xgen installation directory, in order to save the Alertserver.xsd file to copy to the directory. Execute the following script:

Xgen alertserver.xsd

In the current directory, the Com\lianchuang\smartsecurer\alert\config\configfile_xsd directory is generated according to the urn path, and the newly created class file is saved in the directory. If custom complex type data is defined in the XSD, the configfile_xsd

Directory to create the \type directory, and put the relevant Java Class in the directory.

1.3. Write code
For defining XSD documents, the Elementa of each complex type will have Elementa and Elementatypecomplextype classes to map the Java class. You can get a reference to a complex object type that obtains Elementa directly from the Getelementatypecomplextype () method.

As in globe in an XSD file, you can get the Java object by Xxx.getconifgtypecomplextype (). Getglobe (), through Config.getconifgtypecomplextype (). Getglobe (). Getglobetypecomplextype () to get the actual object of that type.

For some basic type element. Xgen defines some of the classes that begin with X, such as int, expressed in Xint. You can construct a Xint object by using the new xint (int i).

The following is the code that reads the specified configuration file and returns the Java object

public static synchronized Config GetConfig (String fileName) throws

FileNotFoundException

{

Creating InputStream Objects

File File = new file (fileName);

FileInputStream ins = new FileInputStream (file);



Chainedentityresolver er = new Chainedentityresolver ();

Unmarshaller un = new Unmarshaller (er);

Globalelement GE = null;

Try

{

GE = Un.unmarshal (ins, false); Note that because I have a smattering of XML and XSD, the Unmarshal method tries it, and only use this method to convert the object of the XML file to normal. Don't know why ...



if (GE!= null && ge instanceof Config)

Configinstance = (Config) GE;

}

catch (Validationexception ex)

{

M_log.error (ex);

}

catch (Marshalexception ex)

{

M_log.error (ex);

}

catch (IOException ex)

{

M_log.error (ex);

}

return configinstance;

}

The following is a sample code for each property parameter of the Print object

public static void Printconfig (config config)

{

if (config = = null)

Return

M_log.debug ("================ alertserver Parameters ==================");

M_log.debug ("ID =" +

Config.getconifgtypecomplextype (). Getglobe ().

Getglobetypecomplextype (). Getalertserver ().

Getalertservertypecomplextype (). GetID ());

M_log.debug ("address =" +

Config.getconifgtypecomplextype (). Getglobe ().

Getglobetypecomplextype ().

Getalertserver (). Getalertservertypecomplextype (). getaddress ());

M_log.debug ("Port =" +

Config.getconifgtypecomplextype (). Getglobe ().

Getglobetypecomplextype ().

Getalertserver (). Getalertservertypecomplextype (). Getport ());



M_log.debug ("Alertservername =" +

Config.getconifgtypecomplextype (). Getglobe ().

Getglobetypecomplextype (). Getalertserver ().

Getalertservertypecomplextype (). Getalertservername ());

M_log.debug ("Registerinterval =" +

Config.getconifgtypecomplextype (). Getglobe ().

Getglobetypecomplextype (). Getalertserver ().

Getalertservertypecomplextype (). Getregisterinterval ());

M_log.debug ("Deliverthreadnum =" +

Config.getconifgtypecomplextype (). Getglobe ().

Getglobetypecomplextype ().

Getalertserver (). Getalertservertypecomplextype ().

Getdeliverthreadnum ());

M_log.debug ("CacheSize =" +

Config.getconifgtypecomplextype (). Getglobe ().

Getglobetypecomplextype (). Getalertserver ().

Getalertservertypecomplextype (). Getcachesize ());

M_log.debug ("batchdbinsertsize =" +

Config.getconifgtypecomplextype (). Getglobe ().

Getglobetypecomplextype (). Getalertserver ().

Getalertservertypecomplextype (). Getbatchdbinsertsize ());



M_log.debug ("================= vomanager Parameters ==================");

for (int i = 0;

I <

Config.getconifgtypecomplextype (). Getglobe (). Getglobetypecomplextype ().

Getvomanagercount ();

++i)

{

M_log.debug ("Vomanger address =" +

Config.getconifgtypecomplextype (). Getglobe ().

Getglobetypecomplextype (). Getvomanager () [i].

Getvomanagertypecomplextype (). getaddress ());

M_log.debug ("Vomanger Port =" +

Config.getconifgtypecomplextype (). Getglobe ().

Getglobetypecomplextype (). Getvomanager () [i].

Getvomanagertypecomplextype (). Getport ());

}

}

2. Using XML format for message communication
When writing a custom socket communication program, you need to define a set of communication protocol specifications, especially heterogeneous systems. We can use XML documents as communication protocols, and combine XML-related object binding tools to convert XML-formatted messages into objects in languages such as Java and C + +.

The following is a combination of the Java language xgen using a sample to describe the flow of traffic.

2.1. Communication flow
L Send XML objects

Create related objects by program, and assign values. Transformed into a StringWriter object using the Unmarshal method, the GetBuffer (). ToString () method of StringWriter returns a converted string. Finally, use the socket to send the string.

L Receive XML objects

Once you receive the XML document, you can marshal to the Java object.

2.2. Specific technical
L Encryption in Communications

Because of the communication through an XML document, the packet is plaintext text, and appropriate encryption is required for some sensitive data. If DES is passed directly on the XMLW document, or a more secure encryption method is used depending on the situation.

L Send an XML document

UDP Socket

Datagramsocket discoverysocket = null;

Packets Sent

Datagrampacket DGP = null;

Converts an XML object to a StringWriter object, which translates to a string object

StringWriter SW = new StringWriter ();

XML-bound objects

Request req = null;

Array of characters to send

byte[] sendbytes = null;

......

......

Try

{

Creating an XML Document Object

req = Xmlobjanalysis.makerequset (M_agentdisc.m_configfilename,

Getdiscoverrespseqno (),

Xmlobjanalysis.discovery_request);



Sw.getbuffer (). SetLength (0);

Serializing the Request object as an XML string

Req.getrequesttypecomplextype (). Setrequestagentip (New Xstring (

Agentkey.getrequestip ()));

Req.marshal (SW);

Encrypt XML documents through des

Sendbytes = Getdesbytes (Sw.getbuffer (). toString ().

GetBytes (), true);

if (sendbytes!= null)

{

DGP = new Datagrampacket (sendbytes, sendbytes.length);

Dgp.setaddress (IA);

Dgp.setport (Agentkey.getport ());

M_log.debug ("Send Discovery PDU:" + agentkey.getrequestip () +

":" +

Agentkey.getport () + ", size =" +

Sendbytes.length);

M_log.debug (New String (Sw.getbuffer ()));

Discoverysocket.send (DGP);

}

}

catch (Exception ex4)

{

M_log.error (EX4);

}



L Receive XML documents



InGram =

New Datagrampacket

(Inbuffer, inbuffer.length);

Try

{

for (;;)

{

Try

{



Insock.receive (InGram);

}

catch (IOException ex)

{

M_log.error

("ERROR reading input socket:"

+ ex.getmessage ());

Break

}

catch (Exception ex)

{

Ex.printstacktrace ();

Try

{

Thread.Sleep (100);

}

catch (Interruptedexception ex2)

{

}

Return

Continue

}

Recvbytes = new Byte[ingram.getlength ()];

System.arraycopy (Ingram.getdata (), 0, recvbytes, 0, Ingram.getlength ());

Dealagentmessage (Recvbytes, hostName);



}

}

Finally

{

if (Insock!= null)

Insock.close ();

}



private void Dealagentmessage (final byte[] origrecvbytes)

{

Basicinfo resp = null;

Decrypting an XML document

byte[] recvbytes = M_agentdisc.getdesbytes (Origrecvbytes, false);

Change the encoding label to gb2312 so that you can analyze the Chinese in the element, otherwise, it can't be translated correctly into Chinese.

String orig = new String (recvbytes);

Orig = Orig.replaceall ("encoding=\" utf-8\ "", encoding=\ "gb2312\");

Converts a string to Bytearrayinputstream

Bytearrayinputstream Bais = new Bytearrayinputstream (Orig.trim ().

GetBytes ());

Try

{

Convert an XML document to an object

RESP = Xmlobjanalysis.getresponsefromxmlstream (Bais);

}

catch (Exception Ex1)

{

M_log.error (EX1);

}



String Requestagentip = Resp.getbasicinfotypecomplextype ().

Getrequestagentip (). get ();

if (resp = null)

{

M_log.error ("Decode reponse error. Ip = "+ Requestagentip);

Return

}



Determine if the agent automatically discovers the response data

if (Resp.getbasicinfotypecomplextype (). GetResponse ().

Getresponsechoicecomplextype (). Getautodiscoveryaschoice ()!= null)

{

......

}

else if (Resp.getbasicinfotypecomplextype (). GetResponse ().

Getresponsechoicecomplextype (). Gethealthcheckaschoice ()!= null)

{

......

}

}





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.