Saturday, March 9, 2013

Change User Portrait from Custom Portlet in Liferay 6.1

Use below tag if you want to provide change and delete user portrait functionality from your custom portlet.



 
 
 
 




"
       logoDisplaySelector=".user-logo"
       showBackground="<%= false %>"



Friday, March 8, 2013

Encrypt URL Parameter in Liferay

Many time we need our URL parameters to be encoded when pass some sensitive information. So here the code which will help you to encode and decode URL Parameters.

Using below snippet you can encrypt your parameters.

 /**
     * Encrypt email address
     * @param emailAddress
     * @return
     */
    public static String encryptData(String emailAddress)
    {

        String encryptedData = StringPool.BLANK;
        try
        {
            encryptedData = Encryptor.encrypt(getEncryptionKey(), emailAddress);
            
        } catch (EncryptorException e)
        {
            LOGGER.error(e.getMessage(), e);
        }
        return encryptedData;
    }




 /**
     * Get encryption key
     * @return
     */
    public static java.security.Key getEncryptionKey()
    {

        Company company = CompanyLocalServiceUtil.getCompanyByWebId("liferay.com");
        java.security.Key key = company.getKeyObj();
        return key;
    }

Below code you can use to decry pt parameter.
 String  emailAddress = Encryptor.decrypt(getEncryptionKey(), emailAddress);

Thursday, January 3, 2013

Save Portlet Preferences in Liferay 6.1

With Liferay 6.1 if you are using configuration mode and if you want to store form elements values in preferences then this post will definitely help you.

You can store form elements value in preferences with less efforts (as compare to version below Liferay 6.1).

You just need to follow few syntax to achieve this functionality. Lets go step by step.

Define your AUI element with below syntax
<aui:input name="preferences--showFeedTitle--" type="checkbox" value="<%= showFeedTitle %>" />


It should follow pattern like preferences--paramName-- .

And make sure you use below Configuration class in your liferay-portlet.xml
<configuration-action-class>com.liferay.portal.kernel.portlet.DefaultConfigurationAction</configuration-action-class>


By using this way we dont need to write any code to store form element value into preferences . DefaultConfigurationAction class will detect form element with specified syntax and store the same in preference for you.

In case if you want to retrieve value from preference then directly use
preferences.getValue("showFeedTitle")
// No need to use that syntax to get value  

Tuesday, November 6, 2012

Enable NTLM for other browser in Liferay 6.1


Integration of NTLM is supported with only Internet Explorer due to security issues.
To enable NTLM for other browsers, follow below instruction make necessary changes in NTLMFilter.java

Below is OOB code


@Override
 public boolean isFilterEnabled(
  HttpServletRequest request, HttpServletResponse response) {

  try {
   long companyId = PortalInstances.getCompanyId(request);

   if (BrowserSnifferUtil.isIe(request) &&
    AuthSettingsUtil.isNtlmEnabled(companyId)) {

    return true;
   }
  }
  catch (Exception e) {
   _log.error(e, e);
  }

  return false;
 }

Before Authentication liferay will perform check whether NTLM is enabled or not and also checks whether current browser is IE only.
So in case if you try to access site with browser other then IE in that case you will see login screen and user will not be authenticated automatically.


So just to enable NTLM with other browser you have to override  isFilterEnabled() method.
Remove check for IE and the updated code will be like this .

@Override
 public boolean isFilterEnabled(
  HttpServletRequest request, HttpServletResponse response) {

  try {
   long companyId = PortalInstances.getCompanyId(request);

   if (AuthSettingsUtil.isNtlmEnabled(companyId)) {

    return true;
   }
  }
  catch (Exception e) {
   _log.error(e, e);
  }

  return false;
 }
About BrowserSnifferUtil
BrowserSnifferUtil is one of the good API which can help you to detect your current browser and operating system based on user agent.

BrowserSnifferUtil.getBrowserId(httpRequest)
Abvoe method will return string . If you current browser is Internet Explorer then this method will return ie .
If your current browser is FireFox then it will return firefox and for remaining browser it will return other.


BrowserSnifferUtil.isIe(httpRequest) will retuen true if your current browser is IE. There are other methods in this util to check for Mozila , chrome , safari etc.

You can also check your current operating system using this util.
like isWindows(httpRequest) method will check if current operating system is windows or not.


Monday, November 5, 2012

Add Resource Permission in LR 6.1


Using ResourcePermission we can easily provid permission on resources. Earlier in LR5.X we were using ResourceLocalServiceUtil for the same purpose.
Look into this post for more information on how to add resource permission in LR5.X

For LR 6.1
 
ResourcePermission resourcePermission = null;
try
   {
    resourcePermission = ResourcePermissionLocalServiceUtil.getResourcePermission(companyId,
    DLFileEntry.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, String.valueOf(fileEntry.getPrimaryKey()), role.getRoleId());
        
 ResourceAction resourceAction = ResourceActionLocalServiceUtil.getResourceAction(DLFileEntry.class.getName(), ActionKeys.VIEW);
  
    if(Validator.isNotNull(resourcePermission)&& !ResourcePermissionLocalServiceUtil.hasActionId(resourcePermission,resourceAction))
    {
      resourcePermission.setActionIds(resourcePermission.getActionIds() + resourceAction.getBitwiseValue());
      ResourcePermissionLocalServiceUtil.updateResourcePermission(resourcePermission);
    }
   
   } catch (com.liferay.portal.NoSuchResourcePermissionException e)
     {    
      resourcePermission = ResourcePermissionLocalServiceUtil.createResourcePermission(CounterLocalServiceUtil.increment());
      resourcePermission.setCompanyId(companyId);
      resourcePermission.setName(DLFileEntry.class.getName());
      resourcePermission.setScope(ResourceConstants.SCOPE_INDIVIDUAL);
      resourcePermission.setPrimKey(String.valueOf(fileEntry.getPrimaryKey()));
      resourcePermission.setRoleId(memberDSIRole.getRoleId());
    
      ResourceAction resourceAction = ResourceActionLocalServiceUtil.getResourceAction(DLFileEntry.class.getName(), ActionKeys.VIEW);
      resourcePermission.setActionIds(resourceAction.getBitwiseValue());// (ActionKeys.VIEW);
      ResourcePermissionLocalServiceUtil.addResourcePermission(resourcePermission);
 }
                   

Wednesday, August 1, 2012

Implement Scheduler in Liferay 6.1

Many times we want our logic to be executed at certain Date/Time .Liferay 6.X comes with in built capability of scheduler. Here is the example which can help you ..!!
1) Make below entry in Liferay-portlet.xml
<scheduler-entry>
 <scheduler-description>test-scheduler</scheduler-description>
  
 <scheduler-event-listener-class>
                     com.test.scheduler.UploadJob
        </scheduler-event-listener-class>
    
 <trigger>
  <cron>
      <cron-trigger-value>0 0 18 * * ? *</cron-trigger-value>
  </cron>
 </trigger>
</scheduler-entry>

This (<cron -trigger-value>0 0 18 * * ? *<cron -trigger-value>) indicates that the scheduler will run every day at 18:00 PM. To know how to write cron expression you can visit below links.
Cron Trigger
Cron Maker

2) create scheduler class.

package com.test.scheduler;
import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageListener;
import com.liferay.portal.kernel.messaging.MessageListenerException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;

public class UploadJob implements MessageListener
{
    private static final Log LOGGER = LogFactoryUtil.getLog(UploadJob.class);

    /**
     * Job that we need to run on scheduler
     */
    public void receive(Message arg0) throws MessageListenerException {
          
            LOGGER.info("Scheduler----> receive()");
     //write your logic.
          
        
    }
} 

Thursday, July 26, 2012

Liferay 6.1 Configuration Mode

Liferay 6.1 has lots of new features . Currently i am working with Liferay 6.1 and come to know about some of the cool features of it. So here i am sharing things i know.

 1) First thing i want to share about Liferay 6.1 is its Configuration Mode . We can easily create Configuration mode just by creating one JSP and few entries in XML .

 What we need to do is we just need to follow some standard to do it with minimal effort.
 Earlier in LR 5.2.X to create configuration we need to do so many stuff.
 -make entry in liferay-portlet.xml
 -create ConfigurationActionImpl class -
-write logic to save configuration data in preferences
-create configuration JSP .

 Now if we do the same thing LR 6.1 then it wont take much time Just follow below steps . Make below entry in your liferay-portlet.xml
com.liferay.portal.kernel.portlet.DefaultConfigurationAction

This is the class created by Liferay which will do all the stuff for us . (to store data in preference , to display configuration JSP) Now to render your configuration page when user click on configuration make below entry in portlet.xml

 config-jsp
 /html/configuration.jsp

you can also specify config-template instead of config-jsp that will also work.
To store you configuration data automatically into preferences we just need to follow some standard.
Let say if you have one text box in configuration JSP and you want to store its data into preferences.
Make sure you create your text field with the following way.

It should follow (preferences--attrName--) pattern.

And if you want to retrive value from preferences then you can get it by doing.
String awardYear = preferences.getValue("awardYear", StringPool.BLANK);


Thursday, July 12, 2012

Language Hook


We can also override a Language.properties files from a hook.The process is almost similar to the ones described in this post.

All you need to do is create a Language file for the language whose messages you want to customize and then refer to it from your liferay-hook.xml.

Here are the steps :

1) Specify below property in liferay-portlet.xml.
 
      content/Language.properties
      content/Language_en.properties
  
2) Create Lanuguage.properties and Language_en.properties under WEB-INF/src/content.
Provide labels you want to override .

Wednesday, July 4, 2012

Override Events Using Hook in Liferay 6.1


Here is the example to override events using hook in Liferay 6.1.

Specify below property in your liferay-hook.xml

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

Now create portal.properties inside example-hook/docroot/WEB-INF/src.

Specify events you wants to override in portal.properties file

i.e
servlet.service.events.pre=com.sample.portal.kernel.events.CustomServicePreAction

You are done ..!! create CustomServicePreAction to override above event.

Friday, June 22, 2012

Upgrade Database from Liferay 6.0 to Liferay 6.1


To upgrade Liferay from 6.0 to Liferay 6.1 use below steps .

Setup LR 6.1 and add below property in your portal-ext.properties file of LR 6.1
//Specify hook you have used in LR 6.0
dl.store.impl=com.liferay.portlet.documentlibrary.store.AdvancedFileSystemStore
jdbc.default.driverClassName=net.sourceforge.jtds.jdbc.Driver
jdbc.default.url=jdbc:jtds:sqlserver://localhost/lportal (point to LR6.0 DB)
jdbc.default.username=
jdbc.default.password=

Before you start server you need to copy paste old documents and images of
LR 6.0 into LR 6.1 .
Copy data folder of LR 6.0 into LR 6.1 set up . If you not copy this documents then migration will not be completed successfully .
You may not see any of your documents or images if you dont copy data folder before migration.

At the time of server start up Liferay automatically detects the Database whether its of current version or any other downgraded version.
(check release_ table for more inforamtion)

Once you start the server upgrade process will automatically start because we have pointed database of LR 6.X.
You will see serveral upgrade logs . Wait for upgrade process to complete .

You can use the migration tool available inside Control Pannel -- > Server Administration -- > Database Migration
at any point of time to migrate your documents and images from one repository to another repository.

Look into Liferay 6.1 user guide for more details about upgradation.
http://www.liferay.com/es/documentation/liferay-portal/6.1/user-guide/-/ai/upgrading-lifer-5