0

I have the following:

public static void main(String args[]) {

     // upload config' data for program - param' are path and Xml's Root node/ where to get data from
     confLoader conf = new confLoader("conf.xml", "config"); 

     System.out.println(conf.getDbElement("dataSource") );
     System.out.println(conf.getDbElement("dataSource") );
     System.out.println(conf.getDbElement("dataSource") );  // Fails 
...

The code that's responsible to build the DOM and parse from ('getDbElement()'):

public class confLoader{

 DocumentBuilderFactory docBuilderFactory;
 DocumentBuilder docBuilder;
 Document doc;
 NodeList nList;

 public confLoader(String path, String XmlRoot){

    try {
            docBuilderFactory = DocumentBuilderFactory.newInstance();
            docBuilder = docBuilderFactory.newDocumentBuilder();
            doc = docBuilder.parse(new File(path));
            // normalize text representation
            doc.getDocumentElement().normalize();                
    nList = doc.getElementsByTagName(XmlRoot);

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

public String getDbElement(String element) {

    Node nNode = nList.item(0); //  1st item/node - sql
    try {
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {     /////  Line 36 - Problematic

            Element eElement = (Element) nNode;
            return (((Node) eElement.getElementsByTagName(element).item(0).getChildNodes().item(0)).getNodeValue());
        }
    } catch (Exception ex) {
        System.out.println("Error retrieving " + element + " :" + ex.getMessage());//Thread.dumpStack();
         ex.printStackTrace();
      }
    return "not available";
 }

}

stacktrace for given code:

  jdbc:mysql://localhost:...
  java.lang.NullPointerException
  jdbc:mysql://localhost:...
  Error retrieving dataSource :null
  not available
  at exercise.confLoader.getDbElement(confLoader.java:36)
  at exercise.Exercise.main(Exercise.java:22)

      Line 36 : if (nNode.getNodeType() == Node.ELEMENT_NODE)

The xml parsing is done twice, and for the 3rd time I try to parse from Xml, I get the NullPointerException.

user1249569
  • 83
  • 1
  • 3
  • 10
  • Use some println(), or step through the code with a debugger, to see which object is null, then you can work out how to fix it. What line does the exception occur on, precisely? Do you have a stack trace? – DNA Sep 25 '12 at 11:23
  • Do you see some pattern in your `getDbPath()`, `getDbUser()` and `getDbPassword()`? Do you think you could do some changes to only have one method? It is just a hint. – maba Sep 25 '12 at 11:30
  • I think your problem is in Sql class, specifically 3 argument constructor. Because I can pass your xml file and read data in it and print in your main class. It works fine. Let me know your sql coding for sql class. – swemon Sep 25 '12 at 11:41
  • -1 for omitting the COMPLETE Stack Trace and not telling us the statement where the NPE occurs. Update the post to include the relevant information and I will remove the downvote. – Jim Garrison Sep 25 '12 at 17:50
  • Sorry. Not sure what exactly you want. Is it done by "printStackTrace()" of the Exception pbject? – user1249569 Sep 25 '12 at 18:13

3 Answers3

2

Too much code! Also, reading configuration pieces on demand is not that useful. And relying on instance variables makes your code more difficult to test and to understand, and even potentially unsafe in a concurrent scenario. You don't need all those classes, methods and things. It's just a matter of

public class Exercise {

    public static void main(String[] args) throws XPathExpressionException {

        XPath xpath = XPathFactory.newInstance().newXPath();
        InputSource in = new InputSource("res/config.xml");

        String user = xpath.evaluate("//sql/user/text()", in);
        String password = xpath.evaluate("//sql/password/text()", in);
        String path = xpath.evaluate("//sql/dataSource/text()", in);

        Sql sql = new Sql(path, user, password);
    }

}

You could optionally make your code a bit more complex, by storing all of your configuration in a Map<String, String>, but really you'd better use a common API like Properties, which is able to load from XML.

Raffaele
  • 20,627
  • 6
  • 47
  • 86
1

Problem solved by removing gnujaxp.jar from the build path.

user1249569
  • 83
  • 1
  • 3
  • 10
0

First of all, I would recommend you don't chain too many methods on one line. Breaking the call structure up into multiple lines will increase readability and ease debugging.

For exaple, rewrite:

return (((Node) (eElement.getElementsByTagName("password").item(0).getChildNodes().item(0)).getNodeValue());

to:

NodeList rootEls = eElement.getElementsByTagName("password");
Node rootEl = rootEls.item(0)
NodeList children = rootEl.getChildNodes();
Node passEl = children.item(0);
return passEl.getNodeValue();

When you get the NullPointerException, with this code, you can extract a lot more information from the line number in the exception.

Secondly, in this case it may prove useful to take a look at the various XML processing libraries for Java and to find one which allows the use of XPath, see also: this tutorial on Xpath.

I hope this helps. Feel free to pose any questions.

Tim Lamballais
  • 1,056
  • 5
  • 10