BLOG
Storing a string as an element of a multivalued property of a node in a Sling based application
By meamitava - JCRLead | Posted on 2009-09-04 04:18
Multivalued property is indeed a problematic issue to handle in case of a Java Content Repository node in a Sling based application. The problem multiplies when we try to carry out any form of tweaking on such a node. I had faced a situation, wherein it was required to store a string as an element of a multivalued property of a JCR node. The main problem was how to store a string as an element of a Value array. I resolved the problem by following the below steps:
- Pass the string to be stored and the node name as parameters to a Servlet
- From the servlet invoke a method to store the string with the following parameters -
HttpServletRequest
String
Nodename
- Within the method obtain a jcrsession object
- Traverse down to the desired node using the jcrsession object
The following variables have been used in the below mentioned code snippet for storing the string:
- demonode – The node containing the multivalued property
- demomutivalue – The property object containing the elements of the multivalued property
- demostring – The string that needs to be stored
Here’s the sample code snippet :
Property demomultivalue = demonode.getProperty("multiprop");
//Creating a ValueFactory object
ValueFactory factory = jcrsession.getValueFactory();
//converting the string to a Value object
Value tempval = factory.createValue(abuseby);
//Checking that the value of the property is not null
if(demomultivalue!=null){
//Checking that the property is of type multivalue
if(abuse.getDefinition().isMultiple()){
//Storing the elements of demomultivalue in a Value array
Value val[] = demomultivalue.getValues();
//Creating a temporary Value array having length one more that
//of the original array
Value temparr[] = new Value[val.length+1];
//Using arraycopy() function to store the elements of original
//array into the temporary one
System.arraycopy(val,0,temparr,0,val.length);
//Appending the value corresponding to the string as the last
//element of the temporary array
temparr[val.length]= tempval;
//Setting the property object with the temporary array
demomultivalue.setValue(temparr);
//Saving the jcrsession
jcrsession.save();
}
}
Hopefully the blog will be helpful for anyone facing the same sort of problem.
-Amitava
.
.
Previous comments on this post
By tanmay - JCRDev | Posted on 2009-09-08 02:34
Good one
BLOG STATS
5625 visitors have read this BlogPopular Posts
The Apache Sling FrameworkTemplate Creation in Day Communique 4.x
JCR and ECM Vendors
Writing Filters in Apache Sling Web Application
Sling based JCR Explorer
JCR DEVELOPERS (level, posts)

