Web Scripts

Web Scripts are basically RESTful web services. Alfresco provides REST architecture-based framework for Web Scripts. In this section, we will talk about Web Script, implementing Web Script, some out of the box Web Script examples, along with some custom web script examples.

What is a Web Script

A REST Web Script is simply a service bound to a URI (Universal Resource Identifier) and based on HTTP. So, the technology that the external application is implemented in is irrelevant, that is, they are cross platform and cross language. You are not locked in to any programming language or development environment.

The Web Script framework lets you roll your own APIs, thereby allowing you to fine-tune the remote APIs that you expose to the external application. REST has proven itself to be simple, flexible, and extremely scalable. It provides a convenient bridge between any native application and the content management, along with easier content streaming than SOAP. Using Web Scripts, the Alfresco system now provides access to its repository services from anywhere, and has easier-to-access content and workflow information. Web Scripts support access and update using standard HTTP methods, and can be constructed using lightweight scripting languages, including JavaScript.

By definition, REST-style Web services are resource-oriented services. You can identify and locate resources by a URI, and the operations that might be performed against those resources are defined by the HTTP specification. The core operations include GET, POST, PUT, and DELETE.

Web Script allows you to:

  • Build custom URI-identified and HTTP-accessible content management web services
  • Turn your Alfresco repository into a content management powered HTTP Server
  • Easily access, manage, and cross-link your content by using a tailored RESTful API

You do not need any special tools or sound Java knowledge. All you need is your favorite text editor to generate the Web Script coding. No compilation, generators, server restarts, or complex installs are required.

With Web Scripts, we can either build our own RESTful interface using lightweight scripting technologies such as JavaScript and FreeMarker, allowing you to arbitrarily map any content in the repository to resources on the web, or we can use pre-built out of the box Web Scripts that already encapsulate many of the required mappings. Typically, Web Scripts are used for querying, searching, and accessing content within the repository.

Primarily, there are two types of Web Scripts:

  • Data Web Scripts

    Data Web Scripts encapsulate access to and modification of content/data held in the repository. Therefore, they are provided and exposed only by the Alfresco Repository server. They provide a repository interface for client applications to query, retrieve, update, and perform processes, typically using document formats such as XML and JSON. Out of the box, Alfresco provides a series of Data Web Scripts—for tagging, activities, site management, and so on.

  • Presentation Web Scripts

    Presentation Web Scripts allow you to build user interfaces such as a dashlet for Alfresco Explorer or Alfresco Share, a portlet for a JSR-168 portal, a UI component within Alfresco SURF, a web site, or a custom application. They typically render HTML (and perhaps include browser-hosted JavaScript). Unlike Data Web Scripts, Presentation Web Scripts may be hosted on the Alfresco Repository server or on a separate presentation server. When hosted separately, the Presentation Web Scripts interact with Data Web Scripts. Out of the box, Alfresco provides a series of Presentation Web Scripts such as Portlets, Office Integration, SURF Components, and so on.

How to implement Web Scripts

Implementation of a Web Script consists of mainly four parts.

  1. Create a Web Script:

    To create a web script, three files are required:

    • A description document, which describes the URL that initiates the Web Script, along with a short name, description, output format, authentication, and transactional needs.
    • A controller—optional Java script or a Java bean.
    • A rendering template (FreeMarker or XSLT to obtain the output in the desired format— XML/HTML/JSON and so on).
  2. Store the Web Script:

    There are two ways to store a Web Script in Alfresco:

    • Store it in Alfresco Explorer.

      You can store the Web Script files in the Company Home | Data Dictionary | Web Script Extensions folder.

      Create the required folder structure under the path listed above and then place the Web Script files, description document, rendering template, and controller script (if you have) in that folder.

    • Store it on file system

      If you want to store it on the file system, you need to store it under the <<alfresco_server>> > tomcat | shared | extension | templates | webscripts folder. You can create the desired folder structure inside the above-mentioned folder and then put all of the Web Script files in there.

  3. Register the web script:

    Once you are done with storing the required Web Script files, you need to register them in Alfresco.

    For registering the Web Scripts stored in Alfresco Explorer, go to http://localhost:8080/alfresco/service/index. Click on the Refresh Web Scripts button. You will see a message showing how many Web Scripts have recently been found and registered.

    For registering the Web Scripts stored on the file system, you need to restart the Alfresco server.

  4. List the Web Scripts for external access:

    Next, you can use the Web Script that we developed using the correct URL mentioned in the description document file. For example, you can go to http://localhost:8080/alfresco/service/index/package/org/alfresco/portlets or to http://localhost:8080/alfresco/service/index. You can choose either Browse by URL or Browse by Package, and then select the Web Script that we created.

Hello World example

We will consider a "Hello World" example in this section, and walk through allfour steps. In this example, we will just try to greet the user who is executing the Web Script.

  1. Create a Web Script:
    • Create a file named greeting.get.desc.xml , which contains the details of the URL, authentication, and so on.
      <webscript>
        <shortname>Welcome</shortname>
        <description>Polite greeting</description>
        <url>/sample/greeting</url>
        <authentication>user</authentication>
      </webscript>

      Here, we don't require any controller as we are only displaying a greeting message.

    • Create a response template file named greeting.get.html.ftl, which contains the following output script:
      Welcome ${person.properties.userName}
  2. Store the Web Script:

    We will store above two files in the Company Home | Data Dictionary | Web Script Extensions folder . We will create a folder structure such as org | alfresco | sample if it's not already there, and will then put the above two files in this sample folder.

  3. Register the Web Script:
    • To register the Web Script, go to http://localhost:8080/alfresco/service/index
    • Click on the Refresh Web Scripts button.
  4. List the Web Scripts for external access:
    • Now you can access this Web Script with the help of the specified URL:

      http://localhost:8080/alfresco/service/sample/greeting

    • When you access this URL from the browser, you will see the following greeting message:

      Welcome admin.

      This indicates that your Web Script is working perfectly.

      This Web Script is authenticated as user. So here, admin is the user name.

Sample out of the box portlet Web Scripts

Alfresco provides some out of the box Web Scripts for portlet integration with JSR 168 portlets. Some examples of portlet Web Scripts are as follows:

Myspaces portlet

This Web Script displays the documents and spaces in the repository as a portlet. You can upload new documents in any space by using a web client, or you can upload new documents in any space with the help of this Web Script.

URL: http://localhost:8080/alfresco/service/ui/myspaces?f={filter?}&p={path}

Example: http://localhost:8080/alfresco/service/ui/myspaces?f=0&p=%2FCompany%20Home

Myspaces portlet

Document list portlet Web Script

This Web Script displays the documents available in the repository. You can filter by the particular type of document. You can also provide a path and query, along with the type of document, as input parameters.

URL:

http://localhost:8080/alfresco/service/ui/doclist?f={filter?}&p={path?}&q={query?}

Example:

http://<server_name>:<port>/alfresco/service/ui/doclist?f=3

In the above example, you need to pass a filter parameter of 3 if you are expecting a PDF document type. So, the following screen displays the PDF documents available in the repository:

Document list portlet Web Script

Web Script to list the latest documents

This example shows how to integrate an external Java-based web application with Alfresco. Here, we have one web application that displays the recently-modified documents on the daily dose documents page. If the daily dose date of any document is greater than or equal to today, this document should be listed on the daily dose page of the web application. All of the documents are managed by the Alfresco repository, and the daily dose date will be one of the metadata elements for this document. Next, we will generate a Web Script that will be responsible for displaying these documents in the web application. This Web Script will return HTML output, which we can easily incorporate into the existing web application.

Daily dose integration Web Script in detail

The following table shows detailed information about the "daily dose integration" Web Script:

Description:

This Web Script is responsible for displaying the latest documents, updated on daily basis on an external web application

Links:

Homepage of the external application

Package:

recentdocuments.dailydose

Web Script base URL:

/recentdocuments/dailydose/listDailyDose

Output:

  • HTML having following details of documents:
  • Document title (with link)
  • Type of document
  • Author
  • Expiration date

Conditions:

Documents whose "End Daily Dose Date" is greater than or equal to the current date

Controller:

Java script as a controller, which will fetch the documents that satisfy the Conditions from the Alfresco repository

Follow the steps listed below to create a Web Script:

  1. Create the listDailyDose.get.desc.xml file, containing:
    <webscript>
    	<shortname>Listing of Daily Dose Document Through Webscript</shortname>
    	<description>Contains the list of daily dose documents</description>
    	<url>/recentdocuments/dailydose/listDailyDose</url>
    	<authentication>guest</authentication>
    	<transaction>required</transaction>
    </webscript>
  2. Create the listDailyDose.get.js file, containing:
          var l_customerDocs =  companyhome.childByNamePath("CustomerDocuments");
          model.m_documents_node=l_customerDocs;
  3. Create the listDailyDose.ftl.html file. See the following code snippet:
    <#list m_documents_node.children as cust_documents>
    <#if (dateCompare(cust_documents.properties["CUST:EndDailyDoseDate"],date)) == 1>
    <tr>
    <td>
    <img src="${url.context}${cust_documents.icon32}"/>
    </td>
    <td align="center">
    <a class="title" href="/alfresco/${cust_documents.url}">${cust_documents.properties.name}</a>
    </td> 		
    <td> </td>
    <td align="center"> ${cust_documents.properties["CUST:DocumentType"]} 
    </td>
    <td> </td>
    <td> ${cust_documents.properties.creator}</td>
    <td> </td>						
    <#if cust_documents.properties["CUST:ExpirationDate"]?exists>
    <td align="center">
    ${cust_documents.properties["CUST:ExpirationDate"]?date} 
    </td>
    <#else> 
    <td> </td>  
    </tr> 
    </#if>
    </#list>
    
  4. Store the Web Script:

    To store this Web Script, browse to Company Home | Data Dictionary | Web Script Extensions and create a folder hierarchy called recentdocuments | dailydose. Store all three of the files in this folder.

  5. Browse to the Company Home | Data Dictionary | Models folder. Add the custModel.xml. Make the model active by selecting the Active property.
  6. Browse to Company Home | Data Dictionary | Web Scripts Extensions folder. Add the web-client-config custom.xmlfile. Deployment of Alfresco Explorer can be achieved as an administrator by using the following URL: http://localhost:8080/alfresco/faces/jsp/admin/webclientconfig-console.jsp.
  7. Use the following command to deploy the file:
    reload
    

    Note

    Download the custModel.xml and web-client-config-custom.xml file from Packt web site.

  8. Create a space called as CustomerDocuments in Company Home. Upload a few documents to the folder. Apply the aspect "Customer Document Details" to all of the documents in the folder.
  9. Register the Web Script. To do this, go to http://localhost:8080/alfresco/service/index
  10. Click on the Refresh Web Scripts button. You will see a message showing how many Web Scripts were found and registered recently.
  11. List the Web Scripts for external access:

    Now you can use the Web Script, that we developed, by using the correct URL mentioned in the description document file. For our example, the URL is:

    http://<server_name>:<port>/alfresco/service/index/uri/recentdocuments/dailydose/listDailyDose

A screenshot of the daily dose page of web application, which is generated with the use of above mentioned Web Script, is shown below:

Daily dose integration Web Script in detail

Integrating Web Script with an external Java application

You can call this HTTP URL in the JSP of your web application, and can embed the HTML output returned by this Web Script in your JSP.

Below is the code snippet provided to call the Web Script from the jsp:

<html>
<title> The Daily Dose </title>
<body bgcolor="#edf6fc" text="blue">
<head bgcolor="#edf6fc"> Welcome to Daily Dose Page</head>
<H2 bgcolor="#edf6fc"> The Daily Dose</H2> 
<iframe bgcolor="#edf6fc" width="60%" height="60%"frameborder=0 src="http://localhost:8080/alfresco/service/recentdocuments/dailydose/listDailyDose"/>
</body>
</html>

Web Script to integrate document search

Because Alfresco is behaving as a content repository, it's a very suitable use case for where we have an external application with any kind of rich user interface. We also have a search interface incorporated into it, which will search inside the content repository and display the result based on some input parameters. You can also define some filtering criteria for searching for documents in the Alfresco repository.

In this example, we will search for documents in Alfresco using some parameters, such as client name, keyword, and so on, which are metadata of the documents. This will return XML/HTML output. You can process XML output in your application and orchestrate the UI layer. And if you want to display the output in HTML format, you can use the HTML output of the same Web Script, which you can directly incorporate into your application.

Document search Web Script in detail

The following table explains the "document search" Web Script in detail:

Description:

This Web Script is responsible for searching for documents in the repository, based on some input parameters

Links:

Homepage of the external application

Package:

custdocuments.searchDocs

Web Script base URL:

  • /custdocuments/searchDocs.xml?keyword={keyword?}&amp;clientname={clientname?}
  • /custdocuments/searchDocs?keyword={keyword?}&amp;clientname={clientname?}

Input Parameters:

keyword

client_name

Output:

XML/HTML (we will use the FreeMarker template language to generate the XML/HTML file)

Document title (with link)

Type of document

Author

Expiration date

Conditions:

None

Controller:

We will use JavaScript as a controller, which will search the documents from the Alfresco repository based on the criteria specified in the input parameters

The four steps below are used to create the "document search" Web Script:

  1. Create a Web Script:

    Basically, three files are required. The first of these is the Description Document, searchDocs.get.desc.xml as. This should contain the following code:

    <webscript>
    	<shortname>
    		Searching of Documents in the repository Through Webscript
    	</shortname>
    	 <description>
    		Searches the documents in the repository
    	</description>
    	 <url>
    	/custdocuments/searchDocs?keyword={keyword?}&amp;clientname={clientname?}
    	</url>
    	 <url>
    	/custdocuments/searchDocs.xml?keyword={keyword?}&amp;clientname={clientname?}
    	</url>
    	 <authentication>user</authentication>
    	 <transaction>required</transaction>
    </webscript>

    The second file that is needed is the Controller. This can be a Java-Script script or Java Bean. In this example, we will use JavaScript. Create a file named searchDocs.get.js , and enter the following code into it:

    var l_folder = "app:company_home/cm:CustomerDocuments";
    var l_search_docs = new Object();
    if (args.startpage == undefined)
    {
       l_search_docs.startPage = 1;
    }
    else
    {
       l_search_docs.startPage = parseInt(args.startpage);
    }
    if (args.count == undefined)
    {
       l_search_docs.itemsPerPage = 5;
    }
    else
    {
       l_search_docs.itemsPerPage = parseInt(args.count);
    }
    l_search_docs.startIndex = (l_search_docs.startPage-1) * l_search_docs.itemsPerPage;
    l_search_docs.searchTerms ="";
    
    if (args.keyword == null || args.keyword.length == 0) {
    	status.code = 400;
    	status.message = ""keyword" argument is null or undefined";
    	status.redirect = true;	
    }
    else if (args.clientname == null || args.clientname.length == 0) {
    	status.code = 400;
    	status.message = ""clientname" argument is null or undefined";
    	status.redirect = true;	
    } 
    else
    {
    	l_search_docs.searchTerms = args.keyword;
    	l_search_docs.clientName = args.clientname;
    	query = buildSearchQuery();
    	var results = search.luceneSearch(query);
    	l_search_docs.results = results;
    	l_search_docs.totalResults = results.length;
    	l_search_docs.totalPages = Math.ceil(results.length / l_search_docs.itemsPerPage);
    	model.m_search_docs = l_search_docs;
    }
    function addQueryCriterion(param, value, isContained) {
    	var valueStub;		
    	if (isContained) {
    		valueStub = "*" + value + "*";	
    	} 
    	else {
    		valueStub = value;
    	}
    	criterion = " AND @CUST\:" + param + ":" + valueStub;
    	return criterion;	
    }
    function buildSearchQuery() {
        	searchQuery = "PATH:"//" + l_folder + "//*"";
    	 if (args.keyword != null) {
    		searchQuery += addQueryCriterion("Keywords", args.keyword, true);
    	}
    	 if (args.clientname != null) {
    		searchQuery += addQueryCriterion("ClientName", args.clientname, true);
    	}
    	return searchQuery;
    }
    

    The third file we need is a rendering template. We can use FreeMarker, or xslt which will render the output in desired format XML/HTML/JSON etc. We will use FreeMarker with HTML output in this example. Create a FreeMarker template file named searchDocs.ftl.xml, and enter the following code into it:

    <?xml version="1.0" encoding="UTF-8"?>
    <items> 
    	<#if m_search_docs.results?exists>
    	<#assign count=0>
    	<#assign index=0>
    	<#list m_search_docs.results as l_result_document>
    	<#if (index>=m_search_docs.startPage) && (index<m_search_docs.startPage+m_search_docs.itemsPerPage)>
    	<#assign count=count+1>
    	<#assign curl=url.serviceContext>
    	<item>
    		<name>${l_result_document.properties.name}</name>
    		<title>
    			<#if l_result_document.properties.title?exists>
    				${l_result_document.properties.title}
    			</#if>
    		</title> 
    		<size> ${l_result_document.size} </size>
    		<author>${l_result_document.properties.creator}</author>	
    		<clientname>										       <#if l_result_document.properties["CUST:ClientName"]?exists>
    			${l_result_document.properties["CUST:ClientName"]}
    		</#if>
    		</clientname>
    		<expirationdate>
    		<#if l_result_document.properties["CUST:ExpirationDate"]?exists>
    		${l_result_document.properties["CUST:ExpirationDate"]?datetime}
    		</#if>					
    		</expirationdate>
    		<modificationdate>
    		<#if l_result_document.properties["cm:modified"]?exists>
    			${l_result_document.properties["cm:modified"]?datetime}
    		</#if>					
    		</modificationdate>
    	</item>	
    	</#if>
    	<#assign index=index+1>
    	</#list>
    	<#else>
    		No results to display.
    	</#if>
    </items>
    

    If you want to use a FreeMarker template file for HTML output, create a file named searchDocs.ftl.html , and enter the following code into it:

    <html>
    <head> 
          <title>Alfresco Search</title>  
    </head>
    <body>
    <b>Search Results:&nbsp;</b>	    
    <#if m_search_docs.results?exists>
    	<#assign count=0>
    	<#assign index=0>
    	Showing page <b>${m_search_docs.startPage}</b> of <b>${m_search_docs.totalPages}</b> from <b>${m_search_docs.totalResults}</b> results for Keyword : <b>${m_search_docs.searchTerms}</b> and Client: 	<b>${m_search_docs.clientName}</b>
    	<br> <br>
    	<table>
    	 <tr>
    	 <th> </th>  <th> Name of Document </th>
    	 <th> </th>  <th> Author </th>
    	 <th> </th>  <th> Client Name </th>
    	 <th> </th>  <th> Expiration Date</th>
    	 </tr>
    	<#list m_search_docs.results as l_result_document>
    	<#if (index>=m_search_docs.startIndex) && 	(index<m_search_docs.startIndex+m_search_docs.itemsPerPage	)>
    	<#assign count=count+1>
    	<#assign curl=url.serviceContext>
    	<tr>
    	<td> 
    	<img src="${url.context}${l_result_document.icon16}"/>
    	</td>
    	<td align="center"> 
    	<a class="title" href="/alfresco/${l_result_document.url}">${l_result_document.properties.name}</a>
    	</td> 		
    	<td> </td>			
    	<td> ${l_result_document.properties.creator} </td>
    	<td> </td>						
    	<td align="center">${l_result_document.properties["CUST:ClientName"]} 	</td>
    	<td> </td>
    	<#if l_result_document.properties["CUST:ExpirationDate"]?exists>
    	<td align="center"> ${l_result_document.properties["CUST:ExpirationDate"]?d	ate} </td>	
    	<#else>
    	<td> </td>
    	</#if>						
    	</tr>
    	<tr>
    	<td> </td>
    	<td> <HR> </td> <td> <HR> </td>
    	<td> <HR> </td> <td> <HR> </td>
    	<td> <HR> </td> <td> <HR> </td>
    	<td> <HR> </td> <td> <HR> </td>
    	</tr>
    	</#if>
    	<#assign index=index+1>
    	</#list>
    	</table>
    	<br>
    	<#if (m_search_docs.startPage > 1)>
        <a href="${url.service}?keyword=${m_search_docs.searchTerms}&clientname=${m_search_docs.clientName}&startpage=0&count=${m_search_docs.itemsPerPage}"></#if>First
        <#if (m_search_docs.startPage > 0)></a></#if> |
        <#if (m_search_docs.startPage > 1)><a 
        href="${url.service}?keyword=${m_search_docs.searchTerms}&clientname=${m_search_docs.clientName}&startpage=${m_search_docs.startPage - 1}&count=${m_search_docs.itemsPerPage}"></#if>Prev
        <#if (m_search_docs.startPage > 0)></a></#if> | 
        <#if (m_search_docs.startPage < m_search_docs.totalPages)><a href="${url.service}?keyword=${m_search_docs.searchTerms}&clientname=${m_search_docs.clientName}&startpage=${m_search_docs.startPage +1}&count=${m_search_docs.itemsPerPage}"></#if>Next<#if (m_search_docs.startPage+1 < m_search_docs.totalPages)></a></#if> |
        <#if (m_search_docs.startPage < m_search_docs.totalPages)><a href="${url.service}?keyword=${m_search_docs.searchTerms}&clientname=${m_search_docs.clientName}&startpage=${m_search_docs.totalPages -	1}&count=${m_search_docs.itemsPerPage}"></#if>Last<#if (m_search_docs.startPage+1 < 	m_search_docs.totalPages)></a></#if>
    <#else>
        <i>No results to display.</i>
    </#if>
        </body>
    </html>
    
  2. Store the Web Script:

    To store this Web Script browse to Company Home > Data Dictionary > Web Script Extensions and create a folder named custdocuments. Store all the above three files here.

    Note

    Download the files from the Packt web site .

  3. Register the Web Script:

    Once you develop the Web Script, you need to register it for use. To do this, go to http://localhost:8080/alfresco/service/index.

    Click on the Refresh Web Scripts button. You will see a message showing how many Web Scripts were found and registered recently.

  4. List the Web Scripts for external access:

    Now you can use the Web Script that we developed, using the correct URL mentioned in the description document file. For our example, URLs are:

    http://<server_name>:<port>/alfresco/service/custdocuments/searchDocs.xml?keyword={keyword?}&clientname={clientName?}

    and

    http://<server_name>:<port>/alfresco/service/custdocuments/searchDocs?keyword={keyword?}&clientname={clientName?}

Calling the Web Script from external application

You can call this HTTP URL in the JSP of your web application, and can embed the HTML output returned by this Web Script in your JSP. You can also use the Web Script with XML output and process the returned XML in your application itself.

The following screenshot shows the XML output returned by this Web Script:

Calling the Web Script from external application

The next screenshot shows the HTML output returned by this Web Script:

Calling the Web Script from external application
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset