Friday, December 7, 2012

Install GUI in Ubuntu Server


First of all, make sure that you have enabled Universe and multiverse repositories in /etc/apt/sources.list fi.
After enabling, you need to use the following command to install:
sudo apt-get update
  • If you want to install GNOME desktop:

          sudo apt-get install ubuntu-desktop
  • If you want to install light weight desktop install xfce using the following command:

          sudo apt-get install xubuntu-desktop
  • If you want to install KDE desktop use the following command:

          sudo apt-get install kubuntu-desktop

Thursday, December 6, 2012

What is Node.js?

Node.js is a server-side JavaScript platform that consists of a very small core library. It runs on the top of V8 JavaScript engine which is Chrome's JavaScript runtime.

Node.js allows us to easily build fast, scalable network applications. From "http://nodejs.org":

"Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices."

JavaScript has come of age and it works really well on server side. JavaScript as a server-side platform supports continuous integration, continuous deployment, connections to relational databases, service-oriented architecture.

Node.js solves I/O bound problems which are alleviated by increased throughput in I/O such as disk, memory, and network bandwidth. Node.js provides a non-blocking I/O model using JavaScript. JavaScript is a single threaded language. When doing slow I/O operations such as reading a database, the program does not wait. Instead, it immediately continues to the next line of code. When the I/O operation returns, it triggers a callback function and the result can be processed.


Installing and Running CoffeeScript in Windows

Some web frameworks such as Ruby on Rails3 and the Play! framework4 support CoffeeScript by default. If you’re using such a framework, none of this installation is necessary; just place your .coffee files in the correct place and the framework will compile them for you.

