Tuesday, 16 September 2014

WHAT IS MAVEN ? A PROJECT MANAGEMENT TOOL (UPDATED)

MAVEN is a Java Dependency Management tool. You wonder what is a dependency management tool.

Its Simple...

For instance, if your working on a project which uses many external jar files, which you generally download from the web and then you configure them in the classpath- which is a conventional way of doing.

But if you use maven tool which is basically command line tool(can also be integrated with popular IDEs like NET BEANS & ECLIPSE), you can create a project without this overhead 
How?

Behind the scenes, maven actually works for us a lot to get the required jars from a central repository(collections of jars),  but as a developer only need to do is to supply it the information specifically related to the project you want to create.

We can supply our project information(required jars-simply called as dependencies) through a simple XML file which is called pom.xml

Let us take an example, consider I am developing a JMS application which uses JMS
(Java Messaging Service) API jar file, here for your application this is a dependency, without which you can't create your app. 

And also consider, you are using logging API(requires log4j jar file) in your project for logging purposes, so this is also considered as another dependency.

so we need JMS jar and log4j jar for my project to be completed,so specify them in pom.xml file

Example:

<?xml version="1.0" encoding="UTF-8"?>

<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">

        <groupId>....your groupid or your company name..</groupId>
       <artifactId>..your project name...</artifactId>
    <version>..your project build version number---</version>
       <modelVersion>4.0.0</modelVersion>

<!-- Here are your project dependencies-->

    <dependencies>
        <dependency>
                       <groupId>javax.jms</groupId>
                      <artifactId>javax.jms-api</artifactId>
                      <version>2.0</version>
        </dependency>
        <dependency>
                      <groupId>log4j</groupId>
                      <artifactId>log4j</artifactId>
                      <version>1.2.17</version>
        </dependency>
  </dependencies>
  <build>
           <!-- I can use various maven plugins for different use cases- like reporting
                 ,  mailing, packaging(such jar, war) -->
          <!-- Here I am using a reporting plugin - Maven-Surefire-Report-Plugin
            .This plugin generates a html report showing all my test case failures  
           passed cases & skipped test cases--> 
         <!-- you have use plugins & dependencies according to your project needs--> 
      <plugins>
          <plugin>                     
                     <dependency>
                              <groupId>org.apache.maven.plugins</groupId>
                              <artifactId>maven-surefire-report-plugin</artifactId>
                              <version>2.16</version>

                              <scope>test</scope>
                    </dependency>
 
          </plugin> 
      </plugins>    
  </build>
</project>


JMS jar details are

                   <groupId>javax.jms</groupId>
                  <artifactId>javax.jms-api</artifactId>      
                    <version>2.0</version>

log4j jar details are

                  <groupId>log4j</groupId>
                  <artifactId>log4j</artifactId>
                 <version>1.2.17</version>


Terminology :

groupId
artifactId
version

are tags that maven generally uses to specify the project structure.

groupId is generally a name which represents a company the project belongs to.

artifactId is name of your project

version is the build release version

Plugins are placed under build tag. As aforementioned, you can use any plugins such as war plugin creates a war file for a web application, jar plugin creates a jar file. In the above example, I have defined a surefire-report plug-in , this creates an HTML report for your tests if there are any tests in your project.

Sample Surefire Report 

You can configure your plugins using a <configuration> tag under <plugin> tag.

Let us, you want your surefire-reports, i.e HTML file, you this file to be stored in an outtput directory called newsite. you can configure like this


      <plugins>
          <plugin>                     
                     <dependency>
                              <groupId>org.apache.maven.plugins</groupId>
                              <artifactId>maven-surefire-report-plugin</artifactId>
                              <version>2.16</version>

                              <scope>test</scope>
                              <configuration>                                      
                     <outputDirectory>${basedir}/target/newsite</outputDirectory>
                              </configuration>
          
          </dependency>
 
          </plugin> 
      </plugins>    

${basedir}  is the default variable represents the path of your project.

say your project is at c:/documents/MyProject  

so ${basedir} points to this path.

By default, Surefire-report plugin stores its reports in site folder under target.


Maven  has build life cycle phases. During this life cycle phases, it performs various operations. Mostly the build phase names are self-explanatory.

