Tuesday, 25 December 2012


Error occurred during initialization of VM
java.lang.OutOfMemoryError: unable to create new native thread

You should have to change your jre...

Thursday, 20 December 2012


How to Submit form By  Using Ancher Tag

<form name="myform" action="MyAction">

Name : <input type='text' name='Arvind' />

      <a href="javascript: submitform()">Go</a>
</form>

<script type="text/javascript">

function submitform()
{
  document.myform.submit();
}
</script>

Tuesday, 11 December 2012

AJAX CALL IN LIFERAY

for drop down country->states->cities
using
step 1)gson.jar
step 2)create url 
<portlet:resourceURL var="ajaxCallResourceURL" />

step 3) script

 function dropdownStates(x,id) {
   AUI().use('aui-io-request',
   function callServer(A)
   {
   
    var stateid=id.substr(0,9);
   
    var dropdownId='#'+stateid+'states';
    var dropdownId1='#'+stateid+'cities';
       var countryValue  = x;
       var countryParameter="country";
       
    A.io.request("<%=ajaxCallResourceURL%>", {
        method: 'POST',
dataType: 'json',
data : {
country : countryValue,
callFor : countryParameter
},
           on : {
            success: function() {
            var states = this.get('responseData');
           
            var selectObject = $(dropdownId);
            var selectObject1 = $(dropdownId1);
            $('>option', selectObject).remove();
            $('>option', selectObject1).remove();
            $.each(states, function(key, value) {
            selectObject.append($('<option/>').val(key).text(value));
                         });
            },

failure: function()
{
alert("Failed to fetch the state for this country. Please try agian.");
}
           }
         
       } );
     
   });
}

function dropdownCities(x,id) {
   AUI().use('aui-io-request',
   function callServer(A)
   {
   
    var stateid=id.substr(0,9);
    var dropdownId='#'+stateid+'cities';
    var stateValue  = x;
       var stateParameter="state";
       
    A.io.request("<%=ajaxCallResourceURL%>", {
        method: 'POST',
dataType: 'json',
data : {
state : stateValue,
callFor:stateParameter
},
           on : {
            success: function() {
            var cities = this.get('responseData');
           
            var selectObject = $(dropdownId);
            $('>option', selectObject).remove();
            $.each(cities, function(key, value) {
            selectObject.append($('<option/>').val(key).text(value));
                         });
            },

failure: function()
{
alert("Failed to fetch the Cities for this state. Please try agian.");
}
           }
         
       } );
     
   });
}

step 4) in which filed,ajax call invoke


<div style="width: 100%;margin-top: 10px;height: 18px;font-size: 12px;font-weight: bold;" >
    <div style="float: left;width: 30%"><font style="color: red;size: 12px">* &nbsp;</font>Country</div>
    <div style="float: left;width: 50%">
    <select style="width: 97%;" onchange="dropdownStates(this.value,this.id)" id="corresponCountry" name="Country" label="">
    <c:forEach items="${countries}" var="countries">
    <option value="<c:out value='${countries.countryCode}'/>">
    <c:out value="${countries.countryName}"/>
    </option>    
    </c:forEach>
    </select>
</div>
     
    </div>
    <div style="width: 100%;margin-top: 10px;height: 18px;font-size: 12px;font-weight: bold;" >
    <div style="float: left;width: 30%"><font style="color: red;size: 12px">* &nbsp;</font>State</div>
    <div style="float: left;width: 50%" >
    <select style="width: 97%;" onchange="dropdownCities(this.value,this.id)"  id="corresponstates" name="states" label="">    
    </select>
    </div>
     
    </div>
    <div style="width: 100%;margin-top: 10px;height: 18px;font-size: 12px;font-weight: bold;" >
    <div style="float: left;width: 30%"><font style="color: red;size: 12px">* &nbsp;</font>Town</div>
    <div style="float: left;width: 50%">
    <select style="width: 97%;"  id="corresponcities" name="cities" label="">
   
    </select>
    </div>
   
    </div>


step 4) In controller class

public void serveResource(ResourceRequest request, ResourceResponse response)
throws IOException, PortletException {
String callFor = request.getParameter("callFor");
----
----
----

if ("country".equalsIgnoreCase(callFor)) {
int country = Integer.parseInt(request.getParameter("country"));
String values = new String();
List<State> states = commonService.findStatesForCountry(country);
Gson gson = new Gson();
values = gson
.toJson(ControllerHelper.convertStateListToMap(states));
response.getWriter().write(values);
}

else if ("state".equalsIgnoreCase(callFor)) {
String values = new String();
int state = Integer.parseInt(request.getParameter("state"));

List<City> cities = commonService.findCitiesForState(state);
Gson gson = new Gson();
values = gson.toJson(ControllerHelper.convertCityListToMap(cities));
response.getWriter().write(values);
}
}



