1 SOAP client examples
A SOAP request can be formulated by generating an XML message that will be transported using the HTTP protocol. The creation of the XML message (serialization) and the obtaining fo the response (deserialization) can be done through different languages.
Below are some examples in the most common languages.
1.1 XSQL-Script client
This section shows several examples of SOAP clients using the XSQL-SCRIPTS language.
1.1.1 SOAPSQLServer.executeQuery
Example 1
Execute an SQL query.
<xsql-script name='executeSQL1'> <body> <set name='m_response'> <soap.call url='http://www.mydeister.com/soap/servlet/rpcrouter' uri='urn:SOAPSQLServer' method='executeQuery' user='soap' password='soap999' > <parameters> <parameter name='dbms'>demo_sports</parameter> <parameter name='sqlcmd'>SELECT codigo, nomdia FROM cdiarios WHERE codigo='DC'</parameter> </parameters> </soap.call> </set> <if><expr><soap.isFault><m_response/></soap.isFault></expr> <then> <println><soap.fault.getCode><m_response/></soap.fault.getCode></println> <println><soap.fault.getString><m_response/></soap.fault.getString></println> </then> <else> <println><m_response/></println> <println><map.get name='m_response'><string>codigo</string></map.get></println> <println><map.get name='m_response'><string>nomdia</string></map.get></println> </else> </if> </body> </xsql-script>
Example 2
Executes an SQL query that returns one or more columns of one or more records. It returns a map where each entry referenced by the name of the column contains an array for the values of that column in each of the different records obtained.
<xsql-script name='sample_executeQueryMultRow'> <body> <set name='m_response'> <soap.call url='http://www.mydeister.com/soap/servlet/rpcrouter' uri='urn:SOAPSQLServer' method='executeQuery' user='soap' password='soap123' > <parameters> <parameter name='dbms'>demo_sports</parameter> <parameter name='sqlcmd'>SELECT * FROM cdiarios</parameter> <parameter name='allowMultiRow'><boolean.true /></parameter> </parameters> </soap.call> </set> <if><expr><soap.isFault><m_response/></soap.isFault></expr> <then> <println><soap.fault.getCode><m_response/></soap.fault.getCode></println> <println><soap.fault.getString><m_response/></soap.fault.getString></println> </then> <else> <set name='l_nomdia'><map.get name='m_response'><string>nomdia</string></map.get></set> <iterator name='s_code' index='idx'> <in> <map.get name='m_response'><string>codigo</string></map.get> </in> <do> <println></println> <println>ROW <idx/></println> <println>CODIGO: <s_code/></println> <println>NOMDIA: <array.get name='l_nomdia'><idx/></array.get></println> </do> </iterator> </else> </if> </body> </xsql-script>
1.1.2 SOAPSQLServer.getQueryValue
Example 1
Executes an SQL query that returns one or more columns from a single record. Returns a map with the value of the columns referenced by name.
<xsql-script name='getQueryValue1'> <body> <set name='m_response'> <soap.call url='http://www.mydeister.com/soap/servlet/rpcrouter' uri='urn:SOAPSQLServer' method='getQueryValue' user='soap' password='soap999' > <parameters> <parameter name='dbms'>demo_sports</parameter> <parameter name='sqlcmd'>SELECT nomdia FROM cdiarios WHERE codigo='DC'</parameter> </parameters> </soap.call> </set> <if><expr><soap.isFault><m_response/></soap.isFault></expr> <then> <println><soap.fault.getCode><m_response/></soap.fault.getCode></println> <println><soap.fault.getString><m_response/></soap.fault.getString></println> </then> <else> <println><m_response/></println> <println><map.get name='m_response'><string>nomdia</string></map.get></println> </else> </if> </body> </xsql-script>
1.1.3 SOAPSQLServer.getQueryValues
Example 1
Executes an SQL query that returns one or more columns of one or more records. It returns a map where each entry referenced by the name of the column contains an array for the values of that column in each of the different records obtained.
<xsql-script name='sample_getQueryVaues> <body> <set name='m_response'> <soap.call url='http://www.mydeister.com/soap/servlet/rpcrouter' uri='urn:SOAPSQLServer' method='getQueryValues' user='soap' password='soap123' > <parameters> <parameter name='dbms'>demo_sports</parameter> <parameter name='sqlcmd'>SELECT * FROM cdiarios</parameter> </parameters> </soap.call> </set> <if><expr><soap.isFault><m_response/></soap.isFault></expr> <then> <println><soap.fault.getCode><m_response/></soap.fault.getCode></println> <println><soap.fault.getString><m_response/></soap.fault.getString></println> </then> <else> <println><m_response/></println> <set name='l_nomdia'><map.get name='m_response'><string>nomdia</string></map.get></set> <iterator name='s_code' index='idx'> <in> <map.get name='m_response'><string>codigo</string></map.get> </in> <do> <println></println> <println>ROW <idx/></println> <println>CODIGO: <s_code/></println> <println>NOMDIA: <array.get name='l_nomdia'><idx/></array.get></println> </do> </iterator> </else> </if> </body> </xsql-script>
1.2 Java Client (Apache SOAP 2.3)
In this section, we will show several examples of java clients developed using APACHE SOAP libraries.
1.2.1 Previous requirements
To compile or execute the examples detailed in this section, at least the libraries listed below are required and can be found at common/lib/webstudio:
- common/lib/webstudio/soap.jar (Apache Soap 2.3)
- common/lib/webstudio/activation.jar (JavaBeans Activation Framework.)
- common/lib/webstudio/mail/jmail_1_4_mail.jar (Java Mail 1.4)
1.2.2 Compilation
An example of compiling a java client could be the following, where SOAPOBJClient1.java is the java code file:
javac -classpath soap.jar SOAPOBJClient1.java
1.2.3 Execution
An example of executing a java client could be the following, where SOAPOBJClient1 is the java class file, to which two arguments are passed:
java -classpath soap.jar;jmail_1_4_mail.jar;activation.jar;. SOAPOBJClient1 http://192.10.10.1/soap/servlet/rpcrouter demo_sports1
1.2.4 SOAPSQLServer.executeSQL
The following example shows a service call routine SOAPSQLServer.executeSQL(String database, String sqlcmd, int[] sqltype, Object[] sqldata, boolean gzip)
rem =========================================================================== rem rem SOAPExecuteSQLClient1.bat rem rem Execute a call to the SOAPSQLServer client for commands executeSQL: rem Element executeSQL(String database, String sqlcmd, Integer[] sqltype, Object[] sqldata, boolean gzip) rem rem =========================================================================== set JDK_HOME="C:\Program Files\Java\jdk1.8.0_05" set SOAP_LIBD=. %JDK_HOME%\bin\javac -classpath soap.jar;%SOAP_LIBD%\jmail_1_3_1_mail.jar SOAPExecuteSQLClient1.java set CLASS_SOAP=%SOAP_LIBD%\soap.jar;%SOAP_LIBD%\jmail_1_3_1_mail.jar;%SOAP_LIBD%\activation.jar set url="http://www.example.com/soap/servlet/rpcrouter" set user=usertest set pass=passtest set dbms=dbmstest %JDK_HOME%\bin\java -classpath %CLASS_SOAP%;. SOAPExecuteSQLClient1 %url% %user% %pass% %dbms% PAUSE
// java import java.sql.Types; import java.net.URL; import java.util.Vector; // dom import org.w3c.dom.Element; // apache SOAP import org.apache.soap.util.xml.DOM2Writer; import org.apache.soap.Fault; import org.apache.soap.Constants; import org.apache.soap.SOAPException; import org.apache.soap.rpc.Call; import org.apache.soap.rpc.Parameter; import org.apache.soap.rpc.Response; import org.apache.soap.transport.http.SOAPHTTPConnection; /** * */ public class SOAPExecuteSQLClient1 { /** * Un signle client */ public static void main(String[] args) throws Exception { if (args.length != 4) { System.err.println("Usage:"); System.err.println(" java " + SOAPExecuteSQLClient1.class.getName() + " url user password database" ); System.exit (1); } // We take the command line arguments. int offset = 5 - args.length; URL url = new URL(args[1 - offset]); String user = args[2 - offset]; String password = args[3 - offset]; String database = args[4 - offset]; //Build the object Call call = new Call(); // Authentication SOAPHTTPConnection hc = new SOAPHTTPConnection(); StringBuffer requestBuilder = null; StringBuffer responseBuilder = null; requestBuilder = new StringBuffer(); responseBuilder = new StringBuffer(); hc.setRequestCopy(requestBuilder); hc.setResponseCopy(responseBuilder); hc.setUserName(user); // USUARIO hc.setPassword(password); // PASSWORD call.setSOAPTransport(hc); call.setTargetObjectURI("urn:SOAPSQLServer"); call.setMethodName("executeSQL"); // La codificacion de la respuesta es un org.w3c.dom.Element call.setEncodingStyleURI(Constants.NS_URI_LITERAL_XML); /* create table soaptest ( f00_serial serial NOT NULL, f01_char char(10), f02_date date, f03_intvl interval hour to second, f04_dtime datetime year to second, f05_boolean boolean, f06_smallint smallint, f07_int integer, f08_int8 int8, f09_dec decimal(14, 2), f10_smfloat smallfloat, f11_float float, f12_money money(14, 2), f13_real real, f14_numeric numeric, f15_varchar varchar(255), f16_nchar nchar(20), f17_lvarchar lvarchar, f18_clob clob, f19_blob blob, f20_text text, f21_byte byte ); create unique index p_soaptest on soaptest (f00_serial); alter table soaptest add constraint primary key (f00_serial) constraint p_soaptest; */ String sqlstmt = "insert into soaptest values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; int[] sqltype = new int[22]; Object[] sqldata = new Object[22]; sqltype[ 0] = Types.INTEGER; sqltype[ 1] = Types.CHAR; sqltype[ 2] = Types.DATE; sqltype[ 3] = Types.CHAR; sqltype[ 4] = Types.TIMESTAMP; sqltype[ 5] = Types.BOOLEAN; sqltype[ 6] = Types.SMALLINT; sqltype[ 7] = Types.INTEGER; sqltype[ 8] = Types.BIGINT; sqltype[ 9] = Types.DECIMAL; sqltype[10] = Types.FLOAT; sqltype[11] = Types.DOUBLE; sqltype[12] = Types.DOUBLE; // money sqltype[13] = Types.DOUBLE; // real sqltype[14] = Types.DOUBLE; // numeric sqltype[15] = Types.VARCHAR; sqltype[16] = Types.VARCHAR; sqltype[17] = Types.LONGVARCHAR; sqltype[18] = Types.CLOB; sqltype[19] = Types.BLOB; sqltype[20] = Types.LONGVARCHAR; sqltype[21] = Types.LONGVARBINARY; sqldata[ 0] = new Integer(0); sqldata[ 1] = "ABCDEFG"; sqldata[ 2] = new java.util.Date(System.currentTimeMillis()); sqldata[ 3] = null; //"0 12:10:00"; sqldata[ 4] = new java.util.Date(System.currentTimeMillis()); sqldata[ 5] = new Boolean(true); sqldata[ 6] = new Short((short)10); sqldata[ 7] = new Integer(20); sqldata[ 8] = new Long(20); sqldata[ 9] = new Double(30.1234); sqldata[10] = new Float(30.1234); sqldata[11] = new Double(30.1234); sqldata[12] = new Double(30.1234); sqldata[13] = new Double(30.1234); sqldata[14] = new Double(30.1234); sqldata[15] = "Varchar test"; sqldata[16] = "Long text field type lvarchar, must be String"; sqldata[17] = "Varchar test"; sqldata[18] = "Long text field type CLOB, can be String or byte[]"; sqldata[19] = new String("Columna de tipo CLOB").getBytes(); sqldata[20] = new String("Texto largo TEXT, debe ser byte[]").getBytes(); sqldata[21] = new byte[] { 0x00, 0x01, 0x02 }; Vector params = new Vector(); params.addElement( new Parameter( "database", String.class, database, Constants.NS_URI_SOAP_ENC ) ); params.addElement( new Parameter( "sqlstmt", String.class, sqlstmt, Constants.NS_URI_SOAP_ENC ) ); params.addElement( new Parameter( "sqltype", int[].class, sqltype, Constants.NS_URI_SOAP_ENC ) ); params.addElement( new Parameter( "sqldata", Object[].class, sqldata, Constants.NS_URI_SOAP_ENC ) ); params.addElement( new Parameter( "gzip", Boolean.class, false, Constants.NS_URI_SOAP_ENC ) ); call.setParams(params); // Invocamos la llamada Response resp; try { resp = call.invoke(url, ""); } catch (SOAPException ex) { if (requestBuilder != null) System.err.println("SOAP REQUEST:\n" + requestBuilder.toString()); if (responseBuilder != null) System.err.println("SOAP RESPONSE:\n" + responseBuilder.toString()); System.err.println("Caught SOAPException (" + ex.getFaultCode() + "): " + ex.getMessage() ); ex.printStackTrace(); return; } if (requestBuilder != null) System.out.println("SOAP REQUEST:\n" + requestBuilder.toString()); if (responseBuilder != null) System.out.println("SOAP RESPONSE:\n" + responseBuilder.toString()); // Verificamos la respuesta y la mostramos if (!resp.generatedFault()) { Parameter ret = resp.getReturnValue(); Element element = (Element)ret.getValue(); System.out.println(DOM2Writer.nodeToString(element)); } else { Fault fault = resp.getFault(); System.err.println("Fault code :" + fault.getFaultCode()); System.err.println("Fault string :" + fault.getFaultString()); System.err.println("Fault ActorURI:" + fault.getFaultActorURI()); Vector details = fault.getDetailEntries(); if (details != null) { while (details.size() > 0) { Object data = details.remove(0); System.err.println("Detail Entry :" + data.getClass().getName()); System.err.println(data); } } Vector entries = fault.getFaultEntries(); if (entries != null) { while (entries.size() > 0) { Object data = entries.remove(0); System.err.println("Fault Entry :" + data.getClass().getName() ); System.err.println(data); } } } // if (!resp.generatedFault()) } // main } // SOAPExecuteSQLClient1
1.3 Java Client (Apache Axis 1.x)
In this section, we will show several examples of java clients developed using AXIS libraries.
1.3.1 Previous requirements
To compile or execute the examples described in this section, we need at least the following packages available from APACHE AXIS:
- axis.jar
- jaxrpc.jar
- wsdl4j-1.5.1.jar
- commons-logging-1.0.4.jar
- commons-discovery-0.2.jar
1.3.2 Compilation
An example of compiling a java client could be the following, where AXISExecuteQueryClient.java is the java code file:
javac -classpath axis.jar;jaxrpc.jar AXISExecuteQueryClient.java
1.3.3 Execution
An example of executing a java client could be the following, where AXISExecuteQueryClient is the java class file, to which is passed four arguments:
java -classpath axis.jar;jaxrpc.jar;wsdl4j-1.5.1.jar;commons-logging-1.0.4.jar;commons-discovery-0.2.jar;. AXISExecuteQueryClient http://webstudioserver/soap/servlet/rpcrouter USER PASSWORD demo_sports "SELECT COUNT(*) contador, MAX(docser) docser from gcomfach"
1.3.4 SOAPSQLServer.executeQuery
Example 1
This example shows how to invoke the SOAPSQLServer.executeQuery service to execute a simple SQL statement.
// java import java.net.URL; import java.util.Hashtable; //Apache Axis import org.apache.axis.client.Service; import org.apache.axis.client.Call; import org.apache.axis.description.*; import org.apache.axis.constants.Style; import org.apache.axis.Constants; import org.apache.axis.constants.Use; import org.apache.axis.soap.SOAPConstants; import javax.xml.namespace.QName; public class AXISExecuteQueryClient { public static void main(String args[]) throws Exception { if (args.length != 5) { System.err.println("Usage:"); System.err.println(" java " + AXISExecuteQueryClient.class.getName() + " url user pass database sqlcmd" ); System.exit (1); } // Tomamos los argumentos de la linea de comandos. int offset = 6 - args.length; URL url = new URL(args[1 - offset]); String user = args[2 - offset]; String password = args[3 - offset]; String database = args[4 - offset]; String sqlcmd = args[5 - offset]; // Observe si usa un proxy! /* System.getProperties().setProperty("http.proxySet", "true"); System.getProperties().setProperty("http.proxyHost","proxy"); //PROXY HOSTNAME System.getProperties().setProperty("http.proxyPort", "8080"); //PROXY PORT */ OperationDesc oper = new OperationDesc(); oper.setName("executeQuery"); ParameterDesc param = new ParameterDesc(new QName("", "database"), ParameterDesc.IN, new QName("http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new ParameterDesc(new QName("", "sqlcmd"), ParameterDesc.IN, new QName("http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); oper.setReturnType(new QName("http://xml.apache.org/xml-soap", "Hashtable")); oper.setReturnClass(Hashtable.class); oper.setReturnQName(new QName("", "executeQueryReturn")); oper.setStyle(Style.RPC); oper.setUse(Use.ENCODED); Service service = new Service(); Call _call = (Call) service.createCall(); _call.setTargetEndpointAddress(url); _call.setSOAPVersion(SOAPConstants.SOAP11_CONSTANTS); _call.setEncodingStyle(Constants.URI_SOAP11_ENC); _call.setUsername(user); // USUARIO _call.setPassword(password); // PASSWORD _call.setOperation(oper); _call.setUseSOAPAction(true); _call.setSOAPActionURI(""); _call.setOperationName(new QName("urn:SOAPSQLServer", "executeQuery")); Object _resp = _call.invoke(new Object[] {database, sqlcmd}); Hashtable m_ret = (Hashtable) _resp; System.out.println(m_ret.toString()); } }
1.4 C sharp (c#)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; namespace SOAPSQLServer2 { class Program { static void Main(string[] args) { String url = "http://wwww.mydeister.com/soap/servlet/rpcrouter"; String username = "USUARIO"; String password = "PASSWORD"; String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)); String database = "demo_formacion"; String sqlcmd = "select tabname from systables where tabid = 1"; String method = "executeSQL"; String targetObjectURI = "urn:SOAPSQLServer"; try { HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url); Request.Method = "POST"; Request.ContentType = "text/xml"; Request.Headers.Add("SOAPAction", method); Request.Headers.Add("Authorization", "Basic " + encoded); Stream postStream = Request.GetRequestStream(); var xml = "<?xml version='1.0' encoding='ISO-8859-1'?>"; xml = xml + "<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"; xml = xml + "<SOAP-ENV:Body>"; xml = xml + "<ns1:" + method + " xmlns:ns1='" + targetObjectURI + "' SOAP-ENV:encodingStyle='http://xml.apache.org/xml-soap/literalxml'>"; xml = xml + "<database xsi:type='xsd:string' SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>" + database + "</database>"; xml = xml + "<sqlcmd xsi:type='xsd:string' SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>" + sqlcmd + "</sqlcmd>"; xml = xml + "</ns1:" + method + ">"; xml = xml + "</SOAP-ENV:Body>"; xml = xml + "</SOAP-ENV:Envelope>"; byte[] byteArray = Encoding.UTF8.GetBytes(xml); postStream.Write(byteArray, 0, byteArray.Length); postStream.Flush(); postStream.Close(); HttpWebResponse Response = (HttpWebResponse)Request.GetResponse(); String content = ""; Console.WriteLine("Response:"); using (var reader = new StreamReader(Response.GetResponseStream())) { content = reader.ReadToEnd(); } Console.WriteLine(content); Console.ReadLine(); Response.Close(); } catch (WebException e) { Console.WriteLine("This program is expected to throw WebException on successful run." + "\n\nException Message :" + e.Message); if (e.Status == WebExceptionStatus.ProtocolError) { Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode); Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription); } } catch (Exception e) { Console.WriteLine(e.Message); } Console.ReadLine(); } } }
1.5 Microsoft VB Client
Call example to SOAPSQLServer.executeSQL(host, db, sqlstatement)
function DeisterSQL( server, database, sqlcmd ) { /*****************************************************************/ /* Invocation of the execute method of the Web Service SOAPSQLServer /*****************************************************************/ Response.Buffer = true; var httpObj, xmlout, xmlin; // Http Peticción, Input and Output Messages var xml; // String XML targetObjectURI= "urn:SOAPSQLServer"; // URI: Remote Web Service to Run method = "execute"; // Remote Method to Execute xmlObj = Server.CreateObject("MSXML2.DOMDocument"); httpObj = Server.CreateObject("MSXML2.XMLHTTP"); /* SOAP Message Construction */ xml="<?xml version='1.0' encoding='ISO-8859-1'?>"; xml = xml +"<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"; xml = xml +"<SOAP-ENV:Body>"; xml = xml +"<ns1:"+ method +" xmlns:ns1='"+ targetObjectURI +"' SOAP-ENV:encodingStyle='http://xml.apache.org/xml-soap/literalxml'>"; xml = xml +"<database xsi:type='xsd:string' SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>"+database+"</database>"; xml = xml +"<sqlcmd xsi:type='xsd:string' SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>"+sqlcmd+"</sqlcmd>"; xml = xml +"</ns1:"+ method +">"; xml = xml +"</SOAP-ENV:Body>"; xml = xml +"</SOAP-ENV:Envelope>"; xmlObj.loadXML(xml); /* HTTP Request Construction */ //httpObj.Open("POST", server + "/soap/servlet/rpcrouter", false); url = server +"/soap/servlet/rpcrouter"; httpObj.Open("POST", url, false, "oys", "david"); httpObj.setRequestHeader ("SOAPAction", "execute"); httpObj.setRequestHeader ("Content-Type", "text/xml"); httpObj.setRequestHeader ("charset", "ISO-8859-1"); /* Authorization: BASE64 code of the user combination:password */ httpObj.setRequestHeader ("Authorization", "Basic ZGF2aWRsYXNlcmFzOmRhdmlkbGFzZXJhcw=="); /* Sending the HTTP request and Receiving the Data */ httpObj.send(xmlObj); /*******************************/ /* Pending Status Control */ /*******************************/ return(httpObj.responseText); } /*****************************************************************/ /* Convert XML-SOAP Response in Recordset /*****************************************************************/ function DeisterXML2RS( xml, DeiRS ) { var xml; // XML String with the SOAP Response Message var source, result // XML Before and after Transform source = Server.CreateObject("MSXML2.DOMDocument"); style = Server.CreateObject("MSXML2.DOMDocument"); result = Server.CreateObject("MSXML2.DOMDocument"); style0 = Server.CreateObject("MSXML2.DOMDocument"); result0 = Server.CreateObject("MSXML2.DOMDocument"); // DeiRS = Server.CreateObject("ADODB.RecordSet"); DeiRS.ActiveConnection = "Provider=MSDAOSP; Data Source=MSXML2.DSOControl.4.0;"; /**** Load the SOAP-XML response ****/ source.loadXML(xml); /**** Transformation File Load ***/ style.async = false; style.load(Server.mappath("../interfase/entrada/deister.xsl")); /**** XSL transformation of the SOAP response **/ result.async = false; result.validateOnParse = true; source.transformNodeToObject(style, result); /*** Load 2nd Transformation File to remove namespaces *****/ style0.async = false; style0.load(Server.mappath("../interfase/entrada/deister0.xsl")); /*** 2ª Transformation **********/ result.transformNodeToObject(style0, result0); /*** The result XML is saved in a Temporary file *****/ result0.save(Server.mappath("../interfase/entrada/deistertmp.xml")); DeiRS.Open(Server.mappath("../interfase/entrada/deistertmp.xml")); } function MakeXSL(fields) { style = Server.CreateObject("MSXML2.DOMDocument"); style0 = Server.CreateObject("MSXML2.DOMDocument"); /****** STRING de XSL *************/ str ="<?xml version='1.0' encoding='ISO-8859-1'?>"; str = str + "<xsl:stylesheet version='1.0' xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:ns1='urn:SOAPSQLServer'>"; str = str + "<xsl:output method='xml' encoding='ISO-8859-1'/>" str = str + "<xsl:template match='/'>"; str = str + "<rowset>"; str = str + "<xsl:for-each select='SOAP-ENV:Envelope/SOAP-ENV:Body/ns1:executeResponse/return/sqlresponse/rowset/row'>"; str = str + "<row>"; for (m=0;m<fields.length;m++) { str = str + "<" + fields[m] + ">"; str = str + "<xsl:value-of select='" + fields[m]+ "'/>"; str = str + "</" + fields[m] + ">"; } str = str + "</row>"; str = str + "</xsl:for-each>"; str = str + "</rowset>"; str = str + "</xsl:template>"; str = str + "</xsl:stylesheet>"; style.loadXML(str); style.save (Server.mappath("../interfase/entrada/deister.xsl")); /****** STRING of XSL *************/ str ="<?xml version='1.0' encoding='ISO-8859-1'?>"; str = str + "<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>"; str = str + "<xsl:output method='xml' encoding='ISO-8859-1'/>" str = str + "<xsl:template match='/'>"; str = str + "<rowset>"; str = str + "<xsl:for-each select='rowset/row'>"; str = str + "<row>"; for (m=0;m<fields.length;m++) { str = str + "<" + fields[m] + ">"; str = str + "<xsl:value-of select='" + fields[m]+ "'/>"; str = str + "</" + fields[m] + ">"; } str = str + "</row>"; str = str + "</xsl:for-each>"; str = str + "</rowset>"; str = str + "</xsl:template>"; str = str + "</xsl:stylesheet>"; style.loadXML(str); style.save (Server.mappath("../interfase/entrada/deister0.xsl")); style = null; style0 = null; }
1.6 RAW Java Client
When in Java you do not have a serialization library such as Apache SOAP (on an Android device), you can make soap messages directly and negotiate with the server in direct http protocol. This mencanism requires more advanced knowledge of Java and interoperability with SOAP. The serialization and deserialization process can be especially complex.
1.6.1 Example 1
The following example shows a service call routine SOAPSQLServer.executeSQL (String database, String stmt)
/* * @(#)soap.java * * Copyright 1997, 2018 DEISTER, S.A. * San Pedro Claver 15, 08017 BARCELONA * All rights reserved. * * This software is confidential and contains information owned * by DEISTER, S.A. You cannot publish this information and you can only * use it in the terms of the user license you have signed with * DEISTER. * * * "C:\Program Files\Java\jdk1.6.0_43\bin\javac" * * */ // java.sql import java.sql.ResultSet; // java.io import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; // java.net import java.net.URL; import java.net.HttpURLConnection; // java.util.zip import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPInputStream; public class soap { protected static final String URI_XML_LITERALXML = "http://xml.apache.org/xml-soap/literalxml"; protected static final String URI_SOAP_ENCODING = "http://schemas.xmlsoap.org/soap/encoding/"; protected static final String WEBSTUDIO_RPCROUTER = "/soap/servlet/rpcrouter"; public static void main(String[] args) throws Exception { if (args.length != 5) { System.err.println("Usage:"); System.err.println(" java soap host port database user pass" ); System.exit (1); } String host = args[0]; // ex. 192.168.10.10 int port = Integer.valueOf(args[1]); // ex. 80 String database = args[2]; // ex. demo_vodafone String user = args[3]; // ex. username String password = args[4]; // ex. password // ATTENTION: The SQL I do is "SELECT*FROM systables" can be changed as desired. System.err.println("Test in progress..."); try { String res = executeSQL(host, port, user, password, database, "SELECT * FROM systables WHERE tabname='systables'"); System.err.println(res); System.err.println("\tCall is done. See the logs in 'wic_conf.wic_user_soaplogs' to check the access, please."); } catch (Exception ex) { ex.printStackTrace(); } System.err.println("End test."); } public final static String executeSQL( String host, int port, String user, String password, String database, String stmt ) throws IOException, org.xml.sax.SAXException, javax.xml.parsers.ParserConfigurationException { StringBuffer buf = new StringBuffer(); buf.append("<?xml version='1.0' encoding='UTF-8'?>\n"); buf.append("<SOAP-ENV:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/'>\n"); buf.append("<SOAP-ENV:Body>\n"); buf.append("<ns1:executeSQL xmlns:ns1='urn:SOAPSQLServer' SOAP-ENV:encodingStyle='" + URI_XML_LITERALXML + "'>\n"); buf.append("<database xsi:type='xsd:string' SOAP-ENV:encodingStyle='" + URI_SOAP_ENCODING + "'>" + database + "</database>\n"); buf.append("<sql xsi:type='xsd:string' SOAP-ENV:encodingStyle='" + URI_SOAP_ENCODING + "'>" + encodeXML(stmt) + "</sql>\n"); buf.append("</ns1:executeSQL>\n"); buf.append("</SOAP-ENV:Body>\n"); buf.append("</SOAP-ENV:Envelope>\n"); InputStream in = SOAPCall(host, port, user, password, buf.toString()); if (in == null) return null; // Convert response to text InputStreamReader is = new InputStreamReader(in); StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(is); String read = br.readLine(); while(read != null) { sb.append(read); sb.append("\n"); read = br.readLine(); } return sb.toString(); } public final static InputStream SOAPCall( String host, int port, String user, String password, String xmlmsg ) throws IOException, org.xml.sax.SAXException, javax.xml.parsers.ParserConfigurationException { URL u = new URL("http", host, port, WEBSTUDIO_RPCROUTER); HttpURLConnection connection = (HttpURLConnection)u.openConnection(); HttpURLConnection.setFollowRedirects(true); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setAllowUserInteraction(false); connection.setRequestProperty("Accept-Encoding", "gzip"); connection.setRequestProperty("Content-Type", "text/xml;charset=utf-8"); connection.setRequestProperty("Content-Encoding", "gzip"); String token = user + ":" + password; String realm = new String(encodeBase64(token.getBytes())); connection.setRequestProperty("Authorization", "Basic " + realm); connection.setRequestProperty("SOAPAction", ""); OutputStream out = connection.getOutputStream(); OutputStreamWriter wout = new OutputStreamWriter(new GZIPOutputStream(out)); wout.write(xmlmsg); wout.flush(); wout.close(); String contentEncoding = connection.getContentEncoding(); int contentLength = connection.getContentLength(); String contentType = connection.getContentType(); InputStream in; if (connection.getResponseCode() != 200) { // Get the ERROR Stream if ("gzip".equals(contentEncoding)) in = new GZIPInputStream(connection.getErrorStream()); else in = connection.getErrorStream(); } else { if ("gzip".equals(contentEncoding)) in = new GZIPInputStream(connection.getInputStream()); else in = connection.getInputStream(); } return in; } /************************************************************************** * * * * XML ENCODE * * * ***************************************************************************/ public final static String encodeXML(String input) { if (input == null) return ""; int size = input.length(); StringBuilder buf = new StringBuilder(size + size / 8); for(int i = 0; i < size; i++) { char c = input.charAt(i); switch(c) { // To avoid: An invalid XML character (Unicode: 0x1a) was found // It occurs when someone pastes in text that contains specific unicode characters that are invalid in XML case 0x1A: buf.append(" "); break; case '"': buf.append("""); break; // La ' ha de ser codificable en un attribute per exemple com ' // I en un texte, no pasa res (sembla) si es codificada case '\'': buf.append("'"); break; case '>': buf.append(">"); break; case '<': buf.append("<"); break; case '&': buf.append("&"); break; default: buf.append(c); } } return buf.toString(); } /************************************************************************** * * * * BASE64 ENCODE * * * ***************************************************************************/ // Mapping table from 6-bit nibbles to Base64 characters. private final static char[] map1 = new char[64]; static { int i=0; for (char c='A'; c<='Z'; c++) map1[i++] = c; for (char c='a'; c<='z'; c++) map1[i++] = c; for (char c='0'; c<='9'; c++) map1[i++] = c; map1[i++] = '+'; map1[i++] = '/'; } /** * Encodes a byte array into Base64 format. * No blanks or line breaks are inserted in the output. * @param in An array containing the data bytes to be encoded. * @return A character array containing the Base64 encoded data. */ public final static char[] encodeBase64 (byte[] in) { return encodeBase64(in, 0, in.length); } /** * Encodes a byte array into Base64 format. * No blanks or line breaks are inserted in the output. * @param in An array containing the data bytes to be encoded. * @param iLen Number of bytes to process in <code>in</code>. * @return A character array containing the Base64 encoded data. */ public final static char[] encodeBase64 (byte[] in, int iLen) { return encodeBase64(in, 0, iLen); } /** * Encodes a byte array into Base64 format. * No blanks or line breaks are inserted in the output. * @param in An array containing the data bytes to be encoded. * @param iOff Offset of the first byte in <code>in</code> to be processed. * @param iLen Number of bytes to process in <code>in</code>, starting at <code>iOff</code>. * @return A character array containing the Base64 encoded data. */ public final static char[] encodeBase64 (byte[] in, int iOff, int iLen) { int oDataLen = (iLen*4+2)/3; // output length without padding int oLen = ((iLen+2)/3)*4; // output length including padding char[] out = new char[oLen]; int ip = iOff; int iEnd = iOff + iLen; int op = 0; while (ip < iEnd) { int i0 = in[ip++] & 0xff; int i1 = ip < iEnd ? in[ip++] & 0xff : 0; int i2 = ip < iEnd ? in[ip++] & 0xff : 0; int o0 = i0 >>> 2; int o1 = ((i0 & 3) << 4) | (i1 >>> 4); int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); int o3 = i2 & 0x3F; out[op++] = map1[o0]; out[op++] = map1[o1]; out[op] = op < oDataLen ? map1[o2] : '='; op++; out[op] = op < oDataLen ? map1[o3] : '='; op++; } return out; } }
1.6.2 Example 2
The following example shows a service call routine SOAPSQLServer.executeSQL(String database, String sqlcmd, int[] sqltype, Object[] sqldata, boolean gzip)
prem =========================================================================== rem rem SOAPExecuteSQLClient1.bat rem rem Executes a call to the SOAPSQLServer client for executeSQL commands: rem Element executeSQL(String database, String sqlcmd, int[] sqltype, Object[] sqldata, boolean gzip) rem rem =========================================================================== set JDK_HOME="C:\Program Files\Java\jdk1.8.0_05" %JDK_HOME%\bin\javac SOAPExecuteSQLClient1.java %JDK_HOME%\bin\java SOAPExecuteSQLClient1 PAUSE
/* * @(#)SOAPExecuteSQLClient1.java * * org.w3c.dom.Element executeSQL(String database, String sqlcmd, int[] sqltype, Object[] sqldata, boolean gzip) * */ // java.util import java.util.Base64; // java.io import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; // java.net import java.net.URL; import java.net.HttpURLConnection; // java.util.zip import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPInputStream; public class SOAPExecuteSQLClient1 { protected static final String URI_XML_LITERALXML = "http://xml.apache.org/xml-soap/literalxml"; protected static final String URI_SOAP_ENCODING = "http://schemas.xmlsoap.org/soap/encoding/"; protected static final String WEBSTUDIO_RPCROUTER = "/soap/servlet/rpcrouter"; public static void main(String[] args) throws Exception { String host = "www.example.com"; String database = "dbmstest"; String user = "usertest"; String password = "passtest"; /* create table soaptest ( f00_serial serial NOT NULL, f01_char char(10), f02_date date, f03_intvl interval hour to second, f04_dtime datetime year to second, f05_boolean boolean, f06_smallint smallint, f07_int integer, f08_int8 int8, f09_dec decimal(14, 2), f10_smfloat smallfloat, f11_float float, f12_money money(14, 2), f13_real real, f14_numeric numeric, f15_varchar varchar(255), f16_nchar nchar(20), f17_lvarchar lvarchar, f18_clob clob, f19_blob blob, f20_text text, f21_byte byte ); create unique index p_soaptest on soaptest (f00_serial); alter table soaptest add constraint primary key (f00_serial) constraint p_soaptest; */ String sqlstmt = "insert into soaptest values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; StringBuffer sqltype = new StringBuffer(); sqltype.append("<sqltype xmlns:ns2='" + URI_SOAP_ENCODING + "' xsi:type='ns2:Array' SOAP-ENV:encodingStyle='" + URI_SOAP_ENCODING + "' ns2:arrayType='xsd:int[]'>\n"); sqltype.append("<item xsi:type='xsd:int'>4</item>\n"); sqltype.append("<item xsi:type='xsd:int'>1</item>\n"); sqltype.append("<item xsi:type='xsd:int'>91</item>\n"); sqltype.append("<item xsi:type='xsd:int'>1</item>\n"); sqltype.append("<item xsi:type='xsd:int'>93</item>\n"); sqltype.append("<item xsi:type='xsd:int'>16</item>\n"); sqltype.append("<item xsi:type='xsd:int'>5</item>\n"); sqltype.append("<item xsi:type='xsd:int'>4</item>\n"); sqltype.append("<item xsi:type='xsd:int'>-5</item>\n"); sqltype.append("<item xsi:type='xsd:int'>3</item>\n"); sqltype.append("<item xsi:type='xsd:int'>6</item>\n"); sqltype.append("<item xsi:type='xsd:int'>8</item>\n"); sqltype.append("<item xsi:type='xsd:int'>8</item>\n"); sqltype.append("<item xsi:type='xsd:int'>8</item>\n"); sqltype.append("<item xsi:type='xsd:int'>8</item>\n"); sqltype.append("<item xsi:type='xsd:int'>12</item>\n"); sqltype.append("<item xsi:type='xsd:int'>12</item>\n"); sqltype.append("<item xsi:type='xsd:int'>-1</item>\n"); sqltype.append("<item xsi:type='xsd:int'>2005</item>\n"); sqltype.append("<item xsi:type='xsd:int'>2004</item>\n"); sqltype.append("<item xsi:type='xsd:int'>-1</item>\n"); sqltype.append("<item xsi:type='xsd:int'>-4</item>\n"); sqltype.append("</sqltype>\n"); byte[] _bytes = "Columna de tipo CLOB".getBytes(); String f19_blob = Base64.getEncoder().encodeToString(_bytes); byte[] _bytes2 = "Texto largo TEXT, debe ser byte[]".getBytes(); String f20_text = Base64.getEncoder().encodeToString(_bytes2); byte[] _bytes3 = new byte[] { 0x00, 0x01, 0x02 }; String f21_byte = Base64.getEncoder().encodeToString(_bytes3); StringBuffer sqldata = new StringBuffer(); sqldata.append("<sqldata xmlns:ns3='" + URI_SOAP_ENCODING + "' xsi:type='ns3:Array' SOAP-ENV:encodingStyle='" + URI_SOAP_ENCODING + "' ns3:arrayType='xsd:anyType[]'>\n"); sqldata.append("<item xsi:type='xsd:int'>0</item>\n"); sqldata.append("<item xsi:type='xsd:string'>ABCDEFG</item>\n"); sqldata.append("<item xsi:type='xsd:dateTime'>2015-06-11T09:17:42.139Z</item>\n"); sqldata.append("<item xsi:type='xsd:anyType' xsi:nil='true'/>\n"); sqldata.append("<item xsi:type='xsd:dateTime'>2015-06-11T09:17:42.139Z</item>\n"); sqldata.append("<item xsi:type='xsd:boolean'>true</item>\n"); sqldata.append("<item xsi:type='xsd:short'>10</item>\n"); sqldata.append("<item xsi:type='xsd:int'>20</item>\n"); sqldata.append("<item xsi:type='xsd:long'>20</item>\n"); sqldata.append("<item xsi:type='xsd:double'>30.1234</item>\n"); sqldata.append("<item xsi:type='xsd:float'>30.1234</item>\n"); sqldata.append("<item xsi:type='xsd:double'>30.1234</item>\n"); sqldata.append("<item xsi:type='xsd:double'>30.1234</item>\n"); sqldata.append("<item xsi:type='xsd:double'>30.1234</item>\n"); sqldata.append("<item xsi:type='xsd:double'>30.1234</item>\n"); sqldata.append("<item xsi:type='xsd:string'>Test de varchar</item>\n"); sqldata.append("<item xsi:type='xsd:string'>Campo de texto largo tipo lvarchar, debe ser String</item>\n"); sqldata.append("<item xsi:type='xsd:string'>Test de nchar</item>\n"); sqldata.append("<item xsi:type='xsd:string'>Campo de texto largo tipo CLOB, puede ser String o byte[]</item>\n"); sqldata.append("<item xsi:type='xsd:base64Binary'>" + f19_blob + "</item>\n"); sqldata.append("<item xsi:type='xsd:base64Binary'>" + f20_text + "</item>\n"); sqldata.append("<item xsi:type='xsd:base64Binary'>" + f21_byte + "</item>\n"); sqldata.append("</sqldata>\n"); try { String res = executeSQL(host, user, password, database, sqlstmt, sqltype.toString(), sqldata.toString()); System.err.println(res); } catch (Exception ex) { ex.printStackTrace(); } System.err.println("End test."); } public final static String executeSQL( String host, String user, String password, String database, String sqlstmt, String sqltype, String sqldata ) throws IOException, org.xml.sax.SAXException, javax.xml.parsers.ParserConfigurationException { StringBuffer buf = new StringBuffer(); buf.append("<?xml version='1.0' encoding='UTF-8'?>\n"); buf.append("<SOAP-ENV:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/'>\n"); buf.append("<SOAP-ENV:Body>\n"); buf.append("<ns1:executeSQL xmlns:ns1='urn:SOAPSQLServer' SOAP-ENV:encodingStyle='" + URI_XML_LITERALXML + "'>\n"); buf.append("<database xsi:type='xsd:string' SOAP-ENV:encodingStyle='" + URI_SOAP_ENCODING + "'>" + database + "</database>\n"); buf.append("<sqlstmt xsi:type='xsd:string' SOAP-ENV:encodingStyle='" + URI_SOAP_ENCODING + "'>" + sqlstmt + "</sqlstmt>\n"); buf.append(sqltype + "\n"); buf.append(sqldata + "\n"); buf.append("<gzip xsi:type='xsd:boolean' SOAP-ENV:encodingStyle='" + URI_SOAP_ENCODING + "'>false</gzip>"); buf.append("</ns1:executeSQL>\n"); buf.append("</SOAP-ENV:Body>\n"); buf.append("</SOAP-ENV:Envelope>\n"); InputStream in = SOAPCall(host, user, password, buf.toString()); if (in == null) return null; // Convert response to text InputStreamReader is = new InputStreamReader(in); StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(is); String read = br.readLine(); while(read != null) { sb.append(read); sb.append("\n"); read = br.readLine(); } return sb.toString(); } public final static InputStream SOAPCall( String host, String user, String password, String xmlmsg ) throws IOException, org.xml.sax.SAXException, javax.xml.parsers.ParserConfigurationException { URL u = new URL("http", host, WEBSTUDIO_RPCROUTER); HttpURLConnection connection = (HttpURLConnection)u.openConnection(); HttpURLConnection.setFollowRedirects(true); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setAllowUserInteraction(false); connection.setRequestProperty("Accept-Encoding", "gzip"); connection.setRequestProperty("Content-Type", "text/xml;charset=utf-8"); connection.setRequestProperty("Content-Encoding", "gzip"); String token = user + ":" + password; String realm= Base64.getEncoder().encodeToString(token.getBytes()); connection.setRequestProperty("Authorization", "Basic " + realm); connection.setRequestProperty("SOAPAction", ""); OutputStream out = connection.getOutputStream(); OutputStreamWriter wout = new OutputStreamWriter(new GZIPOutputStream(out)); wout.write(xmlmsg); wout.flush(); wout.close(); String contentEncoding = connection.getContentEncoding(); int contentLength = connection.getContentLength(); String contentType = connection.getContentType(); InputStream in; if (connection.getResponseCode() != 200) { // Get the ERROR Stream if ("gzip".equals(contentEncoding)) in = new GZIPInputStream(connection.getErrorStream()); else in = connection.getErrorStream(); } else { if ("gzip".equals(contentEncoding)) in = new GZIPInputStream(connection.getInputStream()); else in = connection.getInputStream(); } return in; } }