Maven's default build life cycle phases : validate, compile, test, package, integration-test-process, verify, install and deploy.

  • validate - validate the project is correct and all necessary information is available
  • compile - compile the source code of the project
  • test - test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • package - take the compiled code and package it in its distributable format, such as a JAR.
  • integration-test - process and deploy the package if necessary into an environment where integration tests can be run
  • verify - run any checks to verify the package is valid and meets quality criteria
  • install - install the package into the local repository, for use as a dependency in other projects locally
  • deploy - done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.


Complete list of Build Phases

<scope> represents this plugin is going to be used in only test phase of the build life cycle.

One of Maven plug in's : maven-compiler-plugin. Its scope is only up to compile build phase. Because it is going to be used only in compiling the classes of your project. so you can specify the <scope>compile</scope> for compiler-plugin.
  

Important Note: Once maven builds a project - you are able to see a new target folder, where all distributions(war, jar) , surefire reports , and compiled classes are placed in that target folder.

 Until you have pom.xml file in your project folder, you cannot execute your maven goals.

Oh! what are Maven goals? How to execute maven using command line?

Each and every maven build phases binds to some goals:

say:

assume this format for explanation - Build Phase: Goals

>>>>>>>>>>>>>>>>
compile phase : compiler:compile
>>>>>>>>>>>>>>>

During compile phase, a compiler plugin uses these goals to perform its executions.

For example, Maven-compiler-plugin as another goa

compiler: testCompile (here, compiler represents plugin & testCompile is the goal)

Whats the difference between two goals?

Here, the plugin used is same - maven-compiler-plugin. But these two goals: compile & testCompile are executed in two different build phases

Execute maven compile goal  like this
(on command line)


< proj path>$ mvn compiler:compile 

Note: In proj path - you must have pom.xml file.

This only compiles your main source files. (Exclusdes test source files)

Whereas, testCompile goal is bound to test-compile phase 

As I mentioned, test is also a build phase. test-compile is executed just before test build phase. These test classes are excluded during compilation of normal source files.

>>>>>>>>>
test phase: surefire-report:report
 >>>>>>>>>

Here, Build phase is test.  Plugin used here is maven-surefire-report-plugin.

surefire-report:report

surefire-report represents plugin

report represents goal

Note: This is one of the reporting plugin I have used in test phase. There can be n number of maven reporting plugins. you have decide which to one to choose.
This post will be updated in future also. 
An Updated on 25-Feb-2015

VARIABLE ARGUMENTS - VARARGS -JAVA 5 FEATURE

VARIABLE ARGUMENTS:

It is a feature introduced in Java version 5. It is very handy feature in some situation where you don't know the exact number of arguments for methods.


It is generally known as VARARGS. It is represented by a symbol
ellipsis(...)

example:


class CountMarks{

//create a static method inorder to access in the main method

static void add(int... params){
          int result=0;
          for(int i:params){
             result=result+i;
          }
          System.out.println("sum of marks: "+result);
      }
    public static void main(String args[]){
        m(10);
        m(10,20,30,23,23,23,23,23);
    }
    } 


output:

sum of numbers: 10
sum of numbers: 175



Rules for varargs:


  1.  There should be only one variable argument in a method.
  2.  The variable argument must be the last argument.
Violating these rules leads to COMPILE TIME ERRORS;

Examples: 

Legal:

void sumUp(int... x) {}
//expects from 0 to many ints as parameters

void sumUp(char chr,int... x) {}
//expects first a char, then 0 to many ints

void sumUp(Salary... sal) {}
//expects 0 to many salary objects


ILLEGAL:

void sumUp(int x...) { }
 //Bad syntax

void sumUp(int... x,char... y) {}
 //too many varargs - rule 1 violated

void sumUp(String... s,char b){} 
// var-arg must be last argument-rule 2 
//violated 


Note:  In the above example, We can pass as many numbers as we need, to do the same thing earlier we used to do method overloading. 

JAVA EXCEPTION - IllegalArgumentException

Java Exception -> IllegalArgumentException

IllegalArgumentException is a Runtime Exception.

Class Hierarchy is as follows: 






 IllegalArgumentException thrown to indicate that a method has been passed an Illegal Argument.


Example:

public class Voters {

 String voter_name;
 int voter_age;


//u can throw this exception like this
//rule: age should be > 18 years

 private void checkAge(int voter_age){
     if(voter_age<18)
     {
      throw new IllegalArgumentException();
     }
 }
 //constructor
 public Voters(String voterName,
                 String voterAge) {
   checkAge(voterName,voterAge);
   voter_name=voterName;
   voter_age=voterAge;
 }

           .
           .
           .

  Like this you can throw this exception.



Monday, 15 September 2014

HOW TO SEND MAIL USING JAVAMAIL API

JAVAMAIL API

In order to send e-mail using javamail api,
you need an SMTP server, which is responsible for send your email.

In this example, I am using a gmail SMTP server configuration. In fact, we can also use any other companies SMTP server such as yahoo or a JangoSMTP server.

Through out the example, I am gonna use different javax.mail.* and javax.mail.internet.* package classes.

To use these classes in your program, download the required jars such as mail.jar, activation.jar


Let's see some of the classes used javax.mail.* package & javax.mail.internet.* package classes used in this example.


javax.mail.Session 

javax.mail.Message

javax.mail.Address

javax.mail.Authenticator

javax.mail.Transport

javax.mail.Store

javax.mail.Folder

javax.mail.internet.MimeMessage

javax.mail.internet.InternetAddress


Note:

change the code in these string with your
own details
image-file-location
sender-gmail-address-password
sender-gmail-address
receiver-gmail-address

Example:

package com.javamail;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;



public class SimpleMail {


public static void main(String[] args) {

String mail_to ="receiver-gmail-address";
String mail_from ="sender-gmail-address";


//These are details of SMTP server - gmail smtp server 
//and sender gmail authentication details

final String username="sender-gmail-address";
final String password="sender-gmail-address-password";  
String host="smtp.gmail.com"; 

Properties props=new Properties();

props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");

/*here are details of Jango SMTP server - need to register 
 in JangoSMTP. In this example I am using gmail smtp server 
 so - just commented Jango details But you can try this 
final String username="jangosmtp-username";
final String password="jangosmtp-password";  
String host="relay.jangosmtp.net";
props.put("mail.smtp.port", "25");*/

/*In order to use javamail api need to get the 
 Session object proper sender credentials -
 username & password needs to be given
otherwise, transfer of mail - fails*/
Session session=Session.getInstance(props, 
 new javax.mail.Authenticator() { 
  protected PasswordAuthentication getPasswordAuthentication() {
   return new PasswordAuthentication(username,password);
  }
 });
 
 try {
  //create a default MimeMessage object.
 
 //Message models the message that you want to send
 //Message is an abstract class, so MimeMessage 
 //class provide the implementation
 Message message=new MimeMessage(session);
 
 message.setFrom(new InternetAddress(mail_from));
 
 //set the receviers and type of sending
 
 //you can send as cc: bcc:
 //use Message.RecipientType.CC or Message.RecipientType.BCC
 message.setRecipients(Message.RecipientType.TO, 
   InternetAddress.parse(mail_to));
 
 //set subject   
 message.setSubject("Testing mail through Java");
 
 /*set the message body- a message body can be multipart message
    this means we can send mail text and attachment also*/
 BodyPart messageBodyPart = new MimeBodyPart();
 messageBodyPart.setText("This is the message body ");
 
 
 Multipart multipart =new MimeMultipart();
 
 //adding message body part - part1
 multipart.addBodyPart(messageBodyPart);
 
 //adding attachment -part2
 messageBodyPart=new MimeBodyPart();
 
 String filename="image-file-location";
 
 DataSource source=new FileDataSource(filename);
 messageBodyPart.setDataHandler(new DataHandler(source));
 messageBodyPart.setFileName(filename);
 
 multipart.addBodyPart(messageBodyPart);
 
 //send complete message parts
 message.setContent(multipart);   

 Transport.send(message);

 //a confirmation to your mail program
 System.out.println("Sent message Successfuly");
 
} catch (MessagingException e) {
 throw new RuntimeException(e);
}
}

}