JavaBeat
Search JavaBeat

JAVABEAT
home
articles
tips
QnA
Books
forums
ARTICLE TOPICS
All Articles
Java 5.0
Java 6.0
EJB 3.0
JCA
Struts
JSF
Spring
Groovy
JBoss Seam
Hibernate
Eclipse
JavaFx
Google Guice
J2ME
GWT
WebServices
AJAX
ARCHIVE
2007 | 12 11 10 09 08 07 06 05 04 03
2008 | 07 06 05 04 03 02 01
CERTIFICATION KITS
350 SCJP 1.5 Mock Exams
400 SCJP 1.6 Mock Exams
300 SCWCD 5.0 Mock Exams
300 SCBCD 5.0 Mock Exams
Enter email address:

Latest JavaBeat Articles Delivered by FeedBurner
OUR NETWORK
javabeat
planetoss
Sponsors
Java Jobs eCommerce software Get Ubuntu 8.04 Get FireFox 3.0  

Pages : 1 2 3

Introduction to Java 6.0 New Features, Part–I

Author : Raja
Date : Wed Jun 6th, 2007
Topic : java6  
Enter email address:

Latest JavaBeat Articles Delivered

1) Introduction

This article covers the various new features of Java 6, also known as Mustang. This article assumes that readers have sufficient knowledge over the concepts and terminologies in Java 5.0. For more information on Java 5.0, readers can vist the resources available in javabeat here. Though there is no significant changes at the Language Level, though Mustang comes with a bunch of enhancements in the other areas like Core, XML and Desktop. Most of the features are applicable both to J2SE and J2EE Platforms.

2) Java 6 Features

A feature or an enhancement in Java is encapsulated in the form of a JSR. JSR, which stands for Java Specification Request is nothing but a formal proposal which details the need for a specific functionality to be available in the Java Platform that can be used by Applications. These JSR’s will be reviewed and released by a committee called Java Expert Groups (JEG). This article covers the following list of features (or JSRs') that comes along with the Java 6 Platform.

  • Pluggable Annotation Processing API (JSR 269)
  • Common Annotations (JSR 250)
  • Java API for XML Based Web Services - 2.0 (JSR 224)
  • JAXB 2.0 (JSR 222)
  • Web Services Metadata (JSR 181)
  • Streaming API for XML (JSR 173)
  • XML Digital Signature (JSR 105)
  • Java Class File Specification Update (JSR 202)
  • Java Compiler API (JSR 199)
  • JDBC 4.0 (JSR 221)
  • Scripting in the Java Platform (JSR 223)

The JSRs' that are covered in this article are Common Annotations, JDBC 4.0 and Scripting in the Java Platform. Rest of the JSRs' will be covered in the subsequent article.

3) Common Annotations

The aim of having Common Annotations API in the Java Platform is to avoid applications defining their own Annotations which will result in having larger number of Duplicates. This JSR is targeted to cover Annotations both in the Standard as well the Enterprise Environments. The packages that contain the annotations are javax.annotation and javax.annotation.security . Let us discuss in brief the commonly used Annotations that are available in this JSR in the next subsequent sections.

3.1) @Generated Annotation

Not all the source files or the source code in an application is hand-written by Developers. With the increasing number of Tools and Frameworks, most of the common Boiler-Plate Code is generated by the Tools or the Frameworks itself if they have been properly instructed. Such Tool Generated Code can be marked with @Generated Annotation. Consider the following sample code snippet,

MyClass.java

					
public class MyClass{

    public void developerCode(){
    }

    @Generated(
        value = "ClassNameThatGeneratedThisCode", 
        comments = "This is Tool Generated Code", 
        date = "5 June 2007"
    )
    public void toolGeneratedCode(){
    }

}
					

The value for the @Generated Annotation would be usually the class name that generated this code. Optionally, comments and date can be given to add more clarity to the generated code. Note this @Generated Annotation is not limited to a method definition, it can also be defined for Package Declaration, Class Declaration, Interface Declaration, Local Variable Declaration, Field Declaration, Parameter Declaration etc.

3.2) @Resource and @Resources Annotation

Any Class or Component that provides some useful functionality to an Application can be thought of as a Resource and the same can be marked with @Resource Annotation. This kind of Annotation can be seen normally in J2EE Components such as Servlets, EJB or JMS. For example consider the following code snippet,

					
@Resource(name = "MyQueue", type = javax.jms.Queue, 
    shareable = false, 
    authenticationType = Resource.AuthenticationType.CONTAINER, 
    description = "A Test Queue"
)
private javax.jms.Queue myQueue;
					

Queue is a class available as part of JMS API and it serves as a target for Asynchronous Messages being sent by Applications. The various properties to note in @Resource Annotation are: 'name' which is the JNDI Name of this resource, 'type' which is the type of the resource which usually points to the Fully Qualified Class Name, 'shareable' which tells whether this resource can be shared by other components in the Application or not, 'authenticationType' which indicates the type of authentication to be performed either by the Container or by the Application and the Possible values are AuthenticationType.CONTAINER and AuthenticationType.APPLICATION and 'description' which is a string that describes the purpose of this resource.

When the Application containing the @Resource Annotations are deployed to a Server, the Container will scan for all the Resource references during the time of Application loading and then will populate the @Resource References by assigning new instances.

@Resources is nothing but a collection of @Resource entries. Following is a sample code that defines @Resources Annotation,

					
@Resources({
    @Resource(name = "myQueue" type = javax.jms.Queue),
    @Resource(name = "myTopic" type = javax.jms.Topic),
})
					

3.3) @PostConstruct and @PreDestroy

J2EE Components are usually created by the Container or the Framework on which they are deployed. Container creates new components by calling the Default or the No Argument Constructor. It is a very common need that a component needs to get initialized with some default values after it has been created. @PostConstruct Annotation serves that purpose. It is a Method-Level Annotation, meaning that this Annotation can be applied only to a Method and it will be fired immediately as soon the Component is created by invoking the Constructor.

Consider the following set of code,

MyDbConnectionComponent.java

					
public class MyDbConnectionComponent{

    public MyDbConnectionComponent(){
    }

    @PostConstruct()
    public void loadDefaults(){

        // Load the Driver Class.
        // Get the Connection and Do other stuffs.

    }
}
					

We can see that @PostConstruct Annotation is normally used to Initialize the Resources that are Context specific. The loadDefaults() method which is marked with @PostConstruct Annotation will be called immediately by the Container as soon as an instance of MyDbConnectionComponent is created. There are certain guidelines to be followed while defining the PostConstruct method such as: the method should not be marked as static, return type should be void, it cannot throw any CheckedExceptions etc.

The counterpart to @PostConstruct Annotation is the @PreDestroy Annotation. From the name of the Annotation itself, we can infer that the method that is marked with this Annotation will be called before an object is about to be removed or destroyed by the Container. Like the @PostConstruct Annotation, this is also a Method-Level Annotation and the following code snippet proves this,

MyDbConnectionComponent.java

					
public class MyDbConnectionComponent{

    public MyDbConnectionComponent(){
    }

    @PreDestroy()
    public void releaseResources(){

        // Close the Connection.
        // Unload the Class Driver from the System

    }
}
					

The method releaseResources() will be called by the Container before the object is about to be Destroyed. Resource releasing code are ideal candidates to be placed in the @PreDestroy Annotation method.

3.4) Role Based Annotations

The following sections discuss the various Role-based Annotations that are very common in Applications that are very concerned about Security. A Typical Application is accessed by a wide range of Users and Users themselves fall into Several Roles. Considering an IT Organization, all Employees fall into the General Category of Roles namely Admin, Director, Manager, Engineer, Programmer etc. It is very common to see Applications following Role-Based Security Model. The Annotations @DeclareRoles, @RolesAllowed, @PermitAll, @DenyAll and @RunAs are Role-Based Annotations and are covered here.

3.4.1) @DeclareRoles Annotations

This is a Class-Level Annotation meaning that this Annotation is applicable only to a Class Declaration. If applied to a Class or a Component, it essentially declares the valid Set of Roles that are available for this Component. Consider the following code which will clarify this,

LeaveService.java

					
@DeclareRoles(value = {"Director", "Manager", "Others" })
public class LeaveService{

    @Resource
    private Context context;
	
    public void applyLeave(){

        // Any employee can apply for leave. So no need for any 
        // conditional check.
    }

    public void grantLeave(){
        if(checkUserInRole()){
            // Grant Leave.
        }
    }

    public void cancelLeave(){
        if(checkUserInRole()){
            // Cancel Leave.
        }
    }

    private boolean checkUserInRole(){
        if( (context.isCallerInRole("Director") )
            || (context.isCallerinRole("Manager")) ){
            return true;
        }

        return false;
    }
}
					

In the above example, the component LeaveService has been marked with @DeclareRoles Annotations with Role Name values namely Director and Manager. It has three services namely: applying for leave (applyLeave()), granting for leave (grantLeave()) and cancellation of leave (cancelLeave()). It is acceptable that only Employees in the Superior Role (Director or Manager) can grant or deny leaves to their sub-ordinates. So additional conditional checks are done to ensure that whether the User who is accessing the grantLeave() or the cancelLeave() service belongs to either of the defined Roles(Director or Manager). Since any employee in a company can apply for a leave, (whose Role Name is given as Others), no conditional checks are done in applyLeave() method.

3.4.2) @RolesAllowed Annotation

This is a Class/Method Level Annotation which is used to grant access to some Service(s) to the defined set of Users who are mentioned by their Role Names in the Annotation. Let us get into the following example straightaway,

LeaveService.java

					
@DeclareRoles("A", "B", "C", "X", "Y", "Z")
@RolesAllowed("A", "B", "C")
public class MyServiceComponent{

    @RolesAllowed(value = {"A", "X", "Y"} )	
    public void myService1(){
    }

    @RolesAllowed(value = {"B", "Y", "Z"} )	
    public void myService2(){
    }

    @RolesAllowed(value = {"X", "Y", "Z"} )	
    public void myService3(){
    }

    public void myService4(){
    }
}
					

The above code declares various roles namely "A", "B", "C", "X", "Y" and "Z" for the component MyServiceComponent. The @RolesAllowed Annotation when applied to a method grant Access to Users who are in that Roles only. For example, only Users with Roles "A" or "X" or "Y" are allowed to access the method myService1(). In the case of myService2(), "B", "Y" or "Z" role Users are allowed to access it and so on.

What happens in the case of myService4()??

No @RolesAllowed is specified for this method. The fact is that, if a method doesn’t have @RolesAllowed Annotation attached to it, then it will inherit this property from the class where it has been defined. So, in our case, Users in the Role "A", "B" or "C" can access the method myService4() becuase these set of Roles have been defined at the Class Level. What if the Class Declaration itself doesn’t have the @RolesAllowed Annotation declared? The answer is simple: it will take all the Roles that are defined in @DeclareRoles.

3.4.3) @PermitAll and @DenyAll Annotation

These are Class/Method Level Annotations and if applied to a Class Declaration will affect all the methods in the class, and when applied to a method will affect that method only.

Consider the following sample,

MyClass.java

					
@DeclareRoles(value = {"A", "B", "C"} )
class MyClass{

    @PermitAll()
    public void commonService(){
    }

    @DenyAll
    public void confidentialService(){
    }
}
					

From the above code, it is inferred that commonService() method can be accessible by all Users irrespective of their Roles as it is marked with @PermitAll() annotation and no one can access the confidentialService() because it has been marked with @DenyAll() annotation.

 
Pages : 1 2 3
 

Sponsors
Webmaster Hosting Forum
Java Jobs
MyVideoLib
India News
Internet Advances
Latest QnA
SCJD Tips
When we start a thread by applying start() method on it ,how does it knows that to execute run()method?
About Wrapper class in Java
How to configure weblogic 7.0 in MyEclipse?
Static Block and Static Initializer in Java

JavaBeat Media (2004-2008), India
javabeat | planetoss | links directory | advertise
Copyright (2004 - 2008), JavaBeat