Pages

Wednesday 25 April 2012

Caching a particular Entity disabling - custom portlet

Entity caching disabling - custom portlet

In some cases we need to disable caching for some Entities in Liferay according to requirements. In one of my project i got a requirement where i got this use case for my plugin portlet


By default Liferay caches all the entities.

First Option : One way to do it is, at entity level in service.xml set cache-enabled attribute to false as below

    <entity name="MyModelEntity" table="MyModelEntity" local-service="true" remote-service="true" cache-enabled="false">

Second option:  You can disable the same @ portlet level by setting following properties, in your portal.properties under src folder of your portlet plugin add following porperties (I am not pretty much sure about below one)

value.object.entity.cache.enabled.com.xyz.abc.common.model.MyModelEntity=false;
value.object.finder.cache.enabled.com.xyz.abc.common.model.MyModelEntity=false;

Colored in blue is path to your model entity

I hope it will helpful for some who is looking for similar stuff.

Thanks to http://btnkumar.blogspot.in

Bogs & Wiki links for JSON usage

Hi friends ,
                These are different links for playing around JSON + Liferay.

JSON: Just Some Outstanding News
http://www.liferay.com/web/igor.spasic/blog/-/blogs/9009873

JSON Web Services
http://www.liferay.com/community/wiki/-/wiki/Main/JSON+Web+Services

JSON Serialization
http://www.liferay.com/community/wiki/-/wiki/Main/JSON+Serialization

JSON Service API
http://www.liferay.com/community/wiki/-/wiki/Main/json+service+api

Portlet Communication Configuration
http://www.liferay.com/zh/community/wiki/-/wiki/Main/Portlet+Communication+Configuration

Undersgtanding the Syntax of jQuery - YUI3 - AlloyUI

Getting Started

1.  jQuery 1.4.2     : $('div.foo:first')
2.  YUI 3.3.0        : Y.one('div.foo')
3.  AUI 1.0.1        : A.one('div.foo')
 
 
 
jQuery, YUI3, & AUI use similar selector syntax, but jQuery has added extensions, mainly convenience pseudo-classes, to the Sizzle CSS3-compliant selector engine. YUI3 & AUI comes with three different selector engines; see the section on Selectors.

Please go through below site for more details.I found it very helpful.
            Jquery -- YUI -- AUI (Syntax diff)
Thanks
Srikanth







What we can do with System.properties ?


The system.properties file is provided for a  convenient way to set all properties for the JVM machine and related system settings. Start your application server with the system property “system.properties.load = true” to load it.

 When the server starts, the portal will load system.properties and then system-ext.properties.
Start your application server with the system property “system.properties.final=true” if the properties of
system.properties override all similar command line properties.
If set to false, the properties of system.properties will be set if and only if those properties are not currently set.
Some application servers require you to set the file.encoding and user.timezone on startup regardless of system.properties because the application server reads these properties before
system.properties is ever loaded.
Following  are the default values of the
system.properties properties are shown:
##
## Java
##

    #
    # The file encoding must be set to UTF-8 in order for the
    # internationalization to work correctly.
    #
    file.encoding=UTF-8

    #
    # Java uses the underlying operating system to generate images. If you are
    # using Unix and do not start the portal in a X Windows session, then Java
    # will not know how to generate images and you'll get lots of nasty
    # exceptions. Setting this property to true will fix that. Sometimes this
    # property cannot be set dynamically when the server starts and you'll need
    # to edit your start script to include this as a system property.
    #
    java.awt.headless=true

    #
    # Set the default language.
    #
    user.country=US
    user.language=en

    #
    # The time zone must be set GMT so that the portal knows how to properly
    # translate time across time zones.
    #
    user.timezone=GMT

##
## Servlet Filters
##

    #
    # If the user can unzip compressed HTTP content, the compression filter will
    # zip up the HTTP content before sending it to the user. This will speed up
    # page rendering for users that are on dial up.
    #
    com.liferay.filters.compression.CompressionFilter=true
    com.liferay.filters.compression.CompressionFilter.encoding=UTF-8

    #
    # The strip filter will remove blank lines from the outputted content. This
    # will speed up page rendering for users that are on dial up.
    #
    com.liferay.filters.strip.StripFilter=true
    com.liferay.filters.strip.StripFilter.encoding=UTF-8

    #
    # The layout cache filter will cache pages to speed up page rendering for
    # guest users. Set the refresh time in milliseconds on how often the cache
    # should refresh. Set it to 0 if the cache never times out. Default time out
    # is set to one hour.
    #
    com.liferay.portal.servlet.filters.layoutcache.LayoutCacheFilter=true
    com.liferay.portal.servlet.filters.layoutcache.LayoutCacheFilter.encoding=UTF-8
    com.liferay.portal.servlet.filters.layoutcache.LayoutCacheFilter.refresh.time=3600000

    #
    # The virtual host filter maps hosts to public and private pages. For
    # example, if the public virtual host is www.helloworld.com and the friendly
    # URL is /helloworld, then http://www.helloworld.com is mapped to
    # http://localhost:8080/web/helloworld.
    #
    com.liferay.portal.servlet.filters.virtualhost.VirtualHostFilter=true

    #
    # The CAS filter will redirect the user to the CAS login page for SSO. See
    # http://www.ja-sig.org/products/cas for more information.
    #
    com.liferay.filters.sso.cas.CASFilter=false

##
## Logging
##

    #
    # Set any logger that implements org.apache.commons.logging.Log.
    #
    #org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger

    #
    # Set the following to true if Log4j complains that it was not properly
    # configured.
    #
    log4j.configure.on.startup=true

##
## Encryptor
##

    #
    # Set the security provider class.
    #
    com.liferay.util.Encryptor.provider.class=com.sun.crypto.provider.SunJCE

##
## HTTP
##

    #
    # Set the location of the HTTP proxy that the portal will use to fetch
    # external content.
    #
    #http.proxyHost=192.168.0.200
    #http.proxyPort=4480

    #
    # These are read for backwards compatibility and only used if the
    # "http.proxyHost" and "http.proxyPort" settings are not specified.
    #
    #com.liferay.util.Http.proxy.host=192.168.0.200
    #com.liferay.util.Http.proxy.port=4480

    #
    # Set the proxy authentication type.
    #
    #com.liferay.util.Http.proxy.auth.type=username-password
    #com.liferay.util.Http.proxy.auth.type=ntlm

    #
    # Set user name and password used for HTTP proxy authentication.
    #
    #com.liferay.util.Http.proxy.username=
    #com.liferay.util.Http.proxy.password=

    #
    # Set additional properties for NTLM authentication.
    #
    #com.liferay.util.Http.proxy.ntlm.domain=
    #com.liferay.util.Http.proxy.ntlm.host=

    #
    # Set the connection timeout when fetching HTTP content.
    #
    com.liferay.util.Http.timeout=5000

##
## Format
##

    #
    # Set the location of the class that implements
    # com.liferay.format.PhoneNumberFormat. This class will format phone
    # numbers.
    #
    com.liferay.util.format.PhoneNumberFormat=com.liferay.util.format.USAPhoneNumberFormat
    #com.liferay.util.format.PhoneNumberFormat=com.liferay.util.format.IdenticalPhoneNumberFormat

##
## Axis
##

    #
    # Urls that match the specified pattern will use the SimpleHTTPSender. Urls
    # that do not match the specified pattern will use Axis' default HTTPSender.
    #
    com.liferay.util.axis.SimpleHTTPSender.regexp.pattern=.*mappoint\.net.*

##
## XSS (Cross Site Scripting)
##

    #
    # Set the pattern to strip text of XSS hacks.
    #
    com.liferay.util.XSSUtil.regexp.pattern=(?i)<[\\s]*/?script.*?>|<[\\s]*/?embed.*?>|<[\\s]*/?object.*?>|<[\\s]*a[\\s]*href[^>]*javascript[\\s]*:[^(^)^>]*[(][^)]*[)][^>]*>[^<]*(<[\\s]*/[\\s]*a[^>]*>)*

##
## Upload Servlet Request
##

    #
    # Set the maximum file size. Default is 1024 * 1024 * 1000.
    #
    com.liferay.util.servlet.UploadServletRequest.max.size=104857600

    #
    # Set the temp directory for uploaded files.
    #
    #com.liferay.util.servlet.UploadServletRequest.temp.dir=C:/Temp

##
## Session Parameters
##

    #
    # Encrypt session parameters so that browsers cannot remember them.
    #
    com.liferay.util.servlet.SessionParameters=true

##
## Lucene
##

    #
    # Set a timeout to avoid lock errors.
    #
    #org.apache.lucene.writeLockTimeout=30000

##
## Quartz
##

    #
    # Make threads daemon so the JVM exits cleanly.
    #
    org.quartz.threadPool.makeThreadsDaemons=true

##
## Velocity Engine
##

    #
    # Input a list of comma delimited class names that extend
    # com.liferay.util.velocity.VelocityResourceListener. These classes will
    # run in sequence to allow you to find the applicable ResourceLoader
    # to load a Velocity template.
    #
    com.liferay.util.velocity.VelocityResourceListener=com.liferay.portal.velocity.ServletVelocityResourceListener,\
com.liferay.portal.velocity.JournalTemplateVelocityResourceListener,\
com.liferay.portal.velocity.DefaultVelocityResourceListener

Implement Captcha in Liferay Portlet

Sometimes it is required to add captcha functionality into portlet. Liferay already have everything required, and already used captcha in some internal portlets (login, message board), but, it is implemented using with CaptchaPortletAction - what is not available for plugins (in case you are developing in plugin environment).
So, here is small receipt how to enable liferay's captcha in your portlet developed in plugin environment.

Generate Captcha

In portlet, in my case inherited from JSPPortlet (renamted to MVCPortlet in post-5.2.3) class we need to add method serverResource - something like this:
public class CaptchaSamplePortlet extends JSPPortlet {
    /** Serve Resource used for getting captcha
     *
     */
    @Override
    public void serveResource(ResourceRequest resourceRequest,
                             ResourceResponse resourceResponse) throws IOException, PortletException {
        try {
            com.liferay.portal.kernel.captcha.CaptchaUtil.serveImage(resourceRequest, resourceResponse);
        } catch (Exception e) {
            log.error(e);
        }
    }
}
This method doing everything - generated captcha and returned it's content (with all required http-readers into response), as well as placed required data into session

Display Captcha

Now, to place captcha into jsp you need to place:
<portlet:resourceURL var="captchaURL"/>
<liferay-ui:captcha url="<%= captchaURL %>"/>
That will place captcha control and point it to our portlet resourceURL to generate image
Now, you will have captcha and field to enter captcha text on your form generated by these tags.

Validate Captcha

To check captcha add followed function in your action-handler in portlet-class:
private void checkCaptcha(PortletRequest request) throws Exception {
        String enteredCaptchaText = ParamUtil.getString(request, "captchaText");

        PortletSession session = request.getPortletSession();
        String captchaText = getCaptchaValueFromSession(session);
        if (Validator.isNull(captchaText)) {
            throw new Exception("Internal Error! Captcha text not found in session");
        }
        if (!StringUtils.equals(captchaText, enteredCaptchaText)) {
            throw new Exception("Invalid captcha text. Please reenter.");
        }
    }

    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;
    }
What is all - now, you can do everything - display captcha, enter value - and check it

Monday 23 April 2012

Writing a utility class for finding Role of a User


                Writing a utility class for finding Role of a User


Hi everyone,
                This article is for developers quick reference  to create a Custom Util class which will enable the developer to use a single method and find user’s ROLE .
It internally uses Liferay provided API i.e. com.liferay.portal.service.RoleServiceUtil


Just copy below code into a class and use it anywhere you want.



import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.model.Role;
import com.liferay.portal.model.User;
import com.liferay.portal.service.RoleServiceUtil;

import com.liferay.portal.kernel.exception.SystemException;


/**
 * @Author Srikanth S
 * @Description Portlet provides All Roles dependencies for User.
 */
public class RoleUtil {
     
      private static Log _log = LogFactoryUtil.getLog(RoleUtil.class);
        /**
         * Checks whether the user is power user or not.
         *
         * @param user
         *            instance of user.
         * @return Boolean value true or false.
         */

        public static boolean isPowerUser(User user)
        {
                return isUserInRole(user, "Power User");
        }

        /**
         * Checks whether the user is administrator or not.
         *
         * @param user
         *            instance of user.
         * @return Boolean value true or false.
         */

        public static boolean isAdmin(User user)
        {
                return isUserInRole(user, "Administrator");
        }

        /**
         * Checks whether the user is guest or not.
         *
         * @param user
         *            instance of user.
         * @return Boolean value true or false.
         */

        public static boolean isUser(User user)
        {
                return isUserInRole(user, "User");
        }

        /**
         * Checks whether the user belongs to corresponding role.
         *
         * @param user
         *            instance of user.
         * @param role
         *            role of user.
         * @return Boolean value true or false.
         */

        private static boolean isUserInRole(User user, String role)
        {
                boolean flag = false;

                if (user == null) return false;

                try {
                      for (Role role1 : RoleServiceUtil.getUserRoles(user.getUserId())) {
                              if (role1.getName().equalsIgnoreCase(role)) {
                                      flag = true;
                                      break;
                              }
                      }
                }catch (SystemException se) {
                  if(_log.isDebugEnabled()){
                                    _log.debug("SystemException : "+ se.getMessage());
                               }
               }
                return flag;
        }
}






Now you can use this in any class or even in JSP’s directly as shown below.
Example :<init.jsp>

<%@ page contentType="text/html; charset=UTF-8"%>

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib uri="http://liferay.com/tld/portlet" prefix="liferay-portlet" %>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<%@ taglib uri="http://liferay.com/tld/util" prefix="liferay-util" %>
<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<%@page import="com.cisco.nci.mobileapps.common.util.RoleUtil"%>

<liferay-theme:defineObjects />
<portlet:defineObjects />

<%
      boolean isGuest = !themeDisplay.isSignedIn();
      boolean isAdmin = !isGuest && themeDisplay.getPermissionChecker().isCompanyAdmin();
      boolean isPowerUser = !isAdmin && RoleUtil.isPowerUser(user);
      boolean isUser = !isPowerUser && RoleUtil.isUser(user);
     
      String currentCommunityName = themeDisplay.getLayout().getGroup().getName();
      String pageName = themeDisplay.getLayout().getName(themeDisplay.getLocale()).toLowerCase();
     
      String ctxPath = request.getContextPath();
%>


Hope this was helpful

Regards
Srikanth S