Saturday, July 30, 2011

Declarative Authentication in Java Server Pages

Some programmer prefers authentication through programming to declarative authentication, that all depends upon choice. I also used programed authentication before when I did my Bachelor's projects. I still remember the authentication part was tedious job since we need to write a bunch of code for authentication and the checking of session variable for authenticated user is also not interesting.

So, I was thinking whether there exists some sort of mechanism so that we do not need to do all these redundant things, I mean there should be some server management which will do all those authentication part of user.

I later realized I was not wrong. We can implement the declarative authentication without any much effort; just setting some declaration in server and the application part. This article will focus on how we can achieve these things.

Prerequisites:
1) Java should be installed. New ubuntu versions have built in java with OS; so we do not need to install it. If it is not installed anyway, just install it by selecting from Synaptic package manager.

2) There should be tomcat server installed.(The preferred tomcat version is tomcat 6 which is also supported by netbeans 6.9)
Installation of Tomcat
i)Download the apache tomcat compressed installer file in .tar.gz form and extracted it.
ii) Copy it to /usr/local location.
iii) Run the command to start the server(you must be inside the tomcat directory)
sudo sh bin/startup.sh
Now server is running.

3) The mysql server should be installed.
MySql Startup
i)type sudo apt-get install mysql-server in the terminal.
ii) installation may take longer time. while installing, you must create the user for mysql.
iii) after installation is complete, type sudo mysql -u username -p from terminal to run mysql server locally. Provide password for mysql.
iv) Now you are ready to execute the mysql commands.
3) Apart from creating the other several tables for you application, the authentication part need two compulsory tables to be created. You can give any names while creating and this information is placed in the server settings.
Structure of authentication tables:
tableUser: columnUserName, columnUserCred
tableUserRole: columnRoleName

I have used the following sql query to create those tables:
CREATE TABLE customers(name VARCHAR(100), password VARCHAR(100))
CREATE TABLE customer_roles(name VARCHAR(100),role_name VARCHAR(100))

4) Now we manage some settings in the server.xml file which is located in the conf folder of tomcat installation directory.

&lt!-- It is commented out--&gt
&lt!-- &ltRealm className = "org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase"/&gt
--&gt
&lt!-- Add these lines --&gt
&ltRealm className="org.apache.catalina.realm.JDBCRealm" debug="99"
driverName="com.mysql.jdbc.Driver" connectionURL=
"jdbc:mysql://localhost/dbComputerShopping?user=root&
password=00977" userTable= "customers" userNameCol="name"
userCredCol="password" userRoleTable="customer_roles"
roleNameCol="role_name"/&gt


5) Now, restart the tomcat server and most of the work is done. The remaining part is to create and define the users with roles. Store those information in the above mentioned tables created for authentication.

6) Now we define the login page and the error page in case authentication fails. We set this information in the web.xml file in the application.

&ltlogin-config&gt
&ltauth-method&gtFORM&lt/auth-method&gt
&ltform-login-config&gt
&ltform-login-page&gt/login.jsp&lt/form-login-page&gt
&ltform-error-page&gt/login_error.jsp&lt/form-error-page&gt
&lt/form-login-config&gt
&lt/login-config&gt


7) Now we select the pages which need right to access the pages. This information is also set inside the web.xml file as follows:

&ltweb-resource-collection&gt
&ltweb-resource-name&gtTheShop&lt/web-resource-name&gt
&lturl-pattern&gt/customer.jsp&lt/url-pattern&gt
&lt/web-resource-collection&gt
&ltauth-constraint&gt
&ltrole-name&gtuser&lt/role-name&gt
&ltrole-name&gtmanager&lt/role-name&gt
&lt/auth-constraint&gt
&ltuser-data-constraint&gt
&lttransport-guarantee&gtNONE&lt/transport-guarantee&gt
&lt/user-data-constraint&gt
&lt/security-constraint&gt

Here the page customer.jsp is arbitrary page which is accessed by users with roles user and manager. Other users do not have right to access this page.


Some Description:
This process is not so easy; I could not do it successfully in one time. I tried it many times until I get success. There are some minor problems may occur which can be fixed by seeing the error. Like there should be one compulsory user with manager role which is responsible for tomcat related settings. If you have not set that user, you even can not start the tomcat server.

Now, when user tries to access the page customer.jsp, then since it access right for specific users only, the you get a form for login the you go into the page. If authentication is okay and the role matches, only the page can be accessed by the user. Otherwise server redirects the user to the error page.

request.getRemoteUser() gets the previously logged in user. So, it can be saved in any servlet for later user such as to get other user related information of that user from the database or to check whether user has logged in or not, if logged in, which user has logged in etc.



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.