简体   繁体   中英

Java - Null check on currentNode

I'm pretty new to Java so bear with me. I've got a small bit of code that checks to see if a currentNode has a property of "fileReference" and returns its value. Except it doesn't seem like my null check is working because if nothing is in fileReference I get an error. If a reference to fileReference exists it works fine. Here is the error:

Caused by: javax.jcr.PathNotFoundException: fileReference

Here is my code:

    if(currentNode != null){
        NodeIterator checkNode = currentNode.getNodes();

        while (checkNode.hasNext()) {
            Node imageNode = checkNode.nextNode();
            printNodeTitle = imageNode.getProperty("fileReference").getString();
        }
    } 

       public String getImageNode() { (printNodeTitle != null) ? return printNodeTitle : return ""; }

Any help is greatly appreciated!

I'm pretty confident fileReference is actually a property, not a seperate node (since you are calling properties). Since you know the name of the property you want to get, I suggest getting it directly with a small check if it exists.

if(currentNode != null){
    NodeIterator checkNode = currentNode.getNodes();

    while (checkNode.hasNext()) {
        Node imageNode = checkNode.nextNode();
        if(imageNode.hasProperty("fileReference")){
            Property fileReferenceProp = imageNode.getProperty("fileReference");
            printNodeTitle = fileReferenceProp.getString();
        }
    }
} 

I'm assuming you deal with possible repository exceptions elsewhere

I'm not an expert on sling but try this

if(currentNode != null){
    NodeIterator checkNode = currentNode.getNodes();

    while (checkNode.hasNext()) {
        Node imageNode = checkNode.nextNode();
        Iterator<Node> fileReferences = imageNode.getProperties("fileReference");
        if(fileReferences.hasNext()) { // You might want to improve this
            printNodeTitle = fileReference.next().getString(); // You might want to improve it
        }
    }
} 

You retrieve all nodes with getProperties(String) , if no nodes are found and empty Iterator is retrieved.

The line Node fileReference... I just guessed the type ( Node ) you must change it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM