WebService WSDL file parsing and sending and receiving of SOAP messages (no Java client code generated)

Source: Internet
Author: User
Tags addchild soap xpath soapui wsdl
attached with page JSP, JS, and Dwr action,service and Util, my environment is spring, DWR, ext, jquery. Because the entire tool involved more, so did not complete the operation of the Code to organize, only the core of the code posted out, if you need to run to solve the small problems

In recent time, the company's QA testers need to provide a WebService testing tool, specific requirements for: Testers to provide WebService URL, test tools based on the URL to get WebService published methods and methods of parameters, and then testers in the page input parameters and click Run, and after the tool is run, the results returned on the page are displayed. In fact, testers can use off-the-shelf in the test framework Soapui to test webservice, but testers still feel trouble, team leader also require the tool can not use Wsdl2java to generate WebService client code. I think it may be that you don't want to store too many useless temporary files in your project.

the types of parameters and return values that the test tool supports are: arrays, lists, Java basic data types, Java objects, and nesting of these types. Tool screenshot below







here's how to implement the tool:
Parsing the method contained in the WSDL file using the WSDL4J tool based on the WebService URL parse the schema part of the WSDL using the DOM, and manually parse the parameters of the method using Soapui get the template that sends the SOAP request message to fill in the Sent SOAP request message Gets the return value in the SOAP message returned by the returned SOAP message resolution, which is displayed to the page

before you look at the implementation code, friends who do not understand WSDL and schema can familiarize themselves with the structure of the WSDL and schema files and the individual property fields based on the following URLs
WSDL: http://www.w3school.com.cn/wsdl/index.asp Schema: http://www.w3school.com.cn/schema/index.asp

