Monday, 26 November 2012


Liferay PortletURL in JavaScript
Since few months ago I want to blog post about the new Liferay functionality that let you build PortletURLs using JavaScript only.There are many places you can apply this new way of generating PortletURLs. Imagine a big list of links on your portlet, instead of download repeated hundreds urls from the server site you can simply create a javascript function that retuns a PortletURL instance and set on the fly the parameters you need. And now, you can simply integrate your pure javascript files (.js) with PortletURLs, without over passing it as parameter for your javascript constructor or another work-arround came from our misterious mind.

The usage of this functionality using JavaScript is very simple:

<script>
var  portletURL = new Liferay.PortletURL();
portletURL.setParameter("key1", "value");
portletURL.setParameter("key2", "value");
portletURL.setPortletId(86);
alert( "that is the url: " + portletURL.toString() );
</script>

Or you can simply wrap it into a javascript function:

<script>
function createRowURL( row ) {
   var portletURL = new Liferay.PortletURL();
   portletURL.setParameter("rowNumber", row );

   return portletURL.toString();
}

alert( "row1: " + createRowURL(1) );
alert( "row2: " + createRowURL(2) );
</script>

If you want to know what methods you can play with the JavaScript Liferay.PortletURL you can take a quick look on the methods below:

setCopyCurrentRenderParameters: function(copyCurrentRenderParameters);
setDoAsUserId: function(doAsUserId);
setEncrypt: function(encrypt);
setEscapeXML: function(escapeXML);
setLifecycle: function(lifecycle);
setName: function(name);
setParameter: function(key, value);
setPlid: function(plid);
setPortletConfiguration: function(portletConfiguration);
setPortletId: function(portletId);
setPortletMode: function(portletMode);
setResourceId: function(resourceId);
setSecure: function(secure);
setWindowState: function(windowState);
toString: function();
I've also created some shortcuts for diferent kind of urls on the portal:

var actionURL = Liferay.PortletURL.createActionURL(); // = new Liferay.PortletURL('ACTION_PHASE');
var renderURL = Liferay.PortletURL.createRenderURL(); // = new Liferay.PortletURL('RENDER_PHASE');
var resourceURL = Liferay.PortletURL.createResourceURL(); // = new Liferay.PortletURL('RESOURCE_PHASE');
var permissionURL = Liferay.PortletURL.createPermissionURL(portletResource, modelResource, modelResourceDescription, resourcePrimKey);

Saturday, 17 November 2012

java.lang.OutOfMemoryError in Java

Every one in java development face java.lang.OutOfMemoryError now and then, OutOfMemoryError in Java is one problem which is more due to system's limitation (memory) rather than due to programming mistakes in most cases though in certain cases you could have memory leak which causing OutOfMemoryError.

What is java.lang.OutOfMemoryError in Java

OutOfMemoryError in Java is a subclass of java.lang.VirtualMachineError and JVM throws java.lang.OutOfMemoryError when it ran out of memory in heap. OutOfMemoryError in Java can come any time in heap mostly while you try to create an object and there is not enough space in heap to allocate that object.

Types of OutOfMemoryError in Java

I have seen mainly two types of OutOfMemoryError in Java:

1) Java.lang.OutOfMemoryError: Java heap space
2) Java.lang.OutOfMemoryError: PermGen space

Though both of them occur because JVM ran out of memory they are quite different to each other and there solutions are independent to each other.

Difference between "java.lang.OutOfMemoryError: Java heap space" and "java.lang.OutOfMemoryError: PermGen space"

If you are familiar with different generations on heap and How garbage collection works in java and aware of new, old and permanent generation of heap space then you would have easily figured out this OutOfMemoryError in Java. Permanent generation of heap is used to store String pool and various Meta data required by JVM related to Class, method and other java primitives. Since in most of JVM default size of Perm Space is around "64MB" you can easily ran out of memory if you have too many classes or huge number of Strings in your project. Important point to remember is that it doesn't depends on –Xmx value so no matter how big your total heap size you can ran OutOfMemory in perm space. Good think is you can specify size of permanent generation using JVM options "-XX:PermSize" and  "-XX:MaxPermSize" based on your project need.

One small thing to remember is that "=" is used to separate parameter and value while specifying size of perm space in heap while "=" is not required while setting maximum heap size in java, as shown in below example.

export JVM_ARGS="-Xmx1024m -XX:MaxPermSize=256m"


Another reason of "java.lang.OutOfMemoryError: PermGen" is memory leak through Classloaders and it’s very often surfaced in WebServer and application server like tomcat, webshere, glassfish or weblogic. In Application server different classloaders are used to load different web application so that you can deploy and undeploy one application without affecting other application on same server, but while undeploying if container some how keeps reference of any class loaded by application class loader than that class and all other related class will not be garbage collected and can quickly fill the PermGen space if you deploy and undeploy your application many times. "java.lang.OutOfMemoryError: PermGen” has been observed many times in tomcat in our last project but solution of this problem are really tricky because first you need to know which class is causing memory leak and then you need to fix that. Another reason of OutOfMemoryError in PermGen space is if any thread started by application doesn't exit when you undeploy your application.

These are just some example of infamous classloader leaks, anybody who is writing code for loading and unloading classes have to be very careful to avoid this. You can also use visualgc for monitoring PermGen space, this tool will show graph of PermGen space and you can see how and when Permanent space getting increased. I suggest using this tool before reaching to any conclusion.

Another rather unknown but interesting cause of "java.lang.OutOfMemoryError: PermGen" we found is introduction of JVM options "-Xnoclassgc". This option sometime used to avoid loading and unloading of classes when there is no further live references of it just to avoid performance hit due to frequent loading and unloading, but using this option is J2EE environment can be very dangerous because many framework e.g. Struts, spring etc uses reflection to create classes and with frequent deployment and undeployment you can easily ran out of space in PermGen if earlier references was not cleaned up. This instance also points out that some time bad JVM arguments or configuration can cause OutOfMemoryError in Java.

So conclusion is avoid using "-Xnoclassgc" in J2EE environment especially with AppServer.


Tomcat to Solve OutOfMemoryError in PermGen Space

From tomcat > 6.0 onward tomcat provides memory leak detection feature which can detect many common memory leaks on web-app perspective e.g ThreadLocal memory leaks, JDBC driver registration, RMI targes, LogFactory and Thread spawned by web-apps. You can check complete details on htp://wiki.apache.org/tomcat/MemoryLeakProtection you can also detect memory leak by accessing manager application which comes with tomcat, in case you are experiencing memory leak on any java web-app its good idea to run it on tomcat.
How to solve java.lang.OutOfMemoryError: Java heap space


1) Easy way to solve OutOfMemoryError in java is to increase the maximum heap size by using JVM options "-Xmx512M", this will immediately solve your OutOfMemoryError. This is my preferred solution when I get OutOfMemoryError in Eclipse, Maven or ANT while building project because based upon size of project you can easily ran out of Memory.here is an example of increasing maximum heap size of JVM, Also its better to keep -Xmx to -Xms ration either 1:1 or 1:1.5 if you are setting heap size in your java application

export JVM_ARGS="-Xms1024m -Xmx1024m"

2) Second way to resolve OutOfMemoryError in Java is rather hard and  comes when you don't have much memory and even after increase maximum heap size you are still getting java.lang.OutOfMemoryError, in this case you probably want to profile your application and look for any memory leak. You can use Eclipse Memory Analyzer to examine your heap dump or you can use any profiler like Netbeans or JProbe. This is tough solution and requires some time to analyze and find memory leaks.

How to solve java.lang.OutOfMemoryError: PermGen space

As explained in above paragraph this OutOfMemory error in java comes when Permanent generation of heap filled up. To fix this OutOfMemoryError in Java you need to increase heap size of Perm space by using JVM option   "-XX:MaxPermSize". You can also specify initial size of Perm space by using    "-XX:PermSize" and keeping both initial and maximum Perm Space you can prevent some full garbage collection which may occur when Perm Space gets re-sized. Here is how you can specify initial and maximu Perm size in Java:

export JVM_ARGS="-XX:PermSize=64M -XX:MaxPermSize=256m"

Some time java.lang.OutOfMemoryError  in Java gets tricky and on those cases profiling remain ultimate solution.Though you have freedom to increase heap size in java, it’s recommended that to follow memory management practices while coding and setting null to any unused references.
That’s all from me on OutOfMemoryError in Java I will try to write more about finding memory leak in java and using profiler in some other post. Please share what is your approach to solve java.lang.OutOfMemoryError in Java.


Important Note: From Tomcat > 6.0 onward tomcat provides memory leak detection feature which can detect many common memory leaks on Java application e.g ThreadLocal memory leaks, JDBC driver registration, RMI targes, LogFactory and Thread spawned by webapps. You can check complete details on htp://wiki.apache.org/tomcat/MemoryLeakProtection. You can also detect memoy leak by accessing manager application which comes with tomcat, in case you are experiencing memory leak on any java webapp its good idea to run it on tomcat to find out reason of OutOfMemoryError in PermGen space.


ecj not installed error

window -> preferences-> classpath ->Ant home entries -> add external jars = "from sdk\lib\ecj.jar"

or

window -> preferences -> ant -> runtime ->classpath ->Ant home entries -> add external jars = "from sdk\lib\ecj.jar"

Friday, 16 November 2012


Liferay basic set up

required setup: --------------- Ant, tomcat, sdk, eclipse, build.Administrator.properties, portal-ext.properties, note:= tomcat=delete all folder except root folder in web apps build.Administrator.properties=app.server.dir = E:/IPG-monitor-nov/tomcat/tomcat-7.0.23 portal-ext.properties= jdbc.default.driverClassName=com.mysql.jdbc.Driver jdbc.default.url=jdbc:mysql://localhost/ipg-monitor-nov?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false jdbc.default.username=root jdbc.default.password=root required path setting: ---------------------- ANT_HOME : C:\apache-ant-1.8.2; JAVA_HOME : C:\Program Files\Java\jdk1.6.0_20 Path :%ANT_HOME%\bin;%JAVA_HOME%\bin;

Wednesday, 7 November 2012




Get Web Content List in Liferay by category

e.g.
Product tempproduct=(Product)request.getAttribute("category");
AssetCategory assetCategory;
try {
List<AssetCategory> assetCategoryList = AssetCategoryLocalServiceUtil.getCategories();
System.out.println(assetCategoryList);
List<AssetEntry> assetEntryList = new ArrayList<AssetEntry>();

for (AssetCategory category : assetCategoryList)
{
if (category.getName().equalsIgnoreCase(tempproduct.getProductName())) {
assetCategory = category;
AssetEntryQuery assetEntryQuery = new AssetEntryQuery();
//long classNameId = PortalUtil.getClassNameId(JournalArticle.class.getName());
assetEntryQuery.setAnyCategoryIds(new long[] { assetCategory.getCategoryId() });
assetEntryQuery.setClassName(JournalArticle.class.getName());
assetEntryList = AssetEntryLocalServiceUtil.getEntries(assetEntryQuery);
System.out.println(assetEntryList);

}
}
}catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


Saturday, 3 November 2012


liferay – get current user roles from portlet


all you need is to add the following lin into your jsp
<%
User user = ((ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY)).getUser();
List<Role> roles = (List<Role>) RoleServiceUtil.getUserRoles(user.getUserId());
for (Role role : roles) {
out.println(role.getName() +"Arvind Jaiswal"+ role.getRoleId() );
}
%>