Pattern for application services creation and integration

Do It The jAPS Way

Eugenio Santoboni

First and complete version in Italian 
Chief Solution Engineer
AgileTec s.r.l.

William Ghelfi

Porting to DocBook 4.5 and translation to English 
Chief Interaction Designer
Tzente s.r.l.

Matteo Minnai

English translation 
Junior developer
Tzente s.r.l.

Legal Notice

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the Appendix entitled "GNU Free Documentation License".

The copyright holders make no representation about the suitability of this Document for any purpose. It is provided “as is” without expressed or implied warranty. If you modify this Document in any way, identify your resulting Document as a variant of this Document.

2010-03-24

Revision History
Revision 1.12010-03-18MEM

Revision for the release of jAPS 2.0.10

Revision 1.02009-11-26MEM

English translation


Chapter 1. Scope of the document

Introduction

The aim of this document is to give a detailed description of the architectural model of jAPS 2.0 and the steps to follow to create a new application service.

Target audience

This document is for developers aiming to build a new Application Service su jAPS 2.0.

Prerequisites

In order to take the maximum advantage of the present document, it is necessary to have a basic knowledge about: the Java platform, the Eclipse IDE, the Apache Tomcat servlet container, the PosgreSQL DBMS and the jAPS 2.0 framework.

Resources

Additional informations may be obtained through the following mailing-lists:

Is it also possible to refer to the documentation found in the:

jAPS 2.0 Project - Developer Website

Chapter 2. Introduction

We define the jAPS Manager as a part of the jAPS Core which implements a basic system funtionality. A jAPS Manger is also the main handler of that particular functionality.

The main services belong to one of the following groups:

Basic services:

  • AuthenticationProviderManager: authenticator service..

  • BaseConfigManager: configuration service. Load the configuration parameters from system database, making it available to the invoker.

  • CacheManager: cache handler service.

  • CategoryManager: category handler service.

  • ControllerManager: this service supervises the execution of a request coming from the client.

  • GroupManager: group handler.

  • I18nManager: this service returns the localized strings upon request

  • KeyGeneratorManager: this service superintends the generation of primary keys

  • LangManager: this service handles the various languages of the system

  • NotifyManager: event notification dispatcher service

  • PageManager: page handler

  • PageModelManager: this service handles the various page models

  • RoleManager: role manager

  • ShowletTypeManager: this service manages the showlets (ShowletTypes) types defined in the system

  • UrlManager: this manager creates a URL to page of the Portal from essential informations.

  • UserManager: account manager

CMS services (served by the jACMS plugin):

  • ContentManager: contents manager

  • ContentPageMapperManager: this service manages the map of the contents published in the pages of the portal

  • LinkResolverManager: this manager resolves the symbolic links

  • ResourceManager: resources (audio, video, images etc.) handler

  • SearcheEngineManager: this service creates the indexes of all the objects which will be later parsed by the search engine.

The services defined in the system are initialized during system start-up through the Factory provided by the Spring Framework.

It's important to underline that each service has one and only one instance. The invocation of a service can be obtained in either two ways: through the "Dependency Injection" technique favored by Spring or using the appropriate elements of the system like ApsWebApplicationUtils. Every jAPS manager is described through a specific interface and every object class access a service always using the appropriate interface, never invoking the class directly.

The manager (o jAPS Manager) is the only linking point between the system data -whatever their origin is- and the functionality which use them. An example of service is the PageManager which manages the tree of the portal pages. Every operation involving the pages, such as addition, removal, displaying and so on is handled by the PageManager.

Chapter 3. Architectural model of the jAPS 2.0 framework

Architectural model of the jAPS 2.0

Architectural model of the jAPS 2.0

To fully understand this document it's necessary to describe the architectural model of jAPS: jAPS is mainly composed by 3 layers:

  • Data Access Layer: It is composed by all the elements which superintend the Persistence Layer. The main component are the DAO classes (Data Access Object) which are the only linking element between the framework and the data sources (Database, Filesystem, LDAP service directory etc.)

  • Business Layer: This is the core of the system. Here the concept of jAPS service as manager of every macro functionality, takes place. This layer is built upon the Spring Framework, whose listener, during the system start-up, initializes all the services and injects them in the web application context as beans. The Business Layer utilizes the Data Access layer to get the data needed, gives to the higher layer (the Presentation layer) the elements to display and supports it in the execution of actions.

  • Presentation Layer: The aim of this layer is to build the graphic interfaces which represent the mean through which the users interact with the system. This layer gives a pure View layer (that is, a jsp without any business logic) and a "slim" controller (which checks the consistency of the data submitted and serves the data produced); both of them provide support to the layer below, the Business Layer. In the jAPS framework this layer is divided in two parts: the Portal View (referred as Front-end) and the Administration View (Back-end). These views, which differs by functionality and architecture, are completely independent from each other.

Every application service must be developed in the total respect of the architectural schema above, placing every part in the right layer. The presence of the elements of the new service in all of the three layers depends on characteristics of the service itself. The typical service which needs the usual addition, removal, editing and searching operations will have elements in each layer - take as reference the "Personal Card" management service explained further in this document and found implemented in the "Portal Example" demo. Moreover the "Personal Card" service has customized elements in the "View" layer, both in the Portal and the Administration area. The LDAP plugin, on the contrary, has elements in the Business layer only.

Portal View

This is the part of the presentation layer where the results of the queries to system services are displayed mainly through the Showlets. Showlets are the preferred method to use to make the system services interact with users. The tasks of the Portal View are to provide services based on the current user permissions (every element of the Portal Layer incorporates the rules which govern the access to services) and to serve content as fast as possible (using content caching mechanism). The portal view is handled by a specialized servlet (ControllerServlet) whose primary target is to invoke a precise succession of services (coherency of the URL, user privilege checks etc) which will finally result in the rendering of the requested page.

Administration View

This is the area reserved for administration of the various elements of the Portal (Pages, Contents, Resources etc.) whose access is reserved to a restricted pool of users. The view of the Adminstration Area, comprehensive of the controller logic) has been completely redesigned: the reference framework, firmly tied to the Spring framework, is now Struts2. The View has been modified to met the (Italian) Public Administration requisites of accessibility - taking as a firm point the respect of all the W3C standards.

Distribution of the components of the system layers

The source files, with the exclusion of the test packages and certain supporting elements (eg. the static resources and the templates directories etc.), are enclosed in two packages:

  • com.agiletec.aps : here can be found all the elements of the Data Access Layer, Business and presentation Layer (the last limited to the Portal View only)

  • com.agiletec.apsadmin : this package contains all the elements need to manage the presentation layer of the Administration View

A similar division exists in the directory WEB-INF of the web application: here are contained, including the supporting folders, the usual aps (which contains all the jsp and the tld files of the Portal View layer) and apsadmin (containing all the jsp files belonging to the Administration Area).

Chapter 4. How to create a jAPS2 service

The following paragraphs explain in detail how to create a new service in the jAPS 2.0 framework.

The main objective of the present document is to allow the jAPS-Developers a fast development of new services to integrate with existing ones, without modifying the Base Core sources (java classes, jsp files, configurations, etc).

Business Layer and Data Layer

During the process of the creation of a new service, the following procedure starts from the implementation of the Business and Data Layer of the new functionality.

Active elements: the classes involved are <NAME_OF_THE_HANDLED_OBJECT>Manager (the name of the service) which must extend the AbstractService class. In a similar manner, if the DAO classes are needed, the <NAME_OF_THE_HANDLED_OBJECT>DAO must extend the AbstractDao class.

Implementation

Create the package, external to the core classes, respecting the same schema used by the core.

Example 4.1. Package Manager Card

If the new service is called Card, the resulting name will be it.projectname.aps.system.services.card.


Create an interface, namely Firma del Servizio, which respects the following syntax I<NAME_OF_THE_HANDLED_OBJECT>Manager.

Example 4.2. name of the Manager Card

ICardManager


This interface includes all the public methods (and the costants, if present) of the service which will be accessible from the outside. Every use of the implemented methods must happen through the invocation of this interface.

Create the class of the service <NAME_OF_THE_HANDLED_OBJECT>Manager which extends in turn the AbstractService and implements the methods declared in the interface seen before.

Example 4.3. Manager Card class


public class CardManager extends AbstractService implements ICardManager {
	....
}


Take care to implement the init method of the abstract service (which allows the correct initialization of the service), and the methods declared in the interface properly

Example 4.4. Implementation of the init method


/**
 * Service initialization
 */
public void init() throws Exception {
	.....
}


Add, in the class (or interface) <PROJECT_NAME>SystemConstants contained in a sub-package aps.system of the project, the constant <NAME_OF_THE_HANDLED_OBJECT>_MANAGER which uniquely identifies the name of the service within the project.

Example 4.5. Definition of the name of a manager through a constant


public interface MyProjectSystemConstants {
	
    public static final String CARD_MANAGER = "CardManager";
	
	.......
	
}


Add the service in a new configuration file, which will be later parsed by Spring. The configuration files must be inserted in a directory under the /WEB-INF/<PROJECT_NAME>/conf/ following the same pattern used for the configuration files of the core.

The new Manager must be inserted in the Spring context using a syntax similar to the one shown below:


<bean id="CardManager" 
		class="it.projectname.aps.system.services.card.CardManager" 
		parent="abstractService" >
</bean>

where the id is the value of the constant defined previously.

Important

Care must be taken in the definition of the bean since it must not match any other existing ids in the system unless we intend to extend an existing service on purpose.

Make the system aware of the new service by instructing Spring to load every xml file in the configuration directories of your service. This is typically done editing the /WEB-INF/web.xml and adding to the xml attribute param-value of the parameter contextConfigLocation the file pattern string WEB-INF/<PROJECT_NAME>/conf/**/**.xml. This definition must be added in the last position. The same pattern must be inserted in method getSpringConfigFilePaths of the class test.com.agiletec.aps.ConfigUtils. This class is used to setup the proper environment for the test suites; again, the definition must be placed in the last position.

If the new service uses a DAO (Data Access Object) so that it adds new elements in the Data Layer, the first thing to do is to crate an interface Firma del DAO using this declaration I<NAME_OF_THE_HANDLED_OBJECT>DAO and add, in the class which implements that interface, an instance variable of the same type of the newly created one. This variable must have both getter and setter, with the former being rigorously public.

Example 4.6. Methods signature


public void setCardDao(ICardDAO cardDao);
protected ICardDAO getCardDao();


Create the DAO class <NAME_OF_THE_HANDLED_OBJECT>DAO which implements the interface just created. If we are willing to use a standard JDBC, the class DAO just created must extend the class AbstractDAO.

Example 4.7. DAO Class


public class CardDAO extends AbstractDAO implements ICardDAO {
	....
}


Inject the new DAO in the bean of the service previously described.

Example 4.8. Full definition of the Manager


<bean id="CardManager" 
		class="it.projectname.aps.system.services.card.CardManager" 
		parent="abstractService" >
    <property name="cardDao">
        <bean class="it.projectname.aps.system.services.card.CardDAO" >
            <property name="dataSource" ref="dataSourceBeanName" />
        </bean>
    </property>
</bean>


NOTE: inject the datasource having care to choose the proper reference between the default "portDataSource" or "servDataSource" (which always exist in a jAPS installation) and the new data sources eventually created for the new service.

jUnit tests for the Data Layer and Business Layer

Every service in the DAO must be tested in its public methods. In other words it's necessary to:

  • create a java class named <PROJECT_NAME>ConfigUtils (in the package test.it.projectname) which extends the class ConfigUtils; the methods getSpringConfigFilePaths and closeDataSources must be extended as well. The former provides the path for the configuration files of the new service needed by Spring, the latter handles the database connection closure of the new datasources.

  • create a java class <PROJECT_NAME>BaseTestCase (in the package test.it.projectname.aps) which extends the class test.com.agiletec.aps.BaseTestCase. Override the method getConfigUtils so that it returns an instance of <PROJECT_NAME>ConfigUtils (that is, the class previously created).

  • Create the test classes Test<NAME_OF_THE_HANDLED_OBJECT>Manager and, if needed, the Test<NAME_OF_THE_HANDLED_OBJECT>DAO in the package test.it.projectname.aps.system.services.<NAME_OF_THE_HANDLED_OBJECT> Such classes must extend the classes previously created. Remember to test all the public methods of the new service.

To check a service we have obviously to invoke it in every test class; this is done with the following code:


ImyServiceManager myServiceManager = 
	(ImyServiceManager) 
	this.getService(MyProjectSystemConstants.MY_SERVICE_MANAGER);

To test a DAO is necessary to create it as Spring does, passing to it the datasource and as every requested bean.


DataSource dataSource = (DataSource) 
	this.getApplicationContext().getBean("dataSourceName");
MyServiceDAO myServiceDao = new MyServiceDAO();
myServiceDao.setDataSource(dataSource);

Two databases, namely jAPStestPort and jAPStestServ, are provided for testing purposes. They reflect their "production" counterparts, the jAPSPort and jAPSServ. If the new service requires additional databases they all must have a test and a production version as well.

For every method of the service to test a corresponding method in the appropriate test class must be created:


public void testNomeMetodoDaTestare() {
	........
}

When creating test methods it's important to plan the restore of the data in the state they were prior the execution of the test(s), whatever the result is. This assures the coherence and the correctness of the following test. You don't want a failed test to cause a succession of failures in different classes which previously were just fine.

How to extend existing jAPS-Managers

If the newly born service alters existing managers (by either integrating or modifying functionalities) you are strongly advised to avoid modifying the core! Create inside the package it.projectname.aps.system.services of your project, a new manager which extends the existing one. In the Spring configuration file of your service the id of the service must perfectly match the one of the existing service (of the core of jAPS) that we are going to extend.

Example 4.9. Extension of the User Manager using the same id of the core service (UserManager)


<bean id="UserManager" 
		class="it.projectname.aps.system.services.user.UserManager"
		parent="abstractService" >
	<property name="userDAO" >
		<bean class="it.projectname.aps.system.services.user.UserDAO">
			<property name="dataSource" ref="servDataSource" />
		</bean>
	</property>
	<property name="configManager" ref="BaseConfigManager"/>
</bean>


In the previous example, the new bean id UserManager substitutes, having the same name, the one of the core of jAPS. Remember to insert all the properties found in the declaration of the core bean in the new one.

Presentation Layer - Administration Area

The most of the Application services will need an administration interface. In the core of jAPS, the class which superintend the interface mechanism are all grouped inside the package com.agiletec.aspadmin. This package in turn contains other sub packages organized (and separated) by functionality; each serves a well determined function whose controls are displayed in the Administration Area. The new service must present the sources to manage the back-end interfaces developed following the same structure used in the core.

Implementation

Create the package -outside the Core path!- respecting the schema used in jAPS 2.0, as stated earlier.

Example 4.10. Create a package for the Action classes for the Card service

Suppose to have the need to create Actions to handle the Cards (defined in the homonym class): the resulting name of the package will be: it.projectname.apsadmin.card.


Crate the java interface Firma delle Action which respectes the syntax I<NAME_OF_THE_HANDLED_OBJECT>Action.

Example 4.11. Package containing the class Action for Card management

ICardAction.


This interface presents all the public methods and eventually the constants, which will be implemented in the service class. Every method presented in the interface is an action which can be executed.

If our service provides some search function of the object handled by the service we have to create an additional java interface, namely I<NAME_OF_THE_HANDLED_OBJECT>FinderAction. This is the gate to the finder action class.

Create the action class named <NAME_OF_THE_HANDLED_OBJECT>Action which extends the BaseAction and implements the interface above. If needed, create the finder action class which manages the search operations.

Any action class must have a corresponding Spring configuration file; the syntax to use is close to the one shown in the example below.

Example 4.12. Definition of the action bean


<bean id="cardAction" scope=”prototype” 
		class="it.projectname.apsadmin.card.CardAction" 
		parent="abstractBaseAction" >
</bean>


Important

The scope of the bean of the action classes must be "prototype" and care must be taken when defining the bean: it must not match any other bean id of the core, unless we are extending an existing service, as we have already seen.

Insert the configuration file in a directory named /WEB-INF/<PROJECT_NAME>/apsadmin/conf/.

Once again, make spring aware of the new action by adding the followin string WEB-INF/<PROJECT_NAME>/apasadmin/conf/**/**.xml in the xml attribute param-value of the parameter contextConfigLocation located in the file /WEB-INF/web.xml. This definition must be placed in the last position.

Create, at the same level of the interfaces and classes, a xml file which contains the definitions of the actions previously implemented. These definitions follow the Struts2 rules; there is one definition for every action which can be triggered by users from the user interface.

Example 4.13. Action definitions in the file card.xml


<struts>
<package name="portalExample_do/Card" 
		namespace="/do/Card" extends="japs-default">
	<action name="list" class="cardFindingAction">
		<result type="tiles">admin.Card.list</result>
		<interceptor-ref name="japsDefaultStack">
			<param name="requestAuth.requiredPermission">superuser</param>
		</interceptor-ref>
	</action> 
	......
	<action name="edit" class="cardAction" method="edit">
		<result type="tiles">admin.Card.entry</result>
		<interceptor-ref name="japsDefaultStack">
			<param name="requestAuth.requiredPermission">superuser</param>
		</interceptor-ref>
	</action>
	....
</package>
</struts>


Note: the name of the Struts2 package must present as prefix the name of the project.

Make use of the stack interceptors defined in the file struts.xml:

  • japsDefaultStack: this is the default for the actions of the Administration view which need specific permissions to be executed (eg. check for the user permission when accessing the Administration area). This stack does not enforce validation or range check of the submitted parameters. This stack needs the explicit declaration of the permission needed to execute the action in the requiredPermission tag.

  • japsValidationStack: extension of the japsDefaultStack with the addition of validation checks.

  • japsFreeStack: This stack is to be used for actions both internal and external to the Administration area, which require neither permission nor validation checks.

  • japsFreeValidationStack: Extension of the japsFreeStack stack with validation check enabled.

Create at the same level of the java interface and action classes the appropriate xml files to define the kind and the number of validation checks to perform. These validation files follow the Struts2 syntax for the validation.

Create a new <PROJECT_NAME>-struts.xml in the root of the source files or, in other word, in the same level of the directory where the struts.xml resides. This file must contain all the references to the configuration files of the new actions of the project.

Example 4.14. Example of actions definition in the file PortalExample.xml


<struts>
	<include file="it/myprojectname/apsadmin/card/card.xml"/>
</struts>


The xml file containing the definitions of the various actions of the project must be declared in the parameter Struts2Config within the /WEB-INF/web.xml file. As always the definition must be inserted in the last position.

Internationalization and localization

The property files reside in the same directory of the newly created Action classes; theese files provide support for the Internationalization (i18n). These file must follow strictly the rules as specified in documentation released in the Struts2 framework website.

In the properties files must be inserted not only the static labels of the jsp files of the user interfaces, but all the labels correlated to the validation support. These labels must be provided for both English and Italian language (the file package_it.properties and package_en.properties serve this purpose).

As for the id of the service beans, the keys of the labels must not match any of the common resources keys contained in the files global-messages_en.properties and global-messages_it.properties.

To avoid problems, you are encouraged to subdivide the label in the following groups:

  • on menu basis

  • per titles (h1 e h2)

  • static strings of the jsp files

  • string used by the validation files

Testing Actions with jUnit

Create the proper environment and the classes to test new newly created actions. In other words:

  • create a java class named <PROJECT_NAME>ConfigUtils (or use the class used to test the manager methods) which extends the class ConfigUtils; the methods getSpringConfigFilePaths and closeDataSources must be extended as well. The former provide the path for the configuration files of the new service needed by Spring, the latter handles the database connection closure of the new datasources.

  • Create a java class <PROJECT_NAME>ApsAdminTestCase (inside the package test.it.projectname.apsadmin) which extends the class test.com.agiletec.apsadmin.ApsAdminTestCase, then override the method getConfigUtils (so that it returns an instance of the class previously created) and the setInitParameters (so to load the definition of your actions and all those defined in the same level of the struts.xml)

  • Create the Action classes named Test<NAME_OF_THE_HANDLED_OBJECT>Action which extends the class of the previous step. If needed create the test class of the action which uses the search engine of your service; always test all the Actions!

Creation of the jsp for the Administration area

All the jsp files composing the user interfaces are located in the directory /WEB-INF/<PROJECT_NAME>/apsadmin/jsp/.

Example 4.15. jsp of the card manager service

  • cardFinder.jsp: this is the interface for the search card service; the search itself is handled by the Action class CardFinderAction.

  • entryCard.jsp generates the Card add/remove interface, handled by the Action class CardAction.


The (jsp) interfaces must be declared inside the template called main.layout in the file /WEB-INF/apsadmin/tiles.xml which specifies the configuration of the pages being invoked as a result of the action. Such configuration must obey the rules of Tiles2, a Struts2 plugin.

Define a new Tiles configuration file for the pages, <PROJECT_NAME>-tiles.xml inside the folder /WEB-INF/<PROJECT_NAME>/apsadmin. The pages must extend the main.layout and the single ids represent the result (in the form of tiles type) of every action. The tiles configuration must be declared within the parameter org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG of the descritptor file web.xml of the web application. Again, it must be placed in the last position.

Creation of a new voice in the Administration Area

To add a new element in the Plugin menu create in the directory /WEB-INF/<PROJECT_NAME>/apsadmin/jsp/common/template/ a file named subMenu.jsp which contains the new menu item referring to the new application service (a plugin, in this case) Then create a new bean (a Spring Object) with id <SERVICE_NAME>SubMenu which refers to the class PluginSubMenuContainer; this class has a property called submenuFilePath whose value is the path of the subMenu.jsp just created.

Example 4.16. Declaration of the Menu


<bean id="cardPluginSubMenu" 
		class="com.agiletec.apsadmin.system.plugin.PluginSubMenuContainer" >
	<property name="subMenuFilePath">
		<value>/WEB-INF/demo/apsadmin/jsp/common/template/subMenu.jsp</value>
	</property>
</bean>


Following carefully these steps the new menu item will be included in the Plugin menu in the administration area.

Modify the existing Administration area interfaces

If the Application service is going to modify exinsting interfaces for any reason (eg. integration of new modules, link or whatever) you are adviced to avoid any modification of the Core interfaces. Create instead in the tiles configuration file <PROJECT_NAME>-tiles.xml a new definition with the same name of the core interface to override. So the element to modify is simply rewritten from scratch.

Example 4.17. Redefinition of the "Pages Tree" interface

copy the following definition in the files <PROJECT_NAME>-tiles.xml:


<definition extends="main.layout" name="admin.Page.viewTree">
	<put-attribute name="title" value="title.pageManagement" />
	<put-attribute name="extraResources" 
		value="/WEB-INF/apsadmin/jsp/common/template/extraresources/pageTree.jsp" />        
	<put-attribute name="body" 
		value="/WEB-INF/<PROJECT_NAME>/apsadmin/jsp/page/pageTree.jsp" />
</definition>

where the admin.Page.viewTree is the id of the interface of the page tree handler.


The path of the jsp must be the same of the jsp files of the interface to extend with the solely exclusion of the root directory of your project.

Nei limiti del possibile, è sconsigliato utilizzare questa tecnica; nel caso di inserimento nuove funzionalità che integrano alcune preesistenti, è consigliato utilizzare la tecnica dei SubMenu dei Plugin per creare gli EntryPoint della funzionalità. Whenever it's possible please follow these directions; if the new service adds some new functionality extentending the existing ones, a good practice is to use the submenu technique used for the plugins so to create the entry point for the new service.