On almost every topic
Alfresco Java Based Spring Web Script

This post is a follow-up to jQuery DataTables and Spring Web Scripts that focused on writing a back-end service using light weight scripting techniques. In this post we will replace the JavaScript controller with a controller written in Java. This post is just an example. In most cases you can and should use the JavaScript API. It is recommended to read the previous post before you continue.

Download the sample code

You can download the sample code here. The download contains an Eclipse project as a separate archive file. It requires Eclipse and the Alfresco SDK. You can also use a different editor if you want. The client-side code is also added in the ROOT folder. Add the ROOT folder to the webapps folder of your Alfresco Tomcat distribution and download and add the jQuery DataTables libraries to setup the client.

Import the project

To import the project start Eclipse, select File, Import and then Archive File. Select the archive file simple-search-eclipse.zip and click Finish to import the project. Once the project is imported make sure that you add the project SDK Embedded from the Alfresco SDK.

To do this download the SDK, unpack the files and then in Eclipse select File, Import, then choose Existing Projects into Workspace. In the Import dialog select the samples folder in the Alfresco SDK as root folder, select the SDK Embedded project and click Finish to import the project.

To add the SDK embedded project to the Eclipse project select Project in the menu bar, then Properties and select the Java Build Path. Click Add in the Projects tab to add the project.

What we need to do

In order to use a Java class as the controller for a Web Script, we need to write the Java source file and bind the class to our Web Script using a Spring bean declaration. The Spring bean declaration is an XML configuration file that configures the link between the Web Script and the Java class. 

We also need the Web Script descriptor file simplesearch.get.desc.xml and the view simplesearch.get.json.ftl. The file simplesearch.get.js is no longer needed. It contains the JavaScript controller that will be replaced with the Java class. We start with writing the Java code.

Add the Java class

In the source directory of your project create the following package:

com.someco.alfresco.web.scripts.bean

And add a class SimpleSearch.java as a subclass of:

org.springframework.extensions.webscripts.DeclarativeWebScript

You will end up with the following class definition:

package com.someco.alfresco.web.scripts.bean;

public class SimpleSearch extends DeclarativeWebScript {

}

In order to use Alfresco’s public services we add the ServiceRegistry. This registry provides access to all of Alfresco’s public services like the SearchService or the NodeService. You can also add the different services you need, but since we are required to provide the ServiceRegistry to a method later, we simply add the registry and use that to retrieve the services we need.

package com.someco.alfresco.web.scripts.bean;

public class SimpleSearch extends DeclarativeWebScript {

  protected ServiceRegistry serviceRegistry;

  @Override
  protected Map executeImpl(WebScriptRequest req,
    Status status) {

    return null;
  }

  public ServiceRegistry getServiceRegistry() {
    return serviceRegistry;
  }

  public void setServiceRegistry(ServiceRegistry serviceRegistry) {
    this.serviceRegistry = serviceRegistry;
  }

}

Tip: in Eclipse you can use Source, Generate Getters and Setters… to add the getter and setter methods for the serviceRegistry variable.

We start with setting the required parameters. Add the following lines to the executeImpl method:

String searchTerms = req.getParameter("sSearch");

String displayStartArg = req.getParameter("iDisplayStart");
int displayStart = 0;
try {
  displayStart = new Integer(displayStartArg);
} catch (NumberFormatException e) {
}

String displayLengthArg = req.getParameter("iDisplayLength");
int displayLength = 10;
try {
  displayLength = new Integer(displayLengthArg);
} catch (NumberFormatException e) {
}

return null;

Now that we have the required parameters, we can execute a search if the user provided a search term:

// we will use it to add the TemplateNode items
List list = new ArrayList();

int totalRecords = 0;

ResultSet results = null;

if (searchTerms != null && searchTerms.length() > 0) {

  try {
    // create the query statement
    StringBuilder query = new StringBuilder();
    query.append("TYPE:\"");
    query.append(ContentModel.TYPE_CONTENT);
    query.append("\" AND TEXT:\"");
    query.append(searchTerms);
    query.append("\"");

    // define search parameters
    SearchParameters parameters = new SearchParameters();
    parameters.addStore(Repository.getStoreRef());
    parameters.setLanguage(SearchService.LANGUAGE_LUCENE);
    parameters.setQuery(query.toString());

    // execute the query
    results = serviceRegistry.getSearchService().query(parameters);

    totalRecords = results.length();

    // get the number of items to retrieve for the current page
    int totalPageItems = Math.min(displayLength, totalRecords
        - displayStart);

    // add the nodes to the list for our model
    for (int i = 0; i < totalPageItems; i++) {
      NodeRef node = results.getNodeRef(i + displayStart);

      // the Freemarker model requires TemplateNode objects
      list.add(new TemplateNode(node, serviceRegistry, null));
    }

  } finally {
    // make sure that we close our result set to
    // avoid memory leaks
    if (results != null) {
      results.close();
    }
  }

}

And finally we build the model that will be passed to the view, our Freemarker template:

Map model = new HashMap(7, 1.0f);
model.put("iTotalRecords", totalRecords);
model.put("aaData", list);

return model;

The final Java class looks like this:

package com.someco.alfresco.web.scripts.bean;

public class SimpleSearch extends DeclarativeWebScript {

  protected ServiceRegistry serviceRegistry;

  @Override
  protected Map executeImpl(WebScriptRequest req,
      Status status) {

    String searchTerms = req.getParameter("sSearch");

    String displayStartArg = req.getParameter("iDisplayStart");
    int displayStart = 0;
    try {
      displayStart = new Integer(displayStartArg);
    } catch (NumberFormatException e) {
    }

    String displayLengthArg = req.getParameter("iDisplayLength");
    int displayLength = 10;
    try {
      displayLength = new Integer(displayLengthArg);
    } catch (NumberFormatException e) {
    }

    List list = new ArrayList();

    int totalRecords = 0;

    ResultSet results = null;

    if (searchTerms != null && searchTerms.length() > 0) {

      try {
        StringBuilder query = new StringBuilder();
        query.append("TYPE:\"");
        query.append(ContentModel.TYPE_CONTENT);
        query.append("\" AND TEXT:\"");
        query.append(searchTerms);
        query.append("\"");

        SearchParameters parameters = new SearchParameters();
        parameters.addStore(Repository.getStoreRef());
        parameters.setLanguage(SearchService.LANGUAGE_LUCENE);
        parameters.setQuery(query.toString());

        results = serviceRegistry.getSearchService().query(parameters);
        totalRecords = results.length();

        int totalPageItems = Math.min(displayLength, totalRecords
            - displayStart);

        for (int i = 0; i < totalPageItems; i++) {
          NodeRef node = results.getNodeRef(i + displayStart);
          list.add(new TemplateNode(node, serviceRegistry, null));
        }

      } finally {
        if (results != null) {
          results.close();
        }
      }

    }

    Map model = new HashMap(7, 1.0f);
    model.put("iTotalRecords", totalRecords);
    model.put("aaData", list);

    return model;
  }

  public ServiceRegistry getServiceRegistry() {
    return serviceRegistry;
  }

  public void setServiceRegistry(ServiceRegistry serviceRegistry) {
    this.serviceRegistry = serviceRegistry;
  }

}

I did not add all the import statements. In Eclipse you can organize imports using Source and then Organize Imports (Ctrl+Shift+O).

Add the Spring bean declaration

You can read more about the Spring bean declaration for a Java backed Web Script at Alfresco’s Wiki. Create a file called web-scripts-application-context.xml in the folder config/extension and add the following lines:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE beans PUBLIC '-//SPRING//DTD BEAN 2.0//EN' 
  'http://www.springframework.org/dtd/spring-beans-2.0.dtd'>
<beans>
  <bean id="webscript.com.someco.samples.simplesearch.get" 
    class="com.someco.alfresco.web.scripts.bean.SimpleSearch"
    parent="webscript">
    <property name="ServiceRegistry" ref="ServiceRegistry" />
  </bean>
</beans>

What is important here is that the bean id follows the pattern below:

id="webscript.[packageId].[serviceId].[httpMethod]"

The packageId is the folder where the web script descriptor is located, the serviceId is the name of the service and the method is for example get or post. Also make sure that you set the parent bean to webscript.

Add the descriptor

Finally we need to add the descriptor and the view to the project. These files are the same files as we used for the previous Spring Web Scripts post with the JavaScript controller. First create the following folder in the project:

config/extension/templates/webscripts/com/someco/samples

Next create a file simplesearch.get.desc.xml and add the following lines to the file:

<webscript>
  <shortname>Simple Search</shortname>
  <description>Simple Search Example</description>
  <url>com/someco/simplesearch</url>
  <authentication>user</authentication>
  <format default="json">argument</format>	
</webscript>

Add the view

Then create a file simplesearch.get.json.ftl and add the following Freemarker code:

<#escape x as jsonUtils.encodeJSONString(x)>
{
  "iTotalRecords": ${iTotalRecords}, 
  "iTotalDisplayRecords": ${iTotalRecords},
  "aaData": [
  <#list aaData as child>
    [
    "${child.name}",
    "${child.properties["cm:title"]!""}",
    "${child.properties["cm:author"]!child.properties["cm:creator"]}",
    "${child.properties["cm:modified"]?string("yyyy-MM-dd")}"
    ]<#if child_has_next>,</#if></#list>
  ] 
}
</#escape>

The last two files are no different from the descriptor and the view from the previous post about Spring Web Scripts. We are now ready to deploy the code.

Deployment

To be able to deploy this code check the build.properties file to make sure that the properties refer to your Alfresco distribution and to the Alfresco SDK. Then return to Eclpse, select Window and then Show View and select Ant. In the Ant View click the plus sign and add the build.xml from the Simplesearch project. Click deploy to deploy the code and restart Alfresco.

The Ant build tool writes the Java library simplesearch.jar to the WEB-INF/lib directory and the Web Script files to WEB-INF/classes/alfresco/extension. Make sure to remove the previous Spring Web Script to avoid a naming conflict.

Login to Alfresco and navigate to the Web Script maintenance page to check if the Simple Search service is a registered Web Script:

http://localhost:8080/alfresco/service/

Reload the client page

When you reload the same client HTML file simplesearch.html as we used for the previous post located in the ROOT project, you should see the same result:

Java Backed Web Script 

The main difference is that we did not add sorting to our server-side code.

Add sorting

You can add sorting by adding the parameters for sorting to the class file like we did for the page length and skipcount. To map the column number to a property in Alfresco you can add a static Map.

In order to sort you need to provide a search parameter with the name of the field and a boolean value for ascending order (true) or descending order (false). The field name must be provided in the so called Clark notation preceded by an at sign (@):

@{http://www.alfresco.org/model/content/1.0}name

The following code snippet shows how you can add the sort order to the list of search parameters:

parameters.addSort("@" + ContentModel.PROP_NAME.toString(), true);

Conclusion

In this post I returned to Spring Web Scripts to show how you can replace a JavaScript controller with a Java based controller. In most cases you should be fine writing the controller using JavaScript, but in cases where you need to execute a task that is not easily done using JavaScript, you can use Java.

Read the previous tutorials

Read the related three posts jQuery DataTables and Spring Web Scripts, jQuery DataTables, CMIS and Alfresco and jQuery DataTables and Alfresco.

  1. lewesde reblogged this from bpeters
  2. bpeters posted this