# Soapnachricht aus String erstellen



## Lito (28. Nov 2017)

Hallo,

ich möchte gerne aus eine Gzip Komprimierte Soapnachricht versenden.
Aus folgender Code (abgespekte Version) sollte mein Problem ersichtlich werden:
Wenn ich die generierte Soapnachricht in SOAPUI absende und gZip aktiviere funktioniert alles bestens. Das XML ist wohl valide. Seltsam ist auch das ich im Raw Request in SoapUI sehe das der Gzippte part ca 25 % stärker komprimiert ist als wenn ich Ihn gzippe.

Sieht jemand wo mein Fehler ist ?


```
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.zip.Deflater;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

//import org.apache.axis2.transport.http.HTTPConstants;
import org.w3c.dom.Document;


public class SoapfromStream {

    private String action;
  
    public static void main(String[] args) {
        String soapEnv =  "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:fir=\"http://www.someEndpoint/soap/\">" +
                "  <soapenv:Header>\r\n" +
                "    <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" soapenv:mustUnderstand=\"1\">" +
                "      <wsse:UsernameToken wsu:id=\"UsernameToken-E5796C61BC19712BB2B8BF70FC9BE77E\">" +
                "        <wsse:Username>someName#xx_00_1234567</wsse:Username>" +
                "        <wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">xyz12345</wsse:Password>" +
                "        <wsse:Nonce EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\">MjkzNjNBRDFCQzBENEFEOA==</wsse:Nonce>" +
                "      </wsse:UsernameToken>" +
                "    </wsse:Security>" +
                "  </soapenv:Header>" +
                "  <soapenv:Body>" +
                "    <fir:submitDATDVC>" +
                "      <inDATDVC>" +
                "        <fir:dateiname>DerDateiname-01.xml</fir:dateiname>" +
                "      </inDATDVC>" +
                "      <kundenreferenz>1234567</kundenreferenz>" +
                "      <datei>PD94bW ...someBase64coded... AgPC9Eb2N1bWVudD4gIDwvUHlsZD48L0JpekRhdGE+</datei>" +
                "    </fir:submitDATDVC>" +
                "  </soapenv:Body>" +
                "</soapenv:Envelope>";

        try {
            new SoapfromStream("DATDVC", soapEnv);
        } catch (SOAPException | IOException e) {
            e.printStackTrace();
        }
    }
  
  
    private SOAPMessage createSOAPRequest(String soapEnvStr) throws SOAPException, IOException {
        // Create SOAP Connection
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();
        MessageFactory messageFactory = MessageFactory.newInstance();
        GZIPInputStream bAiS = new GZIPInputStream(new ByteArrayInputStream(compressGZip(soapEnvStr)));
//Bis hierhin sieht alles Gut aus der Fehler passiert wohl beim erstellen der Soapnachricht .createMessage(null, bAiS)
        SOAPMessage gzipReq = messageFactory.createMessage(null, bAiS);
        MimeHeaders mheaders = gzipReq.getMimeHeaders();
        mheaders.setHeader("SOAPAction", "submit"+this.action);
        mheaders.setHeader("Accept-Encoding", "gzip,deflate");  // Eingehend
        mheaders.setHeader("Content-Encoding", "gzip"); // Ausgehend
//        gzipReq.setProperty(HTTPConstants.MC_GZIP_REQUEST, true);
//        gzipReq.setProperty(HTTPConstants.COMPRESSION_GZIP, true);
//        gzipReq.setProperty(HTTPConstants.MC_GZIP_RESPONSE, true);
//        gzipReq.setProperty(HTTPConstants.MC_ACCEPT_GZIP, true);
//        gzipReq.setProperty(HTTPConstants.CHUNKED, true);
//        gzipReq.setProperty(HTTPConstants.HEADER_TRANSFER_ENCODING, true);
        gzipReq.saveChanges();
        printXMLDocument(gzipReq.getSOAPPart());
        SOAPMessage response = soapConnection.call(gzipReq, new URL("https://SoapEndpointURL.de:444/soap"));
        System.out.println("Request SOAP Message:");
        printXMLDocument(response.getSOAPPart());
        return response;
    }
  
    /**
     * Schreibt das XML in Datei (oder auf Konsole)
     * @param document
     * @param type
     */
    public void printXMLDocument(Document document) {
        try {
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(document);
            StreamResult result;
          
            result = new StreamResult(System.out);
          
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            transformer.transform(source, result);
        } catch (TransformerException e) {
          
            e.printStackTrace();
        }
      
    }
  
    /**
     * G-Zippt einen String
     * @param input der Inputstring der komprimiert werden soll
     * @return g-zipptes bytearray
     * @throws IOException
     */
    private byte[] compressGZip(String input) {
        if ((input == null) || (input.length() == 0)) {
            return null;
        }
        ByteArrayOutputStream baOS = new ByteArrayOutputStream();
        GZIPOutputStream gZipOS = null;
        try {
            gZipOS = new GZIPOutputStream(baOS) {{
                def.setLevel(Deflater.DEFLATED);
            }
        };
            gZipOS.write(input.getBytes("UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (gZipOS != null) try {
                gZipOS.flush();
                gZipOS.close();
                gZipOS.finish();
            } catch (IOException ignore) {}
        }
      
        byte[] gzippedContent = baOS.toByteArray();
        System.out.println("Aus " + input.length() + " Zeichen wurden " + gzippedContent.length + " Zeichen gezipped");
      
        //System.out.println("Teste Compression indem der compresst Request decompressed wird:");
        //System.out.println("Decompressed again: " + decompress(gzippedContent).length() + " Zeichen");
        //System.out.println(decompress(gzippedContent));
        return gzippedContent;
    }
  
    private String decompress(byte[] compressed) {
        final StringBuilder outStr = new StringBuilder();
        if ((compressed == null) || (compressed.length == 0)) {
            return "";
        }
        if (isCompressed(compressed)) {
            GZIPInputStream gis;
            try {
                gis = new GZIPInputStream(new ByteArrayInputStream(compressed));
                final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    outStr.append(line);
                }
            } catch (IOException e) {
                // TODO Automatisch generierter Erfassungsblock
                e.printStackTrace();
            }
        } else {
            outStr.append(compressed);
        }
        return outStr.toString();
    }

    public static boolean isCompressed(final byte[] compressed) {
        return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC))
                && (compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));
    }
  
    public SoapfromStream( String action, String SoapEnv) throws SOAPException, IOException {
        System.setProperty("https.protocols", "TLSv1.2");
        System.setProperty("https.cipherSuites", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256");
        this.action =  action;
        createSOAPRequest(SoapEnv);
    }

}
```


----------

