Friday, October 18, 2013

Liferay Auto fields

Liferay Auto fields


The following example gives you the information about how to use liferay auto fields in liferay development.
Life ray auto fields concept provides you can add multiple input fields dynamically to the form.
Means if you want add multiple input fields to the form based on user choice.

Download Auto field portlet from following location


Note:  Portlet developed in Liferay 6.1GA2 EE version

If you want deploy in CE version you just do changes in liferay-plugin-package.properties

Liferay 6.1 EE version

name=LiferayAutoFields
module-group-id=liferay-ee
module-incremental-version=1
tags=
short-description=
change-log=
page-url=http://www.liferay.com
author=Liferay, Inc.
licenses=EE
liferay-versions=6.1.20


Liferay 6.1 CE version

name= LiferayAutoFields
module-group-id=liferay
module-incremental-version=1
tags=
short-description=
change-log=
page-url=http://www.liferay.com
author=Liferay, Inc.
licenses=LGPL
liferay-versions=6.1.1

Example:

Adding multiple phone numbers
Adding multiple addresses
Add multiple images or document
When we get above requirement we can use auto fields.

Here we have to identify which fields you want make it multiple times such fields you have to wrap into particular div or field set. We have to provide that element id to the auto filed script so that when we click add button that wrapper content will be cloned.

At time of clones all names and ids of fields will become unique.

The following g is example code for auto fields

Add following script in jsp page

<%@page import="javax.portlet.ActionRequest"%>
<%@ include file="init.jsp" %>
<portlet:actionURL var="editArticleActionURL" windowState="<%= WindowState.NORMAL.toString()%>">
  <portlet:param name="<%=ActionRequest.ACTION_NAME%>" value="getAutoFieldsData" />
</portlet:actionURL>
<h1>Liferay auto fields example</h1>
<aui:form action="<%=editArticleActionURL%>" method="post" name="LiferayAautoFieldForm">
  <div id="phone-fields">
    <div class="lfr-form-row lfr-form-row-inline">
      <div class="row-fields">
        <aui:input fieldParam='phoneNumber0' id='phoneNumber0' name="phoneNumber0" label="Phone Number" />
        <aui:select id="phoneTypeId0" name="phoneTypeId0" label="Type">
          <aui:option value="11006" label="Business"></aui:option>
          <aui:option value="11007" label="Business Fax"></aui:option>
          <aui:option value="11008" label="Mobile Phone"></aui:option>
          <aui:option value="11009" label="Other"></aui:option>
          <aui:option value="11011" label="Personal"></aui:option>
        </aui:select>
      </div>
    </div>
  </div>
  <aui:layout>
    <aui:column>
      <aui:button type="submit" value="Save Phone Numbers" name="SavePhoneNumbers"
        onClick="saveData();"></aui:button>
    </aui:column>
  </aui:layout>
  <aui:script use="liferay-auto-fields">
    new Liferay.AutoFields(
    {
    contentBox: '#phone-fields',
    fieldIndexes: '
    <portlet:namespace />
    phonesIndexes'
    }
    ).render();
  </aui:script>
</aui:form>

Add following AUI java script in jsp page.

<aui:script use="liferay-auto-fields">
 new Liferay.AutoFields(
       {
           contentBox: '#phone-fields',
           fieldIndexes: '<portlet:namespace />phonesIndexes'
       }
   ).render();
</aui:script>

Add following code in Action class

public void getAutoFieldsData(ActionRequest actionRequest,ActionResponse response)
                                    throws Exception {
                        System.out.println("=============getAutoFieldsData==");
                        String phonesIndexesString = actionRequest.getParameter(
                                                "phonesIndexes");
            System.out.println("=============phonesIndexesString=="+phonesIndexesString);
                                    int[] phonesIndexes = StringUtil.split(phonesIndexesString, 0);

                                    for (int phonesIndex : phonesIndexes) {
                                                String number = ParamUtil.getString(actionRequest, "phoneNumber" + phonesIndex);
                                                System.out.println("=============phoneNumber=="+number);
                                                int typeId = ParamUtil.getInteger(actionRequest, "phoneTypeId" + phonesIndex);
                                                System.out.println("=============typeId=="+typeId);

            }

}

Screen 1



Screen 2 out put in console:



Tuesday, October 8, 2013

Liferay LDAP Integration full detailed information

Liferay  LDAP Integration