How to get Logged in UserId in liferay


ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
User user = themeDisplay.getRealUser();
long userId = user.getUserId();
System.out.println("arvind"+userId);

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() );
}
%>

Wednesday, 26 September 2012

StringTokenizer 
In java, there is a way to break up a line of text into  smaller piece of a string,what are called tokens. This method of breaking up tokens are come from the StringTokenizer class.
In order for the StringTokenizer class to be used, you must import it from a certain library:-

import java.util.*;

example:-

import java.util.StringTokenizer;
public class StringTokenizerExample2{
  public static void main(String args[]){

          String s = "Five+Three=Nine-One";
   String arr[];

          //declare it with 3 tokens as seen above:
   StringTokenizer st = new StringTokenizer(s, "+=-");

   //the array size is the number of tokens in the String:
   arr = new String[st.countTokens()];

          //when there are still more tokens, place it in the array:
   int i = 0;
          while(st.hasMoreTokens()){
  arr[i] = st.nextToken();
                i++;
          }

   //determine the word with the largest length:
          int indexMax = 0;
          for(int i = 1; i < arr.length; i++){
             if(arr[i].length() > arr[indexMax].length())
   indexMax = i;
          }

   System.out.println("The largest element is in index: " 
                + indexMax);

  } //main
} //class

Tuesday, 25 September 2012



Best Example For Comparable Interface

import java.util.*;
public class DateAndName implements Comparable {
    private String date;
    private String name;
    public DateAndName(String date, String name) {
        this.date = date;
        this.name = name;
    }
    public String getDate() {
        return date;
    }
    public String getName() {
        return name;
    }
    public int compareTo(Object obj) {
        if (! (obj instanceof DateAndName)) {
            throw new ClassCastException(
                            "compared object must be instance of DateAndName");
        }
        return this.getDate().compareTo(((DateAndName) obj).getDate());
    }
    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append(getDate());
        sb.append("\t");
        sb.append(getName());
        return sb.toString();
    }
    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        list.add(new DateAndName("03-29-2003", "Harry Potter"));
        list.add(new DateAndName("02-19-2003", "Bilbo Baggins"));
        list.add(new DateAndName("03-07-2003", "Luke Skywalker"));
        System.out.println("Unsorted:");
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i).toString());
        }
        Collections.sort(list);
        System.out.println("");
        System.out.println("Sorted:");
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i).toString());
        }
    }
}

Friday, 21 September 2012

Step By Step tutorial for Bootable Usb or Pen drive


Step 1 –
  • put your pendrive or usb drive to usb port,
  • now start your command prompt by typing cmd in run and hit enter,
  • Make sure that you have Administrative account for this all process of Bootable Usb or Pendrive,
  • now type  –  DISKPART and hit Enter, you will see like in image below,
how to make usb bootable with cmd 2
Step 2 –
  • Now Type – LIST DISK
  • this command will show you all disk available in your system,
how to make usb bootable with cmd 3
Step 3 –
  • Now type SELECT DISK 2
  • as shown in above image ,
  • I choose disk 2 but you may  have different no of disks and their size are also different, my usb disk id 4GB , so i know that this disk 2 is my usb drive,
  • choose write disk because if you select wrong disk then in next step we will format them and it will erase all data from your disk.
Step 4 –
  • Now we have to clean the disk , this cleaning process will erase all sector from your disk,
  • just type  CLEAN , as shown in image given below,
  • now your disk is clean for creating fresh partition,
how to make usb bootable with cmd 5
Step 5 –
  • after cleaning the disk now we have to create a new Primary partition in your disk,
  • for creating Primary partition just type  CREATE PARTITION PRIMARY ,
  • Now you have created primary partition in your usb disk,
how to make usb bootable with cmd 6
Step 6 –
  • Now we have to select this partition and for formating for that
  • first type LIST PARTITION ,it will show all partition in your disk we have just create one partition so here is only one partition,
how to make usb bootable with cmd 8
  • Now select the partition by type  SELECT PARTITION 1
how to make usb bootable with cmd 9
Step 7 –
  • Now we will format the partition by command for formatting and we use NTFS,
  • Just type  FORMAT FS=NTFS ,
  • DISK will start formatting it will take some time,
how to make usb bootable with cmd 11
Step 8 –
  • This is the most important step because now we will activate the partition for booting,
  • just type ACTIVE ,
  • Now just type EXIT and you will out of the DISKPART ,
  • You almost done everything for creating Bootable Usb or Pendrive,
how to make usb bootable with cmd 12
Step 9 –
  • Now your usb disk is ready for booting, it is booting ready,
  • Bootable Usb or Pendrive is ready to boot any windows vista or windows 7,
Step 10 – Creating Bootable VISTA OR WINDOWS 7
  • Now just put your windows vista or windows 7 disk in disk drive and copy all files from disk to your Bootable Usb or Pendrive and your Bootable Usb or Pendrive for VISTA AND WINDOWS 7 is ready to Boot,
  • this will works fin with windows vista and windows 7 , Perfectly.
Note — in any case
  • Make sure that your windows vista and windows 7 have all essential file for Booting,
  • Spatially folder name ( boot and efi )

Note –

  • Make sure to set your BIOS to boot priority will be USB or REMOVABLE DISK,
  • it may be different in different systems,
All done well now enjoy the Bootable Usb or Pendrive for Booting Windows Vista and Windows 7 .

Wednesday, 19 September 2012

How To Add protlet in theme



#set ($VOID = $velocityPortletPreferences.setValue('portlet-setup-show-borders', 'false'))
#set ($myPortletId = "pricingcontroller_WAR_Pricingportlet")
$taglibLiferay.runtime($myPortletId, '', $velocityPortletPreferences.toString())

Tuesday, 18 September 2012


Creating simple struts Portlet in liferay in 5 min
In struts portlet as compare to Jsp portlet we need to add 2 extra xml files

1.struts-config.xml
2.tiles-defs.xml

We have to modify follwing xml files.

These xml files are located under "ext/ext-web/docroot/WEB-INF"

2.1. portlet-ext.xml
--------------------

<portlet>
<portlet-name>Sample</portlet-name>
<display-name>Sample Struts Portlet</display-name>
<portlet-class>com.liferay.portlet.StrutsPortlet</portlet-class>
<init-param>
<name>view-action</name>
<value>/ext/sample/view</value>
</init-param>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
</supports>
<resource-bundle>com.liferay.portlet.StrutsResourceBundle</resource-bundle>
<security-role-ref>
<role-name>power-user</role-name>
</security-role-ref>
<security-role-ref>
<role-name>user</role-name>
</security-role-ref>
</portlet>

2.2. liferay-portlet-ext.xml
----------------------------

<portlet>
<portlet-name>Sample</portlet-name>
<struts-path>ext/sample</struts-path>
<use-default-template>false</use-default-template>
</portlet>

2.3. liferay-display.xml
------------------------

add

<portlet id="Sample" />

inside

<category name="category.sample">

2.4. struts-config.xml
----------------------

<action path="/ext/sample/view" forward="portlet.ext.sample.view" />

2.5. tiles-defs.xml
-------------------

<definition name="portlet.ext.sample" extends="portlet" />
<definition name="portlet.ext.sample.view" extends="portlet.ext.sample">
<put name="portlet_content" value="/portlet/ext/sample/view.jsp" />
</definition>


(create the following two jsp files under "/ext/ext-web/docroot/html/portlet/ext/sample")

2.6. init.jsp
-------------

<%@ include file="/html/portlet/init.jsp" %>

2.7. view.jsp
-------------

<%@ include file="/html/portlet/ext/sample/init.jsp" %>
Simple Struts Portlet!

2.8 Language-ext.properties
---------------------------

Add a new entry in the above file,

javax.portlet.title.Sample=Sample Struts Portlet

orderable search container in liferay by example

Liferay provide us with many good taglib out of them search container is one of them.It is widely used taglib. For simple understanding of search container please check Wiki here is the link Wiki Search Container. One thing that article is missing how to implement ordering using. For that we will follow few step and will do a simple example.

Step 1: Read the wiki article Search Container.
Step 2:Now write the below code in your jsp.

<%
PortalPreferences portalPrefs = PortletPreferencesFactoryUtil.getPortalPreferences(request);
String orderByCol = ParamUtil.getString(request, "orderByCol");

String orderByType = ParamUtil.getString(request, "orderByType");

if (Validator.isNotNull(orderByCol) && Validator.isNotNull(orderByType)) {
portalPrefs.setValue("KK_3", "kk-order-by-col", orderByCol);
portalPrefs.setValue("KK_3", "kk-order-by-type", orderByType);

} else {

orderByCol = portalPrefs.getValue("KK_3", "kk-order-by-col", "name");
orderByType = portalPrefs.getValue("KK_3", "kk-order-by-type", "asc");

}

OrderByComparator orderByComparator = AddressBookUtil.getAddressBookOrderByComparator(orderByCol, orderByType);
%>


Now I will explain what is happening we are getting the column on which we have to do ordering in orderByCol and order asc or desc in orderByType.
In line portalPrefs.setValue("KK_3", "kk-order-by-col", orderByCol);
here "KK_3" is namespace , "kk-order-by-col" is key and orderByCol is value.
In last line OrderByComparator orderByComparator = AddressBookUtil.getAddressBookOrderByComparator(orderByCol, orderByType);
For this you need to write a comparator , I have written it in com.ext.portlet.addressBook.util.AddressBookUtil and write this code


public class AddressBookUtil {

/**
*
* @param orderByCol
* @param orderByType
* @return
*/

public static OrderByComparator getAddressBookOrderByComparator(
String orderByCol, String orderByType) {

boolean orderByAsc = false;

if (orderByType.equals("asc")) {
orderByAsc = true;
}

OrderByComparator orderByComparator = null;

if (orderByCol.equals("name")) {
orderByComparator = new AddressBookNameComparator(orderByAsc);
} else if (orderByCol.equals("status")) {
orderByComparator = new AddressBookStatusComparator(orderByAsc);
}

return orderByComparator;
}

}

Now in same package write AddressBookNameComparator and AddressBookStatusComparator if you want you can write any where else and do the required imports. Below is the code for AddressBookNameComparator

public class AddressBookNameComparator extends OrderByComparator {

public static String ORDER_BY_ASC = "name ASC";

public static String ORDER_BY_DESC = "name DESC";

public AddressBookNameComparator() {
this(false);
}

public AddressBookNameComparator(boolean asc) {
_asc = asc;
}

public int compare(Object obj1, Object obj2) {
AddressBook project1 = (AddressBook) obj1;
AddressBook project2 = (AddressBook) obj2;

int value = project1.getName().toLowerCase().compareTo(
project2.getName().toLowerCase());

if (_asc) {
return value;
} else {
return -value;
}
}

public String getOrderBy() {
if (_asc) {
return ORDER_BY_ASC;
} else {
return ORDER_BY_DESC;
}
}

private boolean _asc;

}

Do the required imports .Same way you can do for other columns.
Step 3: Use the SearchContainer taglib.

<liferay-ui:search-container
emptyResultsMessage="No Result Found"
orderByCol="<%= orderByCol %>"
orderByType="<%= orderByType %>"
>
<liferay-ui:search-container-results results="<%= AddressBookLocalServiceUtil.getAddressBookList(searchContainer.getStart(), searchContainer.getEnd(),orderByComparator)%>">
total="<%= AddressBookLocalServiceUtil.getAddressBookCount() %>"
/>
<liferay-ui:search-container-row classname="com.ext.portlet.addressBook.model.AddressBook" escapedmodel="<%= true %>">
keyProperty="bookId"
modelVar="addressBook"
>


<liferay-ui:search-container-column-text name="name" orderable="<%= true %>" orderableproperty="name">
>

<%= addressBook.getName() %>

</liferay-ui:search-container-column-text>

<liferay-ui:search-container-column-text name="status" orderable="<%= true %>" orderableproperty="status" property="status">
/>

</liferay-ui:search-container-column-text>


<liferay-ui:search-iterator />
</liferay-ui:search-container-row></liferay-ui:search-container-results>
That is all about orderable search container.If you have read the wiki article then you will easily understand this.

popup on popup in liferay
To implement popup on popup in liferay is quite simple. We need to have 2 pages one parent page on which 1st popup is already opened and 2nd page which will be opened in 2nd popup.

For 1st page call:
function parentPage(url) {
var popup = Liferay.Popup(
{
stack: true,
draggable:false,
title: 'Parent Page',
position:[110,50],
modal:true,
width:450,
height:365,
url:url
}
);
}
here stack:true property is important which is responsible for pop on popup.url is which page we want to load . It can be portlet url. Other parameters are self explanatory. 

