Archive

Archive for the ‘Java’ Category

Java 7 Awesome Aspect-Automatic Resource Management

December 19, 2010 7 comments

Introduction:

In my previous article,” Java 7 Awesome Features” I had missed one of the greatest aspect of Java 7.That is nothing but “Automatic Resource Management”. This article deals with the same.

Managing Resource is one of the keen thing in development. Because if we don’t manage the resource effectively it will cause lot of issues like PermGen Space Error, TooManyConnections Error etc.

For avoid those problems Java 7 introduce the great aspect “Automatic Resource Management”. By this feature java can automatically manage the resources effectively. So java frees the developer from lots of overhead. Lets have a prolix look on this.

Syntax:


try(Resource 1;Resource 2;Resource 3….)

{

//block of statements

}

catch(Exception e)

{

//block of statements

}

Here is simple code snippet which shows you the typical try-catch-finally block. In the code we create the jdbc connection for access the data from database.


Connection connection = null;

Statement statement = null;

try

{

connection =    DriverManager.getConnection(“databaseurl”,”username(opt)”,”password(opt)”);

statement = connection.createStatemnet();

boolean executionStatus= statement.execute(“query”);

}

catch(Exception e)

{

//Block of code for handle the exception

e.printStacktrace();

}

finally

{

try

{

statement.close();

connection.close();

}

catch(Exception e)

{

//block of statements for handle exceptions.

}

}

In the above snippet, suppose we forget to close the statement and connection, what happened? May be after some operations (which also open the connection) “Too Many connection error” will occurred.

But java 7 keeps us in safe zone from those kinds of errors by mange the resource automatically. In java 7 we can write the above snippet like this,


Connection connection = null;

Statement statement = null;

try(connection =    DriverManager.getConnection(“databaseurl”,”username(opt)”,”password(opt)”);

statement = connection.createStatemnet())

{

boolean executionStatus= statement.execute(“query”);

}

catch(Exception e)

{

//block of statements for handles the exceptions

}

In the above snippet, there are no overheads like close the connections and statements properly. Java 7 can manage those things automatically for us.

Note:

Java 7 mange the resources which are sub interfaces and implementing classes of AutoCloseable.So we can pass the resources which are extends or implements the interface AutoCloseable.

That’s all folks, I think this article makes you bit more knowledgeable about java 7 awesome aspect “Automatic resource Management”, If you feel the same, please leave your footprints(comments) here. Joyous coding day…..

Simple JPA Application with Hibernate

December 5, 2010 6 comments
Introduction:

Now I am the newbie to JPA.I learn some thing about JPA. So I wanna share that with you all. So only I am here to do the same. This article deals with how to develop the simple JPA application using hibernate vendor support. Let’s get into that.

Prerequisites:

  • JDK 1.5 and above
  • Your favourite IDE.
  • HibernateJPA Library.
  • Mysqljdbc.jar

After create the Project we have to add above required libraries and jars into our library folder.

Steps:
  • Table Creation.
  • Creation of  Persistence.xml
  • Creation of  Entity class
  • Creation of  Entity Manager class
  • Creation of  Test class.
1. Table Creation:

Create table named “Department”, which contains two columns “departmentId” and “departmentName” by executing the following script,

CREATE TABLE `Department` (
`departmentId` int(10) NOT NULL,
`departmentName` varchar(10) default NULL,
PRIMARY KEY  (`departmentId`))
2. Persistence.xml:

This persistence.xml file is act like configuration file for JPA.


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

<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

<persistence-unit name="JPASamplePU" transaction-type="RESOURCE_LOCAL">

<provider>org.hibernate.ejb.HibernatePersistence</provider>

<class>com.bsj.entities.Department</class>

<properties>

<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>

<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/jpadb"/>

<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>

<property name="hibernate.hbm2ddl.auto" value="update"/>

<property name="hibernate.connection.username" value="root"/>

<property name="hibernate.connection.password" value="root"/>

</properties>

</persistence-unit>

</persistence>

Persistence-unit: used to represent the persistence unit.

Transaction-type: type of transaction

There are two type of transactions are avail.

Resource-local: Transactions have to be managed by developer locally.

JTA: Transactions are managed by application server.

Class: Represent the entity.

hbm2ddl.auto: used to perform the action in the database when the SessionFactory is created.

All the others are basic things.

3. Creation of Entity Class:

Entity class is used to represent the table in class format.

package com.bsj.entities;

import java.io.Serializable;

import javax.persistence.Basic;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.NamedQueries;

import javax.persistence.NamedQuery;

import javax.persistence.Table;

@Entity//Represent the class entity class

@Table(name = "department")//Represents the table name

@NamedQueries(

{

@NamedQuery(name = "Department.findAll", query = "SELECT d FROM Department d"), @NamedQuery(name = "Department.findByDepartmentId", query = "SELECT d FROM Department d WHERE d.departmentId = :departmentId"), @NamedQuery(name = "Department.findByDepartmentName", query = "SELECT d FROM Department d WHERE d.departmentName = :departmentName")

})

public class Department implements Serializable

{

private static final long serialVersionUID = 1L;

@Id

@Basic(optional = false)

@Column(name = "departmentId")

private Integer departmentId;

@Column(name = "departmentName")

private String departmentName;

public Department()

{

}

public Department(Integer departmentId)

{

this.departmentId = departmentId;

}

public Department(Integer departmentId, String DepartmentName)

{

this.departmentId = departmentId;

this.departmentName = departmentName;

}

//Getter setter method of variables

}
Annotation used in Entity Class:

@Entity – used to represent the class as Entity class. By using this annotation only we can make simple POJO class as Entity class.

@Table – used Represent the table name which the entity class points out.

@Id – Used to represent the primary key field.Only one primary key is allowed in the entity class.

@Column – used to represent the column details such as name, nullable etc.

QueryAPI:

There are two types of query is avail.
1. Static (Named) Queries: defined statically with the help of annotation (or XML) before the entity class.

A name of the Query  is usually given to the query definition so that other components in the same persistent unit can refer the query by the name.
2. Dynamic queries: are nothing but whose query strings are provided at run-time

4.Creation of Entity Manager Class:

The constructor has the Entity Manager Factory as argument and it allows us to create the Entity Manager.

The Entity Manager class is transaction scoped bean so we have to begin transaction before each action and commit transaction after each operation.

package com.bsj.entities;

import java.util.List;

import javax.persistence.EntityManager;

import javax.persistence.EntityManagerFactory;

import javax.persistence.Query;

public class DepartmentManager

{

private EntityManager em;

public DepartmentManager(EntityManagerFactory emf)

{

em = emf.createEntityManager();

}

/**

* Method used to create department.

* @param department

*/

public void createDepartment(Department department)

{

//Begin Transaction

System.out.println("Creation : ");

em.getTransaction().begin();

em.persist(department); //Persist entity in persistence context.

//Commit Transaction

em.getTransaction().commit();

System.out.println("Department Created SuccessFully");

}

/**

* Method used to search department Name by id.

* @param id

* @return

*/

public Department searchById(Integer id)

{

//Method used to find data

return em.find(Department.class, id);

}

public void updateUser(Department department)

{

System.out.println("Update : ");

em.getTransaction().begin();

em.merge(department);

em.getTransaction().commit();

System.out.println("Update successfully.");

}

public void removeUser(Department department)

{

em.getTransaction().begin();

em.remove(department);

em.getTransaction().commit();

System.out.println("Remove department successfully");

}

public List getAll()

{

Query query = em.createQuery("select a from Department a");

List list = query.getResultList();

return list;

}

public void close()

{

em.close();

}

}

Methods used in Entity Manager:

Persist(entityObject)-Used to persist entity in the persistence context.
Find (Entityclass,value) – Find the datas regarding the input passed as argument.
merge(entityobject) : Update the database regarding to the passing details.
5.Creation of Test class:

We can get the entity manager factory by the  createEntityManagerFactory method of the class Persistence,
createEntityManagerFactory(persistence unit name);
This method has the persistence unit name as argument.
Call the entity manager methods by using the reference of entity manager.

package com.bsj.tester;

import com.bsj.entities.Department;

import com.bsj.entities.DepartmentManager;

import java.util.Iterator;

import java.util.List;

import javax.persistence.EntityManagerFactory;

import javax.persistence.Persistence;

public class TestJPA

{

private DepartmentManager departmentManager;

private EntityManagerFactory emf;

/**

* Method to setup basic thing need for implementation like entiny manager

* factory,entity manager etc.

* @throws Exception

*/

protected void setUp() throws Exception

{

/**

* Create the entity manager factory with the help of persistence.

* @Param NameofPersistence unit form Persistence.xml

*/

emf = Persistence.createEntityManagerFactory("JPASamplePU");

/**

* create Departmanager

* @Param Entity Manager Factory

*/

departmentManager = new DepartmentManager(emf);

}

/**

* Method to close entity manager and entity manager factory.

* (i.e) Remove from the persistence context

* @throws Exception

*/

protected void close() throws Exception

{

departmentManager.close();

emf.close();

}

/**

* Method for test the application.

*/

public void test()

{

/**

* Create the Entity by using constructor of Entity.

*/

Department department = new Department(10, "Chemical");

departmentManager.createDepartment(department);

System.out.println("Before Update :");

Department searchDepartment = departmentManager.searchById(50);

System.out.println("Department Name of Id 50 : " + searchDepartment.getDepartmentName());

searchDepartment.setDepartmentName("EEE");

departmentManager.updateUser(department);

department = departmentManager.searchById(50);

System.out.println("After update.");

System.out.println("Department Name of Id 50 : " + searchDepartment.getDepartmentName());

List list = departmentManager.getAll();

System.out.println("Number of Departments: " + list.size());

System.out.println("List of Departments : ");

Iterator iterator = list.iterator();

while (iterator.hasNext())

{

Department department3 = (Department) iterator.next();

System.out.println("Id : " + department3.getDepartmentId());

System.out.println("Name : " + department3.getDepartmentName());

}

}

public static void main(String args[])

{

System.out.println("Inside TestJPA main");

TestJPA testJPA = new TestJPA();

try

{

testJPA.setUp();

testJPA.test();

testJPA.close();

}

catch (Exception e)

{

e.printStackTrace();

}

System.out.println("End of TestJPA main");

}

}

Thats all folks.If you found this article was helpful to you,don’t forget to leave your valuable comments here.Happy coding….

Java 7 awesome Features

November 15, 2010 38 comments

Whenever, I am crawl through the web i notice the word java 7.Then,I really found out java 7 is today’s hot topic. So i googled it for know something about java 7.At that time i found out some thing interested and useful features in java 7.Thats push me here to share something to you all folks.Lets get into the topic.

The project name of java 7 development is Project Coin.I have listed some of the features below.

Null-safe Method invocation:

This is the greatest feature which is going to added in Java 7.NullPoniterException is one of the most common exception encountered in Java programming.

When I searched “NullPointerException” in Google, it gave about 5,570,000 results! This proves how pervasive the exception is and how much effort a developer has to put in writing java code free from null pointer exception.

Suppose if java has a feature to keep us in safe zone from null pointer exception, how is it? It happens.

Suppose we have a method to fetch postal code of a person’s address:

public String getPostcode(Person person)
{
if (person != null)
{
Address address = person.getAddress();
if (address != null)
{
return address.getPostcode();
}}
return null;
}

Now check the above syntax. We have done lots of if (null! = object) checks to avoid NullPointerException.

public String getPostcode(Person person)
{
return person?.getAddress()?.getPostcode();
}

Null-ignore invocation is concerned with dealing with possible null values in calling one or especially a chain of methods. Check the syntax?. while calling method on an object. This is Null-safe operator in Java 7. Thus, you can avoid lots of if (null!= object) checks in Java 7.

Strings in Switch Statements:

Whenever i am working with switch-case i felt, if the case allowed the string as a case variable we feel so comfort on that. Because the switch case allows only the primitive data types as variable such as integer, char etc.

Whenever i working with the methods that returns status of the operations like succesful, failed like that. At that time i need to convert that in to constants. Then only i can move on switch statements.

But java 7 offers the Strings as case variables in Switch Statements, So we are free from the conversion process.

Multi-Exception Catch:

Another awesome update is Multi-Exception Catch, that means a single catch can handle multiple exceptions. The syntax is

try
{
block of statments
}
catch(Exception1|Exception2|Exception3...)
{
block of statements.
}

It save lot of spaces in the code.

Bracket Notation for Collections:

This feature refers to the ability to reference a particular item in a Collection with square brackets similar to how Arrays are accessed. Collection is one of the key concepts in java.

But when i was a student, I feel so discomfort with collections because of its strutcture.Thats some thing different from basic things in java.

But now its also be like a simple things like array etc. For ex, a Collection class we might consider something similar to arrays.

Instead of:

Collection<String> c = new ArrayList();
c.add(“one”);
c.add(“two”);
c.add(“three”);
Use:
Collection<String> c = new ArrayList {“one”, “two”, “three” };

Thats all folks.If any important updates are missing don’t hesitate to add that as comments.

Java code to Wrap and Rotate image in PDF File

August 2, 2010 2 comments

Introduction:

Now-a-days if we wanna develop an application, that application must have the capability to prefer the Reports. All the reports are  favour to PDF format. If we develop a report for a particular concern the client needs to place their logo in the report. For that we need to insert the image in PDF file. This article deals the same.

The itex.jar makes it most simple and elegant.

Prerequisites:

JDK 1.5 and Above

Jar : itext.jar(Download here)

To make a program over this, firstly we need to import some packages. Remember to make this program the first and foremost thing to remember is to place the iText.jar in WEB-INF/lib of your web application.

Without this .jar the application will not run.

Steps involved in Insert image in PDF File:

Create Document :

This class describes a PDF file’s page size, margins, and other important attributes. It works as a container for a document’s chapters, sections, images, paragraphs, and other content.

Create PdfWriter:

This class is used to create the pdf file.

By using the method getInstace we can create pdf file from the given output stream.

Open pdf File:

Now open the document by using open() method in document class.

Get the Image content:

By using the method getInstace() of image class we can get the image content.

The method has the image filename as argument.

Add contents to Pdf File:

By using add method in document class we can add paragraph and image in the pdf file.

Resize the image:

By using the scaleAbsolute() method we can resize the image. We can pass the width and height as the argument to resize the image.

Rotate image:

By using setRotationDegrees() method of image class we can set the degree which we want to rotate the image.

After rotate the image we add the image into the pdf file by using add method of document class.

Code:

package com.bsj.itext;

import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;

/**
 *
 * @author Muneeswaran
 */
public class WrapImageinPdf
{
 public static void main(String arg[]) throws Exception
 {
 //Create Document
 Document document = new Document(PageSize.A4.rotate());
 //Create PdfWriter:
 PdfWriter.getInstance(document, new FileOutputStream("imagePdf.pdf"));
 Font font = new Font(Font.TIMES_ROMAN, 18, Font.BOLD);
 //Open pdf File:
 document.open();
 Paragraph paragraph = new Paragraph("Original:", font);
 Paragraph par = new Paragraph("After rotate:", font);
 //Get the Image content:
 Image image = Image.getInstance("2.jpg");
 //Add contents to Pdf File:
 document.add(paragraph);
 document.add(image);
 document.add(par);
 //Resize the image:
 image.scaleAbsolute(500.0f, 500.0f);
 image.setBorder(1);
 //Rotate image:
 image.setRotationDegrees(45.0f);
 document.add(image);
 document.close();
 }
}

Output:

I hopes this helps.Go ahead to prefer report and inserting logo in pdf.Before that,if you feel it useful,leave your foot prints here[Comments].

Pattern class of Regular Expression in Java

April 17, 2010 2 comments

Introduction:

This article makes you bit more knowledge in java regular expressions. For manage the regular expressions, the java have the three classes in java.util.regex package. But in this article we focused only Pattern class.

A regular expression is a pattern of characters that describes a set of strings. We use the regular expressions to find, display, or modify some or all of the occurrences of a pattern in an input sequence.

Java.util.regex classes:

The package java.util.regex contains three classes such as,

  • Pattern Class
  • Matcher Class
  • PatternSyntaxExcpetion

Let us take a look at Pattern class.

Pattern Class:

A regular expression which is specified as a string that should be first compiled into an instance of Pattern class. The resulting pattern can be used to create an instance of  Matcher class which contains various in-built methods that helps in performing a match against the regular expression. Many Matcher objects can share the same Pattern object.

Create Pattern using compile():

Pattern class doesn’t have a public constructor. So by using the static method compile we can create the pattern.

Pattern p = Pattern.compile("my regexp");

For Regular expression symbols,click here

Important Note:

The backslash is an escape character in Java Strings. i.e., backslash has a predefine meaning in Java. You have to use “\\” instead of “\”.

If you want to define “\w” then you must be using “\\w” in your regex like this.

Pattern r = Pattern.compile(“\\w+”); //Place your pattern here

“\w“ represents a word character, i.e., short for [a-zA-Z_0-9]

We can create the Pattern with flags.

Syntax:

Pattern pattern=Pattern.compile(regex,flags);

For ex, If we want to neglect the case sensitive we can achieve by using below one,

Pattern pattern = Pattern.compile(“\\w+”,Pattern.CASE_INSENSITIVE);

Validate pattern using matches():

The matches() method is used to check whether the given input is match with the pattern. This method returns true only if the entire input text matches the pattern.

boolean isMatch = Pattern.matches(“\\w+”,”Welcome to java world”);

Get the Pattern using pattern():

The pattern() method is used for find out the pattern of the given string. This method returns the regular expression as a string from which this pattern was compiled.

Pattern p=input.pattern();

Split input using split():

The split() method is used to split the given input text based on the given pattern. It returns a String array. There are two forms of split() method,

  • split(String input)
  • split(String input, int limit)

In the second form, we have an argument called limit which is used to specify the limit i.e. the number of resultant strings that have to be obtained by split() method.

String[] str = pattern.split(input,3);

Sample code for Pattern class and methods:

MailID Validation.java:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Home
 */
class MailIDValidation
{
 public static void main(String args[])
 {
 //Input the string for validation
 String email = "mymail@gmail.com";

 //Set the email pattern string
 Pattern p = Pattern.compile(".+@.+\\.[a-z]+");

 //Match the given string with the pattern
 Matcher m = p.matcher(email);

 //check whether match is found
 boolean matchFound = m.matches();

 if (matchFound)
 System.out.println("Valid Email Id.");
 else
 System.out.println("Invalid Email Id.");
 }
}

I hope it offer bit more knowledge in Regular Expressions. The next article makes you clear in Matcher class in regular expression.Please leave your footprints (comments) here.

Java Code to Receive Mail using JavaMailAPI

March 21, 2010 35 comments

Introduction:

In the previous article, we have looked at sending mail with Java Mail API.Sending e-mail was relatively simple with only one protocol (SMTP) to handle. But Reception involves two protocols, POP3 and IMAP. POP3 is the older protocol, which offers a single queue of mail messages as a single inbox. IMAP is the more modern protocol, which presents mail messages as entries in a hierarchy of folders, one of which will be an inbox.

Java Mail comes with Provider implementations for POP3 and IMAP, and the secure versions of those as POP3S and IMAPS.

Prerequisites:

JDK 1.5 and Above

Jar: Mail. jar

Steps involved in receive mail:

Step 1: Define the mail properties (i.e.) Define the protocol, mail server by using the properties class.

Step 2: Create the session for read the mail with the properties which we already defined.

Step 3: Create and connect the store for read the mail.

Step 4: Define and open the folder which we need to read. Open the folder in read-only mode.

Step 5: Search the unread contents in the specified folder and stored it into messages array.

Step 6: Display the messages.

Description of classes and methods :

Store:

An abstract class that models a message store and its access protocol, for storing and retrieving messages.

Methods:

connect -> It is used to connect the store with the mail server store.

getFolder-> It is used to define the folder which will be read. Return Folder class.

Folder:

Folder is an abstract class that represents a folder for mail messages. Folders can contain Messages, other Folders

Methods:

open   -> Method for open the foder.We must define the mode of open.

search -> Method for get the messages. Return type: Message[].

fetch  -> Method for Fetch the details which is represented by FetchProfile.

close  -> Method for close the folder.

FetchProfile:

List the Message attributes that it wishes to prefetch from the server for a range of messages.

Method:

add  ->  Method for add the attributes which we wish to prefetch.

Message:

This class models an email message. This is an abstract class. Message implements the Part interface

A Message object obtained from a folder is just a lightweight reference to the actual message.

Methods:

getContent  ->  Method for get the content of the message.

Code:

/*
 *  This is the code for read the unread mails from your mail account.
 *  Requirements:
 *      JDK 1.5 and above
 *      Jar:mail.jar
 *
 */
package com.info.mail;
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.Flags.Flag;
import javax.mail.search.FlagTerm;

public class MailReader
{
 Folder inbox;

 //Constructor of the calss.
 public MailReader()
 {
 /*  Set the mail properties  */
 Properties props = System.getProperties();
 props.setProperty("mail.store.protocol", "imaps");
 try
 {
 /*  Create the session and get the store for read the mail. */
 Session session = Session.getDefaultInstance(props, null);
 Store store = session.getStore("imaps");
 store.connect("imap.gmail.com","<mail ID> ", "<Password>");

 /*  Mention the folder name which you want to read. */
 inbox = store.getFolder("Inbox");
 System.out.println("No of Unread Messages : " + inbox.getUnreadMessageCount());

 /*Open the inbox using store.*/
 inbox.open(Folder.READ_ONLY);

 /*  Get the messages which is unread in the Inbox*/
 Message messages[] = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));

 /* Use a suitable FetchProfile    */
 FetchProfile fp = new FetchProfile();
 fp.add(FetchProfile.Item.ENVELOPE);
 fp.add(FetchProfile.Item.CONTENT_INFO);
 inbox.fetch(messages, fp);

 try
 {
 printAllMessages(messages);
 inbox.close(true);
 store.close();
 }
 catch (Exception ex)
 {
 System.out.println("Exception arise at the time of read mail");
 ex.printStackTrace();
 }
 }
 catch (NoSuchProviderException e)
 {
 e.printStackTrace();
 System.exit(1);
 }
 catch (MessagingException e)
 {
 e.printStackTrace();
 System.exit(2);
 }
 }

 public void printAllMessages(Message[] msgs) throws Exception
 {
 for (int i = 0; i < msgs.length; i++)
 {
 System.out.println("MESSAGE #" + (i + 1) + ":");
 printEnvelope(msgs[i]);
 }
 }

 /*  Print the envelope(FromAddress,ReceivedDate,Subject)  */
 public void printEnvelope(Message message) throws Exception
 {
 Address[] a;
 // FROM
 if ((a = message.getFrom()) != null)
 {
 for (int j = 0; j < a.length; j++)
 {
 System.out.println("FROM: " + a[j].toString());
 }
 }
 // TO
 if ((a = message.getRecipients(Message.RecipientType.TO)) != null)
 {
 for (int j = 0; j < a.length; j++)
 {
 System.out.println("TO: " + a[j].toString());
 }
 }
 String subject = message.getSubject();
 Date receivedDate = message.getReceivedDate();
 String content = message.getContent().toString();
 System.out.println("Subject : " + subject);
 System.out.println("Received Date : " + receivedDate.toString());
 System.out.println("Content : " + content);
 getContent(message);
 }

 public void getContent(Message msg)
 {
 try
 {
 String contentType = msg.getContentType();
 System.out.println("Content Type : " + contentType);
 Multipart mp = (Multipart) msg.getContent();
 int count = mp.getCount();
 for (int i = 0; i < count; i++)
 {
 dumpPart(mp.getBodyPart(i));
 }
 }
 catch (Exception ex)
 {
 System.out.println("Exception arise at get Content");
 ex.printStackTrace();
 }
 }

 public void dumpPart(Part p) throws Exception
 {
 // Dump input stream ..
 InputStream is = p.getInputStream();
 // If "is" is not already buffered, wrap a BufferedInputStream
 // around it.
 if (!(is instanceof BufferedInputStream))
 {
 is = new BufferedInputStream(is);
 }
 int c;
 System.out.println("Message : ");
 while ((c = is.read()) != -1)
 {
 System.out.write(c);
 }
 }

 public static void main(String args[])
 {
 new MailReader();
 }
}

