0

I have been following this tutorial to use sax parser. If my input is using xml file, then the below line is working fine. But how can I can parse xml which I get as a response from the web service. How to pass soap response as input to sax parser?

new MySaxParser("catalog.xml");

My code

public class soapTest{
    private static SOAPMessage createSoapRequest() throws Exception{
         MessageFactory messageFactory = MessageFactory.newInstance();
         SOAPMessage soapMessage = messageFactory.createMessage();
         SOAPPart soapPart = soapMessage.getSOAPPart();
                 SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
                 soapEnvelope.addNamespaceDeclaration("action", "http://www.webserviceX.NET/");
         SOAPBody soapBody = soapEnvelope.getBody();
         SOAPElement soapElement = soapBody.addChildElement("GetQuote", "action");
         SOAPElement element1 = soapElement.addChildElement("symbol", "action");
         element1.addTextNode("ticket");
            MimeHeaders headers = soapMessage.getMimeHeaders();
            headers.addHeader("SOAPAction", "http://www.webserviceX.NET/GetQuote");
         soapMessage.saveChanges();
         System.out.println("----------SOAP Request------------");
         soapMessage.writeTo(System.out);
         return soapMessage;
     }
     private static void createSoapResponse(SOAPMessage soapResponse) throws Exception  {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        Source sourceContent = soapResponse.getSOAPPart().getContent();
        System.out.println("\n----------SOAP Response-----------");
        StreamResult result = new StreamResult(System.out);
        transformer.transform(sourceContent, result);
     }
     public static void main(String args[]){
            try{
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();
            String url = "http://www.webservicex.net/stockquote.asmx?wsdl";
            SOAPMessage soapRequest = createSoapRequest();
            //hit soapRequest to the server to get response
            SOAPMessage soapResponse = soapConnection.call(soapRequest, url);

// Not able to proceed from here. How to use sax parser here

        soapConnection.close();

        }catch (Exception e) {
             e.printStackTrace();
        }
}

How to parse and get the value from xml response.

user4324324
  • 559
  • 3
  • 7
  • 25

1 Answers1

1

I have fixed the code, you can proceed as follows:

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

/**
 * Demo xml processing
 */
public class Demo {

    private static final Logger log = Logger.getLogger(Demo.class.getName());

    private static final int CHUNK = 1048576;  //1MB chunk of file

    public static void main(String[] args) {

        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream(CHUNK);

            Writer writer = new OutputStreamWriter(out, "UTF-8");

            /* here put soapMessage.writeTo(out);
               I will just process this hard-coded xml */
            writer.append("<greeting>Hello!</greeting>");
            writer.flush();

            ByteArrayInputStream is
                    = new ByteArrayInputStream(out.toByteArray());

            XMLReader reader = XMLReaderFactory.createXMLReader();

            //define your handler which extends default handler somewhere else
            MyHandler handler = new MyHandler();
            reader.setContentHandler(handler);

            /* reader will be closed with input stream */
            reader.parse(new InputSource(new InputStreamReader(is, "UTF-8")));
            //Hello in the console
        } catch (UnsupportedEncodingException ex) {
            log.severe("Unsupported encoding");
        } catch (IOException | SAXException ex) {
            log.severe("Parsing error!");
        } finally {
            /*everything is ok with byte array streams!
              closing them has no effect! */
        }

    }
}

class MyHandler extends DefaultHandler {

    @Override
    public void characters(char ch[], int start, int length)
            throws SAXException {
        System.out.print(String.copyValueOf(ch, start, length));
    }
}
Konstantin K
  • 94
  • 1
  • 8
  • Thanks for looking into my issue. I am able to stream soap response but my code is getting hanged somewhere. You can read the below post to know my issue http://stackoverflow.com/questions/42210300/stream-soap-response-and-parse-using-sax-parser – user4324324 Feb 13 '17 at 17:50
  • oops it seems like I sketched the code, but omitted stream closure from brewity, I will modify the post (not to throw exceptions, but catch them and close the streams, as it should be done). Then your 'hanging' will probably dissapear – Konstantin K Feb 13 '17 at 19:25
  • have just discovered that I deceived myself and, what is worse, you too, see this: http://stackoverflow.com/questions/484119/why-doesnt-more-java-code-use-pipedinputstream-pipedoutputstream – Konstantin K Feb 13 '17 at 19:41
  • I thought it will be more elegant to use piping, but now it will create new thread, so probably better solution will be to copy input to the buffer and read it back then – Konstantin K Feb 13 '17 at 19:44
  • Any piece of code to demonstrate the buffer example – user4324324 Feb 14 '17 at 06:51
  • see here: http://stackoverflow.com/questions/5778658/how-to-convert-outputstream-to-inputstream – Konstantin K Feb 14 '17 at 10:38
  • Sorry for the broken code at first, I indeed thougth I have discovered a know-how (which as I then read is an old fox and, moreover, misused in my case) – Konstantin K Feb 17 '17 at 02:19
  • Thank you so much. this piece of code really helped me alot – user4324324 Feb 18 '17 at 15:07