Wednesday, 31 July 2013

Conditional Transition in Liferay Workflow using default Kaleo Engine

Conditional Transition in Liferay Workflow using default Kaleo Engine



Loads of material is available on Liferay forums and Liferay WIKI on Workflow in Liferay. I do not intend to play  gimmick by replicating here. I intend to only illustrate how to do conditional transition. Before moving ahead with this blog entry of mine, please go through http://www.liferay.com/documentation/liferay-portal/6.1/user-guide/-/ai/creating-process-definitions first.
Use Case: There is single-approver-definition by default bundled with kaleo workflow engine in Liferay 6.x This default definition worked just fine for my client but with the only difference that if the content is created by a user having Administrator role, then it must NOT be kept pending for approval instead must automatically be considered as approved. And if any user with any role other than Administrator creates the content then it must go through the normal approval process i.e. review and then either reject or approve.
I must mention here that my knowledge of UML (especially statechart & activity diagrams) really helped when I had initially started with BPMN. Well without any further ado, let me illustrate how to achieve the above mentioned requirement.
Create a copy of single-approver-definition called my-workflow and add the following immediately after first state node named as "created"
<condition>
        <name>checkuser</name>
        <description>Checking whether the user is a portal admin</description>
        <script>
            <![CDATA[
           
                import com.liferay.portal.model.User;
                import com.liferay.portal.kernel.workflow.WorkflowConstants;
                import com.liferay.portal.service.UserLocalServiceUtil;
                import com.liferay.portal.model.Role;
                import java.util.List;
               
               
                String userId = (String) workflowContext.get(WorkflowConstants.CONTEXT_USER_ID);
                User user = UserLocalServiceUtil.getUser(Long.valueOf(userId));
                returnValue  = "review";
       
                 List<Role>  roles =  user.getRoles();
                 for (Role r : roles) {
                    println r.getName();
                    if (r.getName().equals("Administrator")) {
                      println "Setting approve for user :  " + user.getFirstName();
                      returnValue = "approve";
                      break;
                    }
                 }
           
                 println user.getFirstName() + " transitioning to : " + returnValue;
                
                 return;
           
            ]]>
        </script>
        <script-language>groovy</script-language>
        <transitions>
            <transition>
                <name>approve</name>
                <target>approved</target>
                <default>true</default>
            </transition>
            <transition>
                <name>review</name>
                <target>review</target>
            </transition>

        </transitions>

    </condition>
Explanation: A condition can have a script which when evaluated must have a value returned back. The name of the variable kaleo looks for is returnValue (normal groovy stuff I suppose). Based on some conditions you set the value in returnValue. Kaleo will do the transition to the value returned by the script. For e.g. if the value of returnValue is "xyz" then it will look for the transition called xyz.
In the script above, I am checking the role of the user logged on to the system. If the user has Administrator role then the value of returnValue is "approve" - this approve is the name of the transition defined withing the condition which is mapped to the target state called "approved". If the user is not Administrator then the transition happens to task called "review". Note that "approved" is the state and "review" is the task. Tasks require user input to proceed and "state" does not.
Res of the entire definition remains as is. I have attached the complete xml to this blog for direct use - my-workflow.xml

Simple Internationalization in Liferay

Simple Internationalization in Liferay


I will make it short and simple
  1. Create the language bundle in src/content folder with files like Language.properties, Language_ar_SA.properties etc.
  2. For portlet api to use this bundle so that it can set the title etc as per the language selected, you need to set this bundle in portlet.xml file using
      <resource-bundle>content.Language</resource-bundle>
    
      
  3. Then in bundle, you can set javax.portlet.title property for portlet to pick up based on the language selected.
  4. In jsps, for properties used in your use cases you can write the following:
      <fmt:setLocale value="<%=themeDisplay.getLanguageId() %>"/>
    
    <fmt:setBundle basename="content.Language" />
    
    <h1><fmt:message key="profile.label"/></h1>
    
  5. In your portlet class you can do the following:
         ThemeDisplay display = (ThemeDisplay) request
                    .getAttribute(WebKeys.THEME_DISPLAY)
       System.out.println(display.getLanguageId());
    
       ResourceBundle rb = ResourceBundle.getBundle("content.Language",
                    LocaleUtil.fromLanguageId(display.getLanguageId()));// LocaleUtil.fromLanguageId("ar"));
       String label = rb.getString("profile.label");
    
       System.out.println(label);

New Action in Hook in Liferay 6.1

New Action in Hook in Liferay 6.1


In one of my projects I needed to define a new action for a Mesage Board Portlet. Overriding the action class of an existing action is cake walk. However, creating a new action and then forwarding to a custom jsp is challenging. As mentioned in the post here : http://www.liferay.com/web/mika.koivisto/blog/-/blogs/7132115 I did create a new action and it did not work owing to ClassCastException for   com.liferay.portal.struts.ActionAdapter  . I could solve this problem but then the custom jsp that was included was not wrapped in the theme. Following are the steps to get the whole thing working:
  1. Do not extend your custom action class from BaseStrutsAction instead extend from BaseStrutsPortletAction class to avoid ClassCastException
  2. Now the jsp that you will return back from the render method in your Action class will take you to jsp but without wrapping it in to theme. In order to get this working, defined the same action in struts-config-ext.xml file, specify some Action class which is already there in core portal. Specify the forward of your own, map it to a custom tiles def of your own. Then create a file called tiles-defs-ext.xml file and define the custom tiles definition. forwarding to jsp that you created in hook.
  3. Restart the tomcat server. 
  4. Deploy your hook. 
Essentially what you are doing is that you are declaring action and tiles definition in struts-config-ext and tiles-defs-ext respectively and then overriding it through a hook.

AutoLogin and Custom Authenticator in Liferay

AutoLogin and Custom Authenticator in Liferay


Nothing can be simpler than implementing AutoLogin and Custom Authenticator in Liferay. Following is the "How-To"
  1. Create a Hooks Project
  2. Put the following properties in portal.properties file in your hooks project
    1. auth.pipleline.pre=com.mslc.authenticators.EMMAuthenticator
    2. auto.login.hooks=com.mslc.authenticators.EMMAutoLogin
    3. auto.login.ignore.paths=/web/guest.home  (optional)
  3. Then create the classes configured
  4. EMMAuthenticator must implement com.liferay.portal.security.auth.Authenticator
  5. EMMAutoLogin must implement com.liferay.portal.security.auth.AutoLogin
  6. EMMAuthenticator must return an int. If it returns Authenticator.SUCCESS then the authentication is passed or else if it returns Authenticator.FAILURE then it has failed.
  7. EMMAutoLogin must return a String[]. The array must contain 3 elements
    1. userId
    2. password
    3. true or false (string format ofcourse) to indicate whether the password is encrypted or not

Service Architecture on Liferay Project - Multiple service.xml file

Service Architecture on Liferay Project - Multiple service.xml file
Top of Form
12/20/12 8:35 AM
The best place to learn Liferay Architecture is the Liferay source code itself. When it comes to creating services in Liferay Usually people create one monolithic service.xml in docroot/WEB-INF folder. Well... that is not the right approach if the number of custom services you intend to develop is large. In one of my projects that I am currently working on, I have 10s of services. The best approach is to create one package structure for each service for e.g. com.mslc.projectname.conceptualnameofservice and create a service.xml file in this package. Different services will have different package structure. You can very well build these services exactly as same as you build services in WEB-INF folder; more conviniently if you have Liferay IDE.  Take a look at Liferay source code and scan through the service.xml files they have create in portal-impl/src folder under package structures like com.liferay.portal, com.liferay.portlet.blogs, com.liferay.portlet.journal etc.
So far so good. But then when you run build-wsdd target in order to generate the service-config.wsdd file in order to expose your service as web service, then you run into problems. By default the build-wsdd target looks for service.xml file in docroot/WEB-INF folder. As mentioned above, the service.xml file can be created in their respective package structure so we do not have service.xml file in docroot/WEB-INF which is expected by build-wsdd. So what do we do ? Here is the solution
1.     open sdk/build-common-plugin file
2.     search for target build-wsdd
3.     you will find one argument called wsdd.input.file in the line which looks like this:
            I.       
<arg value="wsdd.input.file=docroot/WEB-INF/service.xml" />
4.     Change the value to   ${service.input.file}  . This is how the line will look like after changes
    I.     <arg value="wsdd.input.file=${service.input.file}" />
Save the file and run build-wsdd on respective service.xml file. It works like a charm - it generates service-config.wsdd in WEB-INF folder perfectly for each service you build the wsdd for.

Transaction Management with Liferay Service

Transaction Management with Liferay Service


Following are the important points that a Liferay Architect must make note of in order to work with Transactions in Liferay
  1. The entry point to transaction (start of transaction boundary) in Liferay service is the <Entity>LocalServiceImpl class. Hence, while firing DML oriented methods like update, insert and delete on X Entity from Y do not use make calls to XLocalServiceUtil or XLocalService as this will result in two transaction boundaries - one for entity X and the other for entity Y. Relate the two entities through service.xml file (one to many or many to many based on your domain model) or else refer one entity in the other using <reference... in service.xml file. For e.g. if you want to make call on X entity from YLocalServiceImpl then in service.xml file while configuring Y Entity put

    <reference entity="X" package-path="com.company.project.X"></reference>

    On building the service, you will have access to xPersistence in YLocalServiceImpl. You can now make calls to xPersistence for update, insert and delete. <reference... tag is exactly for this reason. You can also include something like <reference entity="User" package-path="com.liferay.portal"></reference> to get the userPersistence object in your Entity. Then the calls to your entity and userPersistence will be the part of same transaction. In other words, updates to your tables and user_ table will be part of same transaction - either everything will commit or evrerything will be rolledback on encounter PortalException or SystemException.
  2. Ensure that your database supports transactions; yes ! this is needless to say but then if you are using MySQL, the database engine other MyISAM does not support transactions. You must use InnoDB as the database engine for your tables.
  3. As you know Liferay Entity code is generated by service builder and you get an interface called XLocalService. It is this interface which is marked with Transactional Annotation. It is set such that if you throw PortalException orSystemException from any of the methods, Hibernate Transaction Manager will rollback the transaction. Hence on violation of any business rule in the custom business-service method of XLocalServiceImpl if you want to rollback the transaction, you must throw either PortalException or SystemException

How to expose Finder methods from service to LocalServiceUtil in liferay portal

How to expose Finder methods from service to LocalServiceUtil in liferay portal 



In liferay portal if we want to find records from table then we need finder methods. To create finder method we need to specify the finder tag in the service.xml file.

Assume that we have a database table named customer having fields like name, city, age etc. We want to find all the customers belonging to a particular city.

Following are the steps to create finder method for the above requirement-

1.  In the service.xml file add the following line after database columns declarations,

<finder name=”City” return-type=”Collection”>
<finder-column name=”city”></finder-column>
</finder>

name– method name , a method named "findByCity" will be generated

Collection – return type
finder column name – name of the corresponding column in the customer table

2.  Run the ant target “ant build-service”. In the SampleUtil.java you will find the following finder -method –

public static java.util.List<com.sample.model.Sample> findByCity(
java.lang.String city) throws com.liferay.portal.SystemException {
return getPersistence().findByCity(city);
}

3.  Copy the finder method from this class and paste it inside theSampleLocalServiceImpl class and modify the method definition as following

-       Remove the static modifier

-       Replace getPersistence() with SampleUtil.

4.  Run the target “ant build-service” again. After build finder will be available in your SampleLocalServiceUtil class.

List<Sample> customerList = SampleLocalServiceUtil.findByCity(“cityname”);