Liferay 6.1 version:
Please go through following link to get understanding about Ldap liferay integration
 Login as admin and go to control panel. Left side Manu in portal category click on portal settings.



 Click on Add button you can add your LDAP server configuration. You can also add multiple LDAP servers.



Server Name: anything that your choice.
Server Types:  This server you have used like Apache AD, Microsoft AD or OpenLDA.
Base Provider URL: this is LDAP URL to connect your server. General port number for LDAP is 389.
Base DN: This specify that where exactly your user nodes available
Example:

meera.com  is my company
I have organization units Finance, IT
In organization I have users
Then Base DN likes: CN=users,OU=finance,DC=meera,DC=com
                 If I have two users in names are Peter in finance and Tom in IT
              Then exact user Node like this
CN=Peter,CN=users,OU=finance,DC=meera,DC=com

CN=Tom ,CN=users,OU=IT,DC=meera,DC=com

 The following are the base DN for above server


 CN=users,OU=finance,DC=meera,DC=com  : find users in meera company finance organization
OR
 CN=users,OU=IT,DC=meera,DC=com      : find users in meera company IT organization

OR

OU=IT,DC=meera,DC=com  : find users and others type objects in meera company in IT organization

OR

OU=finance,DC=meera,DC=com  : find users and others type objects in meera company in finance  organization

OR
DC=meera,DC=com  : find users and other objects /nodes in meera company in both organizations IT and finance

Above all we can specify as base DN based on your requirement


Principle: this is like user name to connect to your LDAP server means admin username

Credentials: this is password means admin password of LDAP

Once you complete all above then click on test server button and see the result you will get following pop up



Now we successfully connected to LDAP server

Configure Authentication Filter and Import Filter



Now go to user section in same screen you can find following screen

You can find first text box is Authentication Search Filter
Note:  Here authentication filters and import filter is very important.
Authentication Filter:


This means in which base user will be searched in ldap when user trying login in  life ray means when we use liferay authentication by emailAddreess  then we need to map liferay email address with appropriate attribute in ldap
Like
(mail=@email_address@)
When its by screen name
Then we need to map liferay screen name with appropriate attribute in LDAP
Like
(cn=@screen_name@)
Or
(sAMAccountName==@screen_name@)

Note here whatever attribute you are going to use then value of attribute should not be duplicate.
Import filter:


This is used to search users from ldap based on filter and all matched results will be imported into
Liferay User_ table
Here we need to consider one thing whatever the import filter used  that results should have  email address related ldap attribute  and screen name mapping ldap attribute otherwise we will get more exceptions.
Here generally we import mostly users means in ldap is  objectClass=person.
We can also narrow the filter by using ldap filters more details how to pass ldap filter go through following link
Note: Some times in ldap all nodes may not be persons and if persons them may not have email address related attributes or screen name attribute in ldap then we get more import problems
So here we need to give proper import filter so that all nodes have mail related attribute or screen name related attributes
Generally the life ray screen name equal attribute cn or sAMAccountName
Similarly liferay email address equal attribute in ldap is userPrincipalName or mail
These attributes should be present in each object class=person node otherwise import issues we can expect.
Example import filer

(objectClass=person) means it will search all ldap nodes that would be object class is person nothing but user. Some time object class may be organizationUser too.
Another Example Filter:

& is operator like and operator in java similarly | is like || operator in java
(&(objectClass=person)(|(department=finace)(department=it)(department=sales)))
The above meaning is the node is person and he is belongs to any one of the department.

Import mappings

Import mapping used when user is import from ldap to liferay User_ table.
Here we are mapping required attribute for liferay from ldap.
In ldap has many attribute for user or objectClass=person.
So we map each appropriate ldap attribute with liferay attributes

Example      
              
Liferay  attribute
LDAP attribute
emailAddress(should not duplicate)
mail / userPrincipalName
Screenname(should not duplicate)
cn/ sAMAccountName / name
password
userPassword
First Name
name/
Last Name
sn
Job Title
title
Group
department




Now we successfully created LDAP server and we also specify the user mappings to import users into liferay

Now we need set some configuration so that when user should be import what are the password policies we need when create password.
The following screen show that configurations

Enabled:

This is starting point to LDAP integration when we enable then only LDAP is integrated to Liferay so we should enable when you want integrate ldap with liferay.
When we enable LDap when the user going to authenticate   will search in LDAP tree  if user find then it will set ladapAuthentication true and user will be imported.
This for every user when they login first time or first attempt then user will be imported.
Required:

Make exceptions for omni  admins so that if they break the LDAP configuration, they can still login to fix the problem
Import Enable:

When we enable this all LDAP user will be imported into liferay User_ table and related entries in other tables like Group_
 Import on Startup Enabled:

 when we enable this all users will be imported at the time of liferay server starts.
Once user is imported then one entry is created in LOCK_ table. This specifies that for what intervals import should be happened. This property we can set in portal properties




Use LDAP Password Policy:
When enable Use LDAP Password Policy option in configuration then when login it won’t  ask  change new password. Only ask terms and conditions otherwise it will ask change to new password when user is attempt first login.

Important Observations:


GroupFriendlyException:
Reason when the user import it is based on liferay user attributes mapping to ldap attribute user will be created.

Generally  cn or sAMsaccount as screen name.
When user imported cn will become as screen name in User_ table. And one more entry is created in group_ table the friendly url same as screen name means /the secreen name or  /cn
When this Friedly URL is duplicate in Group table then you can see GroupFriendlyException   when you get these exceptions the user won’t be imported.

So here we need to very much care full screen name should not be duplicate mean in ldap there are thousands of users, we need to identify attribute value in ldap that should not be duplicate.
If the ldap some thing duplicate mean cn or saMsAccount then should not use these attribute as screen name.
One more thing when we enable import enables then all users will automatically import into User_ table based on configuration.

So here thing is when we enable import enable option in configuration means all ldap users will be imported into liferay.

If we not enable import enable then each user their first login will be imported.

Import on start up means when server start then all user will be imported automatically. The entry will be created in LOCK_ table there you can see expiration Date column. One expiration date less than current date then again import will be start until import won’t be activated.

We can choose authentication either by email Address or by screen name

If we choose any one email mapping in ldap attribute and screen name mapping in ldap should not be duplicate if such case we get

UserScreenNameException  or UserEmail Address exceptions
When we use authentication by email address as our authentication type its better we can make auto generated  screen name then it won’t be any problem when all users is importing. But email should be unique.


When we use screen name it should not be numbers in start of screen name. If such case please set portal property users.screen.name.allow.numeric=true.

You can also change screen name valuator according to your choice by following property.

users.screen.name.validator=com.liferay.portal.security.auth.DefaultScreenNameValidator

Input a class names that implements com.liferay.portal.security.auth.ScreenNameValidator. This class will be called to validate user screen names

users.screen.name.generator=com.liferay.portal.security.auth.DefaultScreenNameGenerator
Input a class names that implements com.liferay.portal.security.auth.ScreenNameGenerator. This class will be called to generate user screen names.

Email address should not be starting with number such case you will get UsereEmaillAddress exception.
You can change userEmaildAddressPolicies you can also skip email address when user in imported by following property.

Related Properties:

users.email.address.required=true

Set this to false if you want to be able to create users without an email address. An email address will be automatically assigned to a user based on the property "users.email.address.auto.suffix".
Set the suffix of the email address that will be automatically generated for a user that does not have an email address. This property is not used unless the property "users.email.address.required" is set to false. The auto generated email address will be the user id plus the specified suffix.
users.email.address.generator=com.liferay.portal.security.auth.DefaultEmailAddressGenerator

Input a class names that implementscom.liferay.portal.security.auth.EmailAddressGenerator. This class will be called to generate an email address for a user that does not specify anemail address. This class will only be used if the propertyusers.email.address.required" is set to false.
users.email.address.validator=com.liferay.portal.security.auth.DefaultEmailAddressValidator

Input a class names that implementscom.liferay.portal.security.auth.EmailAddressValidator. This class will be called to validate user email addresses
users.full.name.generator=com.liferay.portal.security.auth.DefaultFullNameGenerator

Input a class names that implementscom.liferay.portal.security.auth.FullNameGenerator. This class will be called to generate a full name from the user's first, middle and last names
users.full.name.validator=com.liferay.portal.security.auth.DefaultFullNameValidator

Input a class names that implements com.liferay.portal.security.auth.FullNameValidator. This class will be called to validate user first, middle and last names.


Important LDAP Properties In liferay:

ldap.factory.initial=com.sun.jndi.ldap.LdapCtxFactory
Set the values used to connect to a LDAP store means LDAP implementation class
ldap.referral=follow

ldap.page.size=1000

Set the page size for directory servers that support paging. This value needs to be 1000 or less for Microsoft Active Directory Server.
If you want more search results for Microsoft AD server then AD server admin can configure this number in AD configuration. Please contac admin to set this value from AD server configurations.
ldap.range.size=1000

