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).