From my java client I am trying to get data from a python server returning XML. My steps are :
- Validate the Inputstream for XML
- 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.