Saltar al contenido

Cómo convertir un string a un SOAPMessage en Java?

Nuestro grupo especializado despúes de algunos días de investigación y de recopilar de información, encontramos la solución, queremos que te sea de utilidad para tu plan.

Solución:

Convierta la cadena en una secuencia de entrada, luego léala en la fábrica de mensajes SOAP.

InputStream is = new ByteArrayInputStream(send.getBytes());
SOAPMessage request = MessageFactory.newInstance().createMessage(null, is);

Puede leer sobre cómo hacer esto aquí.

Esto funciona para mi:

SOAPMessage sm = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(new MimeHeaders(), is);

He medido la alimentación SOAPMessage con SAXSource para ser aproximadamente un 50% más rápido que la implementación interna de análisis de SAAJ utilizada en la respuesta aceptada:

SOAPMessage message = messageFactory.createMessage();
message.getSOAPPart().setContent(new SAXSource(new InputSource(new StringReader(send))));

Aquí está el punto de referencia que prueba varias fuentes de análisis XML y el impacto del almacenamiento en caché de fábrica:

/*
Benchmark (jdk1.8.0_202 32-bit)                                       Mode  Cnt     Score     Error  Units
SoapMessageBenchmark.testCreateMessage                               thrpt  100  4156,685 ? 215,571  ops/s
SoapMessageBenchmark.testCreateMessageWithMessageFactoryNotCached    thrpt  100  3709,299 ? 115,495  ops/s
SoapMessageBenchmark.testSetContentDom                               thrpt  100  5935,972 ? 215,389  ops/s
SoapMessageBenchmark.testSetContentDomWithDocumentBuilderNotCached   thrpt  100  3433,539 ? 218,889  ops/s
SoapMessageBenchmark.testSetContentSax                               thrpt  100  6693,179 ? 319,581  ops/s
SoapMessageBenchmark.testSetContentSaxAndExtractContentAsDocument    thrpt  100  4109,924 ? 229,987  ops/s
SoapMessageBenchmark.testSetContentStax                              thrpt  100  5126,822 ? 249,648  ops/s
SoapMessageBenchmark.testSetContentStaxWithXmlInputFactoryNotCached  thrpt  100  4630,860 ? 235,773  ops/s
*/

package org.sample;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Timeout;
import org.openjdk.jmh.annotations.Warmup;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.util.StreamReaderDelegate;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stax.StAXSource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 10, time = 100, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 100, timeUnit = TimeUnit.MILLISECONDS)
@Timeout(time = 10)
public class SoapMessageBenchmark 

    private static MessageFactory messageFactory;
    private static DocumentBuilder documentBuilder;
    private static XMLInputFactory xmlInputFactory;

    static 
        try 
            documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
            xmlInputFactory = XMLInputFactory.newInstance();
         catch (SOAPException 

    @State(Scope.Benchmark)
    public static class S 
        byte[] bytes = ("n" +
                                "  n" +
                                "    n" +
                                "      xxxxxxxxxxxxxxxxxxxxn" +
                                "      1063n" +
                                "    n" +
                                "  n" +
                                "  n" +
                                "    n" +
                                "      n" +
                                "        1n" +
                                "        0n" +
                                "        n" +
                                "          2372n" +
                                "          RootAdUnitn" +
                                "          n" +
                                "          TOPn" +
                                "          ACTIVEn" +
                                "          1002372n" +
                                "          n" +
                                "            n" +
                                "              truen" +
                                "              FFFFFFn" +
                                "              0000FFn" +
                                "              FFFFFFn" +
                                "              000000n" +
                                "              008000n" +
                                "              TEXT_AND_IMAGEn" +
                                "              DEFAULTn" +
                                "              DEFAULTn" +
                                "              DEFAULTn" +
                                "            n" +
                                "          n" +
                                "        n" +
                                "      n" +
                                "    n" +
                                "  n" +
                                "").getBytes();
    

    @Benchmark
    public SOAPBody testCreateMessage(S s) throws SOAPException, IOException 
        try (InputStream inputStream = new ByteArrayInputStream(s.bytes)) 
            SOAPMessage message = messageFactory.createMessage(null, inputStream);
            return message.getSOAPBody();
        
    

    @Benchmark
    public SOAPBody testCreateMessageWithMessageFactoryNotCached(S s) throws SOAPException, IOException 
        MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
        try (InputStream inputStream = new ByteArrayInputStream(s.bytes)) 
            SOAPMessage message = messageFactory.createMessage(null, inputStream);
            return message.getSOAPBody();
        
    

    @Benchmark
    public SOAPBody testSetContentDom(S s) throws SOAPException, IOException, SAXException 
        try (InputStream inputStream = new ByteArrayInputStream(s.bytes)) 
            Document document = documentBuilder.parse(inputStream);
            SOAPMessage message = messageFactory.createMessage();
            message.getSOAPPart().setContent(new DOMSource(document));
            return message.getSOAPBody();
        
    

    @Benchmark
    public SOAPBody testSetContentDomWithDocumentBuilderNotCached(S s) throws SOAPException, IOException, SAXException, ParserConfigurationException 
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        try (InputStream inputStream = new ByteArrayInputStream(s.bytes)) 
            Document document = documentBuilder.parse(inputStream);
            SOAPMessage message = messageFactory.createMessage();
            message.getSOAPPart().setContent(new DOMSource(document));
            return message.getSOAPBody();
        
    

    @Benchmark
    public SOAPBody testSetContentSax(S s) throws SOAPException, IOException 
        try (InputStream inputStream = new ByteArrayInputStream(s.bytes)) 
            SOAPMessage message = messageFactory.createMessage();
            message.getSOAPPart().setContent(new SAXSource(new InputSource(inputStream)));
            return message.getSOAPBody();
        
    

    @Benchmark
    public Document testSetContentSaxAndExtractContentAsDocument(S s) throws SOAPException, IOException 
        try (InputStream inputStream = new ByteArrayInputStream(s.bytes)) 
            SOAPMessage message = messageFactory.createMessage();
            message.getSOAPPart().setContent(new SAXSource(new InputSource(inputStream)));
            return message.getSOAPBody().extractContentAsDocument();
        
    

    @Benchmark
    public SOAPBody testSetContentStax(S s) throws SOAPException, IOException, XMLStreamException 
        try (InputStream inputStream = new ByteArrayInputStream(s.bytes)) 
            XMLStreamReader xmlStreamReader = new StreamReaderDelegate(xmlInputFactory.createXMLStreamReader(inputStream)) 
                @Override
                public String getVersion() 
                    return "1.1";
                
            ;
            SOAPMessage message = messageFactory.createMessage();
            message.getSOAPPart().setContent(new StAXSource(xmlStreamReader));
            return message.getSOAPBody();
        
    

    @Benchmark
    public SOAPBody testSetContentStaxWithXmlInputFactoryNotCached(S s) throws SOAPException, IOException, XMLStreamException 
        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        try (InputStream inputStream = new ByteArrayInputStream(s.bytes)) 
            XMLStreamReader xmlStreamReader = new StreamReaderDelegate(xmlInputFactory.createXMLStreamReader(inputStream)) 
                @Override
                public String getVersion() 
                    return "1.1";
                
            ;
            SOAPMessage message = messageFactory.createMessage();
            message.getSOAPPart().setContent(new StAXSource(xmlStreamReader));
            return message.getSOAPBody();
        
    


Ten en cuenta dar visibilidad a esta noticia si te fue de ayuda.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *