Wednesday, March 18, 2009

Difference between ear jar and war files!!!

These files are simply zipped files using java jar tool. These files are created for different purposes. Here is the description of these files:

.jar files: These files are with the .jar extension. The .jar files contain the libraries, resources and accessories files like property files.

.war files: These files are with the .war extension. The war file contains the web application that can be deployed on the any servlet/jsp container. The .war file contains jsp, html, javascript and other files for necessary for the development of web applications.

.ear files: The .ear file contains the EJB modules of the applications.

Blogged with the Flock Browser

Monday, March 16, 2009

Static Import!! Tiger.

Static Imports

The new 'import static' statement is another great addition to the language. As Java programmers, you may well have written code like the following on more than one occasion:

PrintStream o = System.out;
o.print("stuff");
o.print("more stuff");

The reference variable o is no more than a handy shortcut to System.out. In Java 5, you can import a class's static members and refer to them without the usual class name prefix. Thus, you can now do something like this:

import static java.lang.System.out;
// other code here.
out.print("stuff");
out.print("more stuff");

Once the static member is imported, you can use it in your code without the System class prefix. Here's an even better example from the GUI world of Swing.

// without static import.
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

// with static import.
import static javax.swing.WindowConstants.*;
// other code
setDefaultCloseOperation(EXIT_ON_CLOSE);

In the second example, the addition of the static import greatly enhances the readability of the code and cuts down on the amount of code required. I used the * to import all of WindowConstants static members in this case.

Blogged with the Flock Browser

Printf and Scanners!!! Tiger

The printf Method

Here's a handy addition to the java.io.PrintStream and java.io.PrintWriter classes -- the C like printf() method. The first argument to printf() is a String, known as a format string. The remaining arguments are called 'format specifiers'. Thanks to the var-args feature, you can have as many of these format specifiers as you like. This is easier to explain by way of a simple example:

Calendar c = Calendar.getInstance();
System.out.printf("Hi %2s, the current month is:  %1tB", cal, "Andy");

Let's break it down, as there are quite a few things going on here. Let us consider the first format specifier in the format string -- that's the bit that reads, %2s.

The % symbol signifies that we're using a format specifier. The digit that follows is the argument index. In this case it is 2, and therefore refers to the second argument, which is the string "Andy".

The next format specifier is %1tB. From the above explanation, you'll know that it's another format specifier, this time referring to the first argument (the %1 portion tells us that much). On this occasion, we use a t to indicate a date conversion. The B following the t indicates that the month should be output. The resulting string would be, "Hi Andy, the current month is October".

For the C programmers out there, the good news is that Sun decided to make the mini-language behind all this instantly recognizable (though not 100% compatible). If you're wondering how you're supposed to figure out what all these fancy format specifiers do -- and there are lots of them -- the javadcoc for the java.util.Formatter class has all the gory details.

As you can probably see, without the var-args feature, printf() would hardly be possible. This is a rare example of var-args being used in the proper manner.

Scanners

In the past, many beginning programmers were unnecessarily given the wrong impression of Java. This was, in part, due to the difficulty involved in working with the system console -- an area where many Java educations begin.

To read from standard input, it was first necessary to write the exception handling code. Once this was done, you would wrap an InputStreamReader and a BufferedReader around System.in. Finally, you would convert the input into a type that could be used by your program via, say, Integer.parseInt(). This process was most definitely not for the faint of heart!

Say hello to my new friend, java.util.Scanner. This class greatly simplifies the reading of input from a variety of character sources (anything that implements java.lang.Readable, in fact) and makes working with keyboard input a breeze. Here's how you might get yourself a scanner:

Scanner keyboard = Scanner.create(System.in);

Input is read in as set of 'tokens'. On the console, once the enter key is pressed, you can use a nextSomething() method to get at these tokens. The Scanner class has a nextSomething() method for each of the primitive types and for 3 objects: String, BigInteger and BigDecimal. Consider the following code:

Scanner keyboard = Scanner.create(System.in);
System.out.println("Please enter your name:");
String name = keyboard.nextString();
System.out.println("Welcome " + name + " Please enter your age:");
int age = keyboard.nextInt();

Here, I only work with the single token I expect to be provided, but you should know that there is a corresponding series of boolean returning hasNextSomething() methods that you can use to loop over a whole set of tokens.

You can optionally choose to catch the exception, InputMismatchException, in the cases where you believe a nextSomething() method may be called on a token of the wrong type -- this is an unchecked exception and, therefore, you are not forced to handle it.

There is a bit more to scanners than this, such as support for locales and regular expressions. Take a look at the javaDocs and befriend this handy little class.

Blogged with the Flock Browser

Var-args ??? ~Tiger~

Var-args

In Java, method specifications are pretty much set in stone. For example, a method that declares two parameters of a particular type must be called with those parameters. If you supply too many, too few, or incorrectly typed parameters, you will get a compile time error. Of course, we use method overloading to deal with the cases in which we need to declare a varying number or type of parameters.

However, every now and then it makes sense, or is more convenient, to have the one method handle any number of arguments that are thrown its way, just as you're allowed to do in languages like JavaScript and ColdFusion. The way many programmers previously simulated such behavior in Java was to create an array of parameters, then pass that array along as an argument to the desired method.

In Java 5, this rather messy approach is no longer necessary. Consider this method specification:

public void myMethod(Object … args)

Notice the three periods next to the parameter type? This is how we tell the method that it is allowed to accept a varying number of arguments. The type must be Object, and it must be the last or only argument in the method specification. With that in mind, the following method calls are all perfectly legal:

myMethod(23, 34, 78);
myMethod("Hello", "Goodbye");
myMethod(123);

This makes sense, except for one thing. I said that the arguments must be of type Object, yet I clearly pass along primitives in two of these calls! That's autoboxing in action -- the arguments are passed along as Object types; the compiler takes care of the primitive wrapping on our behalf.

As you would expect, inside the method body, the parameters are handled as an array of type Object. The following code sample shows how much code we may have needed to achieve the same thing prior to Java 5.

int num1 = 23;
int num2 = 28;
int num3 = 98;

Integer objNum1 = new Integer(num1);
Integer objNum2 = new Integer(num2);
Integer objNum3 = new Integer(num3);

Integer[] params = {objNum1, objNum1, objNum3}
myMethod(params);

Here, we do all the primitive wrapping ourselves. Then, we create the array-based parameter. Finally, we do the method call. Now that's a lot more work!

Blogged with the Flock Browser

Thursday, March 12, 2009

Connecting to a Database - Step by Step

The database driver

This example shows the different steps needed to connect to a database.
In the example the Microsoft SQL Server is used, but the steps applies to all types of database engines.
The first thing you need to do is to consider what driver to use. There are different types of drivers
(the different types is not covered here) and the most efficient and widely used driver is a Type 4 driver.
A Type 4 driver is completely written in Java and is not dependent on any native code. Each database engine has its own driver,
so you can only use a driver for that particular database engine.

Now, to make the driver available to the JVM you need to load the class:



Class.forName("[nameOfDriver]");

//For Microsoft SQL Server that would be
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");


For the JVM to be able to find that class, you need to make sure the class is in your classpath.
Usually the class is located within a .jar-file that can be downloaded from the database vendor.


Creating the database connection

To create the connection you use the static method getConnection() of the java.sql.DriverManager class.
The method has several overloaded variants, and one of them takes an url, userid and password as arguments.
The database url slightly differs from one type of database to another. For Microsoft SQL Server it looks like this:


//The values within square brackets are the ones to change to suite your environment,
//and the square brackets should thus not be included
Connection con = DriverManager.getConnection("jdbc:sqlserver://[server]:[port];databaseName=[nameofdatabase]",
         "[userid]",
         "[password]");


Create the Statement object and executing a query

Now that we have established a connection, we want to create a Statement object and execute an sql query.


Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM table");


Now we have retrieved the data from the table called 'table' into a ResultSet and all we have to do now is loop through it.
Assume the table has two columns called id which is of type int, and value which is of type varchar:


//The next() mehtod jumps to the next row in the ResultSet.
//When the last row has been processed, the method returns false.

while (rs.next()) {

   System.out.println(rs.getInt("id") + " - " + rs.getString("value"));
   
}


Cleaning up resources

Now all we have to do is close the connection. Actually we should close all of the instances of Connection, Statement and ResultSet and
it's done in reverse order from which they were created:


if (rs != null)
   rs.close();
if (statement != null)
   statement.close();
if (con != null)
   con.close();


For many of the code statements above it is required to handle an SQLException in case anything goes wrong.
Thus you'll have to enclose much of the code in a try / catch block which were excluded in the example to make it more readable.


// Declare the variables outside the try block to be able to call them
// in a finally block where the closing should take place.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;


try {

   //all code here

} catch (SQLException ex) {

   ex.printStackTrace();

} finally {

   //the code for closing here
}

Wednesday, March 11, 2009

Object Oriente Java Script!!

Writing JavaScript in an object-oriented way helps us to simplify complex task at client side. JavaScript supports all the familiar object-oriented programming concepts. JavaScript supports creating/defining new objects and with help of prototype property we can achieve the object oriented behavior.

Lets start with the normal java class and then will see how it looks like with javascript

class Test {
//property and methods
}
Test test = new Test();  // creating an object of type Test

JavaScript:
function Test() {
//property and methods
}

var test = new Test(); // creating a new object

Note that the function keyword is overloaded, it beahaves as normal procedure function and can also be used as constructor.
var temp = Test() // normal function call
var temp = new Test() // as a constructor

Java FX???

What is JavaFX?

JavaFX is a rich client platform for building cross-device applications and content. Designed to enable easy creation and deployment of rich internet applications (RIAs) with immersive media and content, the JavaFX platform ensures that RIAs look and behave consistently across diverse form factors and devices.

The JavaFX 1.1 platform release includes the following components:

  • JavaFX 1.1 SDK which includes the JavaFX compiler and runtime tools, graphics, media, web services, and rich text libraries to create RIAs for the desktop, browser and mobile platforms.

  • NetBeans IDE 6.5 for JavaFX 1.1 which provides a sophisticated integrated development environment for building, previewing, and debugging JavaFX applications. The editor features a drag-and-drop palette to quickly add JavaFX objects with transformations, effects and animation. This IDE also comes with its own set of Building Block samples and the JavaFX Mobile Emulator, a mobile phone simulator.

  • JavaFX 1.1 Production Suite is a suite of tools and plugins that enable designers to export graphical assets to JavaFX applications.