jueves, 17 de enero de 2013

Matlab SOAP Client

Un SOAP client en Matlab que funciona. Encontré este código en internet y lo he tenido que tocar un poquito hasta que por fin ha funcionado y conecto perfectamente con un servidor SOAP. He sudado sangre hasta que ha funcionado, espero que os sirva y que no tengáis que sudar vosotros también.

Saludos!


function [IN OUT]=SOAPClient()

%-------------------------------------------------------------

import java.io.*;
import java.net.*;
import com.mathworks.mlwidgets.io.InterruptibleStreamCopier;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
%-------------------------------------------------------------


IN='';
OUT='';
endpoint='https://www.miendpoint.com?wdsl';
soapAction='mySOAPAction';



url = URL([],endpoint, sun.net.www.protocol.https.Handler);

com.mathworks.mlwidgets.html.HTMLPrefs.setProxySettings

mwtcp = com.mathworks.net.transport.MWTransportClientPropertiesFactory.create();
proxy = mwtcp.getProxy();

if isempty(proxy)
    httpConn = url.openConnection;
else
    httpConn = url.openConnection(proxy);
end


httpConn.setRequestProperty('Content-Type','text/xml; charset=utf-8');

httpConn.setRequestMethod('POST');
httpConn.setDoOutput(true);
httpConn.setDoInput(true);

% Aquí le pasas la petición al servidor en formato XML
message=xmlread('SOAP_Request.xml');

toSend = serializeDOM(message);
toSend = java.lang.String(toSend);
b = toSend.getBytes('UTF8');
IN=char(b');

try
    outputStream = httpConn.getOutputStream;
    outputStream.write(b);
    outputStream.close;
    disp('Mensaje enviado')
catch e
    exception = regexp(e.message, ...
        'Java exception occurred: \n(.*?)\s*\n','tokens','once');
    if ~isempty(exception)
        exception = exception{1};
        if strcmp(exception, ...
                'java.net.ConnectException: Connection refused: connect')
            error('MATLAB:callSoapService:ConnectionRefused','Connection refused.');
        end
        if strcmp(exception, ...
                'ice.net.URLNotFoundException: Document not found on server')
            error('MATLAB:callSoapService:UrlNotFoundOnServer','The requested URL was not found on this server.')
        end
        host = regexp(exception,'java.net.UnknownHostException: (.*)','tokens','once');
        if ~isempty(host)
            error('MATLAB:callSoapService:UnknownHost','Unknown host: %s',host{1})
        end
        error('MATLAB:callSoapService:Exception',exception)
    else
        rethrow(e)
    end
end
try
    disp('Recibiendo mensaje...');
    inputStream = httpConn.getInputStream;
    disp('Mensaje recibido!!')
    byteArrayOutputStream = java.io.ByteArrayOutputStream;
    
    isc = InterruptibleStreamCopier.getInterruptibleStreamCopier;
    isc.copyStream(inputStream,byteArrayOutputStream);
    inputStream.close;
    byteArrayOutputStream.close;

    OUT=byteArrayOutputStream;
    
    message = e.message;
    t = regexp(message,'java.io.IOException: (.*?)\n','tokens','once');
    if ~isempty(t)
        message = t{1};
    end
    


%================================================================
function s = serializeDOM(x)

domSource = javax.xml.transform.dom.DOMSource(x);
tf = javax.xml.transform.TransformerFactory.newInstance;
serializer = tf.newTransformer;
serializer.setOutputProperty(javax.xml.transform.OutputKeys.ENCODING,'utf-8');
serializer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT,'yes');

stringWriter = java.io.StringWriter;
streamResult = javax.xml.transform.stream.StreamResult(stringWriter);

serializer.transform(domSource, streamResult);
s = char(stringWriter.toString);

No hay comentarios: