Wednesday, June 8, 2011

How to Write java Unit Test class and Run

normally.................you can download junit.jar file and add to the project.

But in maven project, You should add the following dependency for download junit.jar file

    <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>


This is small Testing Example...................................




import java.util.ArrayList;
import java.util.List;

public class StringConverter {


    /*if input is String List, you can get Comma seperated String by using this method*/

    public String convertToString(List<String> stringList) {

        StringBuilder concatanatedString = new StringBuilder();
        for(String string : stringList) {
            concatanatedString.append(string);
            concatanatedString.append(",");
        }
        String commaSeperatedString;
        try{
        commaSeperatedString = concatanatedString.toString().substring(0,
                concatanatedString.toString().length() - 1);
        }catch (Exception e){
            commaSeperatedString ="";
        }
        return commaSeperatedString;


    }


    /*if input is comma seperated string, you can get String List by using this method*/

    public List<String> convertToSet(String commaSeperatedList) {
       String[] StringArray = commaSeperatedList.split(",");
       List<String> stringList = new ArrayList<String>();
       for (int i = 0; i < StringArray.length ;i++){
          stringList.add(StringArray[i].trim());
       }
       return stringList;

    }

}


This unit Testing class for StringConverter......................
@BeforeClass ------------------> Setup all variable
@Test---------------------------> run test method.............


import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.testng.Assert;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class StringConverterTest {

    private StringConverter converter;

    private List<String> List1;
    private String stringComma;

    @BeforeClass
    public void setup() {
        converter = new StringConverter();
        List1 = new ArrayList<String>();
        List1.add("st1");
        List1.add("st2");
        List1.add("st3");
        List1.add("st4");
        List1.add("st5");
        List1.add("st6");
        stringComma = "aa,bb,pp,dd,ee,ff,mm";
    }

    @AfterClass
    public void tearDown() {

    }

    @Test
    public void testConvertToStringSuccess() {
        String out = converter.convertToString(List1);
        Assert.assertEquals("st1,st2,st3,st4,st5,st6", out);
    }

    @Test
    public void testConvertToListSuccess() {
        List<String> stringList = converter.convertToSet(stringComma);
        Assert.assertEquals("aa", stringList.get(0));
        Assert.assertEquals("pp", stringList.get(2));
        Assert.assertEquals("ee", stringList.get(4));
        Assert.assertEquals("mm", stringList.get(6));
    }

}


If you want to run single test you can use following command
mvn clean -Dtestcase=<testcase-class-name> test:single

If you want to run all test case, you can use
mvn clean install





Dileepa Sisila Chandrasekera
Computer Science & Engineering
University of Moratuwa
Trainee at hsenid mobile solution (pvt) Ltd.













Tuesday, June 7, 2011

How to add a User to Liferay Database or lportal Manualy

Example Java program:

import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.NoSuchRoleException;
import com.liferay.portal.NoSuchUserException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.model.*;
import com.liferay.portal.security.auth.AutoLogin;
import com.liferay.portal.security.auth.AutoLoginException;
import com.liferay.portal.service.*;
import com.liferay.portal.util.PortalUtil;


public Class AddUser implements AutoLogin{



    public void liferayUserManuallyAdding(String userName, long companyId){
       
        /*These all ids are created by Using CounterLocalServiceUtil class.
        Like  (userId =1 , contactId =2, groupId =3 ) */       
               
            long userId = CounterLocalServiceUtil.increment();
            long contactId = CounterLocalServiceUtil.increment();
            long groupId = CounterLocalServiceUtil.increment();
            long publicLayoutSetId = CounterLocalServiceUtil.increment();
            long privateLayoutSetId = CounterLocalServiceUtil.increment();
           
        /*Create User and set the parameters for User attributes*/
       
            User user1 = UserLocalServiceUtil.createUser(userId);
            user1.setCompanyId(companyId);
            user1.setContactId(contactId);
            user1.setFirstName(username);
            user1.setLastName(coopUserId);
            user1.setEmailAddress(username + "@email.com");
            user1.setScreenName(username);
            user1.setActive(true);
       
        /*Add User to lportal database*/

            UserLocalServiceUtil.addUser(user1);

        /*Following methods are very Important.........whithout following methods we can't add user*/       
       
        /*Create contact and set the contact parameters and add */

            Contact contact1 =ContactLocalServiceUtil.createContact(contactId);
            contact1.setCompanyId(companyId);
            contact1.setUserId(userId);

                 contact1.setAccountId(AccountLocalServiceUtil.getAccounts(0,1).get(0).getAccountId());
            contact1.setFirstName(username);
            contact1.setLastName(coopUserId);
            ContactLocalServiceUtil.addContact(contact1);

        /*Create Group and set the Group parameters and add*/           
       
            Group group = GroupLocalServiceUtil.createGroup(groupId);
            group.setCreatorUserId(userId);

                group.setClassNameId(ClassNameLocalServiceUtil.getClassNameId("com.liferay.portal.model.User"));
            group.setClassPK(userId);
            group.setActive(true);
            group.setCompanyId(companyId);
            group.setName("" + userId);
            group.setFriendlyURL("/" + username);
            GroupLocalServiceUtil.addGroup(group);

        /*Create PublicLayoutSet and set the PublicLayoutSet parameters and add*/

            LayoutSet publicLayoutSet =        LayoutSetLocalServiceUtil.createLayoutSet(publicLayoutSetId);
            publicLayoutSet.setCompanyId(companyId);
            publicLayoutSet.setGroupId(groupId);
            publicLayoutSet.setThemeId("classic");
            publicLayoutSet.setColorSchemeId("01");
            LayoutSetLocalServiceUtil.updateLayoutSet(publicLayoutSet);


        /*Create PrivateLayoutSet and set the PrivateLayoutSet parameters and add*/

            LayoutSet privateLayoutSet = LayoutSetLocalServiceUtil.createLayoutSet(privateLayoutSetId);
            privateLayoutSet.setCompanyId(companyId);
            privateLayoutSet.setGroupId(groupId);
            privateLayoutSet.setThemeId("classic");
            privateLayoutSet.setColorSchemeId("01");
            privateLayoutSet.setPrivateLayout(true);
            LayoutSetLocalServiceUtil.updateLayoutSet(privateLayoutSet);


    }

}





Dileepa Sisila Chandrasekera
Computer Science & Engineering
University of Moratuwa
Trainee at hsenid mobile solution (pvt) Ltd.

Sunday, June 5, 2011

How to Create a Liferay Hook using Liferay SDK


Hooks can fill a wide variety of the common needs for overriding Liferay core functionality. Whenever possible, hooks should be used in place of Ext plugins, as they ar hot- deployable and more forward compatible. Some common scenarios which require the use of a hook are the need to perform custom actions on portal startup or user login, overwrite or extend portal JSPs, modify portal properties, or replace a portal service with your own implementation.
Creating a Hook

1.     First go to the hook directory in liferay sdk…..(before see how to configure buld.xml for ant in previous one how to create portlet and theme)
2.     Then using this command you can create a hook.
(./create.sh example "Example" -----------------à on Linux
create.bat example "Example" -------------------à on Windows)
3.     You should get a BUILD SUCCESFUL message from Ant, and there will now be a new folder inside of the hooks folder in your Plugins SDK. Notice that the Plugins SDK automatically appensds “-hook” to the project name when creating this folder.
4.     Deploying hooks first go to hooks/example-hook directory using Terminal or command prompt. Then enter this command for deploying to liferay server.
(ant deploy) (in build($username).properties should be configured)
5.     You should get a BUILD SUCCESSFUL message, which means that your hook is now being deployed. If you switch to the terminal window running Liferay, and wait for a few seconds, you should see the message “Hook for example-hook is available for use.”

Then Show how to performing custom action

1.     First, create the directory example-hook/docroot/WEB-INF/src/com/sample/hook, and create the file LoginAction.java inside it with the following content.


package com.sample.hook;

import com.liferay.portal.kernel.events.Action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginAction extends Action {

public void run(HttpServletRequest req, HttpServletResponse res) {
System.out.println("## My custom login action");


}


}

2.     Next, create the file portal.properties inside example-hook/docroot/WEB-INF/src with following content.
login.events.pre=com.sample.hook.LoginAction

3.     Finally, edit liferay-hook.xml inside example-hook/docroot/WEB-INF

4.     Enter this line between <hook></hook> tabs.

<portal-properties>portal.properties</portal-properties>

5.     Deploy your hook again and wait for it to complete. Then log out and back in, and you should see our custom message in the terminal window running Liferay.




Dileepa Sisila Chandrasekera
Computer Science & Engineering
University of Moratuwa
Trainee at hsenid mobile solution (pvt) Ltd.

Saturday, June 4, 2011

How to create portlet and theme using Liferay SDK 6.0 plugin


1.      Download the Plugins SDK from http://www.liferay.com/web/guest/downloads/additional
2.      Unzip the ZIP file to your destination of choice. I'll refer to it from now on as $PLUGINS_SDK
Like (export PLUGINS_SDK = /home/…../liferay-sdk-6.0/)
if Linux , include this in bash_profile or in windox , include this in environment variable

3.     Create a file named $PLUGINS_SDK/build.${user.name}.properties where ${user.name} is the name of the user in your system. In that file you can overwrite the values of any of the properties in the $PLUGINS_SDK/build.properties file. Some common properties that are overridden (with example values) are:
app.server.dir=/my-dir/appservers/liferay-portal-tomcat-jdk5-trunk auto.deploy.dir=${user.home}/liferay/deploy
app.server.lib.portal.dir=/my-dir/liferay/trunk/portal-web/docroot/WEB-INF/lib app.server.portal.dir=/my-dir/liferay/trunk/portal-web/docroot
4.      Install Apache Ant and make sure that ANT_HOME/bin is in your path to be able to build and package your work.
Like (export ANT_HOME = home/……/ant)
5.      If you want to create portlet, you can go portlet directory in liferay sdk using terminal or command prompt. If you want to create Theme, you can go theme directory in liferay sdk using terminal or command prompt.
6.      Now you can see create.sh file in the folder. First, you give the permission to execute for this file. Like (chmod +x create.sh). if it is not working using this command you can convert linux format. (dos2unix create.sh) after that give the permission.
COMMON TASK…………………………..
These tasks are common for every plugin….
·        Compile the sources (applicable only to portlets): (ant compile)
·        Create a WAR file of the plugin : (ant war)
·        Deploy the plugin (to the path confibured in the auto.deploy.dir property of the $PLUGINS_SDK/build.${user.name}.properties file)  : (ant deploy)

Creating a new theme
Go to the $PLUGINS_SDK/themes folder and enter this command
·        on windows-----------à create newtheme "My New Theme"
·        on Linux ------------à ./create.sh newtheme "My New Theme"
 
Where newtheme is the name of the folder for your theme and "My New Theme" the display name
  • Navigate to the newly created $PLUGINS_SDK/themes/newtheme/_diffs and add some customizations to the default theme.  You can edit .css file according to your choice
  • Issue 'ant all' in the $PLUGINS_SDK/themes folder to build and deploy.
  • Log in into Liferay and check out your new creation.

Creating a new portlet

Go to the $PLUGINS_SDK/portlets folder and enter this command
·        on windows-----------à create newportlet "My New portlet"
·        on Linux ------------à ./create.sh newportlet "My New portlet"
 
Where newportlet is the name of the folder for your portlet and "My New Portlet" the display name
 
  • Issue 'ant all' in the $PLUGINS_SDK/portlets folder to build and deploy
  • Log in into Liferay and check out your new creation
 
 
 
 
Dileepa Sisila Chandrasekera
Computer Science & Engineering
University of Moratuwa
Trainee at hsenid mobile solution (pvt) Ltd.
 

Friday, June 3, 2011

Integrating Liferay with CAS Server -------Single Sign On


1.      Go to this path ( liferay-portal-6.3.0.0\tomcat-6.0.24\conf ) and open the server.xml file. Uncomment the SSL connections and open port 8443 for build connections https.
<!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the JSSE configuration, when using APR, the
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->
    <!--
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->
Red color things should be uncommented for open the port 8443.
2.       Download the latest available version of the Liferay-portal-cas-4.3.x.war file from www.liferay/web/guest/downloads.
3.       Rename the download file to cas-web.war.
4.       Copy the cas-web.war file and paste it to the Tomcat webapps (liferay-portal-6.3.0.0\tomcat-6.0.24\webapps) directory.
5.       Then To download the Yale CAS Client 2.0.11 go to http://downloads.jasig.org/cas-clients/ and download cas-client-2.0.11.tar.gz or zip(for windows)
6.       Extract the above file and open the folder and navigate to the casclient jar file (cas-client-2.0.11\java\lib).  
7.       Copy the file for Go to the lib file in Tomcat (liferay-portal-6.3.0.0\tomcat-6.0.24\webapps\ROOT\WEB_INF\lib) and paste the casclient jar file to replace the existing one.
The next steps are very important steps. It is described how to generate https key.
1.       In the command prompt or linux terminal go to the ROOT (liferay-portal-6.3.0.0\tomcat-6.0.24\webapps\ROOT) directory.
2.       Enter this command for generate the key…….
keytool -genkey -alias tomcat -keypass changeit -keyalg RSA
3.       Enter changeit for the password.
4.       Answer the list of questions. Note that the first and last name must be the host name of your server and cannot be an IP address. This is very important because an IP address will fail client hostname verification even if it is correct. So example give the (localhost).
5.       No need to give answer for other questions…………when questions are finished, finally give the (yes).
6.       Enter the following command to export he cert you generated from your personal keystore:keytool -export -alias tomcat -keypass changeit -file server.cert
7.       server.cert is a file name.
8.       Enter changeit for the password.

9.       Import the cert into Java's keystore with this command:

keytool -import -alias tomcat -file server.cert -keypass changeit -keystore %JAVA_HOME%/jre/lib/security/cacerts
%JAVA_HOME% means java home path..
10.   Enter changeit for the password.
11.   Enter yes
12.   Then go to (liferay-portal-6.3.0.0\tomcat-6.0.24\webapps\ROOT\WEB_INF\classes) folder and Create portal-ext.properties file if it does not exist yet.
13.   Open portal-ext.properties and enter:
cas.auth.enabled=true
14.   Enter these default values………..in portal-ext.properties for cas integration.

15.   Save the settings.
16.   Start Tomcat and go to Liferay Portal.
17.   Click Sign In. If everything is set up correctly you will be redirected to the CAS server's login screen.
18.   If your user in both CAS data base and liferay database you can login successfully.










Dileepa sisisla Chandrasekera
Computer Science & Engineering (University of Moratuwa)
hsenid mobile Solutions company (trainee)


Monday, March 7, 2011

About Me

Hello, I'm Dileepa Sisila Chandrasekera. I'm undergraduate of University of Moratuwa. Now, I'm training at hsenid mobiles solution (pvt) Ltd.