1 SOAP client examples

A soap request can be formulated by generating an XML message that will be transported using the HTTP protocol. The preparation of the XML message (serialization) and obtaining 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 SOAPOBJServer.getInclude

Example 1

Obtain the values of the include gven_promocr_ambart, where you can optionally specify a condition (in this case cabid=105). The filter_code is a mandatory field and it is used only to check that the include reference exists based on the filter_code parameter.

Copy
<xsql-script name='getInclude1'>
  <body>
     <set name='m_response'>
        <soap.call
           url='http://www.mydeister.com/soap/servlet/rpcrouter'
           uri='urn:SOAPOBJServer'
           method='getInclude'
           user='soap'
           password='soap999'
           >
             <parameters>
                <parameter name = 'dbms'>demo_sports</parameter>
                <parameter name = 'include_code'>gven_promocr_ambart</parameter>
                <parameter name = 'filter_code'>gven_promocr</parameter>
                <parameter name = 'filter_cond'>cabid=105</parameter>
             </parameters>  
        </soap.call>
     </set>
     <println><m_response/></println>
  </body>
</xsql-script>

Example 2

Get the values of the include agreements_estcab.

Copy
<xsql-script name='getInclude2'>
  <body>
     <set name='m_response'>
        <soap.call
           url='http://www.mydeister.com/soap/servlet/rpcrouter'
           uri='urn:SOAPOBJServer'
           method='getInclude'
           user='soap'
           password='soap999'
           >
             <parameters>
                <parameter name = 'dbms'>demo_sports</parameter>
                <parameter name = 'include_code'>acuerdos_estcab</parameter>
                <parameter name = 'filter_code'><string/></parameter>
                <parameter name = 'filter_cond'><string/></parameter>
             </parameters>  
        </soap.call>
     </set>
     <println><m_response/></println>
  </body>
</xsql-script>

1.1.2 SOAPOBJServer.execute

Example 1

Execute the gcompedh_print object in pdf format and save the file generated in the disktool utility.

Copy
<xsql-script name='execute1'>
  <body>
     <set name='m_response'>
        <soap.call
           url='http://www.mydeister.com/soap/servlet/rpcrouter'
           uri='urn:SOAPOBJServer'
           method='execute'
           user='soap'
           password='soap999'
           >
             <parameters>
                <parameter name = 'dbms'>demo_sports</parameter>
                <parameter name = 'objcode'>gcompedh_print</parameter>
                <parameter name = 'qrycond'>gcompedh.cabid=19991</parameter>
                <parameter name = 'type'>pdf</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 = 'm_pdf'>
                  <dom.node.getNodeValue>
                     <dom.node.getFirstChild>
                        <dom.getElementByXPath xpath='/objresponse/object'>
                            <dom.parse><m_response/></dom.parse>
                        </dom.getElementByXPath>
                     </dom.node.getFirstChild>
                   </dom.node.getNodeValue>
              </set>
              <if><expr><isnotnull><m_pdf/></isnotnull></expr>
                  <then>
                     <file.bytes.write>
                          <file name='gcompedh.pdf' type='disktool' />    
                          <byte.decode type='BASE64'><m_pdf/></byte.decode>
                     </file.bytes.write>
                  </then>
              </if>
         </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 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:

Copy
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:

Copy
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 SOAPOBJServer.execute

Example 1

The following example shows how to execute the cataloged object bal_a_sal_p_level using a function call SOAPOBJServer.execute (String database, String objname, String qrycond, Hashtable cols, Hashtable vars, String type, boolean gzip)

The object has the following variables and input fields:

Variable Description
LEVEL Grouping level
EJERIC Accounting year
PERINI Initial period
PERFIN Final period
Field Description
csaldos.empcode Company code
csaldos.proyec Accounting project
csaldos.seccio Accounting section
csaldos.cuenta Balance account
csaldos.sistem Accounting system

The object contains the following SQL code:

Copy
SELECT csaldos.cuenta[1,$NIVEL] nivel,
   SUM(csaldos.debe) debe, SUM(csaldos.haber) haber
FROM csaldos
WHERE csaldos.ejerci = $EJERCI
AND csaldos.period BETWEEN $PERINI AND $PERFIN
AND $0
GROUP BY 1
INTO TEMP @tmp_1 WITH NO LOG;
 
SELECT @tmp_1.nivel, cniveles.nombre,
   SUM(@tmp_1.debe) debe, SUM(@tmp_1.haber) haber,
   SUM(CASE WHEN (@tmp_1.debe - @tmp_1.haber) > 0
            THEN (@tmp_1.debe - @tmp_1.haber)
            ELSE 0
        END) deudor,
   SUM(CASE WHEN (@tmp_1.debe - @tmp_1.haber) < 0
            THEN (@tmp_1.haber - @tmp_1.debe)
            ELSE 0
        END) acreedor,
   SUM(@tmp_1.debe - @tmp_1.haber) salacu
FROM @tmp_1 LEFT JOIN cniveles ON @tmp_1.nivel  = cniveles.codigo
WHERE @tmp_1.debe  != 0 OR
   @tmp_1.haber != 0
GROUP BY 1,2

The source code of the java class that makes the call to the object bal_a_sal_p_level could be like this example:

Copy
/ java
import java.net.URL;
import java.util.Vector;
import java.util.Hashtable;
 
// 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;
 
// java
import java.net.URL;
import java.util.Vector;
import java.util.Hashtable;
 
// 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 SOAPOBJClient1
{
    /**
    * A single client
    */
    public static void main(String[] args) throws Exception
    {
        if (args.length != 2)
        {
            System.err.println("Usage:");
            System.err.println("  java " +
                SOAPOBJClient1.class.getName() +
                " url database"
            );
            System.exit (1);
        }
 
        // We take the command line arguments.
        int offset = 3 - args.length;
        URL url = new URL(args[1 - offset]);
        String database = args[2 - offset];
 
        //Build the objecto
        Call call = new Call();
 
        // Authentication
        SOAPHTTPConnection hc = new SOAPHTTPConnection();
        hc.setUserName("demo");
        hc.setPassword("abcdemo");
        call.setSOAPTransport(hc);
 
        call.setTargetObjectURI("urn:SOAPOBJServer");
        call.setMethodName("execute");
 
        // The response code is a org.w3c.dom.Element
        call.setEncodingStyleURI(Constants.NS_URI_LITERAL_XML);
 
        // The arguments of the call
 
        String      objname = "bal_a_sal_p_nivel";
        String      qrycond = "";
        Hashtable   cols    = new Hashtable();
        Hashtable   vars    = new Hashtable();
        String      type    = "asc";
        Boolean     gzip    = new Boolean(false);
 
        cols.put("csaldos.cuenta", "[67]*");
 
        vars.put("NIVEL",  "1");
        vars.put("EJERCI", "2003");
        vars.put("PERINI", "0");
        vars.put("PERFIN", "12");
 
        Vector params = new Vector();
        params.addElement(
            new Parameter(
                "database",
                String.class,
                database,
                Constants.NS_URI_SOAP_ENC
            )
        );
        params.addElement(
            new Parameter(
                "objname",
                String.class,
                objname,
                Constants.NS_URI_SOAP_ENC
            )
        );
        params.addElement(
            new Parameter(
                "qrycond",
                String.class,
                qrycond,
                Constants.NS_URI_SOAP_ENC
            )
        );
        params.addElement(
            new Parameter(
                "cols",
                Hashtable.class,
                cols,
                Constants.NS_URI_SOAP_ENC
            )
        );
        params.addElement(
            new Parameter(
                "vars",
                Hashtable.class,
                vars,
                Constants.NS_URI_SOAP_ENC
            )
        );
        params.addElement(
            new Parameter(
                "type",
                String.class,
                type,
                Constants.NS_URI_SOAP_ENC
            )
        );
        params.addElement(
            new Parameter(
                "gzip",
                Boolean.class,
                gzip,
                Constants.NS_URI_SOAP_ENC
            )
        );
        call.setParams(params);
 
        // Invocamos la llamada
        Response resp;
        try
        {
            resp = call.invoke(url, "");
        } catch (SOAPException ex) {
            System.err.println("Caught SOAPException (" +
                        ex.getFaultCode() + "): " +
                        ex.getMessage()
            );
            ex.printStackTrace();
            return;
        }
 
        // We verify the answer and show it
        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
} // SOAPOBJClient1

Example 2

This example shows a client in which we indicate the result format of the object execution, which in turn is passed as a parameter. The program generates a file with the execution result according to the selected format.

Copy
// java
import java.net.URL;
import java.util.Vector;
import java.io.InputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.OutputStream;
import java.io.FileOutputStream;
 
// dom
import org.w3c.dom.*;
 
// apache SOAP
import org.apache.soap.util.xml.DOM2Writer;
import org.apache.soap.util.xml.DOMUtils;
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;
import org.apache.soap.encoding.soapenc.Base64;
 
/**
* Example of a java client using apache soap to 
* invoke the execute operation of the SOPAOBJServer service
* Element execute(String database, String objcode, String qrycond, String type)
*/
 
public class SOAPExecuteObjClient
{
    /**
    * A single client to execute an Object.
    */
    public static void main(String[] args) throws Exception
    {
        if (args.length != 7 && args.length != 9 && args.length != 11)
        {
            System.err.println("Usage:");
            System.err.println("  java " +
                SOAPExecuteObjClient.class.getName() +
                " url user pass database objcode qrycond type [proxyHost proxyPort] [proxyUser proxyPassword]"
            );
            System.exit (1);
        }
 
        // We take the command line arguments
 
        URL url           = new URL(args[0]);
        String user       = args[1];
        String password   = args[2];
        String database   = args[3];
        String objcode    = args[4];
        String qrycond    = args[5];
        String type       = args[6];
 
 
        //Build the object
        Call call = new Call();
 
        // Authentication
        SOAPHTTPConnection hc = new SOAPHTTPConnection();
        hc.setUserName(user);             // USUARIO
        hc.setPassword(password);         // PASSWORD
        // Observe si usa un proxy!
        if (args.length >= 9)
        {
          hc.setProxyHost(args[7]);               //PROXY HOSTNAME
          hc.setProxyPort(Integer.parseInt(args[8]));  //PROXY PORT
 
          if (args.length == 11)
          {
             hc.setProxyUserName(args[9]); //PROXY USER
             hc.setProxyPassword(args[10]); //PROXY PASSWORD
          }
        }        
 
        call.setSOAPTransport(hc);
 
        call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
        call.setTargetObjectURI("urn:SOAPOBJServer");
        call.setMethodName("execute");
 
        // We pass 4 parameters to the direct execution function:
        // Element execute(String database, String objcode, String qrycond, String type)
 
 
        Vector params = new Vector();
        params.addElement(
            new Parameter(
                "database",
                String.class,
                database,
                Constants.NS_URI_SOAP_ENC
            )
        );
        params.addElement(
            new Parameter(
                "objcode",
                String.class,
                objcode,
                Constants.NS_URI_SOAP_ENC
            )
        );
 
        params.addElement(
            new Parameter(
                "qrycond",
                String.class,
                qrycond,
                Constants.NS_URI_SOAP_ENC
            )
        );
 
        params.addElement(
            new Parameter(
                "type",
                String.class,
                type,
                Constants.NS_URI_SOAP_ENC
            )
        );
 
        call.setParams(params);
 
        // Invoke the call
        Response resp;
        try
        {
            resp = call.invoke(url, "");
        } catch (SOAPException ex) {
            System.err.println("Caught SOAPException (" +
                        ex.getFaultCode() + "): " +
                        ex.getMessage()
            );
            ex.printStackTrace();
            return;
        }
 
        //Display response message SOAP
        //System.out.println(call.getEnvelopeString(hc));
 
        // We verify the answer and show it
        if (!resp.generatedFault())
        {
            Parameter ret = resp.getReturnValue();
            Element element = (Element)ret.getValue();
            // We get the inputStream of the result (CDATA)
 
		    InputStream in = getObjectDataInputStream(element);		    
 
		    if (in == null)
				System.out.println(DOM2Writer.nodeToString(element));
			else
				inputStreamToFile (in, objcode, type);
        } 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
 
	public static final InputStream getObjectDataInputStream(Element el) throws IOException, Exception
	{
		Element listingEl = DOMUtils.getFirstChildElement(el);
		if (listingEl.getTagName().equals("object")) {
    		String gzip = listingEl.getAttribute("gzip");
	    	if (gzip.equalsIgnoreCase("true")) {
        		byte[] bdata = __parseBLOB(listingEl);
        		return new GZIPInputStream(new ByteArrayInputStream(bdata));
    		} else {
    			byte[] bdata = __parseBLOB(listingEl);
        		return new ByteArrayInputStream(bdata);
    		}
		} else if (listingEl.getTagName().equals("exception")) {
	    	// es una excepción de servicio
	    	return null;
		}
		// Es un documento mal formado!
		throw new IllegalStateException("element child tagname was ["
     	+ listingEl.getTagName() + "] expected was object");
	}
 
	private static byte[] __parseBLOB(org.w3c.dom.Element el) throws Exception
	{
    	String coldata = DOMUtils.getChildCharacterData(el);
 
    	return Base64.decode(coldata);
 
	}
 
	static void inputStreamToFile (InputStream in, String objcode, String type) throws IOException
	{
		//Setup directories
		File baseDir = new File(".");
		File outDir = new File(baseDir, "out");
		outDir.mkdirs();
		String destino = objcode + ".";
		if (type.equalsIgnoreCase("pdf"))
			destino = destino + "pdf";
		else if (type.equalsIgnoreCase("xml"))
			destino = destino + "xml";
		else if (type.equalsIgnoreCase("xls"))
			destino = destino + "xls";
		else
			destino = destino + "txt";
		File outfile = new File(outDir, destino);		
 
		OutputStream out= new FileOutputStream(outfile);
		byte[] buffer= new byte[256];
		while (true) {
			int n= in.read(buffer);
	    	if (n < 0)
        		break;
      		out.write(buffer, 0, n);
    	}
    	in.close();
    	out.close();
  	}
 
} // SOAPExecuteObjClient