Thursday, May 13, 2010

Jar file Vs Executable Jar file

Jar file is the combination of compiled java classes.
Executable jar file is also be combination of compiled java classes with Main class.
Normal jar file can be created as
C:\> jar -cvf TestNew.jar . 
But while creating executable jar file we have to specify the Main-Class in a manifest file. Following are the steps to fallow while creating the executable jar file. Here its explained with a simple class in a test package.
Step1: create a java class TestNew under package test
package test;
public class TestNew{
public static void main(String a[]){
System.out.println("Hello world");
}
}
Step 2: compile the class with fallowing command
C:\>javac TestNew.java -d . 
Note: Once you run the TestNew class you have to get “HelloWorld” in the console. To run use fallowing command
C:\>java test.TestNew
Step 3: Create a “mainClass” file in the directory where your test folder is located . This file contains a single line specifying where the main Class is to be found in the jar file. Note that I use the package specification. Here is the single line:
Main-Class: test.TestNew
Note: specify the single line only don't specify anything
Step 4: create the jar using fallowing command
C:\>jar cmf mainClass test.jar test
Where “c” represents the create that you are going to “create”, "m" specifies the manifest file mainClass (which adds information to the jar file on where the main class will be found) and “f ” refers to “file”.
Note: The file has to be created in your folder with the name test.jar

To view the content of the jar file you can use the fallowing command
C:\>jar tf test.jar
It displays as:
META-INF/
META-INF/MANIFEST.MF
test/
test/TestNew.class
To execute the jar file you can use the following commond
C:\>java -jar test.jar
o/p:
Hello world

Friday, May 7, 2010

Integrating Quartz Job Server with JBoss

I am getting the fallowing error while integrating Quartz job server in the JBoss
javax.naming.CommunicationException: Receive timed out
[Root exception is java.net.SocketTimeoutException: Receive timed out]

The steps i fallowed to configure the Quarts

1. I removed the quartz.jar from the {JBoss_Home}/deploy/lib and Quartz-ra.rar from {JBoss_Home}/deploy folder.

2. Added the quartz 1.6.5.jar and quartz-jboss-1.6.5.jar into {JBoss_Home}/deploy/lib .

3. Added the quartz-service.xml with fallowing details
<?xml version="1.0" encoding="UTF-8"?>
<server>
 <mbean code="org.quartz.ee.jmx.jboss.QuartzService" name="user:service=QuartzService,name=QuartzService">  
   <attribute name="JndiName">Quartz</attribute>
   <depends>jboss.jca:service=DataSourceBinding,name=QuartzDS</depends>
   <attribute name="Properties">      
     org.quartz.scheduler.instanceName = DefaultQuartzScheduler
     org.quartz.scheduler.rmi.export = false
     org.quartz.scheduler.rmi.proxy = false
     org.quartz.scheduler.xaTransacted = false
     org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
     org.quartz.threadPool.threadCount = 5
     org.quartz.threadPool.threadPriority = 4
     org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
   </attribute>
 
 </mbean>
</server>

4. I have written the Servlet to schedule the job
package com.radiant.cisms.help.servlets;

import java.io.IOException;
import java.util.Date;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdScheduler;
import org.quartz.impl.StdSchedulerFactory;


/**
* Servlet implementation class for Servlet: JobSeduleServlet
*
*/
public class JobSeduleServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
  static final long serialVersionUID = 1L;
 
   /* (non-Java-doc)
    * @see javax.servlet.http.HttpServlet#HttpServlet()
    */
   public JobSeduleServlet() throws SchedulerException {
       super();
       sedulingUsingJboss();
   }     
 

   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       System.out.println("under doGet method.................");
       sedulingUsingJboss();
   }    
 
 
   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       System.out.println("under doPost method.................");
       sedulingUsingJboss();
   } 
 

   public void sedulingUsingJboss(){
       System.out.println("under...sedulingUsingJboss................. ");
        try {
              InitialContext ctx = new InitialContext();
              System.out.println("Intial Context........."+ctx);
              System.out.println("..................."+ctx.lookup("Quartz"));
              StdScheduler scheduler = (StdScheduler) ctx.lookup("Quartz");
            
             JobDetail jd=new JobDetail("myjob",scheduler.DEFAULT_GROUP,TestJob.class);
              CronTrigger ct = new CronTrigger("cronTrigger","group2","0 0/5 * * * ?");
              scheduler.scheduleJob(jd,ct);
            
              } catch (Exception exc) {  
                 exc.printStackTrace();
              }
   }
}

5. Above servlet has been configured in web.xml as fallowes
<servlet>
       <servlet-name>JobSeduleServlet</servlet-name>
       <servlet-class>com.radiant.cisms.help.servlets.JobSeduleServlet</servlet-class>
       <load-on-startup>1</load-on-startup>
   </servlet>

<servlet-mapping>
       <servlet-name>JobSeduleServlet</servlet-name>
       <url-pattern>/servlet/JobSeduleServlet</url-pattern>
   </servlet-mapping>
According to console generated by the server Quartz service is loading successfully.
But while calling the JobScheduleServlet it is throwing the exception as fallows
javax.naming.CommunicationException: Receive timed out [Root exception is java.net.SocketTimeoutException: Receive timed out]


Sunday, April 25, 2010

What is the difference between EAR, JAR and WAR file?


In J2EE, application modules are packaged as EAR, JAR and WAR based on their functionality.
Each type of file (.jar, .war, .ear) is processed uniquely by application servers, servlet containers, EJB containers, etc


JAR:
Jar file (file with a .jar extension) is the normal Java Application archive and intended to hold generic libraries of Java classes, resources, auxiliary files, etc
This can be added in classpath for compilation and to run java program. Generally in web applications we keep these files in lib directory of the application.

Ex: ojdbc14.jar – This contains all the classes to connect the oracle database
Servlet-api.jar – contains servlet related classes

WAR:
Web modules which contains Servlet class files,JSP Files,supporting files, GIF and HTML files are packaged as JAR file with .war( web archive) extension
War files (files with a .war extension) are intended to contain complete Web applications. In this context, a Web application is defined as a single group of files, classes, resources, .jar files that can be packaged and accessed as one servlet context.

EAR:
All above files(.jar and .war) are packaged as JAR file with .ear ( enterprise archive) extension and deployed into Application Server.
Ear files (files with a .ear extension) are intended to contain complete enterprise applications. In this context, an enterprise application is defined as a collection of .jar files, resources, classes, and multiple Web application. 

Wednesday, April 21, 2010

HashSet with Example


If your requirement is frequent insert then we go with HashSet.

For efficiency objects added to a HashSet need to implement the hashCode() method in a manner that properly distributes the hash codes. While most system classes override the default hashCode() implementation of the Object.

It is generally faster to add elements to the HasSet then convert the collection to a TreeeSet for sorted traversal.

To optimize HashSet space usage , you can tune initial capacity and load factor.

Example:

public class HashSetExample {

    public static void main(String[] args) {

        HashSet<String> hs=new HashSet<String>();

        // duplicate element is not permitted
        hs.add("b");
        hs.add("a");
        hs.add("c");
        hs.add("d");
        hs.add("d");

        Iterator it=hs.iterator();

        while(it.hasNext())
        {
            String value =(String)it.next();

            System.out.println("Value :"+value);
        }

        System.out.println("Size :"+hs.size());

        hs.remove("d");

        hs.clear();
    }
}

Sortedset with Example


When you want to sort the data we have to go with sortedset by default the sorting order is ascending.
You can customize the sorting order by Implementing comparator interface.

You can use treeset for sorting and for this you need to use the constructor which accepts comparator as argument.

Example:

public class Example {


public static void main(String[] args) {


SortedSet ss=new TreeSet();

ss.add("a");
ss.add("e");
ss.add("g");
ss.add("b");
ss.add("c");

Iterator it=ss.iterator();

while(it.hasNext())
{
String value=(String)it.next();
System.out.println("Value :"+value);
}
}
}

What is the difference between Iterator and ListIterator?

Iterator:
Using Iterator we can iterate only in forward direction and you cannot add elements while iterating and Here cursor always points to specific index.

Example:
 public class Example {
 
  public static void main(String[] args) {
 
    ArrayList aList = new ArrayList();
 
    aList.add("1");
    aList.add("2");
    aList.add("3");
    aList.add("4");
    aList.add("5");
   
    Iterator itr = aList.iterator();
 
     while(itr.hasNext())
      System.out.println(itr.next());
 
  }
}
ListIterator:
Allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list. A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next().
Example:
 public class sample {
 
  public static void main(String[] args) {
    //create an object of ArrayList
    ArrayList aList = new ArrayList();
 
    //Add elements to ArrayList object
    aList.add("1");
    aList.add("2");
    aList.add("3");
    aList.add("4");
    aList.add("5");
 
    //Get an object of ListIterator using listIterator() method
    ListIterator listIterator = aList.listIterator();
 
      
    System.out.println(" forward direction using ListIterator");
    while(listIterator.hasNext())
      System.out.println(listIterator.next());
 
   
    System.out.println("reverse direction using ListIterator");
    while(listIterator.hasPrevious())
      System.out.println(listIterator.previous());
   }
}
 
try the above code and get back to me :)

Monday, April 19, 2010

Developing Charts with JFree Charts

Implementing the charts while developing the Web applications as well as Stand alone applications is crucial part. This must act like business intelligence and it should give more information to the user with small graph or in short form of data. These will play major part in the application for analyzing and capturing application whole information.

For example A shopping cart applications sells the things in online and the owner of shopping cart wants to know the sales details in daily basis or weekly basis or Monthly basis and so on... and he has to get this information in short way and user friendly. He may need the more information like in which country the things are selling more, which materials are selling more and the things which are added for the carts and so on... In these situations representing the data in the graphical format will make the user to feel comfortable and feel like friendly.

As I from Java technology I worked more around to choose open source chart implementing tools for some days. I looked into Jasper Reports, Jfree charts, and some other technologies. Jasper reports are more useful while displaying the data in pdf fomat or excel  format and other formats. This has the ui tool called iReport to define the jrxml files and these jrxml files are parsed and finally we will get the data. This data can be displayed on different formats like pdf, excel,html...etc. Using JFree charts we can display the reports data in a graphical format. This chart can be write into pdf or other formats using JFree api. Here i will explain briefly about JFee charts.

By visiting the www.jfree.org site we can see the Jfree charts features as:
" JFreeChart is a free 100% Java chart library that makes it easy for developers to display professional quality charts in their applications.
  • a consistent and well-documented API, supporting a wide range of chart types;
  • a flexible design that is easy to extend, and targets both server-side and client-side applications;
  • support for many output types, including Swing components, image files (including PNG and JPEG), and vector graphics file formats (including PDF, EPS and SVG);
  • JFreeChart is "open source" or, more specifically, free software. It is distributed under the terms of the GNU Lesser General Public Licence (LGPL), which permits use in proprietary applications. "
The demo application can be downloaded from the site and u can start implementing the JFreechart's applications. JfreeChart developer guide helps more to develop the applications.

As per my opinion JFreeChart is more friendly for the developers while developing the applications. Using this you can implement Pi, Bar, StackedBar, Line, Bubble, Step ..etc charts.

Some times you may need to display JFreeChart image in JSP in that case Cewolf tag library helps more. Using Cewolf Tag library you can display all types charts in JSP and its easy to display tool tip, link and labels.

If you works with JSF, you can use Primefaces or Rich faces to integrate the JFree charts and its easy to implement.

Friday, April 9, 2010

Prime faces

Kowing about prime faces is more worth while developing the Web applications wusing JSF framework. Primefaces is just like a plugin for the JSF. It is more related to the UI of the application. Adding this plugin to the JSF based application gives confidence developer in designing ui interface in competence with other best ui technology.

Its providing more features like AccordianPannel, AutoComplete, Captua, Calender, Charts, Color picker,CommandButton, CommandLink, Confim Dialog, Data Exporter, Data Table, File Upload, File Download, Graphic Image, Image Compare, Layout, Menu, Menu Bar, Panel, PickList, Stack, Stack Menu,Tab, Tab Slider, Tree, Tool Tip ... etc.

Its providing more features related to JavaScript and extention to the JSF tags.

Integrating the Prime faces with JSF applications is too easy, its just adding the jar file into the application and setting up normal requirements in the web.xml file.


Wednesday, March 31, 2010

JSF is Cool..........

After spending with few days on jsf its looking like cool and making me share my happiness with you.

The features given in JSF is very impressive. The development with JSF is giving more happiness.The tag libraries (Core as well as UI tag libraries) given in JSF are more friendly and easy to understand.
The concept of managed-bean, Backing-bean and connecting the beans from the jsf elements (tags) is makes the developer to concentrate on the Business logic more instead of playing with requests and responses. There are more cool features in JSF for the developer as well as user and more plugins to to improvise the JSF functionalities.

I spent more than 2 months with JSF its gave me confidence on my developing skills and its made me think more on business logic.

At present I am enjoying while learning the JSF. I hope, I will come with more explanation on JSF and Integration of JSF with hibernate, spring, struts.

I am sure I will come with architecture of jsf and small examples and complexities discussions with you..............


Sunday, March 7, 2010

JSF Vs Struts Post Your Responces as comments.


I worked on Struts 1.x i felt it was easy. Now I am working on JSF with JBoss Portlets its looks little bit complicated while development. Why its looking like that? Is really JSF is complex when compared to Struts?
 In struts I used to have request and response in My hand so that i felt every thing was in my hand to control the application.
 But Jsf with Portlets is not like that. We need to work around to get the request and response objects.But handling these request and response objects is not as easy as in struts.
I feel working with Jsf and portlets is little bit difficult when I compare  struts frame work.
Is Jsf complex or Jsf with portlets combination is complex ?

Can you please let me know when to go for JSF with portlets otherwise with struts.