Wednesday 10 February 2016

Liferay Content

========How to create own  custome portal instance=======

Liferay Multi Tenancy

Liferay offers Multi Tenancy Features using portal instances. You can create several portal instances in your liferay 6.2 control panel by going to
 Multitenancy-We are looking into Liferay with multiple tenancy for business reasons for  disparate audiences
Liferay provides us facility to run more than one portal instance on a single server. Liferay comes with one
 inbuilt portal instance, which is names 'Liferay' and its web id is 'liferay.com', however it can be
modified with following properties in portal-ext.properties file:

Configuration / Portal Instances .

Click on "Add" and fill out the following form:

A fine (german) menu to add portal instances


WEB-ID is the identification String for this instance. Kind of a unique user generated ID.

Virtual Host is the most important entry. Since liferay doesn´t allow you to switch instances from a dropdown menu this is the URL that will be used to determine which liferay instance to show to you. So if you want your users to access your portal using the URL "http://www.findsite.com" then please enter this URL in the Virtual Host field. Once a user is transferred to your page from your original home page URL he will automatically be transferred to this instance. As far as I know there is no other way to access the other instances without this mechanism.
If you don´t have such a URL ready you need to modify your hosts file.

Maildomain This is used for sending out Emails and logging you in the first time. Example: mymaildomain.com

Max Users: Simply the maximum amount of users in your portal.
So you know how to connect to the server (using your hosts file on your computer) but how do you log in ? The initial login is test@mymaildomain.com / test.

How to create Multitenancy in liferay6.2 here you have to following some step

What is Exts.?
Exts, allow overriding the portal core functionality. Ext plugins provide the most advanced method of extending Liferay,Ext plugins are designed to be used only in special scenarios in which all other plugin types cannot meet the needs of the project.

note-if we need to create our own portal instance than we need to override EditInstanceAction class using ext we cant do using hook.
Step1- first we will create custom table using service builder
Step2:-Build service  and deploye
Step3:-Create hook  Plugin
Step4:-select custom jsp
Step5:-override edit_instance.jsp
Step6:-deploy hook
Step7:-Create Ext plugin(need to create  package com.liferay.portlet.admin.action inside WEB-INF-ext-Impl-src copy this calls from liferay source and pased inside this package)
Step8:Override EditInstanceAction()
Step9:before overrride EditInstanceAction we need share portlet jar inside tomcat-lib-ext
Step10:-now we can customize EditInstanceAction and update Instance.
Step11:-direct deploy
Step:-Restart ext.
Note if you will create custom portal instance than we need to create Organization,group, PageLayout, user , Associate a role with user,create Group for a user,create Contact for a user ,Create AssetEntry ,create ResourcePermission ,create Layoutset for public and private 
 ==update portal instanse===

protected void updateInstance(ActionRequest actionRequest) throws Exception {

        try{
            long companyId = ParamUtil.getLong(actionRequest, "companyId");
            String webId = ParamUtil.getString(actionRequest, "webId");
            String tenantName = ParamUtil.getString(actionRequest, "multitenancyName");
            String companyName = ParamUtil.getString(actionRequest, "companyName");
           
            String tenantAdminEmailId=ParamUtil.getString(actionRequest, "multitenancyAdminEmailId");
            String virtualHostname = ParamUtil.getString(actionRequest,"virtualHostname");
            String mx = ParamUtil.getString(actionRequest, "mx");
            String shardName = ParamUtil.getString(actionRequest, "shardName",PropsValues.SHARD_DEFAULT_NAME);
            boolean system = false;
            int maxUsers = ParamUtil.getInteger(actionRequest, "maxUsers", 0);
           
            long multitenancyId = ParamUtil.getLong(actionRequest, "multitenancyId");

            boolean active = ParamUtil.getBoolean(actionRequest, "active");

            if (companyId <= 0) {

                // Add instance

                Company company = CompanyLocalServiceUtil.addCompany(webId,
                        virtualHostname, mx, shardName, system, maxUsers, active);
               
                // ADD Custom Isantance
               
                PortalCustomInstance portalCustomInstance = PortalCustomInstanceLocalServiceUtil.createPortalCustomInstance(CounterLocalServiceUtil.increment());
                portalCustomInstance.setTenantName(multitenancyName);
                portalCustomInstance.setCompanyId(company.getCompanyId());
                portalCustomInstance.setCompanyName(companyName);
               
                portalCustomInstance.setTenantAdminEmailId(multitenancyAdminEmailId);
               
               

                PortalCustomInstanceLocalServiceUtil.addPortalCustomInstance(portalCustomInstance);
               
                ServletContext servletContext = (ServletContext) actionRequest.getAttribute(WebKeys.CTX);

                PortalInstances.initCompany(servletContext, company.getWebId());

                // Calling CreateRegularOrg method and addOrgUser method
               
                Organization org = null;
                org = CreateOrganization(tenantName, company.getCompanyId(),actionRequest);
               
                insertOrgAdmin(org, mulitenancyAdminEmailId,companyName,virtualHostname,actionRequest);
               
                //Below code is to copy the template use in login page
                Group scopeId= GroupLocalServiceUtil.getGroup(company.getCompanyId(),"Guest");
                createArticle(actionRequest,scopeId.getGroupId(),company.getCompanyId());
            } else {

                // Update instance

                CompanyLocalServiceUtil.updateCompany(companyId, virtualHostname, mx, maxUsers, active);
                PortalCustomInstance portalCustomInstance = PortalCustomInstanceLocalServiceUtil.getPortalCustomInstance(multitenancyId);
                portalCustomInstance.setTenantName(multitenancyName);
               
               
                portalCustomInstance.setTenantAdminEmailId(tenantAdminEmailId);
                            //Update Custom Instance
                PortalCustomInstanceLocalServiceUtil.updatePortalCustomInstance(portalCustomInstance);
            }
        } catch(Exception e){
            SessionErrors.add(actionRequest, "error.tenant.save");
        }
       
          SessionMessages.add(actionRequest, "success");
   
    }
   
====Create Organization ===

    private Organization CreateOrganization(String Name, long companyId,ActionRequest actionRequest) throws PortalException, SystemException {
        
        ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
       
        Company company = CompanyLocalServiceUtil.getCompany(companyId);
        ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();
        serviceContext.setCompanyId(companyId);
        Organization org = null;
        try {
            List<Address> addresses = UsersAdminUtil.getAddresses(actionRequest);
            List<EmailAddress> emailAddresses = UsersAdminUtil.getEmailAddresses(
                actionRequest);
            List<OrgLabor> orgLabors = UsersAdminUtil.getOrgLabors(actionRequest);
            List<Phone> phones = UsersAdminUtil.getPhones(actionRequest);
            List<Website> websites = UsersAdminUtil.getWebsites(actionRequest);
           
    /*Below code is for adding Custom fields for the Organization*/
            ExpandoTable expTable = ExpandoTableLocalServiceUtil.getTable(themeDisplay.getCompanyId(), Organization.class.getName(), "CUSTOM_FIELDS");           
            ExpandoTable expandoTable = ExpandoTableLocalServiceUtil.addTable(companyId, Organization.class.getName(), "CUSTOM_FIELDS");
            ExpandoColumn expandoColumn = ExpandoColumnLocalServiceUtil.addColumn(expandoTable.getTableId(),"code", 15);
           
            ExpandoColumn expColumn = ExpandoColumnLocalServiceUtil.getColumn(expTable.getTableId(), "type");
            ExpandoColumn expandoColumn1 = ExpandoColumnLocalServiceUtil.addColumn(expandoTable.getTableId(),"type", 16);
            expandoColumn1.setDefaultData(expColumn.getDefaultData());
            expandoColumn1.setTypeSettings(expColumn.getTypeSettings());
            expandoColumn1.setTypeSettingsProperties(expColumn.getTypeSettingsProperties());
            expandoColumn1.setType(expColumn.getType());
            ExpandoColumnLocalServiceUtil.updateExpandoColumn(expandoColumn1);
           
            expColumn = ExpandoColumnLocalServiceUtil.getColumn(expTable.getTableId(), "category");
            ExpandoColumn expandoColumn2 = ExpandoColumnLocalServiceUtil.addColumn(expandoTable.getTableId(),"category", 16);
            expandoColumn2.setDefaultData(expColumn.getDefaultData());
            expandoColumn2.setTypeSettings(expColumn.getTypeSettings());
            expandoColumn2.setTypeSettingsProperties(expColumn.getTypeSettingsProperties());
            expandoColumn2.setType(expColumn.getType());
            ExpandoColumnLocalServiceUtil.updateExpandoColumn(expandoColumn2);
            /*Till here*/           
            org = OrganizationServiceUtil.addOrganization(0, multitenancyName, "regular-organization", 19014, 19, 12017,StringPool.BLANK, true, addresses, emailAddresses, orgLabors, phones,websites, serviceContext);            System.out.println("org=======11111111============"+org);
                   
            /*org = OrganizationServiceUtil.addOrganization(0, multitenancyName,"regular-organization", true, 19014, 19, 12017,StringPool.BLANK, true, serviceContext);*/
            org.setCompanyId(companyId);
            org = OrganizationLocalServiceUtil.updateOrganization(org);
           
            org.getExpandoBridge().setAttribute("type", "regular-organization");
            org.getExpandoBridge().setAttribute("code", multitenancyName);
            //Group group = GroupLocalServiceUtil.getCompanyGroup(themeDisplay.getCompanyId());
            Group group = GroupLocalServiceUtil.getOrganizationGroup(themeDisplay.getCompanyId(), org.getOrganizationId());

            group.setCompanyId(companyId);
            GroupLocalServiceUtil.updateGroup(group);
           
           
        } catch (PortalException e) {
            e.printStackTrace();
        } catch (SystemException e) {
            e.printStackTrace();
        }


        return org;
    }

=====Create user=======
private User insertOrgAdmin(ActionRequest actionRequest,Organization organization,ServiceContext serviceContext,long gpIdForUser) throws PortalException, SystemException {
ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
long companyId = themeDisplay.getCompanyId();
long groupId= gpIdForUser;
String password1= "orgadmin";//organization.getName().toLowerCase();
String domainName = null;
long facebookId=0;
String openId=null;
//String firstName=organization.getName();
String lastName=organization.getName();
int prefixId=123;
int suffixId=234;
String jobTitle="Organization Administrator";
domainName = organization.getName();
domainName= domainName.trim();
if(domainName.contains(" ")) {
domainName = domainName.replaceAll("\\s+", "-");
}
//String emailAddress="administrator@"+domainName+".com";
String emailAddress="administrator@panchayatportal.gov.in";
Role role = RoleLocalServiceUtil.getRole(companyId, "Organization Administrator");
User user = null;
if(role!= null){
long idContact = CounterLocalServiceUtil.increment(Contact.class.getName());
//String greeting="Welcome "+role.getName();
String greeting="Welcome Admin";
long id = CounterLocalServiceUtil.increment(User.class.getName());
user = UserLocalServiceUtil.createUser(id);
user.setCompanyId(companyId);
user.setPassword(password1);
//String screenName=organization.getName().toLowerCase()+id;
String screenName="admin"+id;
user.setScreenName(screenName);
user.setEmailAddress(emailAddress);
user.setFacebookId(facebookId);
user.setOpenId(openId);
user.setGreeting(greeting);
//user.setFirstName(firstName);
user.setFirstName("Site Admin");
//user.setLastName(lastName);
user.setJobTitle(jobTitle);
user.setCreateDate(new Date ());
user.setContactId(idContact);
user.setPasswordReset(true);
user.setPasswordEncrypted(false);
user.setPasswordModifiedDate(new Date());
user.setCreateDate(new Date());
user.setModifiedDate(new Date());
user.setLanguageId(themeDisplay.getLanguageId());
user.setTimeZoneId(themeDisplay.getTimeZone().getDisplayName());
UserLocalServiceUtil.addUser(user);

//Associate a role with user
long userid[] = {user.getUserId()};

//UserLocalServiceUtil.addRoleUsers(role.getRoleId(), userid);
Role rolePu = RoleLocalServiceUtil.getRole(companyId, "Power User");
//UserLocalServiceUtil.addRoleUsers(rolePu.getRoleId(), userid);
long roleids[]={role.getRoleId(),rolePu.getRoleId()};
UserGroupRoleLocalServiceUtil.addUserGroupRoles(user.getUserId(), groupId, roleids);

ClassName clsNameUser = ClassNameLocalServiceUtil.getClassName("com.liferay.portal.model.User");
long classNameId=clsNameUser.getClassNameId();

//Insert Group for a user
long gpId = CounterLocalServiceUtil.increment(Group.class.getName());
Group userGrp = GroupLocalServiceUtil.createGroup(gpId);
userGrp.setClassNameId(classNameId);
userGrp.setClassPK(userid[0]);
userGrp.setCompanyId(companyId);
userGrp.setName("group"+String.valueOf(userid[0]));
userGrp.setFriendlyURL("/group"+gpId);
userGrp.setCreatorUserId(PortalUtil.getUserId(actionRequest));
userGrp.setActive(true);
GroupLocalServiceUtil.addGroup(userGrp);

//Insert Contact for a user
//long idContact = CounterLocalServiceUtil.increment(Contact.class.getName());
Contact contact = ContactLocalServiceUtil.createContact(idContact);
contact.setCompanyId(companyId);
contact.setCreateDate(new Date());
contact.setUserName(screenName);
contact.setUserId(user.getUserId());
contact.setModifiedDate(new Date());
contact.setFirstName("contact-"+contact.getContactId());
contact.setLastName("contact-"+contact.getContactId());
contact.setMiddleName("contact-"+contact.getContactId());
contact.setPrefixId(prefixId);
contact.setSuffixId(suffixId);
contact.setJobTitle(jobTitle+contact.getContactId());
contact.setBirthday(new Date());
ContactLocalServiceUtil.addContact(contact);

//Create AssetEntry
long assetEntryId = CounterLocalServiceUtil.increment(AssetEntry.class.getName());
AssetEntry ae = AssetEntryLocalServiceUtil.createAssetEntry(assetEntryId);
ae.setCompanyId(companyId);
ae.setClassPK(user.getUserId());
ae.setGroupId(userGrp.getGroupId());
ae.setClassNameId(classNameId);
AssetEntryLocalServiceUtil.addAssetEntry(ae);

//Insert ResourcePermission for a User
long resPermId = CounterLocalServiceUtil.increment(ResourcePermission.class.getName());
ResourcePermission rpEntry = ResourcePermissionLocalServiceUtil.createResourcePermission(resPermId);
rpEntry.setCompanyId(organization.getCompanyId());
rpEntry.setName("com.liferay.portal.model.User");
rpEntry.setRoleId(role.getRoleId());
rpEntry.setScope(4);
rpEntry.setActionIds(31);
// rpEntry.setPrimaryKey(userid[0]);
ResourcePermissionLocalServiceUtil.addResourcePermission(rpEntry);

//Insert Layoutset for public and private
long layoutSetIdPub = CounterLocalServiceUtil.increment(LayoutSet.class.getName());
LayoutSet layoutSetPub=LayoutSetLocalServiceUtil.createLayoutSet(layoutSetIdPub);
layoutSetPub.setCompanyId(companyId);
layoutSetPub.setPrivateLayout(false);
layoutSetPub.setGroupId(userGrp.getGroupId());
layoutSetPub.setThemeId("classic");
try{
LayoutSetLocalServiceUtil.addLayoutSet(layoutSetPub);
}catch(SystemException se){

}

long layoutSetIdPriv= CounterLocalServiceUtil.increment(LayoutSet.class.getName());
LayoutSet layoutSetPriv=LayoutSetLocalServiceUtil.createLayoutSet(layoutSetIdPriv);
layoutSetPriv.setCompanyId(companyId);
layoutSetPriv.setPrivateLayout(true);
layoutSetPriv.setThemeId("classic");
layoutSetPriv.setGroupId(userGrp.getGroupId());
try{
LayoutSetLocalServiceUtil.addLayoutSet(layoutSetPriv);
}catch(SystemException se){
}
}else{
return null;
}


return user;

}
How to create page by programactially?

Create a new layout (page) 

Use one of the addLayout methods of the LayoutLocalServiceUtil
long userId = themeDisplay.getUserId();
long groupId = themeDisplay.getScopeGroupId();
boolean privateLayout = false;
long parentLayoutId = 0;
String name = "myNewPage";
String title = null;
String description = null;
String type = LayoutConstants.TYPE_PORTLET;
boolean hidden = true;
String friendlyURL = "/myNewPage";
Layout layout = LayoutLocalServiceUtil.addLayout(userId, scopeId.getGroupId(), 
privateLayout, parentLayoutId, name, title, description, 
type, hidden, friendlyURL, serviceContext);

==========Sending Mail to User=======================


System.out.println("====sendMailMessage===");
           
//String mailSubject=ParamUtil.getString(actionRequest,"subject");

            //String mailSubject=ParamUtil.getString(actionRequest,"Your new Account");
            String mailSubject="Your new Account";
            //String mailBody=ParamUtil.getString(actionRequest,"body");
            //String mailBody=ContentUtil.get("Create_User.tmpl");
            //PropsUtil.getProperties().getProperty("admin.email.user.added.subject");
            String mailBody=ContentUtil.get(PropsUtil.getProperties().getProperty("admin.email.user.added.subject"));
            //String mailBody="Dear [$TO_NAME$],<br /><br />&nbsp;&nbsp; A [MULTITENANCY_NAME] user is created. Your profile details as follows.<br /><br />&nbsp;&nbsp; User Name &nbsp;- &nbsp; <b>[$SCREEN_NAME$]</b><br />&nbsp;&nbsp; Full Name &nbsp;- &nbsp; <b>[$TO_NAME$]</b><br />&nbsp;&nbsp; Email &nbsp;- &nbsp; <b>[$EMAIL$]</b><br />&nbsp;&nbsp; Password &nbsp;- &nbsp; <b>[$PASSWORD$]</b><br /><br />&nbsp;&nbsp; You can login using the above credentials, Please reset your password by using Forgot password service from the login page. If the above link does not work, copy & paste the following URL into browser<br /><br />&nbsp;&nbsp; [URL] <br /><br />Regards,<br />[$FROM_ADDRESS$]<br />";
            //String senderMailAddress=ParamUtil.getString(actionRequest,"senderEmailAddess");
            //String receiverMailAddress=ParamUtil.getString(actionRequest,"receiverEmailAddess");
            System.out.println("Mail Subject"+mailSubject);
            try {
                  MailMessage mailMessage=new MailMessage();
                  String Url = "http://"+virtualHost + ":8080";
                  //mailBody = ContentUtil.get(mailBody);
                  mailBody = StringUtil
                            .replace(
                                    mailBody,
                                    new String[] { "[$TO_NAME$]",
                                            "[$MULTITENANCY_NAME$]",
                                            "[$SCREEN_NAME$]", "[$EMAIL$]","[$PASSWORD$]","[$URL$]","[$FROM_ADDRESS$]",},
                                    new String[] {
                                            multitenancyName,
                                            multitenancyAdminEmailId,
                                            "test",
                                            Url,
                                            "M@POWER TEAM",});
                  mailMessage.setHTMLFormat(true);
                  mailMessage.setBody(mailBody);
                  mailMessage.setSubject(mailSubject);
                  mailMessage.setFrom(new InternetAddress("admin@mpowerglobal.com"));
                  mailMessage.setTo(new InternetAddress(multitenancyAdminEmailId));
                  //MailServiceUtil.addUser(org.getCompanyId(), createdUser.getUserId(), null, , null, null, multitenancyAdminEmailId);
                  //MailServiceUtil.sendEmail(mailMessage);
                  MailEngine.send(mailMessage);
                 
                 SessionMessages.add(actionRequest.getPortletSession(),"mail-send-success");
            } catch (AddressException e) {
                e.printStackTrace();
            } catch (MailEngineException e) {
                      e.printStackTrace();
              }   
                 
          
        } catch (SystemException e) {
            e.printStackTrace();
        }
      

        return user;

        }
    
=============create role with user================
long userid[] = {user.getUserId()};
 long groupId = OrganizationLocalServiceUtil.getOrganization(
 org.getCompanyId(), org.getName()).getGroup().getGroupId();

 //UserLocalServiceUtil.addRoleUsers(role.getRoleId(), userid);
 long roleId = RoleLocalServiceUtil.getRole(org.getCompanyId(),
"Organization Administrator").getRoleId();

  UserGroupRoleLocalServiceUtil.addUserGroupRoles(
     createdUser.getUserId(), groupId, new long[] { roleId });
                       
 long adminRoleId = RoleLocalServiceUtil.getRole(org.getCompanyId(),
"Administrator").getRoleId();
                       
  RoleLocalServiceUtil.addUserRole(createdUser.getUserId(), adminRoleId);

  long powerUserRoleId = RoleLocalServiceUtil.getRole(
  org.getCompanyId(),"Power User").getRoleId();

RoleLocalServiceUtil.addUserRole(createdUser.getUserId(),
powerUserRoleId);


Implemented Captch code in login.jsp using hook(customize jsp page) 
Step1- first we have to create resourceURL in login.jsp
example-<portlet:resourceURL var="captchaURL">
                    <portlet:param name="struts_action" value="/login/captcha"/>
                </portlet:resourceURL>

                <liferay-ui:captcha url="<%= captchaURL %>" />

Step2-we have to create  strutsAction.
Example-

public class UserLoginActionValidate extends BaseStrutsPortletAction {

    /*private static final PortletRequest renderRequest = null;*/

    public void processAction(StrutsPortletAction originalStrutsPortletAction,
            PortletConfig portletConfig, ActionRequest actionRequest,
            ActionResponse actionResponse) throws Exception {

        ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest
                .getAttribute(WebKeys.THEME_DISPLAY);

        User user = null;
        String flagStr = ParamUtil.getString(actionRequest, "loginHDN");
        long userId = 0l;
        boolean member = false;

        String enteredCaptchaText = ParamUtil.getString(actionRequest,"captchaText");
        
       
       
        try {
            /*PortletSession session = renderRequest.getPortletSession();
            session.setAttribute("captcha",0, PortletSession.PORTLET_SCOPE);*/
            PortletSession session = actionRequest.getPortletSession();
            String captchaText = getCaptchaValueFromSession(session);
            if (Validator.isNull(captchaText)) {
                // throw new
                // Exception("Internal Error! Captcha text not found in session");
                SessionErrors.add(actionRequest, "invalid-captcha");
                return;
            }
            if (!captchaText.equals(enteredCaptchaText)) {
                System.out.println("IS eroorrrrrr");
                // throw new Exception("Invalid captcha text. Please reenter.");
                SessionErrors.add(actionRequest, "text-verification-failed");
                return;

            }
            // update langauge

            if (flagStr.equalsIgnoreCase("email-address"))
                user = UserLocalServiceUtil.getUserByEmailAddress(
                        themeDisplay.getCompanyId(),
                        ParamUtil.getString(actionRequest, "login"));

            else if (flagStr.equalsIgnoreCase("screen-name"))
                user = UserLocalServiceUtil.getUserByScreenName(
                        themeDisplay.getCompanyId(),
                        ParamUtil.getString(actionRequest, "login"));

            if (Validator.isNotNull(user)) {
                user.setLanguageId(ParamUtil.getString(actionRequest,
                        "languageId"));
           
                user = UserLocalServiceUtil.updateUser(user);
               

            }
            /*
             * User user = UserLocalServiceUtil.getUser(userId); user. long
             * organizationId =
             * OrganizationLocalServiceUtil.getOrganizationId(PortalUtil
             * .getCompanyId(actionRequest), partnerId);
             * OrganizationLocalServiceUtil.getO member =
             * OrganizationLocalServiceUtil.hasUserOrganization(userId,
             * organizationId); if(!member){ SessionErrors.add(actionRequest,
             * "invalid-authentication"); return; }
             */
        } catch (NoSuchUserException e) {
            SessionErrors.add(actionRequest, "invalid-authentication");
            return;
        } catch (CaptchaException e) {
            SessionErrors.add(actionRequest, "invalid-authentication");
            return;
        } 


        originalStrutsPortletAction.processAction(originalStrutsPortletAction,
                portletConfig, actionRequest, actionResponse);
    }

    private String getCaptchaValueFromSession(PortletSession session) {
        Enumeration<String> atNames = session.getAttributeNames();
        while (atNames.hasMoreElements()) {
            String name = atNames.nextElement();
            if (name.contains("CAPTCHA_TEXT")) {
                return (String) session.getAttribute(name);
            }
        }
        return null;
    }

    public String render(StrutsPortletAction originalStrutsPortletAction,
            PortletConfig portletConfig, RenderRequest renderRequest,
            RenderResponse renderResponse) throws Exception {
        return originalStrutsPortletAction.render(null, portletConfig,
                renderRequest, renderResponse);
    }

}

 Note -

Captcha to be shown in case of 3 times password failed


Captcha should  be show if password faild 3 times password failed

 This code we need to write inside public class UserLoginActionValidate extends BaseStrutsPortletAction in hook.

String enteredCaptchaText = ParamUtil.getString(actionRequest,"captchaText");
HttpSession httpSession = PortalUtil.getHttpServletRequest(actionRequest).getSession();
int loginAttemptsCount = 0;
try{
String count = (String) httpSession.getAttribute("LIFERAY_SHARED_count");
System.out.println("helloooo=---"+count);
System.out.println("login count-------"+count);
loginAttemptsCount = Integer.parseInt(count);
}
catch(Exception e){

}
System.out.println("login count outside loop-------"+loginAttemptsCount);
try {
PortletSession session = actionRequest.getPortletSession();
session.setAttribute("captcha",0, PortletSession.PORTLET_SCOPE);

if(loginAttemptsCount>3)
{
String captchaText = getCaptchaValueFromSession(session);
if (Validator.isNull(captchaText)) {
// throw new
// Exception("Internal Error! Captcha text not found in session");
SessionErrors.add(actionRequest, "invalid-captcha");
return;
}
if (!captchaText.equals(enteredCaptchaText)) {
System.out.println("IS eroorrrrrr");
// throw new Exception("Invalid captcha text. Please reenter.");
SessionErrors.add(actionRequest, "text-verification-failed");
return;

}}


}/*}*/ catch (NoSuchUserException e) {
SessionErrors.add(actionRequest, "invalid-authentication");
loginAttemptsCount = loginAttemptsCount+1;
System.out.println("loginAttemptsCount"+loginAttemptsCount);
httpSession.setAttribute("LIFERAY_SHARED_count",String.valueOf(loginAttemptsCount));
return;
} catch (CaptchaException e) {
loginAttemptsCount = loginAttemptsCount+1;
System.out.println("loginAttemptsCount"+loginAttemptsCount);
httpSession.setAttribute("LIFERAY_SHARED_count",String.valueOf(loginAttemptsCount));
SessionErrors.add(actionRequest, "invalid-authentication");
return;
}


originalStrutsPortletAction.processAction(originalStrutsPortletAction,
portletConfig, actionRequest, actionResponse);
}


Step2-some code we need to write in login.jsp

<%
int loginfailedcount = 0;
try{
HttpSession httpSession = request.getSession(false);
String count = (String) httpSession.getAttribute("LIFERAY_SHARED_count");
System.out.println("helloooo=---"+count);
System.out.println("login count-------"+count);
loginfailedcount = Integer.parseInt(count);
}
catch(Exception e){}
%>


  <%
  System.out.println("themeDisplay.getUser().getFailedLoginAttempts()-----"+themeDisplay.getUser().getFailedLoginAttempts());
               if(loginfailedcount > 3){ %>
<portlet:resourceURL var="captchaURL">
<portlet:param name="struts_action" value="/login/captcha"/>
</portlet:resourceURL>

<liferay-ui:captcha url="<%= captchaURL %>" />

Q-i want all language in dropdown box on login page for Multilanguage 

suppose if i get select one spanish language in drop down box on form login page after sing in language should be change to whole liferay application

 

Step-first what we will do ,take  one aui:select box and pass value in option  before select box take one list inside list get all language using languageUTIL

example-

<%
                String loginLabel = null;

                if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
                    loginLabel = "email-address";
                }
                else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
                    loginLabel = "screen-name";
                }
                else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
                    loginLabel = "id";
                }
                %>

<aui:input name="loginHDN" value="<%= loginLabel %>" type="hidden"/>

 

<%
                List<Locale> locales = Arrays.asList(LanguageUtil.getAvailableLocales());
                %>
                <aui:select name="languageId" required="true" label="language">
                    <option selected disabled hidden value=''>--Select--</option>
                    <%
                    System.out.println("language id--->"+themeDisplay.getLanguageId());
                   
                    boolean select=false;
                    for(Locale local : locales){
                        select=false;
                        if(local.toString().equals(themeDisplay.getLanguageId())){
                            select=true;                           
                        }
                    %>
                    <aui:option value="<%=local.toString() %>" selected="<%=select%>"><%=local.getDisplayName() %></aui:option>
                <%}%>
                 </aui:select>   

Step2-next we will create struts action there we will get all language dynamically

example-package com.hook.login;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;

import com.liferay.portal.kernel.struts.BaseStrutsPortletAction;
import com.liferay.portal.kernel.struts.StrutsPortletAction;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.User;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;


public class StrutsLoginAction extends BaseStrutsPortletAction{
   

    public void processAction(StrutsPortletAction originalStrutsPortletAction,
            PortletConfig portletConfig, ActionRequest actionRequest,
            ActionResponse actionResponse)
        throws Exception {
       
        ThemeDisplay themeDisplay =  (ThemeDisplay)actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
       
        User user = null;
       
        String flagStr = ParamUtil.getString(actionRequest, "loginHDN");
       
        if(flagStr.equalsIgnoreCase("email-address"))
            user = UserLocalServiceUtil.getUserByEmailAddress(themeDisplay.getCompanyId(),
                ParamUtil.getString(actionRequest, "login"));
        else if(flagStr.equalsIgnoreCase("screen-name"))
            user = UserLocalServiceUtil.getUserByScreenName(themeDisplay.getCompanyId(),
                    ParamUtil.getString(actionRequest, "login"));
       
        if(Validator.isNotNull(user)){
            user.setLanguageId(ParamUtil.getString(actionRequest, "languageId"));
            UserLocalServiceUtil.updateUser(user);
        }
        originalStrutsPortletAction.processAction(
            originalStrutsPortletAction, portletConfig, actionRequest,
            actionResponse);
    }

    public String render(
            StrutsPortletAction originalStrutsPortletAction,
            PortletConfig portletConfig, RenderRequest renderRequest,
            RenderResponse renderResponse)
        throws Exception {

        return originalStrutsPortletAction.render(
            null, portletConfig, renderRequest, renderResponse);

    }

    public void serveResource(
            StrutsPortletAction originalStrutsPortletAction,
            PortletConfig portletConfig, ResourceRequest resourceRequest,
            ResourceResponse resourceResponse)
        throws Exception {

        originalStrutsPortletAction.serveResource(
            originalStrutsPortletAction, portletConfig, resourceRequest,
            resourceResponse);

    }

}

How to get Language selection drop down list in dock bar:
Step1-  first we will create theme after we have to copy templeate inside diff folder form tomcate server 
goto tomcate server-goto webapps-root-html-classic-diff 

Step2 open portal_normal.vm pased this liferay tage

$theme.runtime("82") 

Step3- deploy theme 
after you can manage according to yr way whare you want that drop down box left and right on dockbar



Following are the steps to implement Custom SQL
  1. Create Simple Liferay MVC Portlet
  2. Define entity in service.xml
  3. Run the Service Builder
  4. Create SQL queries configuration XML file (Custom SQL XML file)
  5. Write Native SQL in Custom SQL xml file
  6. Create Finder Implementation class
  7. Run the Service Builder
  8. Implement Required Custom SQL Method in Finder Implementation Java Class
  9. Run the Service Builder
  10. Write Custom Service Method in respective Local Service Implementation Class
  11. Run the Service Builder
  12. Use Respective Local Service Util class to call service method
CCAvenue payment getway Integration
Step1:- integrate CCAvenue Gateway in 6.2 .
Step2:-goto CCAvenue login and download JSP_Kit
step3:-Extract zip file copy three jsp 1-ccavRequestHandler.jsp. 2-ccavResponseHandler.jsp. 3-dataForm.
Step4:-inside dataForm we need to implement renderUrl and give action name

<%
PortletURL
requestURL=renderResponse.createRenderURL();
requestURL.setParameter("jspPage",
"/html/controller/ccavRequestHandler.jsp");


PortletURL
responseURL=renderResponse.createRenderURL();
responseURL.setParameter("jspPage",
"/html/controller/ccavResponseHandler.jsp");
%>
<aui:form
method="post" name="customerData"
action="<%=requestURL.toString() %>">

Step5:- we have to set Redirect URL for both Redirect URL and Cancel URL
example:<td><aui:input type="text"
name="redirect_url” value="<%=responseURL %>"
/>
<td><aui:input
type="text" name="cancel_url"
value="<%=responseURL%>" />

Step6:-we needto provide orderId
<td><aui:input type="text"
name="order_id" value="ord123" /></td>

Step7:-we have to
provide workingKey in  ccavResponseHandler
Step8:-we have to
provide accessCode and workingKey in  ccavRequestHandler 
Step9:-we need to
make FriendlyURl for response data
Step10:- Use
<requires-namespaced-parameters> tag value “false” in
liferay-portlet.xml 
 
 

Using liferay-ui:ratings tag for your custom entity for Ratting functionality

 <liferay-ui:ratings
                       className="<%= Product.class.getName() %>"
                       classPK="<%= prod.getProductId() %>"/>

Liferay Ratting and comment Example

Step1-->for star

<liferay-ui:ratings-score score="5"/>


Step2---> for comment

 <liferay-ui:discussion classPK="12724" userId="20198" className="<%=Product.class.getName() %>"
             formAction="fm"></liferay-ui:discussion>  

How to implement internationalization  in custom portlet liferay
step- create hook
Step2- select and create “Language.properties” under “src/content” as below. We’ve
already created one entry in this file for a different exercise.
step3-add-new-book=Add new Book
show-all-books=Show All Books
enter-title-to-search=Enter Title to Search
search=Search 
Step4-
 In the other part, pick up the language files that need a proper translation and give the
translated entries. For example, open “Language_fr.properties” and modify the
entries as below. The best place to get the translated text is through Google translation
example-
add-new-book=Commander nouvelle
are-you-sure-you-want-to-delete-selected-books=\
Êtes-vous sûr de vouloir supprimer les livres sélectionnés?
enter-title-to-search=Entrez le titre Ă  la recherche
search=Rechercher
show-all-books=Voir Tous les livres 
Step5- if you want to change content of list than we can use 
this liferay tag
<liferay-ui:message key="show-all-books"/>

How to create renderURL:- 
<%
PortletURL addPortletURL=renderResponse.createRenderURL();
addPortletURL.setParameter("jspPage", "/html/controller/add.jsp");

%>

How to create actionURL:-
<%
PortletURL addProductURL=renderResponse.createActionURL();
addProductURL.setParameter(ActionRequest.ACTION_NAME, "addProduct");


Note:- if you create actionURL in springMVC then you have create actionURL like this

PortletURL saveURL=renderResponse.createActionURL();
    saveURL.setParameter("action", "saveRegion");







%>


Creating Service layer in Service Builder in Liferay

Service Builder is a model-driven code generation tool built by Liferay that allows developers to define custom object models called entities

We need to define business models (entities) and rest is taken care by service builder

It generates set of classes and interfaces which is used to interact with Database (CRUD operation) .

Liferay Service Builder is a tool to create service-persistence layer in Liferay. It uses spring and hibernate internally to generate set of  classes, sql scripts and configuration files to interact with database

Example:- 

"Liferay provides a nice way of creating service and persistence layer. Liferay Service Builder is a tool to create service-persistence layer."

While working with Liferay, you may came across the situation where you need to save / update / retrieve / delete the data from Database in your custom portlet.
For example you are developing a portal for school management in liferay. You want to develop one portlet called student management which will add / updates / read / delete student information into database.

What should be provided as an input to Liferay Service Builder ?

Liferay service builder takes service.xml file as an input and generates set of classes and interfaces to perform CRUD operation on Database.

What is the content of service.xml ?

In service.xml, you need to define your business entities and their relation. Each entity in servce.xml represent DB table and attributes of entity are mapped to table column. You can define multiple entities in same service.xml file. You can also take the references of entities defined by service.xml in other portlets.

Where to place service.xml ?

Liferay expects you to place the service.xml on specific path. It should be placed under /WEB-INF folder as per below screenshot.
Servicexml_location - Liferay service builder

How to run Liferay service builder ?

There are two ways to run Liferay service builder.
  • From command prompt
    • Open the command prompt and go your portlet folder and fire a command ‘ant build-service
  • From Liferay IDE or Liferay Developer Studio.
    • In your Liferay IDE right click on service.xml and select Liferay–>Build Services as per below screenshot.
Build_Service_From_Liferay_IDE - Liferay service builder

Can I place more than one service.xml file for single plugin project ?

No. You can’t. Liferay expects you to place service.xml directly under /WEB-INF and you can’t place more than one file with same name in same folder. In general you can have one service.xml per one liferay plugin project. You can place different service.xml in different plugin project. Bottom line is – each plugin project can have only one service.xml file.

How Liferay Service builder works internally ?

There are two ways to create, build and deploy plugins in Liferay – Maven and Ant. Maven was added starting from liferay 6.2. Prior to 6.2, Ant was the way to build plugins out of the box. I have used Ant which is easy to understand.
For Ant based system, you must have to use liferay-plugin-sdk. When you build service by executing ant build-service command from command line or from Liferay IDE, it will execute build-service ant target from build-common-plugin.xml file. This file is located under your liferay-plugins-sdk folder.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder 6.0.0//EN" "http://www.liferay.com/dtd/liferay-service-builder_6_0_0.dtd">
<service-builder package-path="com.esquare.blog.myservice">
 <author>nilang</author>
 <namespace>education</namespace>

 <entity name="Student" local-service="true" remote-service="false">
  <column name="studentId" type="long" primary="true"/>
  <column name="name" type="String"/>
  <column name="age" type="int"/>
  <column name="fatherName" type="String"/>
  <column name="motherName" type="String"/>
  <column name="standard" type="int"/>
 </entity>
</service-builder>
Explanation:-

  • Liferay service builder can generate local or remote or both type of services. Local service can be used by client code running in same VM(Virtual Machine) where liferay instance is running. Liferay also supports remote service which can be accessed as a web-service (SOAP or JSON) over internet / intranet. In our case we have created Student entity by defining local-service as true and remote-service as false so it will generate only local service.
  • Child elements of Student element’s are columns which exactly reflect the column in the DB table.
  • Each column will have name and type. We can declare the primary key by giving primary=”true”. If more than one column defined as primary=”true” then compound key will be generated.
  •  

    Persistence Layer:-

    • StudentPersistence.java (under /WEB/INF/service/com/opensource/techblog/myservice)
      • Student persistence interface which defines CRUD methods related to Student entity like create, remove, countAll, find, findAll etc
    • StudentPersistenceImpl.java (under /WEB-INF/src/com/opensource/techblog/myservice)
      • This is the implementation class, which implements StudentPersistence.
    • StudentUtil.java (under /WEB/INF/service/com/opensource/techblog/myservice)
      • This util class, which having the instance of StudentPersistenceImpl class


    Service Classes:-

    • StudentLocalService.java
      • local service interface for Student entity.
    • StudentLocalServiceImpl.java
      • local service implementation which implements StudentLocalService interface. Basic CRUD methods will be added by liferay service builder. If you want to add any additional service methods then must be added in this class.
      • However you can’t directly access them from this class. You have to re-run the service builder (through ant build-service command) and service builder will create corresponding (same method signature) static method in StudentLocalSerivceUtil class. You can then access StudentLocalSeriviceUtil class which internally make call to corresponding (same signature) method of StudentLocalServiceImpl.
    • StudentLocalServiceBaseImpl.java
      • This class implements StudentLocalSerivce interface and provides all basic CRUD methods. StudentLocalServiceImpl where we can define additional service methods extends this class.
      • All service Impls and persistence Impls classes related to Student entity are injected into this class. Additionally if you give reference of any other entity, it’s service impls and persistence impls classes are also injected in this class.
    • StudentLocalServiceUtil.java
      • Object of type StudentLocalServiceImpl is injected in StudentLocalServiceUtil class by Liferay service builder through spring injection. Out of all above service classes, only this class is accessible to other API (outside of service layer) for CRUD operation.
      • StuddentLocalServiceUtil has all static method. Each method of StudentLocalServiceUtil will make call to corresponding (same signature) method in StudentLocalSerivceImpl class.

    Model classes:-

    Model class Represent a row in education_student table.


    • StudentModel.java
      • Base model (interface) for Student.
      • This interface and its corresponding implementation (StudentModelImpl) exist only as a container for the default property accessors generated by ServiceBuilder. Helper methods and all application logic should be put in (StudentImpl)
    • StudentModelImpl.java
      • Base model impl which implements StudentModel interface
      • This implementation and its corresponding interface (StudentModel) exist only as a container for the default property accessors generated by ServiceBuilder. Helper methods and all application logic should be put in (StudentImpl).
    • Student.java
      • extends studentModel.java
      • By defaul there is not method defined.
      • Whenever any new (custom) method added to StudentImpl, they will be added to this interface on next service build.
    • StudentImpl.java
      • extends StudentBaseImpl.java.
      • implements Student.java interface.
      • Helper methods and all application logic should be put in this class.
      • Whenever custom methods are added in this class, the corresponding methods will be added to Student interface on next service build.

    Relations among Model interfaces / classes :-

    Following diagram shows the relation between  model interface and classes 

    Out of these model classes / interfaces, only StudentImpl.java is allowed to add additional (custom) methods at model level to developer. Creating Service layer by Service Builder in Liferay - Service_Builder_ModelpngRelations among Service interfaces / classes :-

    Following diagram shows the relation between  service interface and classes 
    Creating Service layer by Service Builder in Liferay - Service_Builder_Service
    Out of these service classes / interfaces, only StudentLocalServiceImpl is allowed to add additional (custom) methods at service level to developer.


    Relations among  Persistence interfaces / classes :-

    Following diagram shows the relation between  persistence interface and classes
    Creating Service layer by Service Builder in Liferay - Service_Builder_Persistence
    None of the class is allowed to add customized methods to developer. 
    So this is all about service layer generated by liferay for each entity.StudentLocalServiceUtil class is available to outer world (Portlet and other plugins) to perform CRUD operation. It contains following methods. We can call them in our portlet to Add / update / delete Students.


    .
    Note that, this class have instance variable of type StudentLocalService, which will get the instance of StudentLocalServiceImpl at run time (by spring injection). We can’t call methods of StudentLocalServiceImpl class directly. Liferay service builder will create corresponding methods of StudentLocalServiceImpl class with same method signature in StudentLocalServiceUtil class.’
    All methods of this (StudentLocalServiceUtil) class will internally call corresponding method of StudentLocalServiceImpl to perform CRUD operation. In general, you have access to XXXLocalServiceUtil class (Where XXX represents entity name). All methods of XXXLocalServiceUtil class will internally call method of XXXLocalServiceImpl class.
    And that’s all. You can create more than one entity to understand the underlying class structure generated by liferay.
    Advantage:1>reduce code
    2>less effort/time of developer

    • One of the important advantage of using liferay service builder is it supports entity level caching which helps to improve performance of read queries.
    • If your business requirement doesn’t satisfy with the basic CRUD operation and finder method, you can still write custom SQL queries and dynamic queries in Liferay service builder. This can be useful in a case when you want to access information from multiple tables by SQL join.


    Row Checker:
    If you want to select multiple rows then you can go with row checker


    Use the below code in jsp:

    <aui:form method="post" name="fm">
                <aui:input name="studentIds" type="hidden" />
                <liferay-ui:search-container delta="5"
                     iteratorURL="<%=iteratorURL%>"
                    rowChecker="<%=new RowChecker(renderResponse)%>">
                    <liferay-ui:search-container-results
                        results="<%=ListUtil.subList(courseStudents, searchContainer.getStart(), searchContainer.getEnd())%>"
                        total="<%=courseStudents.size()%>" />

                    <liferay-ui:search-container-row
                        className="com.ekhub.servicelayer.model.CourseStudent"
                        modelVar="courseStudent" keyProperty="uid">
                        <liferay-ui:search-container-column-text property="uid"
                            name="Student Id" />
                                                            <liferay-ui:search-container-column-text name="Assign"
                            href="<%=studentAssignURL.toString()%>" value="Assign" />
                    </liferay-ui:search-container-row>

                    <liferay-ui:search-iterator searchContainer="<%=searchContainer%>" />
                </liferay-ui:search-container>
                <aui:button value="Assign Selected Students"
                    onClick='<%= renderResponse.getNamespace() + "assignStudents();" %>' />

            </aui:form>



    Script in Jsp page

    <aui:script>
    Liferay.provide(
            window,
            '<portlet:namespace />assignStudents',
            function() {
                        var checkBoxValue = Liferay.Util.listCheckedExcept(document.<portlet:namespace />fm, "<portlet:namespace />allRowIds");
                        if(checkBoxValue==""||checkBoxValue==null){
                                alert('<%= UnicodeLanguageUtil.get(pageContext, "Please select atleast one student to assign") %>');
                                return false;
                        }
                        if (confirm('<%= UnicodeLanguageUtil.get(pageContext, "Are you sure you want to assign the selected students? ") %>')) {
                        document.<portlet:namespace />fm.<portlet:namespace />studentIds.value=checkBoxValue;
                        submitForm(document.<portlet:namespace />fm, "<%=studentAssignURL.toString()%>");
                   
                }
            },
            ['liferay-util-list-fields']
        );
    </aui:script>





    Then in java method write the below code

    public void assignStudentAction(ActionRequest request,
                ActionResponse response) throws IOException, PortletException,
                SystemException, PortalException {
            StudentAssessmentMap  studentAssessmentMap = new  StudentAssessmentMapImpl();
            long assessmentId = ParamUtil.getLong(request, "assessmentId");
            long[] studentIds = StringUtil.split(
                    ParamUtil.getString(request, "studentIds"), 0L);
       
            for (int i = 0; i < studentIds.length; i++)
            {
                studentAssessmentMap.setAssessmentId(assessmentId);
                studentAssessmentMap.setStudentId(studentIds[i]);
                StudentAssessmentMapLocalServiceUtil.addStudentAssessmentMap(studentAssessmentMap);
            }
        }

    Step 1:
    Create Structure
    Go to content


    then click on manage structures.Then fill name and other required fields


    Then select the field types you want.We have fields like document,date,text,etc.Drag and drop the fields you need.


    Then click on settings to change the label name,Required field,repeatable,etc.And save the structure.

    Note:You can use repeatable to get multiple values from the user.


    Step 2:Create Template for this structure.Click on the structure and goto manage templates.



    Give template name and the fields which you selected in structure will be displayed here under fields.


    Click on the fields it will generate code for you dynamically and you can style as you need

    Step 3:Then add web content display.Click on add web content

    Then select the structure and template at the top.It will display the fields.Enter the values and publish the web content display.It will display in the style which you have given in template.








 





No comments:

Post a Comment