Thursday, January 26, 2012

Maven3: Working in Offline Mode

Maven provides the option of running the command offline. If you have have the packages JAR/WAR/EAR available on local repository, then you can run the command in offline mode. It also speeds up the command since it does not check centralized SCMs, central repositories, and issue tracking systems.

There are two ways in which you can work in offline mode:

1. Use an -o switch for any Maven command. For example:

mvn clean install -o
mvn test -o

If there is some dependency issue and you have the dependent jar file in your local system, following command can be used for setting the dependency manually:

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id>
-DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>

2. Set it permanently in the Maven settings file settings.xml. The settings file can be
found in the <m2_home>/conf/ folder or the <user_home>/m2/ directories.


Friday, January 20, 2012

Creating XML document using JavaScript

DOM Leavel 2 provides a document.implementation.createDocument method which can be used to create a blank XML document using the following syntax:

var doc = document.implementation.createDocument(namespaceuri, root, doctype);

We can use this API in the following way:

var doc = document.implementation.createDocument("","root", null);
var node = doc.createElement("node");

This creates an XML DOM document with no default namespace and no doctype.

Browser Support:

  • Internet Explorer 9+
  • Firefox
  • Opera
  • Chrome
  • Safari

HTML5: Page Visibility API

HTML5 has introduced a page Visibility API. As the name suggests, this API give information about whether or not the page is visible to the user. This API provides a visibilitychange event which can be used to notify when the page changes from visible to hidden or hidden to visible.

Note: In Internet Explorer, this event is called msvisibilitychange and in Chrome it’s called webkitvisibilitychange.

Following is the cross browser way for using this API:

var EventHandler = {
    addHandler: function(element, type, handler){
        if (element.addEventListener){
            element.addEventListener(type, handler, false);
        } else if (element.attachEvent){
            element.attachEvent("on" + type, handler);
        } else {
            element["on" + type] = handler;
    removeHandler: function(element, type, handler){
        if (element.removeEventListener){
            element.removeEventListener(type, handler, false);
        } else if (element.detachEvent){
            element.detachEvent("on" + type, handler);
        } else {
            element["on" + type] = null;

function handleVisibilityChange(){
    if (document.hidden || document.msHidden || document.webkitHidden){
        alert("Page is now hidden.");
    } else {
        alert("Page is now visible.");

EventHandler.addHandler(document, "msvisibilitychange", handleVisibilityChange);
EventHandler.addHandler(document, "webkitvisibilitychange", handleVisibilityChange);

Browser Support:

  • Internet Explorer (10+)
  • Chrome (12+)

Wednesday, January 18, 2012

JavaEE6: CDI - Bean and Bean Types

In my last post, I explained about CDI. Now let us talk about different CDI concepts.

Beans in CDI

According to Wikipedia "Beans are reusable software components for Java. Practically, they are classes written in the Java programming language conforming to a particular convention." CDI redefines this concept beyond Java beans and EJB.


  • A bean is a source of contextual objects that define application state and/or logic. These objects are called contextual instances of the bean.
  • A Java EE component is a bean if the lifecycle of its instances may be managed by the container according to the lifecycle context model defined in the CDI specification.
  • The container creates and destroys these instances and associates them with the appropriate context.
  • Contextual instances of a bean may be injected into other objects (including other bean instances) that execute in the same context, and may be used in EL expressions that are evaluated in the same context.

Bean Types

A bean type defines a client-visible type of the bean. A bean may have multiple bean types. For example, the following bean has four bean types:

public class CarFactory extends VehicleFactory implements Factory {

The bean types are CarFactory, VehicleFactory, Factory and Object.

Almost any Java type may be a bean type of a bean:

  • A bean type may be an interface, a concrete class or an abstract class, and may be declared final or have final methods.
  • A bean type may be a parameterized type with actual type parameters and type variables.
  • A bean type may be an array type. Two array types are considered identical only if the element type is identical.
  • A bean type may be a primitive type. Primitive types are considered to be identical to their corresponding wrapper types in java.lang.
  • A bean type may be a raw type.

Tuesday, January 17, 2012

JavaEE 6: What is CDI?

Contexts and Dependency Injection, more commonly known as CDI, is one of the new features for the Java EE Platform. It allows us to bind together the web tier and transactional tier of Java EE platform.

The two most fundamental services provided by CDI are as follows:

  • Contexts: The ability to bind the lifecycle and interactions of stateful components to well-defined but extensible lifecycle contexts
  • Dependency injection: The ability to inject components into an application in a type-safe way, including the ability to choose at deployment time which implementation of a particular interface to inject.

In addition, CDI provides a rich programming model through loose-coupling with strong typing. A bean need not be aware of the actual lifecycle, concrete implementation, threading model or other clients of any bean it interacts with. Events, interceptors and decorators enhance this loose-coupling:

  • event notifications decouple event producers from event consumers,
  • interceptors decouple technical concerns from business logic, and
  • decorators allow business concerns to be compartmentalized.

Along with loose coupling, CDI provides strong typing, as follows:
  • CDI eliminates lookup using string-based names for wiring and correlations, so that the
    compiler will detect typing errors.
  • It allows the use of declarative Java annotations to specify everything, largely eliminating the need for XML deployment descriptors, and making it easy to provide tools that introspect
    the code and understand the dependency structure at development time.

Monday, January 16, 2012

Maven 3: Building and Running a Java Web Application

You can easily create a web application with a Maven Archetype plugin. Following are the steps to generate a web application using Maven 3:

Start the command-line terminal and execute the following generate command:

mvn archetype:generate -DartifactId=testwebapp -DarchetypeArtifactId=maven-archetype-webapp

You should get the following output.

Notice that you will get a prompt asking for the version and package.

[INFO] Scanning for projects...
[INFO] -------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1 ------------------------
[INFO] >>> maven-archetype-plugin:2.0-alpha-5:generate (default-cli) @
standalone-pom >>>


[INFO] Parameter: groupId, Value:
[INFO] Parameter: packageName, Value:
[INFO] Parameter: package, Value:
[INFO] Parameter: artifactId, Value: my-webapp
[INFO] Parameter: basedir, Value: C:\test
[INFO] Parameter: version, Value: 1.0
[INFO] project created from Old (1.x) Archetype in dir: C:\my-web
[INFO] ---------------------------------------------------------------
[INFO] ---------------------------------------------------------------
[INFO] Total time: 11.288s
[INFO] Finished at: Mon Jan 16 00:38:44 CET 2012
[INFO] Final Memory: 9M/495M
[INFO] ---------------------------------------------------------------

The archetype:generate command executed before has created a new project folder, my-webapp, which contains the following POM file:

<project xmlns="" xmlns:xsi=""
  <name>my-webapp Maven Webapp</name>

Following is the structure of application generated:

  |--- src
        |--- main
              |--- resources
              |--- webapp
                     |--- WEB-INF
                             |--- web.xml
                     |--- index.jsp
  |--- pom.xml

The packaging element tells Maven to build as a WAR. Change into the webapp project's directory and write:

mvn clean package

This will generate my-webapp.war in 'target' directory.

Maven can automate the process of deploying, cleaning, and redeploying the WAR on a developer machine web application server, making the entire process less cumbersome for the developer. This is done with the Jetty plugin.

Using the Jetty Plugin enables you to quickly test your web application by skipping the last two steps. By default the Jetty Plugin scans target/classes for any changes in your Java sources and src/main/webapp for changes to your web sources. The Jetty Plugin will automatically reload the modified classes and web sources.

To use the Jetty Plugin just add the following in your pom.xml:

            <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">

Then start Jetty using:

mvn jetty:run

The command will block with Jetty listening on port 8080. Now check that my-webapp is running on localhost:8080/my-webapp.

Java 7: Path API in Java NIO 2

The Path class is introduced in Java 7 which is an upgraded version of the well-known class.

Before Java 7:


File file = new File("abc.xml");

With Java 7:

import java.nio.file.Path;
import java.nio.file.Paths;

Path path = Paths.get("abc.xml");

Usages of Path API

Constructing a Path Between Two Locations

When you need to construct a path from one location to another, you can call the relativize() method, which constructs a relative path between this path and a given path. This method constructs a path originating from the original path and ending at the location specified by the passed-in path. The new path is relative to the original path.

Path path1 = Paths.get("abc.txt");
Path path2 = Paths.get("xyz.txt");

In this case, it is assumed that abc.txt and xyz.txt are siblings, which means that you can
navigate from one to the other by going up one level and then down one level.

Path path1_to_path2 = path1.relativize(path2);

Output: ..\xyz.txt

Comparing Two Paths

The equality of two Paths can be tested in different ways for different purposes. You can test whether two paths are equal by calling the Path.equals() method. It does not access the file system, so the compared paths are not required to exist, and it does not check if the paths are the same file.

Path path1 = Paths.get("/books/java/bitterjava.pdf");
Path path2 = Paths.get("C://books/java/bitterjava.pdf");
    System.out.println("The paths are equal!");
} else {
    System.out.println("The paths are not equal!"); //true

Iterate over the Name Elements of a Path

You can iterate either by using an explicit iterator or with a foreach loop that returns a Path object for each iteration.

Path path = Paths.get("C:", "books/java", "bitterjava.pdf");
for (Path bookname : path) {

Tuesday, January 3, 2012

Changing the default password in SQL Server 2008

SQL Server 2008 password requirements differ from previous SQL Server versions. To modify SQL Server 2008’s default password policy, start by ensuring that mixed mode authentication is enabled. Next, open SQL Server Management Studio and log in as a database owner. And then open a new query window and execute the following SQL command: