Wednesday 16 November 2016

Working with (Three Level) Kaleo Workflow Liferay6.2 :



I have to implement based on roles type of three level workflow.

1) Create three users

 Users and Organisation -> Select add users

                          User 1 :   workflow1@liferay.com

                          User 2 :   Workflow2@liferay.com

                          User 3 :   Workflow3@liferay.com

2) Create two Regulars Roles

                         Role 1 :  approver1
                         Role 2 :  approver2
                         Role 2 :  approver3

3)  Assign the roles to users
             
                          User 1 have assign the role appover1
                          User 2 have assign the role approver2
                          User 3 have assign the role approver3

4)  Below code add to one XML file(ThreeLevel-Defination.xml)

<?xml version="1.0"?>

<workflow-definition
    xmlns="urn:liferay.com:liferay-workflow_6.2.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="urn:liferay.com:liferay-workflow_6.2.0 http://www.liferay.com/dtd/liferay-workflow-definition_6_2_0.xsd"
>

    <name>Three Level Approval</name>
    <description>Workflow assets must be approved first Level.</description>
    <version>1</version>
    <state>
        <name>created</name>
        <metadata><![CDATA[{"transitions":{"Market Review":{"bendpoints":[]},"marketing-review":{"bendpoints":[],"xy":[-60,2]}},"xy":[60,50]}]]></metadata>
        <initial>true</initial>
        <transitions>
            <transition>
                <name>Market Review</name>
                <target>marketing-review</target>
                <default>true</default>
            </transition>
            <transition>
                <name>marketing-review</name>
                <target>marketing-review</target>
            </transition>
            <transition>
                <name>marketing-review</name>
                <target>marketing-review</target>
            </transition>
        </transitions>
    </state>
    <task>
        <name>update</name>
        <metadata><![CDATA[{"transitions":{"resubmit":{"bendpoints":[[431,224]]},"Resubmit":{"bendpoints":[[80,1910]],"xy":[140,-530]}},"xy":[510,350]}]]></metadata>
        <actions>
            <notification>
                <name>Creator Modification Notification</name>
                <template>Your asset was rejected by a reviewer, please modify and resubmit.</template>
                <template-language>velocity</template-language>
                <notification-type>email</notification-type>
             
                <execution-type>onAssignment</execution-type>
            </notification>
        </actions>
        <assignments>
            <user />
        </assignments>
        <transitions>
            <transition>
                <name>resubmit</name>
                <target>marketing-review</target>
            </transition>
        </transitions>
    </task>
    <task>
        <name>marketing-review</name>
        <metadata><![CDATA[{"transitions":{"Marketing Approved":{"bendpoints":[]},"Marketing Denied":{"bendpoints":[]}},"xy":[230,50]}]]></metadata>
        <actions>
            <notification>
                <name>Market Content Review Notification</name>
                <template>You have a new asset waiting for your review in the workflow.</template>
                <template-language>text</template-language>
                <notification-type>email</notification-type>
                <execution-type>onAssignment</execution-type>
            </notification>
        </actions>
        <assignments>
            <roles>
                <role>
                    <role-type>regular</role-type>
                    <name>approver1</name>
                </role>
            </roles>
        </assignments>
        <transitions>
            <transition>
                <name>Marketing Approved</name>
                <target>legal-review</target>
                <default>true</default>
            </transition>
            <transition>
                <name>Marketing Denied</name>
                <target>update</target>
                <default>false</default>
            </transition>
        </transitions>
    </task>
    <task>
        <name>legal-review</name>
        <metadata><![CDATA[{"transitions":{"Legal Denied":{"bendpoints":[]},"Legal Approved":{"bendpoints":[]},"Legal Approval":{"bendpoints":[]}},"xy":[650,60]}]]></metadata>
        <actions>
            <notification>
                <name>Legal Content Review Notification</name>
                <template>You have a new asset waiting for your review in the workflow.</template>
                <template-language>text</template-language>
                <notification-type>email</notification-type>
                <execution-type>onAssignment</execution-type>
            </notification>
        </actions>
        <assignments>
            <roles>
                <role>
                    <role-type>regular</role-type>
                    <name>approver2</name>
                </role>
            </roles>
        </assignments>
        <transitions>
            <transition>
                <name>Legal Denied</name>
                <target>update</target>
                <default>false</default>
            </transition>
            <transition>
                <name>Legal Approved</name>
                <target>thirdlevel</target>
            </transition>
            <transition>
                <name>Legal Approved</name>
                <target>third-level</target>
            </transition>
        </transitions>
    </task>
    <state>
        <name>approved</name>
        <metadata><![CDATA[{"xy":[1190,130]}]]></metadata>
        <actions>
            <action>
                <name>approve</name>
                <script>
                    <![CDATA[
                        import com.liferay.portal.kernel.workflow.WorkflowStatusManagerUtil;
                        import com.liferay.portal.kernel.workflow.WorkflowConstants;

                        WorkflowStatusManagerUtil.updateStatus(WorkflowConstants.toStatus("approved"), workflowContext);
                    ]]>
                </script>
                <script-language>groovy</script-language>
                <execution-type>onEntry</execution-type>
            </action>
        </actions>
    </state>
    <task>
        <name>third-level</name>
        <metadata><![CDATA[{"transitions":{"third Denied":{"bendpoints":[]},"approved":{"bendpoints":[]},"Legal Approved":{"bendpoints":[]},"Third Denied":{"bendpoints":[]}},"xy":[900,70]}]]></metadata>
        <actions>
            <notification>
                <name>Thirdl Content Review Notification</name>
                <template>/* specify task notification template */</template>
                <template-language>text</template-language>
                <notification-type>email</notification-type>
                <execution-type>onAssignment</execution-type>
            </notification>
        </actions>
        <assignments>
            <roles>
                <role>
                    <role-type>regular</role-type>
                    <name>approver3</name>
                    <auto-create>true</auto-create>
                </role>
            </roles>
        </assignments>
        <transitions>
            <transition>
                <name>approved</name>
                <target>approved</target>
            </transition>
            <transition>
                <name>Third Denied</name>
                <target>update</target>
            </transition>
        </transitions>
    </task>
 
</workflow-definition>




5)  Add the two level workflow into Workflow section

    Select Workflow - > Defination -> Add defination

6)  Add the worflow to outofbox assets(Webcontent,Wiki,Messageboards,Blogs etc.)

7) Test it



Working with (Two Level) Kaleo Workflow Liferay6.2 :



1) Create two users

 Users and Organisation -> Select add users

                          User 1 :   workflow1@liferay.com

                          User 2 :   Workflow2@liferay.com

2) Create two Regulars Roles

                         Role 1 :  approver1
                         Role 2 :  approver2

3)  Assign the roles to users
               
                          User 1 have assign the role appover1
                          User 2 have assign the role approver2

4)  Below code add to one XML file(TwoLevel-Defination.xml)

<?xml version="1.0"?>

<workflow-definition
    xmlns="urn:liferay.com:liferay-workflow_6.2.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="urn:liferay.com:liferay-workflow_6.2.0 http://www.liferay.com/dtd/liferay-workflow-definition_6_2_0.xsd"
>
    <name>Legal and Marketing Approval</name>
    <description>Workflow assets must be approved first by Marketing and then by Legal.</description>
    <version>1</version>
    <state>
        <name>created</name>
        <metadata>
            <![CDATA[{"transitions":{"Market Review":{"xy":[-46,-12]}},"xy":[62,51]}]]>
        </metadata>
        <initial>true</initial>
        <transitions>
            <transition>
                <name>Market Review</name>
                <target>marketing-review</target>
                <default>true</default>
            </transition>
        </transitions>
    </state>
    <task>
        <name>update</name>
        <metadata>
            <![CDATA[{"transitions":{"Resubmit":{"bendpoints":[[427,40]],"xy":[-27,11]}},"xy":[530,36]}]]>
        </metadata>
        <actions>
            <notification>
                <name>Creator Modification Notification</name>
                <template>Your asset was rejected by a reviewer, please modify and resubmit.</template>
                <template-language>text</template-language>
                <notification-type>email</notification-type>
                <notification-type>user-notification</notification-type>
                <execution-type>onAssignment</execution-type>
            </notification>
        </actions>
        <assignments>
            <user />
        </assignments>
        <transitions>
            <transition>
                <name>Resubmit</name>
                <target>marketing-review</target>
                <default>true</default>
            </transition>
        </transitions>
    </task>
    <task>
        <name>marketing-review</name>
        <metadata>
            <![CDATA[{"transitions":{"Marketing Approved":{"xy":[-1,-29]},"Marketing Denied":{"xy":[-34,-1]}},"xy":[260,36]}]]>
        </metadata>
        <actions>
            <notification>
                <name>Market Content Review Notification</name>
                <template>You have a new asset waiting for your review in the workflow.</template>
                <template-language>text</template-language>
                <notification-type>email</notification-type>
                <notification-type>user-notification</notification-type>
                <execution-type>onAssignment</execution-type>
            </notification>
        </actions>
        <assignments>
            <roles>
                <role>
                    <role-type>regular</role-type>
                    <name>approver1</name>
                </role>
            </roles>
        </assignments>
        <transitions>
            <transition>
                <name>Marketing Approved</name>
                <target>legal-review</target>
                <default>true</default>
            </transition>
            <transition>
                <name>Marketing Denied</name>
                <target>update</target>
                <default>false</default>
            </transition>
        </transitions>
    </task>
    <task>
        <name>legal-review</name>
        <metadata>
            <![CDATA[{"xy":[260,270]}]]>
        </metadata>
        <actions>
            <notification>
                <name>Legal Content Review Notification</name>
                <template>You have a new asset waiting for your review in the workflow.</template>
                <template-language>text</template-language>
                <notification-type>email</notification-type>
                <notification-type>user-notification</notification-type>
                <execution-type>onAssignment</execution-type>
            </notification>
        </actions>
        <assignments>
            <roles>
                <role>
                    <role-type>regular</role-type>
                    <name>approver2</name>
                </role>
            </roles>
        </assignments>
        <transitions>
            <transition>
                <name>Legal Approval</name>
                <target>approved</target>
                <default>true</default>
            </transition>
            <transition>
                <name>Legal Denied</name>
                <target>update</target>
                <default>false</default>
            </transition>
        </transitions>
    </task>
    <state>
        <name>approved</name>
        <metadata>
            <![CDATA[
                {"xy":[540,285]}
            ]]>
        </metadata>
        <actions>
            <action>
                <name>approve</name>
                <script>
                    <![CDATA[
                        import com.liferay.portal.kernel.workflow.WorkflowStatusManagerUtil;
                        import com.liferay.portal.kernel.workflow.WorkflowConstants;

                        WorkflowStatusManagerUtil.updateStatus(WorkflowConstants.toStatus("approved"), workflowContext);
                    ]]>
                </script>
                <script-language>groovy</script-language>
                <execution-type>onEntry</execution-type>
            </action>
        </actions>
    </state>
</workflow-definition>




5)  Add the two level workflow into Workflow section

    Select Workflow - > Defination -> Add defination

6)  Add the worflow to outofbox assets(Webcontent,Wiki,Messageboards,Blogs etc.)

7) Test it




Wednesday 26 October 2016

Programatically Add the Site and Page in Liferay:


1) Create Custom Portlet

2) Create Custom Class add the code in Controller Class

@Override
    public void doView(RenderRequest renderRequest,
            RenderResponse renderResponse) throws IOException, PortletException {
        // TODO Auto-generated method stub
        ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
        ServiceContext serviceContext = new ServiceContext();
        serviceContext.setAddCommunityPermissions(true);
        serviceContext.setAddGuestPermissions(true);
        Group group=null;
        Layout layout = null;
        try{
            group=GroupLocalServiceUtil.getGroup(themeDisplay.getCompanyId(), "Hello");
            if(group.getName().equalsIgnoreCase("Hello")){
                System.out.println("Group already exists");
            }else{
                group = GroupServiceUtil.addGroup("Hello", "", GroupConstants.TYPE_SITE_PRIVATE, "", true, true, serviceContext);
                layout = LayoutLocalServiceUtil.addLayout(themeDisplay.getUserId(),group.getGroupId(), true, 0, "ShowCase", "", "", LayoutConstants.TYPE_PORTLET, false, "/showcase2/3", serviceContext);
                LayoutLocalServiceUtil.updateLayout(layout);
            }
           
           
           
        }
        catch(Exception e){
            e.printStackTrace();
        }
       
        super.doView(renderRequest, renderResponse);
       
    }





 

 

Embedded the WebContent in Theme:



Add the below code in portal_norma.vm file

<div class="journalContent">
        #set($groupId = $themeDisplay.getScopeGroupId())
        #set($languageId = $request.theme-display.language-id)
        #set($journalArticleLocal=$serviceLocator.findService('com.liferay.portlet.journal.service.JournalArticleLocalService'))
        #set($journalContentUtil =$utilLocator.findUtil('com.liferay.portlet.journalcontent.util.JournalContent'))
        #set($journalArticle = $journalArticleLocal.getArticle($groupId,"WELCOME"))
        #set($latestArticle= $journalArticleLocal.getLatestArticle($groupId,$journalArticle.getArticleId()))
        #set($journalArticleDisplay=$journalContentUtil.getDisplay($groupId, $latestArticle.getArticleId(),"",$themeDisplay.getLanguageId(),$themeDisplay))
        $journalArticleDisplay.getContent()
        $themeDisplay.getLanguageId()

</div>



Monday 24 October 2016

Embedding a Portlet in Theme :

 Add the below code in Portal-Normal.vm


<div class="lang-bar">
                        $velocityPortletPreferences.setValue("portlet-setup-show-borders", "false")
                        #set($sampleLanguageTranslatorPortletId = "languagetranslator_WAR_sampleportlet")
                        $theme.runtime($sampleLanguageTranslatorPortletId ,"", $velocityPortletPreferences.toString())
                        $velocityPortletPreferences.reset()
                    </div>
languagetranslator_WAR_sampleportlet =  portletId value get it from Database Portlet table

select * from Portlet.

Sunday 25 September 2016

Get the user roles in programtically :

if we want to get the roles of postlogin add the below code:
------------------------------------------------------------------------
HttpServletRequest request;
HttpServletResponse response;

HttpSession session = request.getSession(false);

User user = PortalUtil.getUser(request);
if(Validator.isNotNull(user)){

List<Role> userRoles = RoleLocalServiceUtil.getUserRoles(user.getUserId());
Map<String, String> rolesMap = new HashMap<String, String>();
for (Role role : userRoles) {
rolesMap.put(role.getName(), role.getName());
}

}
session.setAttribute("roles", rolesMap);

Get the roels in appropriate portlet:
============================

HashMap<String, String> rolesMap = (HashMap<String, String>) portletSession.getAttribute("roles",
PortletSession.APPLICATION_SCOPE);




Monday 19 September 2016

Expando Values.

Get the custom attribute values or Expando values :
======================================

User user = null;
ThemeDisplay themeDisplay = (ThemeDisplay) req.getAttribute(WebKeys.THEME_DISPLAY);
user = themeDisplay.getUser();
long curLoginUserid = user.getUserId();
ExpandoValue expandoMobileNumberValue =  ExpandoValueLocalServiceUtil.getValue(themeDisplay.getCompanyId(), User.class.getName(), ExpandoTableConstants.DEFAULT_TABLE_NAME, "contact-number-mobile", curLoginUserid);
ExpandoValue expandoUserCountryValue =  ExpandoValueLocalServiceUtil.getValue(themeDisplay.getCompanyId(), User.class.getName(), ExpandoTableConstants.DEFAULT_TABLE_NAME, "User Country", curLoginUserid);
String curLoginMobileNumber = expandoMobileNumberValue.getData();
String curLoginUserCountry = " ";
if(Validator.isNotNull(expandoUserCountryValue))
curLoginUserCountry = expandoUserCountryValue.getData();

Update expando values of login user:
============================

ThemeDisplay themeDisplay = (ThemeDisplay) req.getAttribute(WebKeys.THEME_DISPLAY);
User loginUser = themeDisplay.getUser();
User user = null;
ThemeDisplay themeDisplay = (ThemeDisplay) req.getAttribute(WebKeys.THEME_DISPLAY);
user = themeDisplay.getUser();
long curLoginUserid = user.getUserId();
String updateCompanyName = UpdateForm.getCompanyName();
ExpandoValue expandoValue =  ExpandoValueLocalServiceUtil.getValue(themeDisplay.getCompanyId(), User.class.getName(), ExpandoTableConstants.DEFAULT_TABLE_NAME, "company-name", userId);
expandoValue.setData(updateCompanyName);
ExpandoValueLocalServiceUtil.updateExpandoValue(expandoValue);

User details add and get the programatically.

Add the user details in Programatically.
=============================

ThemeDisplay themeDisplay = (ThemeDisplay) req.getAttribute(WebKeys.THEME_DISPLAY);
User user = null;
String emailaddress = ParamUtil.getString(“emailaddress”);
String screenName = ParamUtil. getString(“screenname”);
List<User> users = UserLocalServiceUtil.getUsers(0, UserLocalServiceUtil.getUsersCount());
for(User user : users) {
    if(emailAddress.equalsIgnoreCase(user.getEmailAddress()) || screenName.equalsIgnoreCase(user.getScreenName())){
            System.out.println(“user is already exists ”);
             }
             else{
             }
         }

               long[] groupIds = {themeDisplay.getLayout().getGroupId()};
               ServiceContext serviceContext = ServiceContextFactory.getInstance(User.class.getName(), req);
serviceContext.setScopeGroupId(themeDisplay.getLayout().getGroupId());
long[] roleIds = {};
long[] organisationIds = {};
long[] userGroupIds = {};


user =UserLocalServiceUtil.addUser(20199, themeDisplay.getCompanyId(), true, "", "", false, screenNam, emailAddrs,facebookId, "", Locale.ENGLISH, firstName, "", lastNameUsr, 1, 1, true, 10, 10, 1900, "", groupIds, roleIds, organisationIds, userGroupIds, true, serviceContext);


Get the current user login details:

=============================

User user = null;
ThemeDisplay themeDisplay = (ThemeDisplay) req.getAttribute(WebKeys.THEME_DISPLAY);
user = themeDisplay.getUser();
long curLoginUserid = user.getUserId();

Update the current user login details:
===========================
String email = UpdateForm.getEmailAddress();
String updateScreenName = UpdateForm.getScreenName();
String updateFstName = UpdateForm.getFisrtName();
String updateLastName = UpdateForm.getLastName();
String updateCompanyName = UpdateForm.getCompanyName();
                             
ThemeDisplay themeDisplay = (ThemeDisplay) req.getAttribute(WebKeys.THEME_DISPLAY);
User loginUser = themeDisplay.getUser();
loginUser.setEmailAddress(email);
loginUser.setUserId(userId);
loginUser.setFirstName(updateFstName);
loginUser.setLastName(updateLastName);
loginUser.setScreenName(updateScreenName);
UserLocalServiceUtil.updateUser(loginUser);

Tuesday 14 June 2016

Upload file and store the file in server some specific path.

index.jsp:
=======
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>

</head>
<body>
<div
style="margin: 12% auto; width: 80%; box-shadow: 10px 10px 5px #888888; background-color: #DCD7D7; height: 500px;">

<center>
<br />
<div>
<div style="margin: 0px 5% 0 0; width: 96%;">
<h2>Crawling Quality Reports</h2>
</div>
<div>
<form action="TestController" method="post" enctype="multipart/form-data" onsubmit="return validateForm()" >
<table style="line-height: 2;">
<tr>
<td>Select Site</td>
<td>:</td>
<td><select name="site" ID="siteid">
<option selected="selected">none</option>
<option>Amazon</option>
<option>FlipKart</option>
<option>Snapdeal</option>
<option>Paytm</option>
<option>Jabong</option>
<option>Babyoye</option>
<option>Firstcry</option>
<option>Purplle</option>
<option>Nykaa</option>
<option>Pepperfry</option>
<option>fabfurnish</option>
<option>Urbanladder</option>
</select></td>
</tr>
<tr>
<td>Select Crawl type</td>
<td>:</td>
<td><select name="crawlType" ID="crawlTypeid">
<option selected="selected">none</option>
<option>C1</option>
<option>C2</option>
<option>C2_1</option>
<option>C2_3</option>
<option>P4</option>
</select></td>


</tr>
<tr>
<td>Select Crawl stage</td>
<td>:</td>
<td><select name="crawlStage">
<option selected="selected">none</option>
<option>FT</option>
<option>MT</option>
</select></td>

</tr>
<tr>
<td>Present Cycle</td>
<td>:</td>
<td><input type="text" name="presentcycle" id="txtpresentcycle" onkeypress="return isNumber(event)"></td>
</tr>
<tr>
<td>previous Cycle</td>
<td>:</td>
<td><input type="text" name="previousCycle" id="txtpreviouscycle" onkeypress="return isNumber(event)"></td>
</tr>
<tr>
<td>Select File for QA</td>
<td>:</td>
<td><input type="file" name="QAFile" /></td>

</tr>
</table>
<div>
<input type="submit" value="Submit" />
</div>
</form>

</div>
</div>
</center>

</div>
</body>
</html>

Add the below jars:
==============

commons-fileupload-1.3.2.jar
commons-io-2.5.jar

Controller Class:
============


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = null;
String filePath = null;
String siteName = "";
String crawlType = "";
String crawlStage = "";
int presentCycle = 0;
int previousCycle =0;
System.out.println("inside---sss"); 
if (!ServletFileUpload.isMultipartContent(request)) {
           // if not, we stop here
         
       }
// configures upload settings
       DiskFileItemFactory factory = new DiskFileItemFactory();
       // sets memory threshold - beyond which files are stored in disk
       factory.setSizeThreshold(MEMORY_THRESHOLD);
       // sets temporary location to store files
       factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
 
       ServletFileUpload upload = new ServletFileUpload(factory);
        
       // sets maximum size of upload file
       upload.setFileSizeMax(MAX_FILE_SIZE);
        
       // sets maximum size of request (include file + form data)
       upload.setSizeMax(MAX_REQUEST_SIZE);
 
       // constructs the directory path to store upload file
       // this path is relative to application's directory
       String uploadPath = getServletContext().getRealPath("")
               + File.separator + UPLOAD_DIRECTORY;
       System.out.println("inside uploadPath " + uploadPath);
       // creates the directory if it does not exist
       File uploadDir = new File(uploadPath);
       if (!uploadDir.exists()) {
           uploadDir.mkdir();
       }
       
       
       try {
           // parses the request's content to extract file data
        System.out.println("inside try uploadPath " + uploadPath);
         //  @SuppressWarnings("unchecked")
           List<FileItem> formItems = upload.parseRequest(request);
           if (formItems != null && formItems.size() > 0) {
               // iterates over form's fields
            for (FileItem item : formItems) {
                   // processes only fields that are not form fields
                   if (!item.isFormField()) {
                       fileName = new File(item.getName()).getName();
                       filePath = uploadPath + File.separator + fileName;
                      
                       File storeFile = new File(filePath);
 
                       // saves the file on disk
                       item.write(storeFile);
                       request.setAttribute("message", "Upload has been done successfully!");
                   }
                   else {
                   
                    if (item.getFieldName().equals("site")) siteName=item.getString();
                    if (item.getFieldName().equals("crawlType")) crawlType=item.getString();
                    if (item.getFieldName().equals("crawlStage")) crawlStage=item.getString();
                    if (item.getFieldName().equals("presentcycle")) presentCycle=Integer.parseInt(item.getString());
                    if (item.getFieldName().equals("previousCycle")) previousCycle=Integer.parseInt(item.getString());
                   
                    System.out.println("getFieldName " + item.getFieldName()); 
                    System.out.println("getFieldName " + item.getString()); 
                   }
               }
           }
       } catch (Exception ex) {
           request.setAttribute("message",
                   "There was an error: " + ex.getMessage());
       }
       

Monday 7 March 2016

LDAP Integration In Liferay :

Two Ways implement the LDAP Integration in Liferay.

1) Control Panel Level
2) Add the connection, user and user group properties in portal-ext.properties

Before going to integrate the LDAP Server in liferay 


First Apache directory download

-> Download the Apache directory studio    https://directory.apache.org/studio/
->UnZip ans Install the Apache directory studio
-> Open ADS and Click new -> select Ldap connection ->click next 
Give your properties

-> Click Next 
-> Give the Bind User and Password properties
->  Click Finish

Integrate LDAP :


1) Add the Properties in Control Panel Level 

Go to control Panel --> Configuration --> Portal Setting -> Authentication -> Select LDAP.

Add the LDAP Server propeties

---> Give the connection property values
-->Click Test LDAP Connection
--> Show as Successfully connected LDAP Server.

Add the User Propeties in Same Page 

--> Click Test LDAP Users 

Show the LDAP Users successfully.

--> Give the Group Properties

--> Click Test LDAP Groups

--> Click Save 
--> Your request completed Successfully 

-->You want enable and disable required click drop down and save it.
 --> Check the ldap user in user table imported or not.

2) Add the below property in portal-ext.propeties 


Stop the server and add the below properties in portal-ext.propeties

ldap.base.provider.url= ldap://192.168.102.248:389
ldap.base.dn= ou=dummy,dc=cignex,dc=com
ldap.security.principal= cn=CignexAdmin,dc=cignex,dc=com
ldap.security.credentials= secret
# Settings for importing users from LDAP to Liferay.
ldap.import.enabled=true
# LDAP import on startup
ldap.import.on.startup=true
# LDAP User Mapping Settings (#LifeRay field = #LDAP field)
ldap.user.mappings=screenName=cn\npassword=userPassword\nemailAddress=mail\nfirstName=givenName\nlastName=sn\ntitle=st\nphone=telephoneNumber
# Settings for com.liferay.portal.security.auth.LDAPAuth can be configured
# from the Admin portlet. It provides out-of-the-box support for the Apache
# Directory Server, Microsoft Active Directory Server, Novell eDirectory,
# and OpenLDAP. The default settings are for the Apache Directory Server.
# The LDAPAuth class must be specified in the property "auth.pipeline.pre"
# to be executed. Encryption is implemented by com.liferay.util.Encryptor.provider.class 
# in system.properties.
ldap.auth.enabled=true
ldap.auth.required=true
request.header.auth.import.from.ldap=true
# LDAP User Search Filter
ldap.import.user.search.filter=(objectClass=inetOrgPerson)
# User Screen Name Validation
users.screen.name.validator=com.liferay.portal.security.auth.LiberalScreenNameValidator
# Set either user or group for import method. If set to user, the portal
# imports all users and the groups associated with those users. If set
# to group, the portal imports all groups and the users associated with
# those groups. This value should be set based on how your LDAP server
# stores group membership information.
ldap.import.method=group
# LDAP Group Search Filter
ldap.import.group.search.filter=(&(objectClass=groupOfNames)(|(cn=it)))
# LDAP Group Mapping (LDAP Group is Mapped to Liferay User Group)
ldap.group.mappings=groupName=cn\ndescription=description\nuser=member\n
# Set this to true to use LDAP's password policy instead of the Liferay's
# password policy. If set to true, it is possible that portal generated passwords
# will not match the LDAP policy. See the "passwords.regexptoolkit.*" properties 
# for details on configuring RegExpToolkit in generating these passwords.
ldap.password.policy.enabled=true 
#  LDAP user's password should not be imported
ldap.import.user.password.enabled=false 
# User password reminder screen should not be on login
users.reminder.queries.enabled=false
users.reminder.queries.custom.question.enabled=false  
# Active Directory stores information about the user account as a series of
# bit fields in the UserAccountControl attribute.
# If you want to prevent disabled accounts from logging into the portal you
# need to use a search filter similar to the following:
# (&(objectclass=person)(userprincipalname=@email_address@)(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))    
ldap.auth.search.filter=(cn=@screen_name@)
#LDAP error mappings for password
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

--> Start the server 

--> Check the Ldap user are imported successfully or not.







Friday 19 February 2016

Post Login and Pre Logout Actions using Session in Liferay :

When user Login into the portal, Login and logout values with current date stored in DB.

Step1:
=====
Create new hook plugin project.

Step2:
=====
Create the service.xml file add the below code

<service-builder package-path="org.monitoring">
<namespace>PKS</namespace>
<entity name="Logindetails" uuid="true" local-service="true" remote-service="true">
<!-- PK fields -->

