0

From my java client I am trying to get data from a python server returning XML. My steps are :

  1. Validate the Inputstream for XML
  2. Convert Inputstream into XML for processing

My validation code in the Client Class as follows

public static boolean isValidXML(InputStream xmlInputStream) {
    try {
        Source xmlFile = new StreamSource(xmlInputStream);
        URL schemaFile = new URL("https://www.w3.org/2001/XMLSchema.xsd");
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(schemaFile);
        Validator validator = schema.newValidator();

        validator.setErrorHandler(new ErrorHandler() {

                // all the overridden methods 
        });

        validator.validate(xmlFile);

    } catch (SAXException ex) {
        System.out.println(ex.getMessage());
        return false;

    } catch (IOException e) {
        System.out.println(e.getMessage());
        return false;
    }
    return true;
}

}

And the processing of InputStream goes like this

HttpURLConnection con = (HttpURLConnection) obj.openConnection();
if (MyClient.isValidXML(con.getInputStream())) {
            BufferedReader inputReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String inline = "";
            while ((inline = inputReader.readLine()) != null) {
                sb.append(inline);
            }

            SAXBuilder builder = new SAXBuilder();

            Document document = (Document) builder.build(new 
            ByteArrayInputStream(sb.toString().getBytes()));
}

On executing, the while loop statement - while ((inline = inputReader.readLine()) != null) throwing the stream is closed exception.

If I remove the validation part, then the processing happens as expected, except of course throwing parsing error for some malformed XML. So probably the stream is getting closed somewhere in the validation part, but I am not sure where.

Thanks for reading. I appreciate your help.

  • here is my old topic about it: https://stackoverflow.com/questions/23660919/validate-and-read-with-the-same-inputstream and here you have some other solutions https://stackoverflow.com/questions/9501237/read-stream-twice – pL4Gu33 Jun 03 '18 at 08:29
  • Thanks! I used the IOUtils.copy as in the first answer in https://stackoverflow.com/questions/9501237/read-stream-twice – InconsistentHashing Jun 05 '18 at 07:23

1 Answers1

0

It happens because you have both exhausted and closed the input stream by validating it. You are both keeping a dog and barking yourself. If the parsing already throws an exception when the input isn't valid, you don't need the validation step at all. So remove it.

user207421
  • 305,947
  • 44
  • 307
  • 483