XML Parsing from an input stream Java

bugiman picture bugiman · Sep 17, 2012 · Viewed 40.3k times · Source

Hi everyone am currently working on an application that needs to parse an xml document so as to authenticate users.Am using URLConnection class of the java.net.* package to connect to as specific URL which gives an returns its response in xml format. When i try to parse the document using jdom , i get the following error:
org.jdom2.input.JDOMParseException: Error on line 1: Premature end of file

Can anyone pinpoint the problem and assist me with a remedy? thanks, here is a section of my code

try {
  String ivyString = "http://kabugi.hereiam.com/?username=" + ivyUsername + "&password=" + ivyPassword;

  URL authenticateURL = new URL(ivyString);
  URLConnection ivyConnection = authenticateURL.openConnection();
  HttpURLConnection ivyHttp = (HttpURLConnection) ivyConnection;
  System.out.println("Response code ==>" + ivyHttp.getResponseCode());
  if (ivyHttp.getResponseCode() != 200) {
    ctx.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid username or password!", ""));
    page = "confirm.xhtml";
  } else {
    BufferedReader inputReader = new BufferedReader(new InputStreamReader(ivyConnection.getInputStream()));
    String inline = "";
    while ((inline = inputReader.readLine()) != null) {
      System.out.println(inline);
    }
    SAXBuilder builder = new SAXBuilder();

    Document document = (Document) builder.build(ivyConnection.getInputStream());
    Element rootNode = document.getRootElement();
    List list = rootNode.getChildren("data");
    for (int i = 0; i < list.size(); i++) {
      Element node = (Element) list.get(i);
      System.out.println("Element data ==>" + node.getChildText("username"));
      System.out.println("Element data ==>" + node.getChildText("password"));

    }

    page = "home.xhtml";
  }
} catch (Exception ex) {
  ex.printStackTrace();
  // ctx.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid username or password!", ""));
}

Answer

maneesh picture maneesh · Sep 18, 2012

Looks like its because you are reading the inputstream twice. Once to print it and next to build the document. When you come to the point where you build the Document object, the input stream is already read fully and at its end. Try the following code which reads the stream only once

        BufferedReader inputReader = new BufferedReader(new InputStreamReader(ivyConnection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String inline = "";
        while ((inline = inputReader.readLine()) != null) {
          sb.append(inline);
        }

        System.out.println(sb.toString());
        SAXBuilder builder = new SAXBuilder();

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