Saturday 12 April 2014

Processing list in webscript response xml/json ftl

Hello everyone !

I am sure this would be helpful to you if you are looking for a solution about how to iterate over a list in the ftl. Let's start then.

Returning appropriate responses (xml/json ftls) are the must when you need to do further processing based on your webscript response.
Here, I am providing the code snippets which will be useful to you when you need to process/iterate over the list in your xml/josn ftls for your webscript response.

For example, consider a scenario, where in you have to get the name/noderefs of all the contents from one space. I am sure you would like to get this done by writing a webscript.
In your webscript backend class, you will perform a lucene query, and generally we prefer to use a List in java backed webscript. Hence, will populate the list with the result noderefs.
Now, you need to process this result list and return the name/noderef in the xml/json ftls as the webscript response.

To process a list in webscript response ftls, you need to do below things -

1. Java backed webscript -
 - In your java backed declarative webscript, initialize the model object.
   Map<String, Object> model = new HashMap<String, Object>();
 - Prepare the List object to be set.
   List<NodeRef>  resultList = new ArrayList<NodeRef>();
   resultList = queryResult(query) // You are invoking a function which has code for performing lucene query and return the list.
 - Populate the model object
   model.put("nodelist", resultList);
 - Do return the model object from your webcript backend class.
   return model;

2. If you want to return xml as the response. Then, use below code in your webscript's response xml.ftl (yourwebscript.xml.ftl)
   <?xml version="1.0" encoding="UTF-8"?>
    <#escape x as x?html>
    <nodes>
        <#list nodelist as node>
            <nodeid>${node.id}</nodeid>
            <name>${node.name}</name>      
        </#list>
    </nodes>
    </#escape>

3. If you want to return json as the response. Then, use below code in your webscript's response json.ftl (yourwebcript.json.ftl)
   <#escape x as jsonUtils.encodeJSONString(x)>
   {
   "nodes": [
         <#if nodelist??>      
             <#assign first=true>
             <#list nodelist as node>
                 <#if node??>
                    <#if !first>
                     ,
                    <#else>
                    <#assign first=false>
                     </#if>
                     {
                        "nodeid":"${node.id}",
                         "name":"${node.name}"
                     }                  
                 </#if>
             </#list>      
         <#else> </#if>
       ] 
   }
  </#escape>

Processing a list in ftl is simpler now. You may want to try it in your webscripts.

Thanks,
Ramesh C

No comments:

Post a Comment