Set the number of values to return in each query to a multivaluedattribute for directory servers that support range retrieval. The range size must be 1000 or less for Windows 2000 and 1500 or less for Windows Server 2003.
ldap.auth.method=bind  / dap.auth.method=password-compare

Set either bind or password-compare for the LDAP authentication method. Bind is preferred by most vendors so that you don't have to worry about encryption strategies.
LDAP Password Import Algorithm:

Set the password encryption to use for comparing passwords during import and to use for encrypting passwords during export. Comparing password during import will only be used when the property "ldap.auth.method" is set to password-compare. If the encryption is set to NONE, which is the default value, passwords are considered as plain text. The SHA-51  algorithm is currently unsupported.
    #ldap.auth.password.encryption.algorithm=BCRYPT
    #ldap.auth.password.encryption.algorithm=MD2
    #ldap.auth.password.encryption.algorithm=MD5
    ldap.auth.password.encryption.algorithm=NONE
    #ldap.auth.password.encryption.algorithm=SHA
    #ldap.auth.password.encryption.algorithm=SHA-256
    #ldap.auth.password.encryption.algorithm=SHA-384
    #ldap.auth.password.encryption.algorithm=SSHA
    #ldap.auth.password.encryption.algorithm=UFC-CRYPT
ldap.attrs.transformer.impl=com.liferay.portal.security.ldap.DefaultAttributesTransformer

You can write your own class that implements com.liferay.portal.security.ldap.AttributesTransformer to transform the LDAP attributes before a user or group is imported to the LDAP store.
LDAP Connection Properties:

Specify the settings for LDAP connections. Any property prefixed with "ldap.connection." will be passed to the LDAP context as an environment variable. See the following link:
ldap.connection.com.sun.jndi.ldap.connect.pool=true
ldap.connection.com.sun.jndi.ldap.connect.timeout=500
ldap.connection.com.sun.jndi.ldap.read.timeout=15000

ldap.import.interval=10
ldap.import.method=user or ldap.import.method=group

We have choose any one of two
 Set either user or group for import method. If set to user, the portal will import all users and the groups associated with those users. If set to group, the portal import all groups and the users associated thosegroups. This value should be set based on how your LDAP server stores group membership information.
ldap.import.lock.expiration.time=86400000

Set the lock expiration time for LDAP import. By default, the expiration time is 1 day.
ldap.import.group.search.filter.enabled=true

If set to true, the group filter will be applied, but only to groups in the specified base DN. If set to false, the filter will not be applied and all groups that are associated with the imported users will be imported regardless of the base DN.
ldap.import.group.cache.enabled=true

Specify whether group DN lookups will be cached during LDAP import and login. If set to true, this will speed up LDAP import and login, but updates to group attributes will not be recognized until the cache entry expires. The cache size and timeout may be configured in the configuration file specified in the property "ehcache.single.vm.config.location".
 ldap.import.create.role.per.group=false

    Set this to true if the portal should automatically create a role per  group imported from LDAP. The role will be assigned to the group so that users can automatically inherit that role when they are assigned to the group.
   

Set these following values to be a portion of the error message returned by the appropriate directory server to allow the portal to recognize messages from the LDAP server. The default values will work for Fedora DS.
    ldap.error.password.age=age
    ldap.error.password.expired=expired
    ldap.error.password.history=history
    ldap.error.password.not.changeable=not allowed to change
    ldap.error.password.syntax=syntax
    ldap.error.password.trivial=trivial
    ldap.error.user.lockout=retry limit

    ldap.import.user.password.enabled=true

   Set this to false when the LDAP user's password should not be imported.
 ldap.import.user.password.autogenerated=false

Set this to true to auto generate the password for imported users from LDAP This property is only in use if the property "ldap.import.user.password.enabled" is set to false.

ldap.import.user.password.default=test

    #ldap.import.user.password.default=screenName
Set either screenName or plain text as the default password for the  imported LDAP user. Setting the value to screenName will use the user's screen name as the password for the imported LDAP user. Setting the value to any other plain text value will use that value as the password for the  imported LDAP user. This property is only in use if the properties "ldap.import.user.password.enabled" and "ldap.import.user.password.autogenerated" are both set to false.
ldap.user.ignore.attributes=

   Set the user attributes that are controlled from the portal. When adding or updating a user from LDAP, these attributes will be skipped.
