Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Saturday, June 26, 2010

Java Exceptions for Beginners

Exceptions in java are any abnormal, unexpected events or extraordinary conditions that may occur at runtime. They could be file not found exception, unable to get connection exception and so on. On such conditions java throws an exception object. Java Exceptions are basically Java objects. No Project can never escape a java error exception.

Java exception handling is used to handle error conditions in a program systematically by taking the necessary action. Exception handlers can be written to catch a specific exception such as Number Format exception, or an entire group of exceptions by using a generic exception handlers. Any exceptions not specifically handled within a Java program are caught by the Java run time environment

An exception is a subclass of the Exception/Error class, both of which are subclasses of the Throwable class. Java exceptions are raised with the throw keyword and handled within a catch block.



public class DivideException {

public static void main(String[] args) {
division(100,4); // Line 1
division(100,0); // Line 2
System.out.println("Exit main().");
}

public static void division(int totalSum, int totalNumber) {

System.out.println("Computing Division.");
int average = totalSum/totalNumber;
System.out.println("Average : "+ average);
}
}

An ArithmeticException is thrown at runtime when Line 11 is executed because integer division by 0 is an illegal operation. The “Exit main()” message is never reached in the main method

Output

Computing Division.
java.lang.ArithmeticException: / by zero
Average : 25
Computing Division.
at DivideException.division(DivideException.java:11)
at DivideException.main(DivideException.java:5)

Exception in thread “main”

Exceptions in Java

Throwable Class

The Throwable class provides a String variable that can be set by the subclasses to provide a detail message that provides more information of the exception occurred. All classes of throwables define a one-parameter constructor that takes a string as the detail message.

The class Throwable provides getMessage() function to retrieve an exception. It has a printStackTrace() method to print the stack trace to the standard error stream. Lastly It also has a toString() method to print a short description of the exception. For more information on what is printed when the following messages are invoked, please refer the java docs.

Syntax

String getMessage()

void printStackTrace()

String toString()

Class Exception

The class Exception represents exceptions that a program faces due to abnormal or special conditions during execution. Exceptions can be of 2 types: Checked (Compile time Exceptions)/ Unchecked (Run time Exceptions).

Class RuntimeException

Runtime exceptions represent programming errors that manifest at runtime. For example ArrayIndexOutOfBounds, NullPointerException and so on are all subclasses of the java.lang.RuntimeException class, which is a subclass of the Exception class. These are basically business logic programming errors.

Class Error

Errors are irrecoverable condtions that can never be caught. Example: Memory leak, LinkageError etc. Errors are direct subclass of Throwable class.

Checked and Unchecked Exceptions

Checked exceptions are subclass’s of Exception excluding class RuntimeException and its subclasses. Checked Exceptions forces programmers to deal with the exception that may be thrown. Example: Arithmetic exception. When a checked exception occurs in a method, the method must either catch the exception and take the appropriate action, or pass the exception on to its caller

Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. Unchecked exceptions , however, the compiler doesn’t force the programmers to either catch the exception or declare it in a throws clause. In fact, the programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBounds Exception. They are either irrecoverable (Errors) and the program should not attempt to deal with them, or they are logical programming errors. (Runtime Exceptions). Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

Exception Statement Syntax

Exceptions are handled using a try-catch-finally construct, which has the Syntax

try {

} catch ( ) { // 0 or more

}
} finally { // finally block

}

try Block
The java code that you think may produce an exception is placed within a try block for a
suitable catch block to handle the error.

If no exception occurs the execution proceeds with the finally block else it will look for the
matching catch block to handle the error. Again if the matching catch handler is not found execution
proceeds with the finally block and the default exception handler throws an exception.. If an exception is
generated within the try block, the remaining statements in the try block are not executed.

catch Block
Exceptions thrown during execution of the try block can be caught and handled in a catch block. On exit from a catch block, normal execution continues and the finally block is executed
(Though the catch block throws an exception).

finally Block
A finally block is always executed, regardless of the cause of exit from the try block, or whether any catch block was executed. Generally finally block is used for freeing resources, cleaning up, closing connections etc. If the finally clock executes a control transfer statement such as a return or a break statement, then this control
statement determines how the execution will proceed regardless of any return or control statement present in the try or catch.

The following program illustrates the scenario.

try {

} catch ( ) { // 0 or more


}
} finally { // finally block

}

Output

Computing Division.
Exception : / by zero
Finally Block Executes. Exception Occurred
result : -1

Below is a program showing the Normal Execution of the Program.

Please note that no NullPointerException is generated as was expected by most people



public class DivideException2 {

public static void main(String[] args) {
int result = division(100,0); // Line 2
System.out.println("result : "+result);
}

public static int division(int totalSum, int totalNumber) {
int quotient = -1;
System.out.println("Computing Division.");
try{
quotient = totalSum/totalNumber;

}
catch(Exception e){
System.out.println("Exception : "+ e.getMessage());
}
finally{
if(quotient != -1){
System.out.println("Finally Block Executes");
System.out.println("Result : "+ quotient);
}else{
System.out.println("Finally Block Executes. Exception Occurred");
return quotient;
}

}
return quotient;
}
}

Output

null (And not NullPointerException)


Special thanks to ttp://www.javabeginner.com.

Monday, August 24, 2009

How to use HTTP connection instead of a stream socket

This J2ME tips illustrates a method of using HHTP connection instead of a stream socket. This code looks very similar to the socket code, but there is a striking difference. The socket code first opened an OutputStream and sent the request to the webserver before trying to read the response.

String url = "http://learnsunjava.blogspot.com/";

conn = (HttpConnection)Connector.open(url,
Connector.READ_WRITE
);
if (conn.getResponseCode( ) == HttpConnection.HTTP_OK) {
is = conn.openInputStream( );
final int MAX_LENGTH = 128;
byte[] buf = new byte[MAX_LENGTH];
int total = 0;
while (total <>) {
int count = is.read(buf, total, MAX_LENGTH - total);
if (count < 0) {
break;
}
total += count;
}
is.close( );
String reply = new String(buf, 0, total);
}

How to use GET and POST methods in HTTP from a MIDlet-J2ME

//This example shows how to use GET and POST methods in HTTP from a MIDlet.


import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class HttpTest1 extends MIDlet {

private Display display;

public HttpTest1() {
try {

//NOTE:Comment out the functionality which you don't want to test
getBirthdayFromNameUsingGet("John");
getBirthdayFromNameUsingPost("John");
}
catch (IOException e) {
System.out.println("IOException " + e.toString());
}
}

/**
* MIDlet lifecycle functions
*/
public void startApp() { }

public void pauseApp() {

}

public void destroyApp(boolean unconditional) {
}

/**
This function connects to web server and passes the parameter name to the
target in HTTP Get request. Upon successful connection, web server returns
birthday for 'name'.
This function also calls getConnectionInformation to retrieve properties of
HTTPConnection
**/

public void getBirthdayFromNameUsingGet(String name) throws IOException {

HttpConnection httpConn = null;
String url = "http://localhost:8080/examples/servlet/GetBirthday?name=" + name;

InputStream is = null;
OutputStream os = null;

try {
// Open an HTTP Connection object
httpConn = (HttpConnection)Connector.open(url);

// Setup HTTP Request
httpConn.setRequestMethod(HttpConnection.GET);
httpConn.setRequestProperty("User-Agent",
"Profile/MIDP-1.0 Confirguration/CLDC-1.0");


// This function retrieves the information of this connection
getConnectionInformation(httpConn);

/** Initiate connection and check for the response code. If the
response code is HTTP_OK then get the content from the target
**/
int respCode = httpConn.getResponseCode();
if (respCode == httpConn.HTTP_OK) {
StringBuffer sb = new StringBuffer();
os = httpConn.openOutputStream();
is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1)
sb.append((char) chr);

// Web Server just returns the birthday in mm/dd/yy format.
System.out.println(name+"'s Birthday is " + sb.toString());
}
else {
System.out.println("Error in opening HTTP Connection. Error#" + respCode);
}

} finally {
if(is!= null)
is.close();
if(os != null)
os.close();
if(httpConn != null)
httpConn.close();
}

}

/**
This function connects to web server and passes the parameter name to the
target in HTTP POST request. Upon successful connection, web server returns
birthday for 'name'.
This function also calls getConnectionInformation to retrieve properties of
HTTPConnection
**/

public void getBirthdayFromNameUsingPost(String name) throws IOException {

HttpConnection httpConn = null;
String url = "http://localhost:8080/examples/servlet/GetBirthday";
InputStream is = null;
OutputStream os = null;

try {
// Open an HTTP Connection object
httpConn = (HttpConnection)Connector.open(url);
// Setup HTTP Request to POST
httpConn.setRequestMethod(HttpConnection.POST);

httpConn.setRequestProperty("User-Agent",
"Profile/MIDP-1.0 Confirguration/CLDC-1.0");
httpConn.setRequestProperty("Accept_Language","en-US");
//Content-Type is must to pass parameters in POST Request
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

// This function retrieves the information of this connection
getConnectionInformation(httpConn);


os = httpConn.openOutputStream();

String params;
params = "name=" + name;

os.write(params.getBytes());

/**Caution: os.flush() is controversial. It may create unexpected behavior
on certain mobile devices. Try it out for your mobile device **/

//os.flush();

// Read Response from the Server

StringBuffer sb = new StringBuffer();
is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1)
sb.append((char) chr);

// Web Server just returns the birthday in mm/dd/yy format.
System.out.println(name+"'s Birthday is " + sb.toString());

} finally {
if(is!= null)
is.close();
if(os != null)
os.close();
if(httpConn != null)
httpConn.close();
}

}


/*** After setup, attributes of the HttpConnection object can be retrived using
various get methods.
***/
void getConnectionInformation(HttpConnection hc) {

System.out.println("Request Method for this connection is " + hc.getRequestMethod());
System.out.println("URL in this connection is " + hc.getURL());
// It better be HTTP:)
System.out.println("Protocol for this connection is " + hc.getProtocol());
System.out.println("This object is connected to " + hc.getHost() + " host");
System.out.println("HTTP Port in use is " + hc.getPort());
System.out.println("Query parameter in this request are " + hc.getQuery());

}

}

J2EE Interview Questions


Question:
What is J2EE?
Answer: J2EE Stands for Java 2 Enterprise Edition. J2EE is an environment for developing and deploying enterprise applications. J2EE specification is defined by Sun Microsystems Inc. The J2EE platform is one of the best platform for the development and deployment of enterprise applications. The J2EE platform is consists of a set of services, application programming interfaces (APIs), and protocols, which provides the functionality necessary for developing multi-tiered, web-based applications. You can download the J2EE SDK and development tools from http://java.sun.com/.

Question: What do you understand by a J2EE module?
Answer: A J2EE module is a software unit that consists of one or more J2EE components of the same container type along with one deployment descriptor of that type. J2EE specification defines four types of modules:
a) EJB
b) Web
c) application client and
d) resource adapter

In the J2EE applications modules can be deployed as stand-alone units. Modules can also be assembled into J2EE applications.

Question: Tell me something about J2EE component?
Answer: J2EE component is
a self-contained functional software unit supported by a container and configurable at deployment time. The J2EE specification defines the following J2EE components:

  • Application clients and applets are components that run on the client.
  • Java servlet and JavaServer Pages (JSP) technology components are Web components that run on the server.
  • Enterprise JavaBeans (EJB) components (enterprise beans) are business components that run on the server.J2EE components are written in the Java programming language and are compiled in the same way as any program in the language. The difference between J2EE components and "standard" Java classes is that J2EE components are assembled into a J2EE application, verified to be well formed and in compliance with the J2EE specification, and deployed to production, where they are run and managed by the J2EE server or client container.
    Source: J2EE v1.4 Glossary
Question: What are the contents of web module?
Answer: A web module may contain:
a) JSP files
b) Java classes
c) gif and html files and
d) web component deployment descriptors

Question: Differentiate between .ear, .jar and .war files.
Answer: These files are simply zipped file 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 extenstion. The .jar files contains 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 application.

Question: What is the difference between Session Bean and Entity Bean?
Answer:

Session Bean: Session is one of the EJBs and it represents a single client inside the Application Server. Stateless session is easy to develop and its efficient. As compare to entity beans session beans require few server resources.

A session bean is similar to an interactive session and is not shared; it can have only one client, in the same way that an interactive session can have only one user. A session bean is not persistent and it is destroyed once the session terminates.

Entity Bean: An entity bean represents persistent global data from the database. Entity beans data are stored into database.