Java code sending Mail with Attachment using Java Mail API

March 3, 2010 39 comments

Introduction

In a day-to-day life the emails are occupied our life.If we can send our mails by using our java code without help of browser how we feel?

This article do this.By using the JavaMail API send our mail with attachment without help of browser.This code need a mail.jar file.You can download this at http://www.java2s.com/Code/Jar/JKL/Downloadmailjar.htm


Code:


/ * This code is only for design the frame
 *
 * @author muneeswaran
 */
package com.mail;

import javax.mail.MessagingException;
import javax.swing.*;

public class MailSender extends JFileChooser
{

    private JTextField attachmentTextField;
    private JLabel jLabel1, jLabel2, jLabel3, jLabel4, jLabel5, jLabel6;
    private JScrollPane jScrollPane1;
    private JTextArea messageTextArea;
    private JButton sendButton, cancelButton, browseButton;
    private JTextField ccTextField, subjectTextField, toTextField;
    String toAddress = null, ccAddress = null, message = null,
            receipientsList[] = null, attachments[] = null, receipients, subject;
    String fromAddress = "put your full mail id"; //Place your mail id here.
    String authenticationPassword = "your password";//Place your password here

    public MailSender()
    {
        initComponents();
    }

    private void initComponents()
    {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel("To");
        toTextField = new javax.swing.JTextField(20);
        jLabel3 = new javax.swing.JLabel("CC");
        ccTextField = new javax.swing.JTextField(20);
        jLabel4 = new javax.swing.JLabel("Subject");
        subjectTextField = new javax.swing.JTextField(20);
        jLabel5 = new javax.swing.JLabel("Attachemnet");
        attachmentTextField = new javax.swing.JTextField(20);
        browseButton = new javax.swing.JButton("Browse");
        jLabel6 = new javax.swing.JLabel("Message");
        jScrollPane1 = new javax.swing.JScrollPane();
        messageTextArea = new javax.swing.JTextArea(20, 10);
        sendButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        //setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("AlMateen-Bold", 3, 14)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(1, 203, 221));
        jLabel1.setText("Mail Sender");
        jScrollPane1.setViewportView(messageTextArea);
        sendButton.setText("Send");
        sendButton.addActionListener(new java.awt.event.ActionListener()
        {

            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                sendButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener()
        {

            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                cancelButtonActionPerformed(evt);
            }
        });

        browseButton.addActionListener(new java.awt.event.ActionListener()
        {

            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                browseButtonActionPerformed(evt);
            }
        });

        jLabel1.setBounds(100, 50, 200, 50);
        jLabel2.setBounds(50, 100, 100, 50);
        toTextField.setBounds(150, 100, 300, 40);

        jLabel3.setBounds(50, 150, 100, 50);
        ccTextField.setBounds(150, 150, 300, 40);

        jLabel4.setBounds(50, 200, 100, 50);
        subjectTextField.setBounds(150, 200, 300, 40);

        jLabel5.setBounds(50, 250, 100, 50);
        attachmentTextField.setBounds(150, 250, 200, 40);
        browseButton.setBounds(375, 250, 100, 20);

        jLabel6.setBounds(50, 300, 100, 50);
        messageTextArea.setBounds(150, 300, 300, 40);