#ldap.user.ignore.attributes=aimSn,comments,facebookId,facebookSn,greeting,icqSn,jabberSn,jobTitle,languageId,msnSn,mySpaceSn,openId,prefixId,reminderQueryAnswer,reminderQueryQuestion,skypeSn,smsSn,suffixId,timeZoneId,twitterSn,ymSn

Note: If you want change any portal properties related to LDAP simple you can create portal-ext.properties file and add properties and change to required value. This file should be in Liferay_Home directory.

Important java classes involved in LDAP liferay integration:  

 com.liferay.portal.security.auth.LDAPAuth.java
 com.liferay.portal.security.ldap.PortalLDAPImporterImpl.java
com.liferay.portal.security.ldap.DefaultLDAPToPortalConverter.java
com.liferay.portlet.login.action.LoginAction.java

Example of LDAP tree


CN=Users ,OU=finance,DC=watsons,DC=local DC=com
CN=Commn Name
OU=Organization Unit
DC=Domain Name

CN=Users,DC=watsons,DC=local









Saturday, September 28, 2013

Liferay Portlet Displaying AUI Date Time

Liferay  Portlet Displaying  AUI Date Time.

Objective:

Display date time and date with different ways in liferay development.
I have displayed date and date time using life ray dete picker. Liferay date picker display date with minimal code in jsp so that we can display date or calendar in different ways.
I have created different dates or calendar in different ways and in back end means action class I collected selected date.
I have collected date in different ways like direct date format, date as string format and date as mille seconds,

Download the liferay portlet from following URL


I am providing war file and source code portlet. You can directly place war file your liferay portal deploy folder it will be deployed.
The port let available in sample category as Display Date Action.
The following is sample code to display date:
The following is jsp code


<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<div id="myDatePicker" class="aui-datepicker aui-datepicker-display aui-helper-clearfix">
</div>
<aui:input name="startDateHidden" id="startDateHidden" type="hidden"  value="" ></aui:input>
<aui:script>
var startDatePicker;
AUI().use(
  'aui-datepicker',
  function(A) {
    startDatePicker=new A.DatePickerSelect(
      {
     appendOrder: ['m', 'd', 'y'],
        calendar: {
        dateFormat: '%m/%d/%Y',
         
        }
      }
    ).render('#myDatePicker');

 function submitForm(){
       var startDate;
       var endDate;   
    A.one("#<portlet:namespace/>startDateHidden").
set('value',startDatePicker.calendar.getFormattedSelectedDates ()[0]); 
  document.<portlet:namespace/>date.submit();
}
</aui:script>


Action class getting date:


DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date startDate=ParamUtil.getDate(actionRequest,"startDateHidden", dateFormat);
String startDateString=ParamUtil.getString(actionRequest,"startDateHidden");


Important Points:


  •        Display only date using AUI library
  •     Display Date in different formats
  •        Display date and time using AUI and liferay Time tag.
  •     Get the date in action class in different formats.
  •        Validate two dates.
Note:

  •  I have done this in liferay 6.1 CE. If you are using other version simple use my code.
  • All out put you can see in console. In console you can see all information.
  •  For more details you can walk through jsp code and action class code.

Screen Shots:



The following are reference links



Tuesday, September 24, 2013

Liferay PDF generation from HTML using flying saucer

Liferay PDF generation from HTML using flying saucer

Objective:

Generate PDF content in liferay using html content. Generally we use itext library to generate pfd. When we use itext library we need to write so much java code to prepare PDF. I have done example which generate PDF by using html.
I am using one of library called flying saucer from this we can convert xhtm or html content as PDF.
We can also apply CSS to html so that same view we can get in PDF. For more details you can follow the link.

Download porlet from following link


In download link I am providing .war and source code.
If you want use .war file simply download war file and place into your liferay portal deploy directory then it will be deployed and portlet is available in sample category and portlet name is Pdf Action.
I have done simple example so that you can get idea to generate PDF using html.
I just hard code some HTML table in action class I am passing html content to flying saucer it will convert the html to PDF.
You can go through the code you will get more info.
I have used liferay 6.1 CE.
Note:
If you are using lower version you just copy portlet class code and jar files to you existed portlet. Otherwise portlet won’t be deployed.

If you get any problem in download file is not able to view or no data in download file please refer this following link

https://www.liferay.com/community/forums/-/message_boards/message/31500678




Recent Posts

Recent Posts Widget

Popular Posts