Sunday, 9 December 2012

Introduction To Maven Concepts

Basic
Introduction To Maven Concepts (Crash Course)
What are maven parent projects?
How to refresh maven dependencies during a build process?
How to Add License Headers to Code Files via Maven?
Conditional Javadoc Generation In Maven
How to add an external repository in a maven pom.xml?
Errors
Solving: "The following artifacts could not be resolved: javax.jms:jms:jar:1.1"
Miscellaneous
How to deploy a .war to Tomcat 7 during a maven build process?
How to add JSTL taglibs in a maven project?
How to process LessCss .less files into .css files in a maven build process?
How to access files/data in the maven resource directory at runtime?
Code Coverage with Maven (One Pass) 
How to Use Sonar from Maven for Code Quality?  
How to Include a Jar in A Maven Project?


Introduction To Maven Concepts (Crash Course)

This is the post I wish someone had written to connect dots in 2007, when Maven documentation was scarce. This Maven tutorial is a starting point for those who have no experience with Maven, or who are willing to improve their global understanding of Maven concepts. It explains what Maven is, what you can do with it, but not how to do it. I will also give pointers to additional documentation.

What is Maven?

Maven is a software project implementation tool, but not a project management tool. In a factory, it would be the complete assembly line, taking in raw materials and producing finished products ready for use. It is mostly used by Java programmers, but it can be configured for other programming languages too.

If ever you have to work on a large Java project, you will most probably have to learn either about Maven or 
Ant (another project implementation tool). Otherwise, your project will quickly become unmanageable as it grows in size. Ant requires you to configure all your requirements from top to bottom. You have to build the whole assembly line for a given project. On the other side, Maven comes with default behaviors. If there is something you don't like in the assembly line, you can reconfigure it or extends parts to meet your specific needs.

There has been some religious wars between Ant users and Maven in the past. But today, they coexists in peace. In fact, it is pretty common for a Maven project to call Ant as a module to perform tasks it cannot perform itself.

Both Maven and Ant are functionally interchangeable. If an existing project works fine with Ant, you should not convert it to Maven. However, if you start a project from scratch, you may want to consider Maven, because of the very large support community and an incredible number of mature modules available for free under an open source license.

What Is The Form Factor?

Maven is a package you download and install on your PC. You just need to unzip it in a directory and make sure it is accessible from the command line (i.e., it has to be 'in the path'). Maven is a command line product with no graphic user interface (GUI). However, it is well integrated in free software development applications such as NetBeans or Eclipse. Most often, you will never need to run Maven from the command line. If you plan to use Ant with Maven, you will need to install it on your PC too.

How Does It Work?

When you start using Maven, it will first create a local repository on your PC. As you compile your software projects, all the results are posted in this local repository. The produced items are called artifacts. You can configure Maven to post those artifacts in other remote repositories or locations too, if necessary.

In addition to this local repository, there is what is called the 
central repository. It is a huge online repository containing tons of free artifacts contributed under an open source license over many years by thousands of developers. When Maven needs one of these artifacts to build a project and can't find it the local repository, it tries to fetch it from the central repository, if the local PC is connected to the Internet. Maven can be configured to search those artifacts in other public or private repositories too.

As a consequence, the first time Maven builds a project, it will download many artifacts from the central repository. It is a one time operation. You are not allowed to post something directly to the central repository. If you want to contribute your own artifacts, you need to read 
this.

There are three main types of repositories, the central repository, your local repository and public or private proprietary repositories.

What Is A Maven Project?

Contrary to many other software implementation tools, Maven projects operate according to a standard directory structure where different items (code files, test files, etc...) are expected to be found in well-known directories. It is part of the delivered assembly line.

It is not a good idea to try to reconfigure this directory structure to fit your karma. If another software engineer gets to work on your project, he will be confused. On the other side, if you get to work on another Maven project, you will be happy to find what you are looking for where it is supposed to be. Learn about Maven 
directory structures. Don't be a baby, open your mouth and do take the pill (lol)!

Another key project item is the Project Object Model XML file often called '
pom' or 'pom.xml'. Each project has its own directory structure with a pom.xml located at its root. Here is one the simplest possible pom.xml:
<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.mycompany</groupId>
  <artifactId>SimpleMavenProject</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>pom</packaging>

</project>

It contains the 4 items making the 
coordinates of the project. Basically, it is the location of the project in repositories; a concatenation of the group id, the artifact id, and the project version (for a definition of SNAPSHOT, see (*) below) together with directory separators. The packaging explains how and which default artifacts will be bundled into the repository. You can organize and identify your projects as you wish using the coordinates you want. The packaging depends of the type of project your want to create.

The POM is where you will configure the different parts of the assembly line to meet your needs if default configuration is not enough.

Typically, under the hood, all Maven projects are created using an archetype. It is a kind of template used to create the default content of POMs and the default directory structure of Maven projects. You can create your own archetypes if you need to, but existing ones will cover most of your needs.

How Does The Compile Process Work?

The compile process is called the build process in Maven. It can be configured to perform much more than a simple compilation. Therefore, you should avoid mentioning a 'compile process' when talking about Maven, because it is only one of the phases of one of Maven's build processes (one step in the assembly line).

When a build process is executed, it goes through a 
life cycle using the information contained in the POM. Each life cycle is made of phases. Plugins are attached to phases. A phase can contain multiple plugins. A plugin is basically a set of operations of a given type which may be executed during a build cycle. Each possible plugin operation is called a goal. When a plugin is attached to a phase, a goal is specified (or else the default goal is executed).

The life cycle goes through each phase, sequentially, and executes each default (or configured in the POM) plugin goal, sequentially, until the end or until one of the plugin goal fails to execute. A Maven goal (as opposed to a plugin goal) is a step in the life cycle of a build process. By default, a build process will go the whole way through, unless a specific Maven goal is specified. In this case, Maven stops at this life cycle step, even if it is executed successfully.

By default, some plugins are attached to phases. Each plugin has a default goal which will be invoked unless it is configured differently in the POM. This is the default assembly line. You can also attach additional plugins to the phases of your build cycles. These will be downloaded from the central repository if necessary. You can also write your own plugins if you need to and use them in your build cycles.

Think about all this in terms of Lego's attached to a structural frame.

What About Maven Dependencies?

Large projects often use existing pieces of code (libraries) by making an explicit reference to them. In Maven projects, such dependencies to existing artifacts are specified in the POM, using their coordinates. Sometimes, these dependencies are just required for the build process (for the testing phase for example). Sometimes, they need to be shipped as part of the delivered artifacts. The type of use of the dependency is called a scope. It is specified in the POM 

What About Profiles?

In order to cover complex situations (for example) when you need to create different types of artifacts for different target platforms, it would be tedious to maintain multiple POMs for the same project. The solution is called build profiles in Maven.

This is a mean to set additional configuration if the build process is to be executed for a specific platform (building for Windows or for Linux for example). In this case, corresponding plugins are only executed if they have been defined in the corresponding platform profile in the POM. A POM can be executed by specifying (or not) a build profile. This determines the set of plugins which will be executed on top of the default configuration.

Conclusion

There are many other features available in Maven. We have only mentioned the basics. If you want to learn more about Maven, including how to use it, the best resource available on the net is the Maven Complete Reference online guide.

After reading this guide, you should explore existing Maven modules. Learn what they can do for you. If you need help, type your question in Google followed by the word 'StackOverflow'. It most probably has already been answered. If not, go to 
StackOverflow.com and ask your question there.

-----

(*) SNAPSHOT versions can be confusing at the beginning. Let's assume you are working on a project and have released version 1.0.0. You are now working on version 1.1.0, but it has not been released and won't be released until you are done. Version 1.1.0 is work in progress. Yet, with Maven's build process, you are creating temporary work in progress artifacts. In order to differentiate these from production ready artifacts, you can add -SNAPSHOT to the work in progress version of your project (i.e.,  
<version>1.1.0-SNAPSHOT</version>).

When you create Maven projects with dependencies to other artifacts/libraries, by default, maven ignores SNAPSHOT versions of those dependencies. Yet, if you want to access a specific SNAPSHOT version of a dependency, you can explicitly specify it in your 
pom.xml. This is often necessary during the development phase of a project. 

For Maven parent projects, see 
here • More about Maven tips and tricks here.
 

Monday, 19 November 2012

Date Formatting in Java

Date Formatting kinda very trivial. but i found some interesting as well as useful information to convert date objects in java into our own formatting.. There are 3 ways we can format Date object in java using the java.text package.

Here it is the hierarchy structure for java.text package.


Option #1 Using java.text.SimpleDateFormat


SimpleDateFormat is a concrete subclass of DateFormat. It allows you to define your own formatting patterns that are used to display date and time information. It allows formatting (date -> text), parsing (text -> date), and normalization.One of its constructors is shown here:
SimpleDateFormat(String formatString)
The argument formatString describes how date and time information is displayed. An example of its use is given here:
SimpleDateFormat sdf = SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz");
In most cases, the number of times a symbol is repeated determines how that data is presented. Text information is displayed in an abbreviated form if the pattern letter is repeated less than four times. Otherwise, the unabbreviated form is used. For example, a zzzz pattern can display Pacific Daylight Time, and a zzz pattern can display PDT. For numbers, the number of times a pattern letter is repeated determines how many digits are presented. For example, hh:mm:ss can present 01:51:15, but h:m:s displays the same time value as 1:51:15.
Finally, M or MM causes the month to be displayed as one or two digits. However, three or more repetitions of M cause the month to be displayed as a text string.
The following program shows how this class is used:
Example #1
// Demonstrate SimpleDateFormat.

import java.text.*;
import java.util.*;
public class SimpleDateFormatDemo {
public static void main(String args[]) {
Date date = new Date();
SimpleDateFormat sdf; sdf = new SimpleDateFormat("hh:mm:ss");
System.out.println(sdf.format(date));
sdf = new SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz");
System.out.println(sdf.format(date));
sdf = new SimpleDateFormat("E MMM dd yyyy");
System.out.println(sdf.format(date));
}
}
Sample output from this program is shown here:
11:51:50 
19 Feb 1999 11:51:50 CST 
Fri Feb 19 1999



Example #2
Parsing a request Date String into Date object, and then format it according to your need:

private SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
private SimpleDateFormat sdf2 = new SimpleDateFormat("MM/dd/yy");

//
Parses text from a string to produce a Date.
Date checkInDate = sdf2.parse("
06/05/2013");
object1.setCheckInDate(sdf1.format(checkInDate));

NOTE:   The argument of parse method is always be a string.

Option #2 Using java.text.DateFormat

import java.text.DateFormat;
import java.util.Date;

public class DateFormatExample1 {

public static void main(String[] args) {
// Make a new Date object. It will be initialized to the current date.
Date now = new Date();

// See what toString() returns
System.out.println(" 1. " + now.toString());

// Next, try the default DateFormat
System.out.println(" 2. " + DateFormat.getInstance().format(now));

// And the default time and date-time DateFormats
System.out.println(" 3. " + DateFormat.getTimeInstance().format(now));   
System.out.println(" 4. " + DateFormat.getDateTimeInstance().format(now));

// Next, try the short, medium and long variants of the default time format
System.out.println(" 5. " + DateFormat.getTimeInstance(DateFormat.SHORT).format(now));
System.out.println(" 6. " + DateFormat.getTimeInstance(DateFormat.MEDIUM).format(now));
System.out.println(" 7. " + DateFormat.getTimeInstance(DateFormat.LONG).format(now));

// For the default date-time format, the length of both the date and time elements can be specified. Here are some examples:
System.out.println(" 8. " + DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(now));
System.out.println(" 9. " + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(now));
System.out.println("10. " + DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(now));

}
}

When you run this class, you will see output that looks something like that shown in

1. Tue Nov 04 20:14:11 EST 2003
2. 11/4/03 8:14 PM
3. 8:14:11 PM
4. Nov 4, 2003 8:14:11 PM
5. 8:14 PM
6. 8:14:11 PM
7. 8:14:11 PM EST
8. 11/4/03 8:14 PM
9. Nov 4, 2003 8:14 PM
10. November 4, 2003 8:14:11 PM EST


Option #3 Using java.text.Format

Format formatter;

// The year
formatter = new SimpleDateFormat("yy");    // 02
formatter = new SimpleDateFormat("yyyy");  // 2002

// The month
formatter = new SimpleDateFormat("M");     // 1
formatter = new SimpleDateFormat("MM");    // 01
formatter = new SimpleDateFormat("MMM");   // Jan
formatter = new SimpleDateFormat("MMMM");  // January

// The day
formatter = new SimpleDateFormat("d");     // 9
formatter = new SimpleDateFormat("dd");    // 09

// The day in week
formatter = new SimpleDateFormat("E");     // Wed
formatter = new SimpleDateFormat("EEEE");  // Wednesday

// Get today's date
Date date = new Date();

// Some examples
formatter = new SimpleDateFormat("MM/dd/yy");
String s = formatter.format(date);
// 01/09/02

formatter = new SimpleDateFormat("dd-MMM-yy");
s = formatter.format(date);
// 29-Jan-02

// Examples with date and time; see also
// Formatting the Time Using a Custom Format
formatter = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
s = formatter.format(date);
// 2002.01.29.08.36.33

formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
s = formatter.format(date);
// Tue, 09 Jan 2002 22:14:02 -0500



Sunday, 18 November 2012

Some potential tripstraps for the SCJP exam.

  1. ·         Two top-level public classes cannot be in the same source file.
  2. ·         main() cannot call an instance (non-static) method.
  3. ·         Methods can have the same name as the constructor(s).
  4. ·         Watch for thread initiation with classes that don't have a run() method.
  5. ·         Local classes cannot access non-final variables.
  6. ·         Case statements must have values within permissible range.
  7. ·         Watch for Math class being an option for immutable classes.
  8. ·         instanceOf is not the same as instanceof.
  9. ·         Constructors can be private.
  10. ·         Assignment statements can be mistaken for a comparison; e.g., if(a=true)...
  11. ·         Watch for System.exit() in try-catch-finally blocks.
  12. ·         Watch for uninitialized variable references with no path of proper initialization.
  13. ·         Order of try-catch-finally blocks matters.
  14. ·         main() can be declared final.
  15. ·         0.0 == 0.0 is true.
  16. ·         A class without abstract methods can still be declared abstract.
  17. ·         RandomAccessFile descends from Object and implements DataInput and DataOutput.
  18. ·         Map does not implement Collection.
  19. ·         Dictionary is a class, not an interface.
  20. ·         Collection (singular) is an Interface, but Collections (plural) is a helper class.
  21. ·         Class declarations can come in any order (e.g., derived first, base next, etc.).
  22. ·         Forward references to variables gives a compiler error.
  23. ·         Multi-dimensional arrays can be "sparse" -- i.e., if you imagine the array as a matrix, every row need not have the same number of columns.
  24. ·         Arrays, whether local or class-level, are always initialized
  25. ·         Strings are initialized to null, not empty string.
  26. ·         An empty string is not the same as a null reference.
  27. ·         A declaration cannot be labelled.
  28. ·         continue must be in a loop (e.g., for, do, while). It cannot appear in case constructs.
  29. ·         Primitive array types can never be assigned to each other, even though the primitives themselves can be assigned. For example, ArrayofLongPrimitives = ArrayofIntegerPrimitives gives compiler error even though longvar = intvar is perfectly valid.
  30. ·         A constructor can throw any exception.
  31. ·         Initializer blocks are executed in the order of declaration.
  32. ·         Instance initializers are executed only if an object is constructed.
  33. ·         All comparisons involving NaN and a non-NaN always result in false.
  34. ·         Default type of a numeric literal with a decimal point is double.
  35. ·         int and long operations / and % can throw an ArithmeticException, while float and double / and % never will (even in case of division by zero).
  36. ·         == gives compiler error if the operands are cast-incompatible.
  37. ·         You can never cast objects of sibling classes (sharing the same parent).
  38. ·         equals() returns false if the object types are different. It does not raise a compiler error.
  39. ·         No inner class can have a static member.
  40. ·         File class has no methods to deal with the contents of the file.
  41. ·         InputStream and OutputStream are abstract classes, while DataInput and DataOutput are interfaces.
  42. import java.util.*;
    import statement doesn't import subpackage's(packages inside java.util package) classes, interfaces, Enums & annotations.
    It just simply import all these stuff inside the current package(java.util package)
  43. try-catch-finally
    whenever a exception occur in the try block it moved to the catch then further if there any exception occur in catch
    block it moved to the finally block..  
  44. dot (.) and pipe(|), these special symbols are really very special for java. whenever we use them we need to put  double back slash (\\) symbol to escape it.