Tuesday, February 24, 2009

New Features in Java 6 (Mustang Edition)

What's New in Java SE 6

  

 
By Danny Coward, Java SE Platform Lead
Approved Feature List Table: Mark Reinhold, Java SE Chief Engineer, Updated February 2007
 

Articles Index

Version 6 of the Java Platform, Standard Edition (Java SE), was released for general availability in December 2006. So here are the top 10 things you need to know about the release, if you're still hovering hesitantly over that Download Page link. Subsequent articles will provide more in-depth information.

Contents
 
Top 10 Things You Need to Know
Approved Features
 
Top 10 Things You Need to Know
  1. Web Services
    All developers get first-class support for writing XML web service client applications. No messing with the plumbing: You can expose your APIs as .NET interoperable web services with a simple annotation. Not your style? Want to handle the XML directly? Knock yourself out: Java SE 6 adds new parsing and XML to Java object-mapping APIs, previously only available in Java EE platform implementations or the Java Web Services Pack.

  2. Scripting
    You can now mix in JavaScript technology source code, useful for prototyping. Also useful when you have teams with a variety of skill sets. More advanced developers can plug in their own scripting engines and mix their favorite scripting language in with Java code as they see fit.

    Perhaps You ThougHt yOu couldN't program with a scripting language and Java togetheR. Which will yoU Be trYing ?

  3. Database
    For a great out-of-the-box development experience with database applications, the Java SE 6 development kit – though not the Java Runtime Environment (JRE) – co-bundles the all-Java JDBC database, Java DB based on Apache Derby. No more need to find and configure your own JDBC database when developing a database application! Developers will also get the updated JDBC 4.0, a well-used API with many important improvements, such as special support for XML as an SQL datatype and better integration of Binary Large OBjects (BLOBs) and Character Large OBjects (CLOBs) into the APIs.

  4. More Desktop APIs
    Much has been said about this spoonful of sugar (to go with the Desktop team's cake), so we will only skim a little. GUI developers get a large number of new tricks to play like the ever popular yet newly incorporated SwingWorker utility to help you with threading in GUI apps, JTable sorting and filtering, and a new facility for quick splash screens to quiet impatient users.

  5. Monitoring and Management
    The really big deal here is that you don't need do anything special to the startup to be able to attach on demand with any of the monitoring and management tools in the Java SE platform. Java SE 6 adds yet more diagnostic information, and we co-bundled the infamous memory-heap analysis tool Jhat for forensic explorations of those core dumps.

  6.  
    "For those of you deafened by your screaming inner geek, roll up your sleeves and give it a try."
     
     
    Danny Coward
    Java SE Platform Lead
     
  7. Compiler Access
    Really aimed at people who create tools for Java development and for frameworks like JavaServer Pages (JSP) or Personal Home Page construction kit (PHP) engines that need to generate a bunch of classes on demand, the compiler API opens up programmatic access to javac for in-process compilation of dynamically generated Java code. The compiler API is not directly intended for the everyday developer, but for those of you deafened by your screaming inner geek, roll up your sleeves and give it a try. And the rest of us will happily benefit from the tools and the improved Java frameworks that use this.

  8. Pluggable Annotations
    It is becoming a running joke in Java technology circles, at least some that contain us, that for every wished-for feature missing in Java technology, there's a budding annotation that will solve the problem. Joke no more, because Java tool and framework vendors can put a different smile on your face, defining their own annotations and have core support for plugging in and executing the processors that do the heavy lifting that can make custom annotations so cool.

  9. Desktop Deployment
    Those of you deploying applications to the desktop will soon discover that it's a tale of a large number of smaller changes that add up to a big difference to existing applications: better platform look-and-feel in Swing technology, LCD text rendering, and snappier GUI performance overall. Java applications can integrate better with the native platform with things like new access to the platform's System Tray and Start menu. At long last, Java SE 6 unifies the Java Plug-in technology and Java WebStart engines, which just makes sense. Installation of the Java WebStart application got a much needed makeover.

  10. Security
    You can have all the security features you like in the platform — and this release adds a few more, like the XML-Digital Signature (XML-DSIG) APIs for creating and manipulating digital signatures — but if you don't have well supported security administrators, your security may be at risk. So Java SE 6 has simplified the job of its security administrators by providing various new ways to access platform-native security services, such as native Public Key Infrastructure (PKI) and cryptographic services on Microsoft Windows for secure authentication and communication, Java Generic Security Services (Java GSS) and Kerberos services for authentication, and access to LDAP servers for authenticating users.

  11. The -lities: Quality, Compatibility, Stability
    You probably knew that Sun has done regular feature releases of the Java SE platform over the last 10 years. So we certainly feel like we've built up some expertise in this area, such as the ever growing 80,000 test cases and several million lines of code testing conformance (being just one aspect of our testing activity). You probably noticed that, unlike the last release, people have been downloading binary snapshots for the last 20 (not just 6) months. And what's more, they've been filing bugs. So, before we even got to beta, we'd fixed a number of quality and regression issues. Doesn't that add up to a better product? Oh, and by the way, performance is looking better than J2SE 5.0.

So now you know all you need to know. Go on, try it! If you need more persuasion, peruse the following table of approved features.

Features

The following summary of the approved feature list is sorted by area, component, and feature name. The first part of the table highlights platform specification features; the second part lists features co-bundled with the Java Development Kit (JDK). For more details, please see the Release Contents specification. You can check out the initial implementations of many – though not all – of these new features in the weekly snapshot builds of the reference implementation.

Client (Desktop)
Core
Enterprise
2D - GIF image writer
JSR 223: Scripting for the Java Platform
JSR 250: Common annotations
AWT
- Access to Desktop helper applications
- Fast splash screens
- Improved modal dialogs
- System-tray support
Debug
- Access to heap contents
- Attach-on-demand
- Multiple simultaneous agents
JDBC
- JSR 221: JDBC 4.0
Internationalization
- Pluggable locale data
- Resource-bundle enhancements
- Unicode string normalization
Libs
- Array reallocation
- Collections: Deques
- Collections: Sorted sets and maps with bidirectional navigation
- Critical file-I/O enhancements
- Floating point: Add core IEEE 754 recommended functions
- java.util.concurrent updates
JSR 202: Java Class-File Specification Update
- Password prompting
- Reflective access to parameter names
- Service-provider lookup
XML
- JavaBeans Activation Framework (JAF) 1.1
- JSR 173: Streaming API for XML (StAX)
- JSR 181: Web Services Metadata
- JSR 222: Java Architecture for XML Binding (JAXB) 2.0
- JSR 224: Java API for XML Web Services (JAX-WS) 2.0
Swing
- Baseline/gap APIs
- Improve Swing drag-and-drop
- JTabbedPane: Tabs as components
- JTable sorting, filtering, and highlighting
- SwingWorker
- Text-component printing
Management & Monitoring
- Generalized lock monitoring
- Generalized MBean descriptors
- Generic annotations for MBean descriptor contents
- MXBeans
 
 
Net
- Internationalized domain names
- Internationalized resource identifiers
- Programmatic access to network parameters
- Simple HTTP cookie manager
 
 
Security
- JSR 105: XML Digital-Signature APIs
 
 
Tools
- JSR 199: Java Compiler API
- JSR 269: Pluggable Annotation-Processing API
 
Features Co-Bundled With the JDK
 

For More Information
Blogged with the Flock Browser

JDBC 3.0 New Features!!!

  1. Reusabilty of prepared statements by connection pools.
  2. In this version there is number of properties defined for the ConnectionPoolDataSource. These properties can be used to describe how the PooledConnection objects created by DataSource objects should be pooled.
  3. A new concept has been added to this API is of savepoints: One of the useful new features is transactional savepoints. With JDBC 3.0, the transactional model is now more flexible. Now you can start a transaction , insert several rows in it and then create a savepoint. This savepoint serves as a bookmark. The application can rollback to the savepoint and then commit the group of inserts as if the updates have never been attempted.  For eg:

    Statement st=connection.createStatement();
    int rowcount=st.executeUpdate("insert into employee  values("tim"));
    int rowcoutn=st.executeUpdate("insert into salary values(20000.0);
    Savepoint sv=connection.setSavePoint("savepoint");        //create save point for inserts
    int rowcount=st.executeUpdate("delete from employee");
    connection.rollback(sv);                                                  //discard the delete statement but keeps the inserts
    connection.commit();                                                      //inserts are now permanent
  4. Retrieval of parameter metadata.
  5. It has added a means of retrieving values from columns containing automatically generated values.
  6. Added a new data type i.e. java.sql.BOOLEAN.
  7. Passing parameters to CallableStatement.
  8. The data in the Blob and Clob can be altered: JDBC 3.0 introduces a standard mechanism for  updating BLOB and CLOB data.
  9. DatabaseMetaData API has been added.
  10. It allows stored procedure parameters to be called by name.
Blogged with the Flock Browser

Tuesday, February 17, 2009

What is Java Servlet?

 Java Servlets

are server side java programs that require either a web sever or an Application server for execution. Examples for Web Servers include Apache’s Tomcat Server and Macromedia’s JRun. Web Servers include IBM’s Weblogic and BEA’s weblogic server. Examples for other Server programs include JSPs and Enterprise Java Beans (EJBs). In the forthcoming sections, we will get acquainted with Servlet fundamentals and other associated information required for creating and executing Java Servlets.

  1. Basic Servlet Structure
            

    As seen earlier, Java servlets are server side programs or to be more specific; web application that run on servers that comply HTTP protocol. The javax.servlet and javax.servlet.http packages provide the necessary interfaces and classes to work with servlets. Servlets generally extend the HttpServlet class and override the doGet or the doPost methods. In addition, other methods such as init, service and destroy also called as life cycle methods might be used which will be discussed in the following section. The skeleton of a servlet is given in Figure

     



  1. A Servlet’s Life Cycle
    The first time a servlet is invoked, it is the init method which is called. And remember that this is called only once during the lifetime of a servlet. So, you can put all your initialization code here. This method next calls the service method. The service method in turn calls the doGet or doPost methods (whichever the user has overridden). Finally, the servlet calls the destroy method. It is in a sense equivalent to the finally method. You can reset or close references / connections done earlier in the servlet’s methods (e.g. init, service or doGet /doPost). After this method is called, the servlet ceases to exist for all practical purposes. However, please note that it is not mandatory to override all these methods. More often than not, it is the doGet or doPost method used with one or more of the other life cycle methods.



  2. A Servlet Program


                            



    Output Screens

    To appreciate the execution of the servlet life cycle methods, keep refreshing the browser (F5 in Windows). In the background, what actually happens is – with each refresh, the doGet method is called which increments i’s value and displays the current value. Find below the screen shots (Figures 5 through 7) captured at random intervals. The procedure to run the servlets using a Web Server will be demonstrated in the next section (1.3.). 






Blogged with the Flock Browser

What are Sockets and Threads?

What are Sockets and Threads?

A socket is a software endpoint that establishes bidirectional communication between a server program and one or more client programs. The socket associates the server program with a specific hardware port on the machine where it runs so any client program anywhere in the network with a socket associated with that same port can communicate with the server program.

A server program typically provides resources to a network of client programs. Client programs send requests to the server program, and the server program responds to the request.

One way to handle requests from more than one client is to make the server program multi-threaded. A multi-threaded server creates a thread for each communication it accepts from a client. A thread is a sequence of instructions that run independently of the program and of any other threads.

Using threads, a multi-threaded server program can accept a connection from a client, start a thread for that communication, and continue listening for requests from other clients.

About the Examples

The examples for this lesson consist of two versions of the client and server program pair adapted from the FileIO.java application presented in Part 1, Lesson 6: File Access and Permissions.

Example 1 sets up a client and server communication between one server program and one client program. The server program is not multi-threaded and cannot handle requests from more than one client.

Example 2 converts the server program to a multi-threaded version so it can handle requests from more than one client.

Example 1: Client-Side Behavior

The client program presents a simple user interface and prompts for text input. When you click the Click Me button, the text is sent to the server program. The client program expects an echo from the server and prints the echo it receives on its standard output.

Example 1: Server-Side Behavior

The server program presents a simple user interface, and when you click the Click Me button, the text received from the client is displayed. The server echoes the text it receives whether or not you click the Click Me button.

Example 1: Compile and Run

To run the example programs, start the server program first. If you do not, the client program cannot establish the socket connection. Here are the compiler and interpreter commands to compile and run the example.

  javac SocketServer.java
javac SocketClient.java

java SocketServer
java SocketClient

Example 1: Server-Side Program

The server program establishes a socket connection on Port 4321 in its listenSocket method. It reads data sent to it and sends that same data back to the server in its actionPerformed method.

listenSocket Method

The listenSocket method creates a ServerSocket object with the port number on which the server program is going to listen for client communications. The port number must be an available port, which means the number cannot be reserved or already in use. For example, Unix systems reserve ports 1 through 1023 for administrative functions leaving port numbers greater than 1024 available for use.

public void listenSocket(){
try{
server = new ServerSocket(4321);
} catch (IOException e) {
System.out.println("Could not listen on port 4321");
System.exit(-1);
}

Next, the listenSocket method creates a Socket connection for the requesting client. This code executes when a client starts up and requests the connection on the host and port where this server program is running. When the connection is successfully established, the server.accept method returns a new Socket object.
  try{
client = server.accept();
} catch (IOException e) {
System.out.println("Accept failed: 4321");
System.exit(-1);
}

Then, the listenSocket method creates a BufferedReader object to read the data sent over the socket connection from the client program. It also creates a PrintWriter object to send the data received from the client back to the server.
  try{
in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
out = new PrintWriter(client.getOutputStream(),
true);
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
}
}

Lastly, the listenSocket method loops on the input stream to read data as it comes in from the client and writes to the output stream to send the data back.
    while(true){
try{
line = in.readLine();
//Send data back to client
out.println(line);
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
}
}

actionPerformed Method

The actionPerformed method is called by the Java platform for action events such as button clicks. This actionPerformed method uses the text stored in the line object to initialize the textArea object so the retrieved text can be displayed to the end user.

public void actionPerformed(ActionEvent event) {
Object source = event.getSource();

if(source == button){
textArea.setText(line);
}
}

Example 1: Client-Side Program

The client program establishes a connection to the server program on a particular host and port number in its listenSocket method, and sends the data entered by the end user to the server program in its actionPerformed method. The actionPerformed method also receives the data back from the server and prints it to the command line.

listenSocket Method

The listenSocket method first creates a Socket object with the computer name (kq6py) and port number (4321) where the server program is listening for client connection requests. Next, it creates a PrintWriter object to send data over the socket connection to the server program. It also creates a BufferedReader object to read the text sent by the server back to the client.

public void listenSocket(){
//Create socket connection
try{
socket = new Socket("kq6py", 4321);
out = new PrintWriter(socket.getOutputStream(),
true);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("Unknown host: kq6py");
System.exit(1);
} catch (IOException e) {
System.out.println("No I/O");
System.exit(1);
}
}

actionPerformed Method

The actionPerformed method is called by the Java platform for action events such as button clicks. This actionPerformed method code gets the text in the Textfield object and passes it to the PrintWriter object, which then sends it over the socket connection to the server program.

The actionPerformed method then makes the Textfield object blank so it is ready for more end user input. Lastly, it receives the text sent back to it by the server and prints the text out.

public void actionPerformed(ActionEvent event){
Object source = event.getSource();

if(source == button){
//Send data over socket
String text = textField.getText();
out.println(text);
textField.setText(new String(""));
out.println(text);
}
//Receive text from server
try{
String line = in.readLine();
System.out.println("Text received: " + line);
} catch (IOException e){
System.out.println("Read failed");
System.exit(1);
}
}

Example 2: Multithreaded Server Example

The example in its current state works between the server program and one client program only. To allow multiple client connections, the server program has to be converted to a multithreaded server program.

First Client
Second Client
Third Client
The multithreaded server program creates a new thread for every client request. This way each client has its own connection to the server for passing data back and forth. When running multiple threads, you have to be sure that one thread cannot interfere with the data in another thread.

In this example the listenSocket method loops on the server.accept call waiting for client connections and creates an instance of the ClientWorker class for each client connection it accepts. The textArea component that displays the text received from the client connection is passed to the ClientWorker instance with the accepted client connection.

public void listenSocket(){
try{
server = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on port 4444");
System.exit(-1);
}
while(true){
ClientWorker w;
try{
//server.accept returns a client connection
w = new ClientWorker(server.accept(), textArea);
Thread t = new Thread(w);
t.start();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
}
}

The important changes in this version of the server program over the non-threaded server program are the line and client variables are no longer instance variables of the server class, but are handled inside the ClientWorker class.

The ClientWorker class implements the Runnable interface, which has one method, run. The run method executes independently in each thread. If three clients request connections, three ClientWorker instances are created, a thread is started for each ClientWorker instance, and the run method executes for each thread.

In this example, the run method creates the input buffer and output writer, loops on the input stream waiting for input from the client, sends the data it receives back to the client, and sets the text in the text area.

class ClientWorker implements Runnable {
private Socket client;
private JTextArea textArea;

//Constructor
ClientWorker(Socket client, JTextArea textArea) {
this.client = client;
this.textArea = textArea;
}

public void run(){
String line;
BufferedReader in = null;
PrintWriter out = null;
try{
in = new BufferedReader(new
InputStreamReader(client.getInputStream()));
out = new
PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("in or out failed");
System.exit(-1);
}

while(true){
try{
line = in.readLine();
//Send data back to client
out.println(line);
//Append data to text area
textArea.append(line);
}catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
}
}
}
}

The JTextArea.append method is thread safe, which means its implementation includes code that allows one thread to finish its append operation before another thread can start an append operation. This prevents one thread from overwriting all or part of a string of appended text and corrupting the output. If the JTextArea.append method were not thread safe, you would need to wrap the call to textArea.append(line) in a synchronized method and replace the run method call to textArea.append(line) with a call to appendText(line):
  public synchronized void appendText(line){
textArea.append(line);
}
The synchronized keyword means this thread has a lock on the textArea and no other thread can change the textArea until this thread finishes its append operation.

The finalize() method is called by the Java virtual machine (JVM)* before the program exits to give the program a chance to clean up and release resources. Multi-threaded programs should close all Files and Sockets they use before exiting so they do not face resource starvation. The call to server.close() in the finalize() method closes the Socket connection used by each thread in this program.

  protected void finalize(){
//Objects created in run method are finalized when
//program terminates and thread exits
try{
server.close();
} catch (IOException e) {
System.out.println("Could not close socket");
System.exit(-1);
}
}

JDK Tools and Utilities.

JDK Development Tools

General Information

The following documents contain important information you will need to know to get the most out of the JDK tools.

JDK File Structure [Solaris] [Linux] [Windows]
Setting the Classpath [Solaris and Linux] [Windows]
How Classes are Found [Solaris, Linux and Windows]

Basic Tools

These tools are the foundation of the JDK. They are the tools you use to create and build applications.
Tool Name Brief Description Links to Reference Pages
javac The compiler for the Java programming language. [Solaris and Linux] [Windows]
java The launcher for Java applications. In this release, a single launcher is used both for development and deployment.
The old deployment launcher, jre, is no longer provided.
[Solaris and Linux] [Windows]
javadoc API documentation generator.
See Javadoc Tool page for doclet and taglet APIs.
[Solaris and Linux] [Windows]
apt Annotation processing tool.
See Annotation Processing Tool for program annotation processing.
[Solaris, Linux, and Windows]
appletviewer Run and debug applets without a web browser. [Solaris and Linux] [Windows]
jar Create and manage Java Archive (JAR) files.
See Java Archive Files page for the JAR specification.
[Solaris and Linux] [Windows]
jdb The Java Debugger.
See JPDA for the debugger architecture specifications.
[Solaris and Linux] [Windows]
javah C header and stub generator. Used to write native methods. [Solaris and Linux] [Windows]
javap Class file disassembler [Solaris and Linux] [Windows]
extcheck Utility to detect Jar conflicts. [Solaris and Linux] [Windows]

Security Tools

These security tools help you set security policies on your system and create apps that can work within the scope of security policies set at remote sites.
Tool Name Brief Description Links to Reference Pages
keytool Manage keystores and certificates. [Solaris and Linux] [Windows]
jarsigner Generate and verify JAR signatures. [Solaris and Linux] [Windows]
policytool GUI tool for managing policy files. [Solaris and Linux] [Windows]

These security tools help you obtain, list, and manage Kerberos tickets.

Tool Name Brief Description Links to Reference Pages
kinit Tool for obtaining Kerberos v5 tickets. Equivalent functionality is available on the Solaris operating system via the kinit tool. For example, for Solaris 8, see the kinit reference page. [Windows]
klist Command-line tool to list entries in credential cache and key tab. Equivalent functionality is available on the Solaris operating system via the klist tool. For example, for Solaris 8, see the klist reference page. [Windows]
ktab Command-line tool to help the user manage entires in the key table. Equivalent functionality is available on the Solaris operating system via the kadmin tool. For example, for Solaris 8, see the kadmin reference page. [Windows]

Internationalization Tools

This tool helps to create localizable apps.
Tool Name Brief Description Links to Reference Pages
native2ascii Convert text to Unicode Latin-1. [Solaris and Linux] [Windows]

Remote Method Invocation (RMI) Tools

These tools help to create apps that interact over the Web or other network.
Tool Name Brief Description Links to Reference Pages
rmic Generate stubs and skeletons for remote objects. [Solaris and Linux] [Windows]
rmiregistry Remote object registry service. [Solaris and Linux] [Windows]
rmid RMI activation system daemon. [Solaris and Linux] [Windows]
serialver Return class serialVersionUID. [Solaris and Linux] [Windows]

Java IDL and RMI-IIOP Tools

These tools are used when creating applications that use OMG-standard IDL and CORBA/IIOP.
Tool Name Brief Description
tnameserv Provides access to the naming service.
idlj Generates .java files that map an OMG IDL interface and enable an application written in the Java programming language to use CORBA functionality.
orbd Provides support for clients to transparently locate and invoke persistent objects on servers in the CORBA environment. ORBD is used instead of the Transient Naming Service, tnameserv. ORBD includes both a Transient Naming Service and a Persistent Naming Service. The orbd tool incorporates the functionality of a Server Manager, an Interoperable Naming Service, and a Bootstrap Name Server. When used in conjunction with the servertool, the Server Manager locates, registers, and activates a server when a client wants to access the server.
servertool Provides ease-of-use interface for the application programmers to register, unregister, startup, and shutdown a server.

Java Deployment Tools

Utilities for use in conjunction with deployment of java applications and applets on the web.
Tool Name Brief Description
pack200 Transforms a JAR file into a compressed pack200 file using the Java gzip compressor. The compressed packed files are highly compressed JARs, which can be directly deployed, saving bandwidth and reducing download time.
unpack200 Transforms a packed file produced by pack200 into a JAR file.

Java Plug-in Tools

Utilities for use in conjunction with the Java Plug-in.
Tool Name Brief Description with Links to Reference Pages
htmlconverter Converts an HTML page (file) containing applets to the OBJECT / EMBED tag format for Java Plug-in.

Java Web Start Tools

Utilities for use in conjunction with Java Web Start.
Tool Name Brief Description
javaws Command line tool for launching Java Web Start and setting various options.
See Java Web Start Guide for more information.

Java Troubleshooting, Profiling, Monitoring and Management Tools

Tool Name Brief Description
jvisualvm

A graphical tool that provides detailed information about the Java technology-based applications (Java applications) while they are running in a Java Virtual Machine. Java VisualVM provides memory and CPU profiling, heap dump analysis, memory leak detection, access to MBeans, and garbage collection.See Java VisualVM for more information.

jconsole A JMX-compliant graphical tool for monitoring a Java virtual machine. It can monitor both local and remote JVMs. It can also monitor and manage an application.
See Monitoring and Management for the Java Platform for more information.

Java Web Services Tools

Tool Name Brief Description
schemagen Schema generator for Java Architecture for XML Binding.
wsgen Tool to generate JAX-WS portable artifacts.
wsimport Tool to generate JAX-WS portable artifacts.
xjc Binding compiler for Java Ardchitecture for XML Binding.

Monitoring Tools

You can use the following tools to monitor JVM performance statistics. The tools described in this section are unsupported and experimental, and should be used with that in mind. They may not be available in future JDK versions.

These tools are supported on all platforms except Windows 98 and Windows ME.

Tool Name Brief Description
jps Experimental: JVM Process Status Tool - Lists instrumented HotSpot Java virtual machines on a target system.
jstat Experimental: JVM Statistics Monitoring Tool - Attaches to an instrumented HotSpot Java virtual machine and collects and logs performance statistics as specified by the command line options.
jstatd Experimental: JVM jstat Daemon - Launches an RMI server application that monitors for the creation and termination of instrumented HotSpot Java virtual machines and provides a interface to allow remote monitoring tools to attach to Java virtual machines running on the local system.

Troubleshooting Tools

The following tools can be used for specific troubleshooting tasks. The tools described in this section are unsupported and experimental in nature and should be used with that in mind. They may not be available in future JDK versions.

Some of these tools are not currently available on Windows platforms.

Tool Name Brief Description
jinfo Experimental - Configuration Info for Java - Prints configuration information for for a given process or core file or a remote debug server.
jhat Experimental - Heap Dump Browser - Starts a web server on a heap dump file (eg, produced by jmap -dump), allowing the heap to be browsed.
jmap Experimental - Memory Map for Java - Prints shared object memory maps or heap memory details of a given process or core file or a remote debug server.
jsadebugd Experimental - Serviceability Agent Debug Daemon for Java - Attaches to a process or core file and acts as a debug server.
jstack Experimental - Stack Trace for Java - Prints a stack trace of threads for a given process or core file or remote debug server.

Refer to the Java SE Troubleshooting web site for descriptions of tools, options, and other information to use in analyzing problems. The documents at this site contain suggestions about what to try before submitting a bug report and what data to collect for a report.


Scripting Tools

The following tool can be used to run scripts that interact with the Java platfrom. This tool is unsupported and experimental in nature and should be used with that in mind. It might not be available in future JDK versions.
Tool Name Brief Description
jrunscript Experimental - Script shell for Java - Runs a script.

Form validation for email id in Java Script.

Here is a script that checks for the validity of email, avoiding invalid characters, position of @ and . dot and domian name is checked for the well known domains such as .com, .net or else and restricts the user to enter the valid domain name.

Code:

<HTML>
<HEAD>
<META http-equiv="Content-Language" content="en-us">
<META http-equiv="Content-Type" content="text/html; charset=windows-1252">
<META name="GENERATOR" content="Microsoft FrontPage 4.0">
<META name="ProgId" content="FrontPage.Editor.Document">
<TITLE>EMAIL VALIDATION</TITLE>
<STYLE>
A:link {text-decoration: none; color: #0000ff;}
A:visited {text-decoration: none; color: #ff0000;}
A:active {text-decoration: none; color: #FFff00;}
A:hover {text-decoration: underline; color:#00ffff;}
</STYLE>
<SCRIPT LANGUAGE=JAVASCRIPT>
function checkfield(loginform)
{
    ok=true
    if(loginform.elements[0].value=="")
    {
        alert("Please enter e-mail address.")
        loginform.elements[0].focus()
        ok=false
    }
    else
    {
        mail=loginform.elements[0].value
        at_pos=mail.indexOf("@")
        dot_pos=mail.indexOf(".")
        if(at_pos<1 || dot_pos<1)
        {
            alert("Please check position of '@' and '.' in email address.")
            loginform.elements[0].focus()
            ok=false
        }
        else
        {
            mail=loginform.elements[0].value
            condition="yes"
            var at_count=0
            var dot_count=0
            var temp=0
            for(var i=0;i<mail.length;i++)
            {
                if((mail.charCodeAt(i)>0 && mail.charCodeAt(i)<48)||(mail.charCodeAt(i)>57 && mail.charCodeAt(i)<65)||(mail.charCodeAt(i)>91 && mail.charCodeAt(i)<97)||mail.charCodeAt(i)>122)
                {
                    if(mail.charAt(i)=="@"||mail.charAt(i)==".")
                    {
                            if(mail.charAt(i)=="@"){at_count++}else{dot_count++} // counts the no. of times @ and . appears in email
                            if(dot_count>=1)
                            {
                                dot_pos=i
                                if((dot_pos>at_pos) && temp==0)
                                {
                                    pos=dot_pos-at_pos
                                    temp++
                                }                               
                            }
                    }
                    else
                    {
                        condition="no"
                        i=mail.length
                    }
                }
            }
            if(condition=="no")
            {
                alert("Your email contains a blank space or special character.")
                loginform.elements[0].focus()
                ok=false
            }
            else
            {
                if(at_count>1)
                {
                    alert("E-mail contains extra @ ")
                    loginform.elements[0].focus()
                    ok=false
                }
                else
                {
                    if(pos<2)
                    {
                        alert("Missing domain name between '@' and '.'")
                        loginform.elements[0].focus()
                        ok=false
                        i=mail.length
                    }
                    else
                    {   
                        count=dot_pos+1
                        domain=""
                        for(count;count<mail.length;count++)
                        {
                            domain=domain+mail.charAt(count)       
                        }
                        dom=new Array("au","com","net","org","edu","in","mil","gov","arpa","biz","aero","name","coop","info","pro","museum")
                        error="yes"
                        for(var k=0;k<dom.length;k++)
                        {
                            if(domain==dom[k])
                            {
                                k=dom.length
                                error="no"
                            }
                        }
                        if((error=="yes" && (domain.length>2)) || (domain.length<2))
                        {
                            alert("Domain name must end with well known domains \n or 2-lettered country name. eg com,edu,in etc.")
                            loginform.elements[0].focus()
                            ok=false
                        }                               
                    }
                }
            }
        }
    }
    return ok
}
</SCRIPT>
</HEAD>
<BODY text="#000080" bgcolor="#C0C0C0">
<FORM name="loginform" onSubmit="return checkfield(loginform)">
<TABLE border="0" width="100%">
<TR>
<TD width="25%"></TD>
<TD width="50%" colspan="2">
<P align="center"><B><FONT size="5">EMAIL VALIDATION</FONT></B></TD>
<TD width="25%"></TD>
</TR>
<TR>
<TD width="100%" colspan="4"></TD>
</TR>
<TR>
<TD width="100%" colspan="4"></TD>
</TR>
<TR>
<TD width="100%" colspan="4"></TD>
</TR>
<TR>
<TD width="100%" colspan="4"></TD>
</TR>
<TR>
<TD width="25%" rowspan="3"></TD>
<TD width="15%">Enter your e-mail :</TD>
<TD width="35%"><INPUT name="T1" size="27" tabindex="1"></TD>
<TD width="25%" rowspan="3"></TD>
</TR>
<TR>
<TD width="15%"></TD>
<TD width="35%"></TD>
</TR>
<TR>
<TD width="15%"></TD>
<TD width="35%"><INPUT type="submit" value="Submit" name="B1" tabindex="3"></TD>
</TR>
<TR>
<TD width="100%" colspan="4"></TD>
</TR>
<TR>
<TD width="100%" colspan="4"></TD>
</TR>
<TR>
<TD width="100%" colspan="4" align="center"><B>for more scripts contact : Abhishek Chitransh </B></TD>
</TR>
<TR>
<TD width="100%" colspan="4" align="center"><B>email: <A href="mailto:abhishekc.in@gmail.com">abhishekc.in@gmail.com</A></B></TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>

what is an annotation? (Java Tiger Edition)

Defined as part of JSR 175: A Metadata Facility for the Java Programming Language,
annotations offer a way to associate metadata with program elements
(such as classes, interfaces, and methods). They can be thought of as
additional modifiers without changing the generated bytecode for those
elements.

The concept of introducing metadata to source code isn't new with
J2SE 5.0. You can add an @deprecated tag to a method's javadoc comments
and the compiler treats this as metadata about the method. This ability
has been in place since the 1.0 release of J2SE. The initial release of
the platform already had deprecated methods, with the getenv() method
of System (though this wasn't in the Java Language
Specification until the 1.1 addendum). The concept is almost the same
now, at least the @ part of the syntax. Only the location has changed
-- an annotation tag goes in source, not comments. The main point here
is that annotations are a systematic way to support a declarative
programming model.



This leads to the first annotation that comes with J2SE 5.0:
@Deprecated. Notice the capital D here. Functionally, @Deprecated in
source works the same as @deprecated in the javadoc associated with a
class or method. By flagging methods with the @Deprecated tag, you're
alerting the compiler to warn the user when the method or class is used.



The following Main class has a method named deprecatedMethod() that
is flagged with the @Deprecated annotation and a, @deprecated comment:














   public class Main {

   

     /**

      @deprecated Out of date. Use System.foobar() instead.

     */ 



     @Deprecated

     public static void deprecatedMethod() {

       System.out.println("Don't call me");

     }

   }









You compile a class with annotations the same way as you do for one without annotations:



   > javac Main.java


As expected, this produces Main.class.



If you use the deprecated method, it produces a compilation-time
warning -- just like using the @deprecated tag in a javadoc. Here's an
example:













   public class User {

     public static void main(String args[]) {

       Main.deprecatedMethod();

     }

   }







Compile the class:



   > javac User.java


and you'll see the following warning about using a deprecated method:



   Note: User.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.


Adding the -Xlint to the compilation line shows specifically what is wrong:



   > javac -Xlint:deprecation User.java

User.java:3: warning: [deprecation] deprecatedMethod() in
Main has been deprecated
Main.deprecatedMethod();
^
1 warning


The change from the @deprecated comment to the @Deprecated
annotation doesn't introduce anything really new to the system. It only
slightly changes the way of doing the same thing. The other two new
annotations available to the J2SE 5.0 platform, @Override and
@SuppressWarnings, do introduce new functionality to the platform.



The @Override annotation can be used with method declarations. As
its name implies, you use the @Override annotation to flag a method
that is supposed to override a method of the superclass. Why use it? To
catch errors sooner. How many times have you meant to override a
method, but either misspelled the method name, specified the wrong
arguments, or had a different return type? In other words, how often
have you defined a new method when what you really wanted to do was
override an existing one? By using @Override, you'll find the problem
in the following class sooner rather than later:













   public class Overrode {

     @Override

     public int hashcode() {

       return 0;

     }

     

     @Override

     public boolean equals(Object o) {

       return true;

     

   }







The problem here is that the method name should be hashCode, not
hashcode. Suppose the method declaration is buried in the source for a
much larger class definition. Without the first @Override annotation,
how long would it take you to realize that your hashCode() method (with
camel-case for spelling, not all lowercase) is not being called, and
you're getting the default behavior of the parent Object class? Thanks
to the @Override annotation, compiling the class produces a compile
time error, alerting you to the problem:



   > javac Overrode.java

Overrode.java:2: method does not override a method from its
superclass
@Override
^
1 error


The sooner you can find errors of this nature, the cost of
correction becomes drastically reduced. Note that the hashCode() method
should never return a constant. For a fuller description of the proper
usage of hashCode() and equals(), see Item 8 in the book Effective Java Programming Language Guide by Joshua Bloch.



The final of the three new annotations in J2SE 5.0,
@SuppressWarnings, is the most interesting. It tells the compiler not
to warn you about something that it would normally warn you about.
Warnings belong to a category, so you have to tell the annotation what
types of warnings to suppress. The javac compiler defines seven options
to suppress: all, deprecation, unchecked, fallthrough, path, serial,
and finally. (The language specification defines only two such types:
deprecation and unchecked.)



To demonstrate, let's look at the suppression of the fallthrough
option. Let's start with the following class. Notice that the class is
missing a break statement for each case of the switch statement:













   public class Fall {

     public static void main(String args[]) {

       int i = args.length;

       switch (i) {

         case 0:  System.out.println("0");

         case 1:  System.out.println("1");

         case 2:  System.out.println("2");

         case 3:  System.out.println("3");

         default: System.out.println("Default");



       }

     }

   







Compile the class with javac. You'll see that it simply creates the .class file, and displays no warnings:



   javac Fall.java 


If you want the compiler to warn you about switch statements that
fall through (that is, one or more break statements are missing), you
compile with the -Xlint:fallthrough option:



   javac -Xlint:fallthrough Fall.java 


This produces the following warnings:



   Fall.java:6: warning: [fallthrough] possible fall-through 
into case
case 1: System.out.println("1");
^
Fall.java:7: warning: [fallthrough] possible fall-through
into case
case 2: System.out.println("2");
^
Fall.java:8: warning: [fallthrough] possible fall-through
into case
case 3: System.out.println("3");
^
Fall.java:9: warning: [fallthrough] possible fall-through
into case
default : System.out.println("Default");
^
4 warnings


But what if you want to ignore the fact that the switch statement is
missing a break statement for each case? That's where the
@SuppressWarnings annotation comes into play. If you add the following
line before the main() method declaration:



   @SuppressWarnings("fallthrough")


Compiling the class with the -Xlint:fallthrough option:



   javac -Xlint:fallthrough Fall.java 


will just generate the .class file and display no warnings.



@SuppressWarnings annotations can also be used to suppress other
warnings such as those that would be displayed if you used a collection
without specifying the data type of the collection elements. Don't use
the @SuppressWarnings annotation simply to avoid the compilation-time
warning. Use it where an unchecked warning is unavoidable, such as when
using a library that isn't built with generics in mind.



That's really about it for the built-in annotations. However one
additional thing to note, annotations (with any arguments) are
typically specified on a line by themselves.



There is much more that can be done when you define your own
annotations, rather than using the ones already defined in J2SE 5.0.
For information on defining annotations see Annotationson http://java.sun.com