<column name="loginId" type="long" primary="true" id-type="identity"></column>
<column name="userId" type="long"></column>
<column name="username" type="String"></column>
<column name="emailAddress" type="String"></column>
<column name="loginDate" type="Date"></column>
<column name="logoutDate" type="Date"></column>
<column name="loginIp" type="String"></column>

  <!-- Order -->
              <order by="asc">
                     <order-column name="loginId" />
              </order>
           
     <!-- Finder methods -->
<finder return-type="Collection" name="findByUserName">
<finder-column name="username"></finder-column>
</finder>

<finder return-type="Collection" name="Name_EmailAddress">
<finder-column name="emailAddress"></finder-column>
<finder-column name="username"></finder-column>
</finder>
</entity>

</service-builder>



Step3:
=====
Create 2 new Custom Classes in Src\ folder
1)  LoginDetails  

package com.test.hook;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.kernel.events.Action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.monitoring.model.Logindetails;
import org.monitoring.model.impl.LogindetailsImpl;
import org.monitoring.service.LogindetailsLocalServiceUtil;

import com.liferay.portal.kernel.events.ActionException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.model.User;
import com.liferay.portal.util.PortalUtil;

public class LoginDetails extends Action {

public LoginDetails() {
super();
}
public void run(HttpServletRequest request, HttpServletResponse response) throws ActionException {

/* String date = null;
*/ Date date = new Date();
/*SimpleDateFormat formatter;
formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");

date = formatter.format(date1);
System.out.println("+++++ Current Logintime +++++"+date);
*/

System.out.println("===Getting Current Login Time=== :"+date);

      try {
      User currentUser;
      long userId;
      String emailaddress;
      String username;
     
      try {
     
currentUser = PortalUtil.getUser(request);
System.out.println("Current Username:   "+currentUser);
userId = currentUser.getUserId();
System.out.println("UserId:   "+userId);
    emailaddress = currentUser.getEmailAddress();
    username = currentUser.getFirstName();
   
     String ipAddress = PortalUtil.getOriginalServletRequest(request).getRemoteAddr();
         System.out.println("====Your IP Address Is === :"+ipAddress);
   
        long loginId = CounterLocalServiceUtil.increment(Logindetails.class.getName());
Logindetails logindetails = new LogindetailsImpl();
logindetails.setLoginId(loginId);
logindetails.setUserId(userId);
logindetails.setUsername(username);
logindetails.setLoginIp(ipAddress);
logindetails.setEmailAddress(emailaddress);
System.out.println("===Got Current Login Time===:"+date);
logindetails.setLoginDate(date);

LogindetailsLocalServiceUtil.addLogindetails(logindetails);
HttpSession session = request.getSession();
        session.setAttribute("loginID",logindetails.getLoginId());
        System.out.println("before: "+logindetails.getLoginId());
             
} catch (PortalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
   
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
       

}

}

2) LogoutDetails  :
package com.test.hook;
import java.util.Date;

import com.liferay.portal.kernel.events.Action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.monitoring.model.Logindetails;
import org.monitoring.service.LogindetailsLocalServiceUtil;
import com.liferay.portal.kernel.events.ActionException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;

public class LogoutDetails extends Action {

public MonitoringLogout() {
super();
}

public void run(HttpServletRequest request, HttpServletResponse response) throws ActionException {

System.out.println("monitoring portlet created");
System.out.println("===Getting Current Logout Time === :"+new Date());

Date date;
date = new Date();
   
try {        
    try {

       HttpSession session = request.getSession();
     
       System.out.println("Object o   :"+session);
     
        Long  sessiId =(Long)session.getAttribute("loginID");
        System.out.println("after: "+sessiId);
        Logindetails login = LogindetailsLocalServiceUtil.getLogindetails(sessiId);
        login.setLogoutDate(date);
        LogindetailsLocalServiceUtil.updateLogindetails(login);
} catch (PortalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
   
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Step4 :
=====
  Create portal.properties file under Src folder add the below property

login.events.post=com.test.hook.LoginDetails
logout.events.pre=com.test.hook.LogoutDetails

Step 5:
=====
Add the below entity in liferay-hook.xml

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

Step 6:
======
Deploy the hook and see the results.

  Inter Portlet Communication (IPC) in Liferay 7.4 Public Render Parameter IPC: 1) Create a new module project -> SenderPortlet 2) In  Se...