In child page you can simply write another popup.

function childPage(url) {
var popup = Liferay.Popup(
{

title: 'Child Page',
position:[110,50],
modal:true,
width:450,
height:365,
url:url
}
);
}

Monday, 17 September 2012

Simple java program to read json from text file

import java.io.IOException;
import java.io.InputStream;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.apache.commons.io.IOUtils;


public class ClassloaderTest {

public static void main(String [] args) {
ClassLoader cl = ClassloaderTest.class.getClassLoader();
InputStream is = cl.getResourceAsStream("json.txt");
try {

String s = IOUtils.toString( is );
JSONObject json = (JSONObject) JSONSerializer.toJSON(s);

JSONObject searchresults = json.getJSONObject("searchresults");
System.out.println("ssssssss" + searchresults.optString("count", ""));
JSONArray jarray = searchresults.getJSONArray("URI");
for(int i=0 ; i < jarray.size(); i++) {
System.out.println("jarray [" + i + "] --------" + jarray.getString(i));
}
} catch(IOException e) {
e.printStackTrace();
}
}



}

and content of json.txt is below
{
"searchresults": {
"URI": ["qa1", "qa2", "qa3", "qa4", "qa5"],
"count": "5"
}

jason.txt you can keep in the same package where your class is.
Hope this post helps others.

Sunday, 16 September 2012


A Simple SOAP Web Service Example in Eclipse :-

Create Basic Web Service

  1. Create new Dynamic Web Project.
  2. Create new Java class (call it “DoesMagic”).
  3. Add method like this (perhaps):

1public class DoesMagic{
2    public String doBasicStuff(String message)
3    {
4        return "This is your message: " + message;
5    }
6}

4. Right click on class you just made, New -> Other -> Web Services -> Web Service, you should get a form like the one below:

This will create all the necessary files to be able to publish your class as a web service.  If you want you can also create a client automatically by moving the slider – but what it generates may be hard to understand at first glance, so I have written a simple example of client code (see later on…).
5.  In order to run the web service – just,  Run as -> Run on Server.  Once the web service is running and alive on Tomcat – then we should be able to use it via some client code (see next bit).

Create Basic Web Service Client

Must create a project that has all the axis.jar type stuff in the WebContent folder – this can usually be made by generating a client application via the above wizard – you don’t have to use all the auto generated classes to access your web service, just do the following:
1.  Create a new Java Class – call it TestClient.
2.  Make it a main class, and enter the following code:

01import javax.xml.namespace.QName;
02import org.apache.axis.client.Call;
03import org.apache.axis.client.Service;
04 
05public class TestClient {
06 
07public static void main(String [] args)
08{
09    try{
10       String endpoint = "http://localhost:8080/TestWebService/services/DoesMagic";
11 
12       Service service = new Service();
13       Call call = (Call) service.createCall();
14       call.setTargetEndpointAddress( new java.net.URL(endpoint) );
15       call.setOperationName( new QName("http://testPackage.fc.com", "doBasicStuff") );
16 
17       String ret = (String) call.invoke( new Object[] {"Hello World"} );
18       System.out.println(ret);
19       }
20       catch(Exception e){
21           System.err.println(e.toString());
22       }
23}
24}

3.  Go to your web service project you made before and look at the source code for the wsdl file that has been created.  It’s in the folder WebContent -> wsdl.  Inside there you will find a wsdl that is the same name as your class.
4. You need to look at the wsdl and find the endpoint – which looks similar to:
"http://localhost:8080/TestWebService/services/DoesMagic"
and you need to get the namespace and the method name you want to invoke  (as shown above, should be in a very similar format).
5. In this case, when we get to the point that the call.invoke command is being issued it is casting the result to a String and we are sending in a String called “Hello World” – this should create a message in the console like “This is your message: Hello World”.
6. To test the class, just run the project as a Java Application and you should see the result in the Console printed out.

Friday, 14 September 2012


How to add a portlet to the Liferay Control Panel


If you want your portlet to be available in the liferay control panel, just add the following in liferay-portlet.xml file:


<control-panel-entry-category>portal</control-panel-entry-category>
<control-panel-entry-weight>2</control-panel-entry-weight>
<instanceable>false</instanceable>


control-panel-entry-category defines where the portal will be shown, for example "portal" or "server".

control-panel-entry-weight defines the position of the portlet in the category you defined above.

control-panel-entry-class is optional and is used to define rights (who can see the portlet and who doesn´t).

Tuesday, 24 July 2012

Setup Android SDK With Eclipse
I started using Android SDK recently and I like it a lot. In this article I tell you how to setup the SDK to work in combination with the Eclipse ADT plugin.


1)If you want to download Eclipse you can download it from http://www.eclipse.org/downloads/.
2)You can download Android SDK for your system
3)You will need latest version of JDK to be able to use Android SDK with Eclipse.
   You can download the latest JDK from JAVA's website at        
    http://java.sun.com/javase/downloads/index.jsp.

