Thursday, July 28, 2011

Sending Email in Java

It is not so complicated to create your own email sending application using Java by using the JavaMail API. To send an email, we need SMTP server and its credentials. Since I faced a lot of problems regarding the sending of an email and finally I got the working code. Yes, may be the modified source code may also work which may ultimately be simpler than this.

In this article, my focus will be on the problem solution, so I have used the SMTP server of google. Google is very good because it is providing a lot facilities to its users like if you have google account you have everything!

Now we start creating a sample application which is responsible for sending an email. To achieve this, we need the following properties to be set:
1) SMTP server
2) Server credentials
3) Port Number


We need to create Session object for which we need Properties object where we can set the properties we require and Authenticator object for authentication which needs the server credentials.

A sample program which is working for jdk 1.6 is presented here:

import javax.mail.PasswordAuthentication;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
* This class is responsible for sending emails.
* @author krishna
*/
public class EmailSender {

//gmail SMTP server
private String SMTPServer = "smtp.gmail.com";
//SMTP server username, in our case, it is the sender also
private String from = "abc";
//SMTP password
private String password = "xyz";

/**
* Constructor
*/
public EmailSender() {
}
/**
* Sends a message email
* @param to To address
* @param subject Subject
* @param content message content
* @return result:true or false
* @throws MessagingException
*/
public boolean SendMail(String to, String subject, String content)
throws MessagingException {

try {

//Create Session
Properties props = new Properties();
props.put("mail.smtp.host", this.SMTPServer);
//Port 465 is SSL port for gmail smtp server
props.put("mail.smtp.port", "465");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");

Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,password);
}
});

//Create Message
Message message = new MimeMessage(session);
message.setSubject(subject);
message.setText(content);


//Set Addresses
Address fromAddress = new InternetAddress("this.from);
Address toAddress = new InternetAddress(to);
message.setFrom(fromAddress);
message.setRecipient(Message.RecipientType.TO, toAddress);

//Send
Transport.send(message);
} catch (Exception ex) {
ex.printStackTrace();
}
return true;
}
}


I think the above mentioned code works fine for you too. The only change you need is change the SMTP server credentials and google users can use their email id and password as credential. This user name will be from email address too. We can call the SendMail method of EmailSender object. The SendMail method takes the email address to whom we are going to send the message, subject text and content text.

This covers the basic of email sending which only consists of sending text messages only; but we can do a lot of extensions on this like attaching files, text rendering etc.

Thanks for reading this !

Sunday, July 17, 2011

Layers in Java

Possibilities of Using Layers: The layers of a panel can be used to create more better interactive systems. We can use the glass-panes and layers to show some extra information on the top of other controls while blocking mouse events on the controls. We can create interactive tutorials and manuals with animations in the middle of some process. Similarly, layered panes are also used for selected object highlighting, focusing or showing detail information in pop up like window.

The dragging and dropping can be made more user friendly by use of layered panes for showing the thumbnail of dragged component on the mouse pointer. Since we do not need more than one layer for this, so glass pane is sufficient to accomplish this task.

How to use Layers:
Glass Pane:For glass pane, we create component for glass pane and then set this component as glass pane.
CustomGlassPane glassPane=new CustomGlassPane();
frame.setGlassPane(glassPane);
While creating glass panes, we generally need to disable input events inside the glass pane. So, we need to implement disable the listeners in the glass pane component. Initially glass pane component is invisible, so when required we make the glass pane visible.

Layered Panes:For layered panes, we define the layered component and then set this component as layered pane as follows:
LayeredComponent component=new LayeredComponent();
JlayeredPane layeredPane=getRootPane().getLayeredPane();
layeredPane.add(component,depth);

The depth defines where in the z-order the layer to be displayed. We need to define the layout of the layered pane because there will not be any default layout for this.

Glass Pane Limitations:
(i)
We can not create multiple glass panes because sometimes we may require multiple glass panes to be implemented to achieve our goal.
(ii) Glass pane always cover the entire frame, so if we need to cover only part of the frame, then its not possible.

Layered Panes Limitations:
The layered panes remove the trade offs of glass pane because we can have multiple layers and layers can be set for each child container on the frame. However, we need to create our own layout for the layered component. Although we can use OverlayLayout but that is very simple to meet our requirements. The main disadvantage of layered panes is the complexity of implementation; so many designers prefer to select layout manager to fulfill the requirement of depth-wise positioning of components.

Animation in Java

--> We can implement animation by creating a timer, and when we need animation for a particular object, then we start the timer and inside timer, there is some animation related processing which gets executed to show the object differently on different time interval. The small changes in the object between the two time intervals gives the feeling of smooth animation.
We create a timer and when we need the animation, the timer is started, and the a block of code for animation executes which changes the look and position of object on the timer interval. After the animation is completed, we can reset the look or position of the object. The stopping condition of animation would be when timer is stopped or when some required state is reached by the object through animation.
We create a class for animation which does the task of animation as follows:

private class Animator implements ActionListener{
public void actionPerformed(ActionEvent e){//Do Animation}
}

And inside the object, we created a timer as follows:
private Timer animationTimer=new Timer(delay,new Animator());
//To start animation
animationTimer.start();
//To Stop animation
animationTimer.stop();
Thus, the value of delay can be changed according to our requirement what type of animation we are needing. The animator class should be accessible to the object to be animated to get state of the object. Suppose we want to create an animation with changing the position of an object, then the animator class should get the current position of the object, calculates the new position and sets the new position as current position. This process is repeated with some delay defined in timer, thus gives the feeling of smoothly moving object.

UNDO-REDO Mechanism

UNDO-REDO mechanism works based upon Command Design Pattern that is we define a set of commands that can be executed and un-executed. Actually, execution does some task and it may contain several steps. The un-execution performs in opposite way to take to a state before execution was called.

While doing an action, command for that action is executed and since this action can be undone so, the command is put in the list of undo commands. When an undo command is executed, the task should be unexecuted and this task can be redone, so it is put in the list of redo commands. One thing to note here is, after we undo and then perform a task, then we can not redo, so in such case, the redo command lists are cleared.

To implement undo-redo, we first of all need to create the commands which are capable of executing and unexecuting the commands. To simplify, we define an interface which has the methods execute() and unexecute():

public interface Icommand{
/* Executes */
public void execute();
/* Unexecutes */
public void unExecute();

}

Then we define the actual command implementing this interface. The actual tasks performed by the command are defined inside the implemented command. This is done as follows:

public class AddButtonCommand implements ICommand {
@Override
public void execute(){//Define here}

@Override
public void unExecute(){//Define here}
}

After we define the required commands, we define a manager class which stores the history of the undo and redo commands and manages them. A sample manager class looks like this:

public class UndoredoManager {
//Undo commands list
private Stack undoList=null;
//Redo commands list
private Stack redoList=null;
public void undo(){//execute undo command}
public void redo(){//Execute redo command}
public void addCommand(ICommand command){//new command}
}

The above undo-redo manager class keeps track of the command list of undo and redo, and executes the command upon request. The list management through stack is appropriate for undo and redo because recently added undo command is used while redoing.

Painting in Java

To perform painting in any component, we need to override the paint methods of the component. The painting process calls three overridable methods: paintComponent(Graphics g), paintChildren(Graphics g) and paintBorder(Graphics).

We generally override paintComponent method for painting the components. Since the painting in swing is carried out by Event Dispatcher Thread, there should be
some queuing mechanism to handle the requests. The event queue actually contains the queues of painting requests and the painting requests managed by RepaintManager by calling the paint method of the component to paint. In the first part, paintComponent method is called which paints own contents, and calls paintBorder which paints the border of the component and finally paints the children it contains by calling paintChildren method.

We can override paint(Graphics) too but we have to manage many other things like border of the control and child components the control contains. We use the Graphics object to paint on the component which is provided at the time of painting. For 2 dimensional painting, we generally cast the Graphics object into Graphics 2D object which can perform better for 2D painting. Since we render only part of the component, while other parts, we wanted to remain as it is. In that situation, we call the parent's paintComponent method and do our painting task so that there would not be undesired painting effects. We do not need to dispose the Graphics object because this object is referenced by other painting methods too. In some cases, we need to change the properties of Graphics object which is specific to a painting only, in such a scenario, we copy the Graphics object and do the painting , and after finishing the painting , we dispose the copy of Graphics object.

Double Buffering:
Double buffering is an indirect process of rendering in which the actual rendering
operations are not performed on the image displayed on the screen, rather an off-screen image(called back buffer) is used to create a rendered image and that image is copied to the screen. This process is repeated and the final result is the smoother display of the images on the screen.

Tuesday, July 12, 2011

Value of PI(Monte Carlo Method)

The value of PI is fixed, it is defined in terms of accuracy by estimating depending upon our requirement of accuracy. So, the value of PI should be very accurate for astronomic calculations for planets while we may not need such accuracy for general purpose calculation like to calculate the surface area of football.

There are several methods to calculate the value of PI, but this time, I am quite impressed by the Monte Carlo Method which is clearly explained by my friend Nobal Niraula in his technical blog. So, I am gonna implement that method in java and I have written a sample java code for that.

/**SAMPLE JAVA IMPLEMENTATION FOR CALCULATION OF PI**/
float PI = 0;long hit = 0;long count = 0;
long throws=100000;/*Set how accurate value you need*/
Random random = new Random();
while (count <= throws) {
/* X coordinate*/
float x = random.nextFloat();
/* Y coordinate */
float y = random.nextFloat();
/*Check whether the point lies inside the arc*/
if (Math.sqrt(x * x + y * y) <= 1) {
hit++;
}
count++;
}
/*Calculate the value of PI*/
PI = 4 * (float) hit / count;

The calculation process is rather simple. We assume an inscribed circle inside a unit square, and then generate random number uniformly to get the x and y co-ordinates of the point lying inside the square. We count the number of points which are inside the inscribed circle. For calculation simplicity, we choose only 1/4th of the square and calculation will be as follows:
(points_in_circle)/(points_in_square)=PI/4(radium=1)
so, PI=4*(points_in_circle)/(points_in_square)

In the above implementation, hit is the count of points in the circle and count is the points in the square. The accuracy is determined by throws; the higher the value we set probably the most accurate value in the cost of execution time.

Wednesday, June 22, 2011

Observable and Observers

We need to accept some conventions while developing an application and out of them, MVC is an accepted pattern by many developers because it makes the code easy to understand by isolating the controller portion of the code from view and model.

It is easy to imaging in MVC way, but while implementing we need to face some challenges like:
1) The controller and model are sometimes so tied, it is very difficult or complex to isolate the model from controller.
2) The communication among model,view and controller may not be straightforward.

Here, I will focus the communication part and how java is achieving this in an efficient way. Suppose, we are going to implement notification between two classes Receiver, Sender where Receiver object receives the notification sent by Sender. To implement this, we need to:
i) extend class Observable in Sender class.
ii) implement the Observer interface in Receiver class

The Sender class will be like this:

class Sender extends Observable{
private void doSomeTask(){
//Notify here
this.setChanged();
this.notifyObservers(object);
}
}

The class Receiver will look like this:

class Receiver implements Observer{
//Create observable object
Sender sender;
public Receiver(){
//add the observer object
this.sender.addObserver(this);
}
@Override
public void update(Observable observable, Object object){
//check the observable class
if(observable==this.sender){
//do some job here
}
}
}

The overriden method update of receiver class gets the notification from the observer. The update method takes the Observable object and the object sent from the Obvervable.

Advantages:
i) We can completely separate Model from Controller.
ii) Replaces creation of event handler which is lengthy process and requires more steps.

Disadvantages:
The one disadvantage is the observable class should be subclass of Observable and since inheritance in java does not allow multiple inheritance. So, if observable class needs to have more than one super class, it is not feasible, we need to change the implementation.