Question: Why J2EE is suitable for the development distributed multi-tiered enterprise applications?
Answer: The J2EE platform consists of multi-tiered distributed application model. J2EE applications allows the developers to design and implement the business logic into components according to business requirement. J2EE architecture allows the development of multi-tired applications and the developed applications can be installed on different machines depending on the tier in the multi-tiered J2EE environment . The J2EE application parts are:

a) Client-tier components run on the client machine.
b) Web-tier components run on the J2EE server.
c) Business-tier components run on the J2EE server and the
d) Enterprise information system (EIS)-tier software runs on the EIS servers

Question: Why do understand by a container?
Answer: Normally, thin-client multi-tiered applications are hard to write because they involve many lines of intricate code to handle transaction and state management, multithreading, resource pooling, and other complex low-level details. The component-based and platform-independent J2EE architecture makes J2EE applications easy to write because business logic is organized into reusable components. In addition, the J2EE server provides underlying services in the form of a container for every component type. Because you do not have to develop these services yourself, you are free to concentrate on solving the business problem at hand (Source: http://java.sun.com/j2ee/1.3/docs/tutorial/doc/Overview4.html ).

In short containers are the interface between a component and the low-level platform specific functionality that supports the component. The application like Web, enterprise bean, or application client component must be assembled and deployed on the J2EE container before executing.

Question: What are the services provided by a container?
Answer: The services provided by container are as follows:
a) Transaction management for the bean
b) Security for the bean
c) Persistence of the bean
d) Remote access to the bean
e) Lifecycle management of the bean
f) Database-connection pooling
g) Instance pooling for the bean

Question: What are types of J2EE clients?
Answer: J2EE clients are the software that access the services components installed on the J2EE container. Following are the J2EE clients:
a) Applets
b) Java-Web Start clients
c) Wireless clients
d) Web applications

Wednesday, December 31, 2008

Enums

  • An enum specifies a list of constant values that can be assigned to a particular type.
  • An enum is NOT a String or an int; an enum constant's type is the enum type. For example, WINTER, SPRING, SUMMER, and FALL are of the enum type Season.
  • An enum can be declared outside or inside a class, but NOT in a method.An enum declared outside a class must NOT be marked static, final, abstract, protected, or private.
  • Enums can contain constructors, methods, variables, and constant class bodies.
  • enum constants can send arguments to the enum constructor, using the syntax BIG(8), where the int literal 8 is passed to the enum constructor.
  • enum constructors can have arguments, and can be overloaded.
  • enum constructors can NEVER be invoked directly in code. They are always called automatically when an enum is initialized.
  • The semicolon at the end of an enum declaration is optional.

Sunday, December 21, 2008

Coupling and cohesion

"Object-oriented programming has two main objectives: to build highly cohesive classes and to maintain loose coupling between those classes. High-cohesion means well-structured classes and loose coupling means more flexible, extensible software."

"Cohesive means that a certain class performs a set of closely related actions. A lack of cohesion, on the other hand, means that a class is performing several unrelated tasks. Though lack of cohesion may never have an impact on the overall functionality of a particular class or of the application itself the application software will eventually become unmanageable as more and more behaviours become scattered and end up in wrong places."

"Whenever one object interacts with another object, that is a coupling. In reality, what you need to try to minimise is coupling factors. Strong coupling means that one object is strongly coupled with the implementation details of another object. Strong coupling is discouraged because it results in less flexible, less scalable application software. However, coupling can be used so that it enables objects to talk to each other while also preserving the scalability and flexibility."

"In OO programming, coupling is unavoidable. Therefore, the goal is to reduce unnecessary dependencies and make necessary dependencies coherent."

Java Date

Date and time, An essential factor in a program for implementing many concepts at real-time. Java provides a special class – date Class in the java.util Package (sort of catch-all for handy utilities).

Date provides methods for examining and manipulating date and time. Time in java is measured in milliseconds since January 1, 1970. Java attempts to handle time from the system with which it is interfacing. UTC is coordinated Universal Time, which seems to be the worldwide standard.

Note : In the date class, dates before January 1, 1970 are generally not usable.

List of the methods to see full scope of the Date class:

Methods

Purpose

UTC(int, int, int, int, int)

Calculates a UTC value from YMDHMS

after(Date)

check whether this date comes after the specified date

before(Date)

Checks whether this date comes before the specified date

equals(Object)

Compares this object against specified object

getDate()

Returns the day of the month

getDay()

Returns the day of the week

getHours()

Returns the hour

getMinutes()

Returns the minute

getMonth()

Returns the month

getSeconds()

Returns the seconds

getTime()

Returns the time in milliseconds since the epoch

getTimezoneOffset()

Returns the time zone offset in minutes for the current locale that is appropriate for this time

getYear()

Returns the year after 1900

hashCode()

Compares a number that is used when storing objects in hash tables.

parse(String)

given a string representing a time, parses it and returns the time value.

setDate(int)

Sets the date

setHours(int)

Sets the hour

setMinutes(int)

Sets the minute

setMonth(int)

Sets the month

setSecondsint()

Sets the seconds

setTime(int)

Sets the time

setYear(int)

Sets the year

toGMTString()

Converts a date to string object, using the internet GMT conversions.

toLocalString()

Converts a date to string object, using the locale conversions.

toString()

Converts a date to string object, using UNIX conversions.

It is important to remember that months start with 0, which is January, and end with 11, which is December. The days of the week also start with 0, which is Sunday, and go through 6, which is Saturday. Dates of the month are normal.

Tuesday, December 9, 2008

Find Bugs in Java Programs

FindBugs program which uses static analysis to look for bugs in Java code. It is free software, distributed under the terms of the Lesser GNU Public License. The name FindBugs™ and the FindBugs logo are trademarked by The University of Maryland. As of July, 2008, FindBugs has been downloaded more than 700,000 times.

FindBugs requires JRE (or JDK) 1.5.0 or later to run. However, it can analyze programs compiled for any version of Java. The current version of FindBugs is 1.3.6, released on 12:34:14 EST, 13 November, 2008.


Additional open source projects

The following software is being made available by the University of Maryland and the FindBugs project. The software is still preliminary, and needs volunteers to help mature it.

  • Multithreaded test case, a framework designed to make it easy to create test cases for concurrent software in which multiple threads must coordindate their activity to perform a test (e.g., testing a concurrent blocking queue, with one thread that blocks when it trys to add to a full queue, and another thread that unblocks the first by removing an element).
  • Checked uncontended lock, an implementation of the Java 5 Lock and ReadWriteLock interfaces that throw exceptions if they detect lock contention. These locks are designed to be used for debugging, and can be used in places where you don't believe you need to use a lock but want to verify that at runtime.

Monday, December 8, 2008

Garbage collection

The garbage collector first performs a task called marking. The garbage collector traverses the application graph, starting with the root objects; those are objects that are represented by all active stack frames and all the static variables loaded into the system. Each object the garbage collector meets is marked as being used, and will not be deleted in the sweeping stage.

The sweeping stage is where the deletion of objects take place. There are many ways to delete an object: The traditional C way was to mark the space as free, and let the allocator methods use complex data structures to search the memory for the required free space. This was later improved by providing a defragmenting system which compacted memory by moving objects closer to each other, removing any fragments of free space and therefore allowing allocation to be much faster:

memory collection

For the last trick to be possible a new idea was introduced in garbage collected languages: even though objects are represented by references, much like in C, they don’t really reference their real memory location. Instead, they refer to a location in a dictionary which keeps track of where the object is at any moment.

Fortunately for us - but unfortunately for these garbage collection algorithms - our servers and personal computers got faster (and multiple) processors and bigger memory capacities. Compacting memory areas this large often was very taxing on the application, especially considering that when doing that, the whole application had to freeze due to the changes in the virtual memory map. Fortunately for us though, some smart people improved those algorithms in three ways: concurrency, parallelization and generational collection.

Sunday, December 7, 2008

Know thy acronyms

Maybe it's caused by the passing of time, maybe it's because of its open nature or maybe it's simply because people like to make them up. In any event, few technologies in computing are as littered with acronyms as Java is.

Just for fun, while eating lunch (yeah I know it's bad habit) I compiled a list off the top of my head of what an average developer might be subjected to, when tracking technologies in the Java space.
  • AWT - Abstract Window Toolkit (UI)
  • BGGA - Gilad Bracha, Neal Gafter, James Gosling, and Peter von der Ahe (Closures)
  • CICE - Concise Instance Creation Expressions (Closures)
  • EAR - Enterprise ARchive (Packaging)
  • EDT - Event Dispatching Thread (Lingo)
  • EJB - Enterprice Java Beans (Packaging/technology)
  • FCM - First Class Methods (Closures)
  • JAR - Java ARchive (Packaging)
  • JAX-RPC - Java API for Xml-based Remote Procedure Call
  • JAX-RS - The Java API for RESTful Web Services
  • JAX-WS - Java API for Xml-based Web Services
  • JAXB - Java Archtecture for Xml Binding
  • JAXP - Java API for Xml Processing
  • JCK - Java Compatibility Kit
  • JCP - Java Community Process
  • JDBC - Java DataBase Connector
  • JDK - Java Development Kit
  • JDO - Java Data Objects
  • JDOM - Java Document Object Model
  • JEE - Java Enterprise Edition
  • JLS - Java Language Specification
  • JME - Java Micro Edition
  • JMM - Java Memory Model
  • JMS - Java Messenging Service
  • JMX - Java Management Specification
  • JNDI - Java Naming and Directory Interface
  • JNI - Java Native Interfacing
  • JNLP - Java Network Launch Protocol
  • JPA - Java Persistency API
  • JPQL - Java Persistency Query Language
  • JRE - Java Runtime Environment
  • JRO - Java Runtime Object
  • JSE - Java Standard Edition
  • JSF - Java Server Faces
  • JSP - Java Server Pages
  • JSR - Java Specification Request
  • JSTL - JavaServer Pages Standard Tag Library
  • JTA - Java Transaction API
  • JTS - Java Transaction Service
  • JVM - Java Virtual Machine
  • JWS - Java Web Start (Deployment)
  • JXTA -Juxtapose (Peer-2-Peer)
  • NIO - New Input/Output API
  • NPE - NullPointerException (Lingo)
  • POJO - Pure Old Java Object (Lingo)
  • RT - Runtime (rt.jar, the JRE)
  • SAF - Swing Application Framework (JSR-296)
  • SOP - System.out.print (Lingo)
  • SWT - Standard Widget Toolkit (UI)
  • StAX - Pull-parsing XML
  • WAR - Web ARchive (Packaging)
I have only included direct Java acronyms, not framework (Swing, Spring, Struts...), libraries (iText, JodaTime, log4j...), tools (Maven, JUnit, JMeter...) or general purpose technologies (SVN, HG, CVS...).

The amount of acronym soup is staggering. No wonder people are sometimes overwhelmed.

NetBeans plugin: Special copy/paste

The very little I've had to paste code into this fairly new blog, was enough to give me the idea of creating an extension to NetBeans which would help to remedy this formatting nightmare. Now, in my world, there's approximately a 100:1 ratio between idea and actual realization, so I'd have to salute the awesome OpenIDE API's for making this possible spending just a few late nights and taking just 200 lines of code. Without further ado, I present, my first NetBeans plugin.

Special copy/paste
The plugin will add a couple of new actions to the context-sensitive popup-menu of the source editor, which will allow you to copy the selected text as preformatted HTML, as well as a CSS version which will preserve the formatting used in NetBeans.


Using the "Copy as HTML and CSS" menu as in the above screen dump will result in you being able to paste it directly into a website/wiki/blog and have it display like this:

/**
* @param args the command line arguments
*/

public static void main(String[] args) {
// TODO code application logic here
}

For a larger example of what the output of the plugin looks like, take a look at the plugin's own source code.

It's supposed to be language agnostic, in that it should work with all types of sources NetBeans is able to tokenize. The plugin will try to mimic the formatting of the tokens in regard to font family, keyword and literal colors. It will however *not* be able to show member-wide variables in green as NetBeans does nor show method and class decelerations in bold. This is a limitation caused by the fact that I am only using the NetBeans lexer API rather than doing any kind of semantic analysis or parsing.

If you want to give the plugin a try, download it from NetBean's Plugin Portal. Source code is available here.


Update:
It has been made clear to me through the comments, that NetBeans already contains functionality to extract source code as HTML. You can find the feature in the "File" menu under the ill named item "Print to HTML". Since it would appear other people than just me did not associate "print" with that of exporting HTML content, I have filed an issue for the relocation and/or renaming of this.