        sendButton.setBounds(100, 400, 75, 20);
        cancelButton.setBounds(200, 400, 75, 20);
        JFrame mailFrame = new JFrame("Mail Sender");
        mailFrame.add(jLabel1);
        mailFrame.add(jLabel2);
        mailFrame.add(toTextField);
        mailFrame.add(jLabel3);
        mailFrame.add(ccTextField);
        mailFrame.add(jLabel4);
        mailFrame.add(subjectTextField);
        mailFrame.add(jLabel5);
        mailFrame.add(attachmentTextField);
        mailFrame.add(browseButton);
        mailFrame.add(jLabel6);
        mailFrame.add(messageTextArea);
        mailFrame.add(sendButton);
        mailFrame.add(cancelButton);

        mailFrame.setLayout(null);
        mailFrame.setVisible(true);
        mailFrame.setSize(500, 500);
        mailFrame.setResizable(false);
        mailFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
        // TODO add your handling code here:
    }

    private void browseButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
        JFileChooser selectFile = new JFileChooser();
        selectFile.showOpenDialog(this);
        attachmentTextField.setText(selectFile.getSelectedFile().toString());
    }

    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt)
    {

        toAddress = toTextField.getText().trim();
        ccAddress = ccTextField.getText().trim();
        subject = subjectTextField.getText().trim();
        message = messageTextArea.getText().trim();
        String attachment = attachmentTextField.getText() + " ";

        attachments = attachment.split(" ");

        receipients = toAddress + "," + ccAddress;
        receipientsList = receipients.split(",");

        SendMailUsingAuthentication mailUsingAuthentication =
                new SendMailUsingAuthentication();
        try {
            mailUsingAuthentication.postMail(receipientsList,
                    subject, message, fromAddress, authenticationPassword, attachments);
        } catch (MessagingException messagingException) {
            messagingException.printStackTrace();
        }
    }

    void login(String userName, String password)
    {
        fromAddress = userName;
        authenticationPassword = password;
        System.out.println("User name : " + fromAddress);
    }

    public static void main(String[] args)
    {
        new MailSender();
    }
}

This is the Code for send Mail with attachment


/* This code is used for send the mail to the any users.</div>
 * It is done by Java Mail Api.
 * By using this code we can send mail with out enter into your mail Account.
 * @author muneeswaran
 */
package com.mail;

import java.util.Properties;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;

public class SendMailUsingAuthentication {

    private String HOST_NAME = "gmail-smtp.l.google.com";
    String messageBody;

    public void postMail(String recipients[], String subject, String message,
            String from, String emailPassword, String[] files) throws MessagingException {
        boolean debug = false;
        java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", HOST_NAME);
        props.put("mail.smtp.auth", "true");

        Authenticator authenticator = new SMTPAuthenticator(from, emailPassword);
        Session session = Session.getDefaultInstance(props, authenticator);

        session.setDebug(debug);

        // create a message
        Message msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(message);

        Multipart multipart = new MimeMultipart();

        //add the message body to the mime message
        multipart.addBodyPart(messageBodyPart);

        // add any file attachments to the message
        addAtachments(files, multipart);
        //Put all message parts in the message
        msg.setContent(multipart);
        Transport.send(msg);
        System.out.println("Sucessfully Sent mail to All Users");
    }

    protected void addAtachments(String[] attachments, Multipart multipart)
            throws MessagingException, AddressException {
        for (int i = 0; i <= attachments.length - 1; i++) {
            String filename = attachments[i];
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            //use a JAF FileDataSource as it does MIME type detection
            DataSource source = new FileDataSource(filename);
            attachmentBodyPart.setDataHandler(new DataHandler(source));
            attachmentBodyPart.setFileName(filename);
            //add the attachment
            multipart.addBodyPart(attachmentBodyPart);
        }
    }

    private class SMTPAuthenticator extends javax.mail.Authenticator {

        String username;
        String password;

        private SMTPAuthenticator(String authenticationUser, String authenticationPassword) {
            username = authenticationUser;
            password = authenticationPassword;
        }

        @Override
        public PasswordAuthentication getPasswordAuthentication() {

            return new PasswordAuthentication(username, password);
        }
    }
}