Code Explanation:
entity Bean used to display method and method parameters on the page
/**
 * @author Zhengtian
 * * 
 * @date 2011-8-4 afternoon
 11:21:50
/@SuppressWarnings ("all")
public Class Webservicemethod {
	private String name;

	Public String GetName () {return
		name;
	}

	public void SetName (String name) {
		this.name = name;
	}

}


Import java.util.ArrayList;

Import java.util.List; public class ParameterInfo {private string name;//parameter name private string value;//parameter value private string type;//argument type privat E String childtype;//If it is an array, then the type of the field array element is private list<parameterinfo> children = new arraylist<parameterinfo&

	gt; ();
		Public ParameterInfo () {} public ParameterInfo (string name, String type) {this.name = name;
	This.type = type;
	Public String GetName () {return name;
	public void SetName (String name) {this.name = name;
	Public String GetValue () {return value;
	public void SetValue (String value) {this.value = value;
	Public String GetType () {return type;
	public void SetType (String type) {this.type = type;
	Public list<parameterinfo> GetChildren () {return children;
	public void Setchildren (list<parameterinfo> children) {This.children = children;
	Public String Getchildtype () {return childtype; } public void Setchildtype(String Childtype)
	{this.childtype = Childtype;
	/** * Add Sub parameter * * @param param/public void addChild (ParameterInfo param) {children.add (param);
 }
}


get the method for WebService publishing
Public list<webservicemethod> Getallmethodbyserviceurl (String webserviceurl) throws Exception {
		//Results
		list<webservicemethod> list = new arraylist<webservicemethod> ();
		try {
			//Modify the URL to a valid URL, i.e. WebServiceURL = Getwebserviceurl with a WSDL suffix
			(webserviceurl);
			if (Stringutils.isnotempty (WebServiceURL)) {
				list<string> methodlist = wsdlutil.getoperationlist ( WebServiceURL);
				for (String methodname:methodlist) {
					Webservicemethod Webservicemethod = new Webservicemethod ();
					Webservicemethod.setname (methodname);

					List.add (Webservicemethod);}}
		catch (Exception e) {
			e.printstacktrace ();
			throw new RuntimeException (e);
		}
		return list;
	}


/**
	 * Get all the methods in WSDL * * 
	 @param wsdlurl
	 * @return
	 * @throws Exception * * Public
	Static List <String> getoperationlist (String wsdlurl) throws Exception {
		Document document = Getdefinitiondocument ( Wsdlurl);
		XPath XPath = getxpath (document);

		NodeList operations = domutil.findnodelist (document, "Wsdl:definitions/wsdl:porttype/wsdl:operation");

		Returns the result set List
		list<string> operationlist = new arraylist<string> ();
		for (int i = 0; i < operations.getlength (); i++) {
			Node operation = Operations.item (i);
			String OperationName = domutil.getnodename (operation);
			if (OperationName!= null &&! "". Equals (OperationName)) {
				Log.debug ("parse" + Wsdlurl + "method:" + OperationName);
				Operationlist.add (OperationName);
			}
		return operationlist;
	}



get the parameters of the method
	/**
	 * WebServiceURL The parameters according to the name of the method * 
	 * @param methodname
	 * * @param webserviceurl *
	 @return
	 * Throws Exception
	 *
	/Public list<parameterinfo> Getparambymethodnameandwsurl (String methodname, String WebServiceURL) throws Exception {
		try {
			Document document = Wsdlutil.getdefinitiondocument (WebServiceURL);
			Returns the result
			list<parameterinfo> inputparamlist = new arraylist<parameterinfo> ();
			Analytic parameter
			StringBuilder xpathbuilder = new StringBuilder ();
			Wsdlutil.getinputparam (Inputparamlist, document, MethodName, Xpathbuilder, NULL, false);
			return inputparamlist;
		} catch (Exception e) {
			e.printstacktrace ();
			throw new RuntimeException (e);
		}
	}


the core method of parsing input parameters

/** * @param inputparamlist * @param document * @param operationname * @param xpathbuilder * @p Aram Parentparam * @param isselfdefinition * @throws Exception * * public static void Getinputparam (List<paramete rinfo> Inputparamlist, document document, String OperationName, StringBuilder xpathbuilder, ParameterInfo Parentpara
		M, Boolean isselfdefinition) throws Exception {//get complextypename String complextypename = "";
		if (Parentparam = = null) {complextypename = OperationName; else {if (Parentparam.gettype (). Equals (SchemaDefaulyType.type_array.type)) {complextypename = Parentparam.getch
			Ildtype ();
			else {complextypename = Parentparam.gettype (); }///Get all the element nodes list<node> children = getsequenceelementofcomplextype (document, Parentparam, Complextyp
		ename, Xpathbuilder, isselfdefinition);
			for (int i = 0; i < children.size (); i++) {//Sub node node child = Children.get (i); String name = DOmutil.getnodename (child);
			Parameter parameterinfo param = new ParameterInfo ();

			Param.setname (name); Whether a type attribute is present (whether its type is referenced or defined by itself) if (Domutil.assertnodeattributeexist (Child, "type")) {//type exists a String type = Domuti

				L.getnodetype (child);
					if (Domutil.isarray (child)) {Param.settype (SchemaDefaulyType.type_array.type);

					Param.setchildtype (type);
					If it is a simple array, add a child parameter to the ParameterInfo Childparam = new ParameterInfo ("", type);

					Param.addchild (Childparam); Array of complex types if (! Domutil.isdefaulttype (Child)) {Getinputparam (inputparamlist, document, OperationName, Xpathbuilder, Childparam, FAL
					SE); } else {Param.settype ("AnyType". Equals (Type)?

					"Object": type); Complex Type if (! Domutil.isdefaulttype (Child)) {StringBuilder Complextxpath = new StringBuilder ("Wsdl:definitions/wsdl:types/xs:sche
						Ma ");
					Getinputparam (inputparamlist, document, OperationName, Complextxpath, param, false); }} else {//If the Type property does not exist, it means that the types of the node define String currentappendstr = "/xs:complextype[@name = '" + parentparam.gettype () + "']/xs" in its child nodes).
				: sequence/xs:element[@name = ' "+ name +" '] ";
				Xpathbuilder.append (CURRENTAPPENDSTR); Node inner = domutil.findnode (document, xpathbuilder.tostring () + "/xs:complextype/xs:sequence/xs:element[position" ()

				=1] ");
					if (Domutil.isarray (inner)) {//Gets the type of the array String type = Getsequenceelementtype (document, inner);
					Param.settype (SchemaDefaulyType.type_array.type);

					Param.setchildtype (type);
					Add a child parameter to an array parameterinfo Childparam = new ParameterInfo ("", type);

					Param.addchild (Childparam); if (! Domutil.isdefaulttype (type)) {//Complex Type array getinputparam (inputparamlist, document, OperationName, Xpathbuilder, CHILDPA
					RAM, True);
					} else {Param.settype (name);
				Traverse its sub nodes xs:element Getinputparam (inputparamlist, document, OperationName, Xpathbuilder, param, true); //Restore XPath Xpathbuilder.delete (xPathbuilder.length ()-Currentappendstr.length (), xpathbuilder.length ());
			} if (Parentparam = = null) {inputparamlist.add (param);
			else {parentparam.addchild (param);
 }
		}
	}


when the page finishes entering parameters, the method is executed
/** *
	 Implementation Method * * 
	 @param webserviceurl
	 * @param methodname
	 * @param paramstr
	 * @return
	 * Throws Exception
	 *
	/public string Executionmethod (string WebServiceURL, String methodname, String paramstr) Throws Exception {
		String result = "";
		try {
			//convert JSON parameter to list<parameterinfo>
			list<parameterinfo> paramlist = Convertstrtolistparam ( PARAMSTR);

			list<parameterinfo> resultlist = new Soaputil (). SendRequest (methodname, Paramlist, WebServiceURL);

			result = Jsonarray.fromobject (resultlist). toString ();
		catch (Exception e) {
			e.printstacktrace ();
			throw new RuntimeException (e);
		}
		return result;
	}


send a SOAP request, and then get the SOAP message returned
/** * Request * * @param operation * @param params * @param wsdlurl * @return * @throws Exception/Publi C list<parameterinfo> SendRequest (string operation, list<parameterinfo> paramlist, String wsdlurl) throws
		Exception {//get operation Operation operationinst = Getoperation (wsdlurl, Operation, NULL);
		Assembly Request messages String message = Buildrequest (Wsdlurl, Operationinst, paramlist);
		Sends a request, gets the returned SOAP message String address = wsdlurl.substring (0, Wsdlurl.indexof ("? wsdl"));
		String Responsestr = sendrequest (address, message, operationinst.getaction ());
		Document soapdocument = getresponsedocument (RESPONSESTR);
		Determines whether the returned SOAP message is Soap:fault if (Isfaultresponsesoap (soapdocument)) {processfaultresponsesoap (soapdocument);
		}//Parse return result list<parameterinfo> outputparamlist = new arraylist<parameterinfo> ();
		list<map<string, object>> wsdlmapsoaplist = new arraylist<map<string, Object>> (); String Complexttypename = Operation + "Response"; Getoutputparam (Wsdlutil.getdefinitiondocument (wsdlurl), Soapdocument, Complexttypename, ComplextTypeName,

		Wsdlmapsoaplist, outputparamlist, NULL);
	return outputparamlist;
 }


resolves a parameter to a sent SOAP message core method
/** * Build SOAP message * * @param wsdldocument * @param * @param operationinst * @param paramlist * Param parentnode * @throws Exception * * private void Buildsoapmessage (document Wsdldocument, document Soapdocument, O Peration Operationinst, list<parameterinfo> paramlist, Node parentnode, ParameterInfo parentParam) throws Excepti
		On {//operation name String OperationName = Operationinst.getname (); If it is the root node of the action method, empty its child nodes if (parentnode = = null) {parentnode = Getoperationnodeinrequestsoapdom (soapdocument, Operatio
			Nname);
		Parentnode.settextcontent (""); 
			for (int i = 0; i < paramlist.size (); i++) {//Get the parameter name, type, value parameterinfo param = paramlist.get (i);
			String value = Param.getvalue ();
			String name = Param.getname ();

			String type = Param.gettype (); Determine if the base type if (Domutil.isdefaulttype (type) | | (Stringutils.isnotempty (name) && stringutils.isnotempty (type)) | | ("Entry". Equals (type) | | "Jsonentry". equALS (type)) {if (Stringutils.isempty (name)) {if (i > 0) {Element ele = soapdocument.createelement (par
						Entnode.getnodename ());
						Text text = Soapdocument.createtextnode (value);

						Ele.appendchild (text);
						Node Grandparentnode = Parentnode.getparentnode ();
					Grandparentnode.appendchild (ele); else {if ("entry". Equals (type) | |
							"Jsonentry". Equals (Type)) {Element ele = soapdocument.createelement (type);

							Parentnode.appendchild (ele); Assembly node if (Param.getchildren (). Size () > 0) {list<node> childlist = Domutil.getchildelementnodes
								(parentnode);
								Node Lastchildnode = Childlist.get (Childlist.size ()-1);
							Buildsoapmessage (Wsdldocument, Soapdocument, Operationinst, Param.getchildren (), Lastchildnode, param);
							} else {text text = Soapdocument.createtextnode (value);
						Parentnode.appendchild (text); }} else {Element ele = Soapdocument.createelEment (name);
					Text text = Soapdocument.createtextnode (value);
					Ele.appendchild (text);

					Parentnode.appendchild (ele); Assembly Sub-node if (Param.getchildren (). Size () > 0) {list<node> childlist = domutil.getchildelementnodes (par
						Entnode);
						Node Lastchildnode = Childlist.get (Childlist.size ()-1);
					Buildsoapmessage (Wsdldocument, Soapdocument, Operationinst, Param.getchildren (), Lastchildnode, param); }} else {//If not the base type, assemble the node's child nodes if (i > 0) {Element ele = soapdocument.createelement (parentnode.g
					Etnodename ());
					Node Grandparentnode = Parentnode.getparentnode ();
					Grandparentnode.appendchild (ele); Assembly node if (Param.getchildren (). Size () > 0) {list<node> childlist = domutil.getchildelementnodes (gra
						Ndparentnode);
						Node Lastchildnode = Childlist.get (Childlist.size ()-1);
					Buildsoapmessage (Wsdldocument, Soapdocument, Operationinst, Param.getchildren (), Lastchildnode, param);
}				else {//Assembly child node if (Param.getchildren (). Size () > 0) {buildsoapmessage (wsdldocument, soapdocument
					, Operationinst, Param.getchildren (), parentnode, param);
 }
				}
			}

		}
	}


resolves the returned SOAP message to the page parameter core method
/** * resolves the SOAP message returned and populates the result with the outputparamlist * * @param wsdldocument * @param soapdocument * @param operationres Ponsename * @param complexttypename * @param wsdlmapsoaplist * @param outputparamlist * @throws Exception/PU Blic void Getoutputparam (document Wsdldocument, document Soapdocument, String operationresponsename, String Complexttypename, list<map<string, object>> wsdlmapsoaplist, list<parameterinfo> outPutParamList, ParameterInfo parent) throws Exception {//Get the returned parameter list<node> outputnodelist = wsdlutil.getsequenceelementofcom

		Plextype (Wsdldocument, complexttypename); for (int i = 0; i < outputnodelist.size (); i++) {map<string, object> wsdlmapsoap = new hashmap<string, OBJ
			Ect> ();
			Assembly parameters param Node Outputnode = outputnodelist.get (i);
			String name = Domutil.getnodename (Outputnode);

			String type = Domutil.getnodetype (Outputnode);
			ParameterInfo Currentparam = new ParameterInfo (); Currentparam. SetName (name); if (Domutil.isdefaulttype (Outputnode)) {//This parameter is the base type if (Domutil.isarray (Outputnode)) {//array currentparam.settype (
					WsdlUtil.SchemaDefaulyType.type_array.getType ());

					Currentparam.setchildtype (type);
					Assembly Mapping Relationship Wsdlmapsoap.put ("name", name);
					Wsdlmapsoap.put ("Index", New Integer (-1));

					Wsdlmapsoaplist.add (WSDLMAPSOAP); Gets the number of the array in the return SOAP message int arraylength = Getarraylengthfromresponsesoap (soapdocument, Operationresponsename, WSDLMAPSO

					Aplist);
						Takes the value for (int j = 1; J <= Arraylength + +) {parameterinfo param = new ParameterInfo () from the SOAP message;
						Param.setname (name);

						Param.settype (type);

						Wsdlmapsoap.put ("Index", New Integer (j));
						String value = Getvaluefromresponsesoap (Soapdocument, Wsdlmapsoaplist, operationresponsename);

						Param.setvalue (value);
					Currentparam.addchild (param);
					} else {//is not an array currentparam.settype (type); Value from the returned SOAP message, based on the mapping relationship WsdlmapsoaP.put ("name", name);

					Wsdlmapsoap.put ("Index", New Integer (-1));
					Wsdlmapsoaplist.add (WSDLMAPSOAP);
					String value = Getvaluefromresponsesoap (Soapdocument, Wsdlmapsoaplist, operationresponsename);
				Currentparam.setvalue (value); } else {//This parameter is a complex type if (Domutil.isarray (Outputnode)) {//array currentparam.settype (Wsdlutil.schemadefaulytype.
					Type_array.gettype ());

					Currentparam.setchildtype (type);
					Assembly Mapping Relationship Wsdlmapsoap.put ("name", name);
					Wsdlmapsoap.put ("Index", New Integer (-1));

					Wsdlmapsoaplist.add (WSDLMAPSOAP); Gets the number of the array in the return SOAP message int arraylength = Getarraylengthfromresponsesoap (soapdocument, Operationresponsename, WSDLMAPSO

					Aplist);
						Takes the value for (int j = 1; J <= Arraylength + +) {parameterinfo param = new ParameterInfo () from the SOAP message;

						Param.settype (type);

						Wsdlmapsoap.put ("Index", New Integer (j)); Continue to find Getoutputparam (Wsdldocument, Soapdocument, Operationresponsename, type, WSDLMApsoaplist, outputparamlist, param);
					Currentparam.addchild (param);
					} else {//is not an array currentparam.settype (type);
					Wsdlmapsoap.put ("name", name) from the returned SOAP message, based on the mapping relationship;

					Wsdlmapsoap.put ("Index", New Integer (-1));

					Wsdlmapsoaplist.add (WSDLMAPSOAP); Continue to find Getoutputparam (Wsdldocument, Soapdocument, Operationresponsename, type, wsdlmapsoaplist, outputparamlist, cur
				Rentparam);
			}//Add parameter if (parent = null) {Outputparamlist.add (Currentparam);
			else {parent.addchild (currentparam);
		////Remove the current node Wsdlmapsoaplist.remove (Wsdlmapsoaplist.size ()-1) in the mapping relationship;
 }
	}

Webservicetest.rar (8.1 MB) Download number of times: 1246 size: 63.9 KB size: 69.1 KB size: 69.1 KB size: 87.3 KB size: 71.2 KB size: 90.7 KB View picture attachment
Related Article

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.