Installation Steps
  • First of all, install Node.js from http://nodejs.org/download/.
  • Once the install is complete, you should be able to run Node.js from your terminal
    via node command.
    • node --help
  • The next step is to install coffee via Node.js supported NPM (Node's Package Manager). 
  • To install the coffee script module, use the following command:
    • npm install -g coffee-script
  • This will fetch the module and make it available via Node.js.
  • Open new command prompt and check if the coffee script is installed properly by using the following command:
    • coffee --help
  • Now you can save your coffee script code as .coffee file and run the files using the following command:
    • coffee FileName.coffee
  • To compile the coffeescript into Javascript, use -c (compile) flag:
    • coffee -c FileName.coffee
    • This generates a JavaScript file of the same name in the same directory, but with the .js extension.

What is CoffeeScript?

CoffeeScript is a wrapper written over JavaScript. CoffeeScript code is transcompiled directly into JavaScript code which leverage the ubiquity of the web browser, which is the widely used execution environment for JavaScript.

Now the question arises simply: Why write a language that’s simply a copy of another language?
  •  The primary purpose of CoffeeScript is to provide a simpler version of JavaScript. 
  • CoffeeScript aims to highlight and retain the fantastically powerful parts of JavaScript while and repairing its rough spots. 
  • It aims to be more expressive.

Monday, April 16, 2012

Java 7: Reduce Applet Loading time using JNLP

Prior to Java 7, the JNLP file has to be downloaded first from the network before the applet can be launched. But with Java 7, the JNLP file can be embedded directly into the HTML code which reduces the amount of time the applet loading time. Following are the steps to embed a JNLP file:
  1. Create a JNLP file for your applet.
  2. Encode the contents of the JNLP file using the Base64 scheme.
  3. When deploying the applet in a web page, specify the 'jnlp_embedded parameter' with it's value set to the Base64 encoded JNLP string.
Example:
<script>
    var attributes = {} ;
    <!-- Base64 encoded string truncated below for readability -->
    var parameters = {jnlp_href: 'xyz-applet.jnlp',
        jnlp_embedded: 'PCEtLSAKLyoKICogQ29weXRSSDSDSD+-Dgkhmnwrr ...'
    } ;
    deployJava.runApplet(attributes, parameters, '1.6');
</script>
Note: Some encoding tools may wrap the encoded string into several 76-column lines. To use this multi-line attribute value in JavaScript code, specify the attribute value as a set of concatenated strings.

Friday, April 13, 2012

Java 7: Diamond Operator in Generics


Java 7 promotes the concept of convention over configuration. It simplifies the use of generics by using the diamond operator(<>) for constructor type inference. When using the diamond operator, the compiler infers the parameter types for the constructors which avoids explicit specification of the object. Before Java7:
List list = new ArrayList();
With Java 7, the diamond operator makes this shorter and simpler. It avoids unchecked warnings in a program and also reduces generic verbosity.
List list = new ArrayList<>();
In above case, compiler automatically infers 'String' for the constructor of ArrayList.

Monday, February 27, 2012

MyLifeBits - An interesting project in Big Data

I was now a days reading on Big data and got to know about this interesting Microsoft's project. MylifeBits is a lifetime store of everything. It is the fulfillment of Vannevar Bush’s 1945 Memex vision including full-text search, text & audio annotations, and hyperlinks.

The software research:Jim Gemmell and Roger Lueder have developed the MyLifeBits software, which leverages SQL server to support: hyperlinks, annotations, reports, saved queries, pivoting, clustering, and fast search. MyLifeBits is designed to make annotation easy, including gang annotation on right click, voice annotation, and web browser integration. It includes tools to record web pages, IM transcripts, radio and television.

See the demos here:
http://research.microsoft.com/en-us/projects/mylifebits/mylifebitsdemo.aspx

Friday, February 10, 2012

Maven 3: How to Speed-up Build Process?

I was working on one of the project and one of my worry was that 'mvn clean install' was taking too long. I tried the following options which resulted in faster build. Here are my learnings:

  • Maven Commands: Maven 3 has come up with some advanced commands known as reactors. One of theeir experimental features is Parallel Builds. This build-mode analyzes your project's dependency graph and schedules modules that can be built in parallel according to the dependency graph of your project. The commands are as follows:

    mvn -T 4 clean install         # Builds with 4 threads
    mvn -T 2C clean install        # Runs 2 thread per cpu core
    

    Second command works better for multicore processors.
  • Using mvnsh: mvnsh(Maven Shell) allows developers to execute maven goals/phases in a pre-loaded shell environment. It is a CLI interface for Apache Maven that enabled faster turn-around. Maven Shell does not come with Maven 3 build. You can download it separately from Sonatype site.

    Following are the excellent article which provides details on mvnsh:

    http://ericmiles.wordpress.com/2010/03/23/intro-to-maven-shell
    http://ericmiles.wordpress.com/2010/03/26/maven-shell-features

    How to use mvnsh?

    After downloading the mvnsh, you can use it in following manner:

    Run mvnsh.bat from /bin directory. This will take you to maven shell environment with mvnsh(/):bin> shell option.

    Now traverse to your project's POM.xml directory using:

    cd <YOUR_POM_XML_DIR>

    This will take you to mvnsh(/):<YOUR_POM_XML_DIR>> shell in mvnsh environment and now you can run your normal mvn commands.

Wednesday, February 8, 2012

What Do You Need to know while Moving Your Source Code to Java 7?

Are you shifting your project to Java 7? Almost all existing programs should run on Java SE 7 without modification. But still there are some minor potential source and binary incompatibilities in the JRE and JDK that involve rare circumstances and "corner cases".

Oracle documentation here explains in detail all the incompatibilities which an application developer needs to take care while moving the project to Java 7. I strongly recommend to read all the incompatibilities from the Oracle site. However, in order to save time, few of the more commonly used are described below:

Area: JSR 334
Synopsis: Improved Exception Handling May Cause source Incompatibility
Description: The following example shows two source incompatibilities: 
class Foo extends Exception {}
class SonOfFoo extends Foo {}
class DaughterOfFoo extends Foo {}
...
try {
   throw new DaughterOfFoo();
} catch (final Foo exception) {
   try {
      throw exception; // used to throw Foo, now throws DaughterOfFoo
   } catch (SonOfFoo anotherException) { // Reachable? }
}

 The first incompatibility is that the throw exception; statement throws a Foo exception in JDK 6, but throws a DaughterOfFoo exception in Java SE 7.
 The second incompatibility is that the catch (SonOfFoo ...) statement compiled under JDK 6 but, under Java SE 7, gets the following error: 
error: exception SonOfFoo is never thrown in body of corresponding try statement
 Such code is likely to be rare, but should be fixed by removing the non-reachable statements.
Nature of Incompatibility: source


Area: API: Language
Synopsis: Spec for java.lang.Float.parseFloat(String) and parseDouble(String) Updated to Document Exception
Description: The java.lang.Float.parseFloat(String) and java.lang.Float.parseDouble(String) methods have been throwing an undocument NullPointerException when passed a null argument since the methods were introduced in J2SE 1.2. The spec has been updated to document the NPEs.
Nature of Incompatibility: behavioral


Area: API: Language
Synopsis: java.lang.Character.isLowerCase/isUpperCase Methods Are Updated to Comply with the Specified Unicode Definition
Description: The specification and the implementation of the isLowerCase and isUpperCase methods have been updated to comply with the Unicode Standard definition to be GD=Lu/Ll + Other_UpperCase/LowerCase. Two new methods, java.lang.Character.isAlphabetic(int) and java.lang.Character.isIdeographic(int) have also been added.
Nature of Incompatibility: behavioral

 
Area: API: Utilities
Synopsis: Inserting an Invalid Element into a TreeMap Throws an NPE
Description: Due to an error in java.util.TreeMap, it was previously possible to insert invalid null elements and elements not implementing the Comparable interface into an empty TreeMap or TreeSet. Only a single invalid element could be inserted into an empty TreeMap or TreeSet; additional elements would cause the expected NullPointerException or ClassCastException. Most other operations upon the collection would also fail. As of Java SE 7, inserting an invalid null element or an element not implementing Comparable into an empty TreeMap or TreeSet throws a NullPointerException.
Nature of Incompatibility: behavioral

 
Area: API: Utilities
Synopsis: Formatter.format() Now Throws FormatFlagsConversionMismatchException
Description: The Formatter.format(String,Object...) method now throws a FormatFlagsConversionMismatchException exception when the "#" flag is specified for conversion "s" and the following argument is not a Formattable instance (including the special case "null").
Nature of Incompatibility: behavioral

 
Area: API: NIO
Synopsis: The Behavior for Several java.nio.channels.DatagramChannel Methods have Changed
Description: The DatagramChannel is the selectable channel for datagram-oriented sockets in the java.nio.channels package. The behavior for the send, receive, and connect methods have been modified. To restore the previous behavior, the sun.nio.ch.bugLevel property can be set to the value of "1.4", "1.5", or "1.6". See the DatagramChannel class specification for more information.
Nature of Incompatibility: behavioral


Area: API: Internationalization
Synopsis: Separation of User Locale and User Interface Locale
Description: The default locale can be independently set for two types of uses: the format setting is used for formatting resources, and the display setting is used in menus and dialogs. The new Locale.getDefault(Locale.Category) method takes a Locale.Category parameter. Previous behavior can be restored by setting the sun.locale.formatasdefault system property to true.
Nature of Incompatibility: behavioral


Area: API: JDBC
Synopsis: New RowSetFactory Interface to allow Creation of a RowSetFactory
Description: New API was introduced to support RowSet 1.1 and, specifically, the ability to write more portable code by creating a RowSetFactory. As part of this update, the definition of some constants has changed slightly, but should not affect most users.
Nature of Incompatibility: source

 
Area: API: JDBC
Synopsis: New JDBC Methods, Including new Methods in Interfaces
Description: For the Java SE 7 release, there are new methods to support JDBC 4.1. This includes methods added to the java.sql.Connection, java.sql.Driver, javax.sql.CommonDatasource, and java.sql.Statement interfaces. Because all methods of an interface must be implemented, previous code that uses these interfaces will not compile on Java SE 7 unless you add the new methods. See the JDBC documentation for more information.
Nature of Incompatibility: source


Area: API: Utilities
Synopsis: Updated sort behavior for Arrays and Collections may throw an IllegalArgumentException
Description: The sorting algorithm used by java.util.Arrays.sort and (indirectly) by java.util.Collections.sort has been replaced. The new sort implementation may throw an IllegalArgumentException if it detects a Comparable that violates the Comparable contract. The previous implementation silently ignored such a situation.
 If the previous behavior is desired, you can use the new system property, java.util.Arrays.useLegacyMergeSort, to restore previous mergesort behavior.
Nature of Incompatibility: behavioral


Area: API: IO
Synopsis: java.io.File.setReadOnly and setWriteable Methods Have New Behavior
Description: As of JDK 7, on Windows, the java.io.File setReadOnly and setWritable methods no longer set the DOS readonly attribute on directories. This means that these methods will fail, by returning false, if the file is a directory. To preserve the relationship with canWrite, the canWrite method returns true if the file is a directory.
 Applications that want to set directories on Windows to be read only must use the new API. In particular, the Files.isWritable method takes into account the effective access (as determined by the file's discretionary access control list) and whether the file is located on a writable volume.
Nature of Incompatibility: behavioral

Tuesday, February 7, 2012

Java 7: Garbage First(G1) Collector

The Garbage-First Garbage Collector (or G1 GC for short) is a new GC that is being introduced in the Java HotSpot VM in JDK 7. In Java 7, Concurrent Mark-Sweep Collector (CMS) is replaced by G1 and enabled by default. It is a server-style collector, targeted at multi-processor machines with large amounts of memory that meets a soft real-time goal with high probability, while achieving high throughput.

This allow users to specify a soft real-time goal, stating their desire that collection consume no more than x ms of any y ms time slice. By making this goal explicit, the collector can try to keep collection pauses as small and infrequent as necessary for the application, but not so low as to decrease throughput or increase footprint unnecessarily.

There are two major differences between CMS and G1.

  • G1 is a compacting collector. G1 compacts sufficiently to completely avoid the use of fine-grain free lists for allocation, which considerably simplifies parts of the collector and mostly eliminates potential fragmentation issues.
  • G1 offers more predictable garbage collection pauses than the CMS collector and allows users to set their desired pause targets.

How Does G1 Work?

Please read Dr. Dobbs article which explains in detail the working of G1.

Further Reading about G1:

Monday, February 6, 2012

JDBC 4.1: 'try-with-resources' Statement Automatically Close Resources

Before Java 7, the biggest worry while working with JDBC was to close the resources. If we don’t close them, we can be left with unclosed resources to the database. This means that we could eventually run out of resources.

Java 7 solves this problem by introducing a 'try-with-resources' statement which automatically close resources of type java.sql.Connection, java.sql.Statement, and java.sql.ResultSet objects, regardless of whether a SQLException or any other exception has been thrown. A try-with-resources statement consists of a try statement and one or more declared resources. This statement ensures that any resources declared in the try statement will be closed automatically.

NOTE: If multiple resources variables are declared in try statement, they are closed in reverse order in which they are declared.

Example:

public static void showEmployees(Connection con) throws SQLException 
{
    String query = "select EMP_NAME, EMP_ID, EMP_ADDRESS, 
                     EMP_DESIGNATION from EMPLOYEES";

    try (Statement stmt = con.createStatement()) 
    {
        ResultSet rs = stmt.executeQuery(query);

        while (rs.next()) 
        {
            String empName = rs.getString("EMP_NAME");
            int empID = rs.getInt("EMP_ID");
            String empAddress = rs.getFloat("EMP_ADDRESS");
            String empDesignation = rs.getInt("EMP_DESIGNATION");
            System.out.println(empName + ", " + empID + ", " + 
                      empAddress + ", " + empDesignation);
        }
    }
}

The above highlighted statement is a try-with-resources statement declares one resource stmt which will be automatically closed as soon as try block terminates.

Wednesday, February 1, 2012

Java SE 6 End of Life (EOL)

Java SE 6 will no longer be publicly available after July 2012. Customers interested in continued access to critical bug fixes and security fixes as well as general maintenance for JDK 6 have the option to purchase Oracle Lifetime Support.

Further details are available on Oracle site:

http://www.oracle.com/technetwork/java/javase/eol-135779.html

Is it the time to think about shifting to Java 7?

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.

<settings>
...
<offline>true</offline>
...
</settings>

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");
doc.documentElement.appendChild(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.

In CDI,

  • 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 -DgroupId=com.example.app -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]
[INFO] >>> maven-archetype-plugin:2.0-alpha-5:generate (default-cli) @
standalone-pom >>>

........

[INFO] Parameter: groupId, Value: com.example.app
[INFO] Parameter: packageName, Value: com.example.app
[INFO] Parameter: package, Value: com.example.app
[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
app
[INFO] ---------------------------------------------------------------
[INFO] BUILD SUCCESS
[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="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelversion>4.0.0</modelVersion>
  <groupid>com.example.app</groupId>
  <artifactid>my-webapp</artifactId>
  <packaging>war</packaging>
  <version>1.0</version>
  <name>my-webapp Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupid>junit</groupId>
      <artifactid>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalname>my-webapp</finalName>
  </build>
</project>

Following is the structure of application generated:

my-webapp
  |
  |--- 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:

<build>
    <finalname>my-webapp</finalName>
 <plugins>
      <plugin>
        <groupid>org.mortbay.jetty</groupId>
        <artifactid>maven-jetty-plugin</artifactId>
        <version>6.1.10</version>
        <configuration>
          <scanintervalseconds>10</scanIntervalSeconds>
          <connectors>
            <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
              <port>8080</port>
              <maxidletime>60000</maxIdleTime>
            </connector>
          </connectors>
        </configuration>
      </plugin>
    </plugins>
  </build>

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 java.io.File class.

Before Java 7:

import java.io.File;

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);
System.out.println(path1_to_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");
if(path1.equals(pat2)){
    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) {
    System.out.println(bookname);
}

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:

ALTER LOGIN sa WITH PASSWORD = ‘sa’ UNLOCK, CHECK_POLICY = OFF, CHECK_EXPIRATION = OFF