Tuesday, October 23, 2012

How to include custom jar into your Maven repository?

Still you will find jars which are not there in Maven repository. Classic example is suppose you create a common utility jar and you want to use it across projects or it could be a third party jar which has private licence and so cannot be there in Maven central repository. In above cases, you can actually put the required jar easily in the Maven local repository. For demonstration purpose, we are using Kaptcha.
Here is the command:
mvn install:install-file 
-Dfile=c:\kaptcha-2.3.2.jar 
-DgroupId=com.google 
-DartifactId=kaptcha 
-Dversion=2.3.2 
-Dpackaging=jar

Remember to remove the newlines from above command incase you are copying and pasting.
Below is the result from command line after executing the command:
C:\>mvn install:install-file -Dfile="c:\kaptcha-2.3.2.jar" -DgroupId=com.google
-DartifactId=kaptcha -Dversion=2.3.2 -Dpackaging=jar
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-install-plugin:2.3.1:install-file (default-cli) @ standalone-po
m ---
[INFO] Installing c:\kaptcha-2.3.2.jar to C:\Users\dharmvir.singh\.m2\repository
\com\google\kaptcha\2.3.2\kaptcha-2.3.2.jar
[INFO] Installing C:\Users\DHARMV~1.SIN\AppData\Local\Temp\mvninstall71581647865
23828175.pom to C:\Users\dharmvir.singh\.m2\repository\com\google\kaptcha\2.3.2\
kaptcha-2.3.2.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.587s
[INFO] Finished at: Tue Oct 23 15:23:57 IST 2012
[INFO] Final Memory: 3M/15M
[INFO] ------------------------------------------------------------------------
Job is done. You can now specify the dependency of this jar as shown:

      com.google
      kaptcha
      2.3.2

Monday, October 15, 2012

Configuring Maven inside proxy network

Maven version I used is 3.0.4 and environment is windows 7 enterprise edition.

Well, it is pretty simple,

collect your proxy server and port configuration and if username and password  are there then them too and save them in your settings.xml.
Settings.xml can be found either in <userhome>/.m2/settings.xml (Apache documentation tells about this path but I couldn't find it in this location, link to proxy config doc.. proxy config mini guide) or (I found them in this path <maven unzipped directory>/config/settings.xml, in my case path was D:/apache-maven-3.0.4/config/settings.xml)
Now, you have to uncomment this section from settings.xml and save the correct info here as shown:
 
    
    
      optional
      true
      http
      proxyuser
      proxypass
      Your Proxy server IP Here
      Your proxy server port numbere here
      local.net|some.host.com
    
    
  

Related Articles

Eclipse proxy setting

Thursday, June 28, 2012

5.JAVA BASICS..CONCEPT OF STATIC

Here you will learn about the static keyword which in itself a very useful concept.

What do you understand by static? 
  By seeing the word static three things come to our mind
 1) Class Global variable- It means that it is global to the class. No object copy.
 2) One copy in memory - Only one copy exists in memory.
 3) It exists in memory even before creation of objects.

We will take some examples of objects and their memory allocation.

class Test
{
int a;
float b;
int d=10;
}

class TestMain
{
public static void main(String[] args)
{
Test obj1=new Test();
Test obj2=new Test();
Test obj3=new Test();
obj3.d=15;
obj3.b=5.0;
obj2.a=5;
obj3=new Test();       //Line 7
obj3.d=16;
}
}
Following is the heap diagram with objects.

In the above figure you will find that all the objects are created in the heap memory. obj1,obj2,obj3 are the references which points to these objects. The references obj1,obj2,obj3 are defined inside the method, we can say that these references are using stack memory. In the above objects,you will also  find that all the objects have their own copy of variables. Each object have different value of variables. In short all objects have their own variables.
Obj3 firstly refers to other object and after line-7 it points to different object.

Example of static:
class Test
{
int a;
float b;
static int c
int d=10;
}

class TestMain
{
public static void main(String[] args)
{
Test obj1=new Test();
Test obj2=new Test();
Test obj3=new Test();
obj3.d=15;
obj3.b=5.0;
obj2.a=5;
obj3=new Test();       //Line 7
obj3.d=16
obj1.c=6;
obj3.c=10;
obj2.c=15;
Test.c=20;
}
}

In the above example 'c' is the static variable,so there exists only one copy of variable c and is not inside any of the object area,instead it has a separate memory space which is accessible by any of the objects and even by the class. This is how the static works.

static in broader terms:

Following are the different ways of using keyword static
  • Variables
  • Methods
  • Classes
  • Block

Variables:
A static variable have one copy and any instance can change its value.
Use of Static variables: Whenever you fell a resource should be accessible by all the instances and you need only one copy. Take a simple example of a basket of chocolates, take 'N' students who can take chocolate from this basket.Student will act as an object. When a student takes a chocolate from basket then the number of chocolates decreases. In these types of examples, take count_of_chocolate as a static variable and when an object takes it the count of chocolate decreases.

Static variables exist in memory even before the instances are created. By this statement don't misunderstand that it will always exist in memory. It will only exist in memory when a class gets loaded( you will learn class loading later).

Difference between static variables and normal variables
  • static variables- Class global
    normal variables- Object specific
  • static variables- Only one copy
    normal variables- copies are equal to the number of objects that exist in memory
  • static variables- Exist when class gets loaded
    normal variables- Exist when instance get created, each object has different copy
  • static variables- Every object have access to this variable,also accessed by class name
    normal variables- Object able to access its own copy.

Static methods:
Prefixing static before a method name makes a method static.
Where the normal methods exist in memory?
There is only one copy of normal methods,it does not depend on the number of objects. The methods are stored in Method area. Method area is a separate memory in Heap which stores the class methods.Methods are executed from this area.
Static Methods- They are also stored in the same area and only one copy exist in memory.

Difference between static method and normal method
Both have one copy in memory. Static method exist in memory even when there is no object while the normal method exist only after instance is created.
Can static method access non static variable???..
No. Static method and variable exist in memory when a class gets loaded while the non static variable and method exist only after instance is created. This is the reason why static method cannot access non static variable.

Static Classes:
Remember an outer class can never be static as there is no point in declaring an outer class an static class. Only the nested classes are allowed to be static. Technically, inner classes are not called static, inner classes are local and anonymous classes. Static classes are same as normal classes, the only difference is that static classes cannot access not static member variables and methods of the parent class.
Static class behaves like normal classes.
  Nested Classes: Nested classes are of 2 types
  a) static nested classes
  b) Non-static Nested Classes- These classes are called Inner Class.

To know more about Inner and nested class please read http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Static Blocks:
A class can have number of static block and normal block.
All normal block will be executed each time a instance is created in the order they are exist in class and are executed before the constructor is called while the static block is executed only once on class loading (it's execution does not depend on the number of instance). As the static block is executed on class loading, it is executed before normal blocks gets executed.

Here is a simple example to understand the difference between static and normal block

public class StaticBlockExp {

 static{
  System.out.println("1.static block");
 }
 static{
  System.out.println("2.static block");
 }
 {
  System.out.println("Welcome to Java");
 }
 {
  System.out.println("Welcome to world of java");
 }
 public StaticBlockExp()
 {
  System.out.println("Constructor");
 }
 public static void main(String[] args) {
  new StaticBlockExp();
  new StaticBlockExp();
 }
}

Output of above program:
1.static block
2.static block
Welcome to Java
Welcome to world of java
Constructor
Welcome to Java
Welcome to world of java
Constructor

From this it is clear that static blocks are executed only once while normal blocks are executed each time an instance is created.


Thursday, June 21, 2012

Spring 3.2 M1 released...

Spring 3.2 comes with a lot of new stuff. Below is a brief listing of the features that are in 3.2 version:
  1. Initial support for asynchronous @Controller methods
  2. Early support for JCache-based cache providers
  3. Significant performance improvements in autowiring of non-singleton beans
  4. Initial delay support for @Scheduled
  5. Ability to choose between multiple executuors with @Async
  6. Enhanced bean profile selection using the not (!) operator
  7. 47 bugs fixed, 8 new features and 36 improvements implemented
There are a lot of other stuff.. checkout Spring source website ...

Tuesday, June 12, 2012

System.out.println(), What is it?

System is a class in java.lang package. It is a system related class and most of times make native calls. As far as out is concerned. System class declares it something like this:
  public final static InputStream in = null; 
  public final static PrintStream out = null; 
  public final static PrintStream err = null; 
As shown above both err and out are instances of PrintStream class (java.io.PrintStream). System class has setters for all the three mentioned above but no getters. InputStream is again from java.io package. Setters are written something like as shown:
  public static void setOut(PrintStream out) { 
    checkIO(); 
    setOut0(out); 
 }
Summarizing above, System is class in java.lang package and out is the instance of PrintStream class from java.io package and println() is a method from the PrintStream class obviously.

Friday, May 18, 2012

JAXB: XSD datatypes mapping to Java DataTypes

Below is the list of mappings from XSD data types to Java data types
XSD types Java DataTypes
bytebyte
intint
integerjava.math.BigInteger
decimaljava.math.BigDecimal
longlong
floatfloat
doubledouble
durationjavax.xml.datatype.Duration
datejavax.xml.datatype.XMLGregorianCalendar
dateTimejavax.xml.datatype.XMLGregorianCalendar
stringjava.lang.String
nonNegativeIntegerjava.math.BigInteger
nonPositiveIntegerjava.math.BigInteger
unsignedByteshort
unsignedIntlong
unsignedLongjava.math.BigInteger
unsignedShortint
anyURIjava.lang.String
base64Binarybyte [] (byte array)
booleanboolean
ENTITIESList
ENTITYjava.lang.String
timejavax.xml.datatype.XMLGregorianCalendar
gDayjavax.xml.datatype.XMLGregorianCalendar
gMonthjavax.xml.datatype.XMLGregorianCalendar
gYearjavax.xml.datatype.XMLGregorianCalendar
gMonthDay javax.xml.datatype.XMLGregorianCalendar
gYearMonthjavax.xml.datatype.XMLGregorianCalendar
Whatever data types are not there in Java JAXB has created appropriate datatypes in their API, for example, XMLGregorainCalendar. Now the question is how to convert it our facourite dataypes like java.util.Date or java.sql.Date or java.util.Calendar etc. You can probably write an Adaptor class which has static methods to do all these conversion.

Thursday, May 3, 2012

Why to prefer static factory methods over constructors to get the object of a class?

Instead of creating objects using new operator you can also use static method to instantiate a class. Code listing:
// instantiating a class using constructor
Dog dog = new Dog(); 
..........................................

// instantiating the class using static method
Class Dog{
  private Dog(){
  }
  // factory method to instantiate the class
  public static Dog getInstance(){
    return new Dog();
  }
}
Using static factory methods have both advantages as well as disadvantages. Advantages:
  1. Static factory methods can have different name than class whereas constructors cannot: As methods have names, they convey their purpose clearly as opposed to constructors. A class can have only one constructor with a given signature, developers get around this restriction by changing the order of parameters passed to constructors; In case of methods you can give a different name to resolve the issue.
  2. Static methods support conditional instantiation: Each time you invoke a constructor an object will get created but you might not want that. (for example, in singleton class you will maintain a single object). Or suppose you want to check some condition only then you want to create a new object.
  3. Methods can return subtypes of return type: Suppose there is a class Animal and it has subclass Dog. We have static method with signature
      public static Animal getInstance(){
       ...
      }
    }
    
    then method can return Both objects of type Animal and Dog which provides great flexibility.
Disadvantages:
  1. If constructor of the class is not public or protected then the class cannot be sub classed: If you ask if there is a workaround to this, there is not. But honestly, it is better as you cannot use inheritance and so you have to use composition which is always better than inheritance any day.
  2. Another disadvantage is you cannot differentiate between static factory methods and regular factory methods: There is no syntactical difference but if you follow some naming convention then it is easy to identify. For example, getInstance() is used in many frameworks to provide the instance of a class (java.util.Calendar, ).
Examples of static factory methods in Java:
  1. Pattern.compile
  2. Calendar.getInstance
  3. Collections.synchronizeCollection
List is very big. References

Monday, February 20, 2012

JAR to JAVA converter

I went through many websites,but i did not find any converter for jar file to .java files at one go.
So, I thought of writing a script for this conversion. This script also keeps the package structure same as in the jar file

Following are the prerequisites
  • This is restricted to windows platform
  • Unzip utility should be installed in the system
  • jad decompiler should be installed.
    If you don't have jad installed, you can find from the following link
    click here to download
  • Unzip the jad.zip downlaoded in step2,set the jad.exe in the systems path variable.
  • Run the command prompt in the administrator mode

Steps to run the batch file
  • cd "path to which batch file is placed"
  • jar2java.bat "jar file name/jar file path with jar file name"
  • Note: Give jar file name without extension
Download the batch file from here

Note:Remove the extention .txt to make it .bat file.

Example:
Step 1) >cd D:\jartojava (Copy the above downloaded batch file in this folder)
Step 2) jartojava> jar2java.bat abc (copy abc.jar in this folder)
Here a folder named abc is created with all the java files found in abc.jar.