Search code examples
javajcrmagnolia

String cannot be cast to javax.jcr.Value


I am getting the following error String cannot be cast to javax.jcr.Value when I try to set a properties for the JCR node using the following code. The javax.jcr.Node.setProperty(String name, Value value) expects value for the "value" parameter but the casting does not work.

// using for-each loop for iteration over Map.entrySet() 
for (Entry<String, Object> entry : map.entrySet()) { 
    try {
        //fetch the value of uuid mapped to the key "jcr:uuid"
        String uuid= (String) map.get("jcr:uuid");
        //get the JCR workspace session value for website
        Session session = MgnlContext.getJCRSession(RepositoryConstants.WEBSITE);
        //get the JCR node specified by the given identifier
        Node node = session.getNodeByIdentifier(uuid);

        //verify if the value for the specific value is of type HashMap
        //this means we have a nested map which denotes another node
        if (entry.getValue() instanceof HashMap ) {
            System.out.println("New node: " + entry.getKey());
            //Creates a new node at relPath of the specified node type
            node.addNode(entry.getKey(),NodeTypes.Page.NAME);
            //initializes a new map that points to the nested map
            HashMap<String , Object> newmap = (HashMap<String, Object>) entry.getValue();
            //recursion happens here
            loadMap(newmap);

        } else {
            //Sets the single-value property for all entries to the specified value.

            node.setProperty(entry.getKey(), (Value)entry.getValue()); ---> *error here*
            System.out.println("Key = " + entry.getKey() + 
                            ", Value = " + entry.getValue()); 
        }       
    } catch (ItemNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (RepositoryException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Here is the solution thanks to @Ducaz035

String value= (String)entry.getValue();
node.setProperty(entry.getKey(), value);

Solution

  • I believe you can use javax.jcr.Node#setProperty(java.lang.String, java.lang.String) directly. In fact, it accepts String as a value.

    The problem in your code is not about String or Value but you try to insert Object, maybe cast Object to String and then set the property