Installing Android SDK

 Lets see how it works out when we click Lets see how it works out when we click 'installer_r20.0.1-windows.exe' installer for windows
1. When you click the '.exe' installer windows will ask you if you want to save the file or cancel download as seen in the figure below. Select Save File and wait for the file to download.




2. After the file has downloaded run the setup file. You will be shown the welcome screen. Press Next on this screen.




3. If Jave SE Development Kit (JDK) is not found on your system you will be asked to download it from the Java website. Click on Visit java.oracle.com to install the JDK. Without the JDK you cannot continue with the installation. If you already have JDK installed you can proceed to Step 4.




4. After Installing the JDK you can press the Back button and then click Next button on the Android SDK installer. Now you will see that the previously disabled 'Next' button is enabled. Click the Next button to proceed forward.
5. You will now be asked to choose the directory where you want to install Android SDK tools. Remember the name and location of the SDK directory on your system as you will need to refer to the SDK directory later, when setting up the ADT plugin and when using the SDK tools from command line. In this article we use the default SDK location C:\Program Files\Android\android-sdk.




After choosing the location where the SDK will be installed press Next.
6. Next you will be asked to Choose if you want to make a Start Menu Folder. If you do not want to make a Start Menu Folder select the box Do not create shortcuts. If you want to create Start Menu Folder than just click Install.




The Installation will start and after installation you will be asked to press Next button to proceed to the Finish page where you can decide to Start SDK Manager

lets install Android Development Tools in Eclipse.

Installing the ADT Plugin for Eclipse

As stated on the Android's Developer website "Android offers a custom plugin for the Eclipse IDE, called Android Development Tools (ADT), that is designed to give you a powerful, integrated environment in which to build Android applications. It extends the capabilites of Eclipse to let you quickly set up new Android projects, create an application UI, debug your applications using the Android SDK tools, and even export signed (or unsigned) APKs in order to distribute your application. In general, developing in Eclipse with ADT is a highly recommended approach and is the fastest way to get started with Android."

Follow the steps below to install the ADT plugin in Eclipse:
1. Eclipse must be installed on your system to preoceed further from here

2. I use Eclipse 3.6 (Helios). Start Eclipse and then select Help > Install New Software...


3. Click Add, on the top right corner. A small Add Repository Dialog appears. In this Dialog enter "ADT Plugin" for the Name and the following URL for the Location:
https://dl-ssl.google.com/android/eclipse/
If you have trouble downloading the plugin, try using 'http' in the Location URL, instead of 'https'. Now ClickOK.
4. Next you will be back in the Available Software dialog. In this dialog select the checkbox next to Developer Tools and click Next.
5. Eclipse will look for dependencies and then show you the next window. Here you can see a list of the tools to be downloaded. Click Next.
6. Next you will be shown the license agreements. Read and accept the license agreements, then clickFinish.
7. After the installation finishes, restart Eclipse.

Configuring the ADT Plugin

The next step is to modify the ADT preferences in Eclipse to point to the Android SDK. 
1. Start Eclipse. Select Window > Preferences... to open the Preferences panel.




2. In the left panel you can see Android. Select Android. You can now click Browse... to locate the folder where you have downloaded the Android SDK. Select the folder which contains the tools folder.
3. Now you are all done to move to the final step before you can start development for Android SDK. ClickApply, then OK.

Adding Platforms and Other Components

This is the last step before you can start developing your apps for Android SDK. In this step we will see how to use Android SDK and AVD Manager to download the important SDK components for the development environment. The steps involved are
1. Start Eclipse, select Window > Android SDK and AVD Manager or we can go to the root directory (in this tutorial 'C:\Program Files\Android\android-sdk')where we have installed the Android SDK and double-click the 'SDK Manager.exe' file.
2. You can now use the graphical user interface to browse through the SDK repository and select new or updated components. The Android SDK and AVD manager then installs the selected components in your SDK environment. This can be seen as in the image below: