SUN CA : University of Delhi Agraj's Weblog

Tuesday May 27, 2008

I have already answered some FAQ's on SCJP 1.5 certification examination in my previous blog entry. Just wanted to share some more information on the exam that i got to know.
There are 7 sections in the exam with equal weightage to each :

  1. Declarations, Initialization and Scoping
  2. Flow Control
  3. API Contents
  4. Concurrency
  5. OO Concepts
  6. Collections / Generics
  7. Fundamentals

 The exam consists of 72 MCQ's in total and you are given time of 3 hours to solve them. More than enough, I say.

In Delhi, there are a few prometric test centers where you can take the test. The one i know about, is NIIT Limited, located at P-17/90, Madras Hotel Complex, Connaught Place. It is located near the popular Sarvana Bhawan and McDonalds, so you won't be having much trouble finding it. You can also call them on 011-41516458 to know more.
The examination costs about Rs. 7000/- as of now but most of the times they (NIIT people) offer some kind of discount vouchers, so don't forget to ask for one. You might just get lucky. Otherwise also, the amount's not much really if you look at the advantages of being a SCJP certified professional.

Here are a few useful links:
To learn more about Sun Microsystems certification programs visit here
To register for any Sun Microsystems exam, logon here

Friday May 09, 2008

I'm glad to announce that 18 students from Department of Computer Science, University of Delhi would be
doing Summer Projects related to Glassfish. A list of involved students can be seen here.

These students got this wonderful opportunity of working on open-source projects and it would definitely
help them in increasing their technical expertise on Java EE and Glassfish and work under the able guidance
and support of mentors assigned to them.

I would like to thank Arun Gupta, Judy Tang, Sriram, Gopal Jorapur for their endless efforts and encouragement.

 

Sunday May 04, 2008


This post shows how to send Email using Java.....this means you can write a simple Java Program that sends a mail using your mail account details or you can embed this functionality in your Web Application. Instead of explaining details of how it works, i will first give you the code that i used and then direct you to some useful links/resources that help you to understand better.

Resources Required:
JavaMail
JavaBeans Activation Framework
JAF(JavaBeans Activation Framework) is already shipped with Java SE 6, so Java SE 6 users need not download it separately.
NetBeans 6.1 IDE
Needless to say, NetBeans 6.1 IDE has helped me and other students of my University in completing assignments and projects on time and with ease. So, if you don't have it, download it right away here. You can also order NetBeans Starter Kit DVD here.

Why you need to download them ?
JavaMail consists of various jar files such as mail.jar, mailapi.jar, smtp.jar, pop3.jar whereas JAF mainly consists of activation.jar file. You need to download them and include these jar files in your CLASSPATH so that your JVM(Java Virtual Machine) can find the JAF classes.

Getting Started

Open the NetBeans 6.1 IDE.


Pretty fast than previous releases. Took about only 14.35 seconds on my machine.
Go to File --> New Project
Under Categories, choose "Web" and then select to create a simple Web Application.



Click Next and Type in Project Name : JavaMail. Be sure to select Glassfish as your server.

 

Click Finish and allow NetBeans to create files for your project.

Now, index.jsp opens up in the editor by default. Copy and paste the following code in your index.jsp file. It simply creates a HTML form that asks for the receiver's email address, subject and message body of the email.
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title> Java Mail </title>
    </head>
    <body>
        <form action="sendMail.jsp" method="POST">
            <table border="0" align="center" cellpadding="5">
                <tbody>
                    <thead><tr> <td colspan="3" align="center">
                    <b> Send Mail </b> </td> </tr> </thead>
                    <tr>
                        <td> To </td> <td> : </td>
                        <td> <input type="text" name="to" value="" /> </td>
                    </tr>
                    <tr>
                        <td> Subject </td> <td> : </td>
                        <td> <input type="text" name="subject" value="" /> </td>
                    </tr>
                    <tr>
                        <td> Message </td> <td> : </td>
                        <td> <textarea name="message" rows="8" cols="30">
                        </textarea></td>
                    </tr>
                    <tr>
                        <td colspan="3" align="center">
                        <input type="submit" value="Send Mail" />
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <input type="reset" value="Reset" />
                        <td>
                    </tr>
                </tbody>
            </table>
        </form>
    </body>
</html>

Save your index.jsp and it looks like


 

Now, we create a bean in which we store all the mail related information : sender's email id and password and receiver's email id, subject and message body of the email and the name of the smtp server that we use to send email.

Right-click the project node and select New --> Java Class
A wizard like the following appears, fill in the appropriate details as
Class Name : Mail
Package Name : jMail


Mail.java class open up in the editor.
Add the following instance variables to the bean:
String to;
String from;
String message;
String subject;
String smtpServ;

Generate the getter, setter methods for them by right-clicking in the editor and select Refactor --> Encapsulate Fields. Then check all the setter and getter methods and click Refactor so that NetBeans 6.1 generates code for them.

 

It is here, we make use of the JavaMail API and send mail using the following code. But before doing that, import the required packages.
import javax.mail.*;
import javax.mail.internet*;
import java.util.*;

Now, as you has already noticed, NetBeans is showing errors showing that it doesn't know of javax.mail package even if you have correctly downloaded and installed the JAF and JavaMail API. To make NetBeans aware of the existence of these packages, perform the following steps:
Right click the project node (JavaMail), click to Properties to change properties of the project
Now go to Libraries Tab. (since we need to add jar files to our project)


Click on Add JAR/Folder Button. A window opens up.
Browse to the location where you have installed/unzipped your JavaMail API and then include

  • activation.jar
  • pop3.jar
  • mail.jar
  • mailapi.jar
  • smtp.jar 

If you do not perform this step, then NetBeans will not recognize JAF and JavaMail classes and hence will not compile the program given below which makes use of classes such as Message, Session, Transport etc.
Compile your program to check whether you have been able to successfully include these jar files or not.

Now, the main function sendMail( ), which is actually responsible for sending mail:
public int sendMail(){
        try
        {
            Properties props = System.getProperties();
              // -- Attaching to default Session, or we could start a new one --
              props.put("mail.transport.protocol", "smtp" );
              props.put("mail.smtp.starttls.enable","true" );
              props.put("mail.smtp.host",smtpServ);
              props.put("mail.smtp.auth", "true" );
              Authenticator auth = new SMTPAuthenticator();
              Session session = Session.getInstance(props, auth);
              // -- Create a new message --
              Message msg = new MimeMessage(session);
              // -- Set the FROM and TO fields --
              msg.setFrom(new InternetAddress(from));
              msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
              msg.setSubject(subject);
              msg.setText(message);
              // -- Set some other header information --
              msg.setHeader("MyMail", "Mr. XYZ" );
              msg.setSentDate(new Date());
              // -- Send the message --
              Transport.send(msg);
              System.out.println("Message sent to"+to+" OK." );
              return 0;
        }
        catch (Exception ex)
        {
          ex.printStackTrace();
          System.out.println("Exception "+ex);
          return -1;
        }
  }

// Also include an inner class that is used for authentication purposes

private class SMTPAuthenticator extends javax.mail.Authenticator {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            String username =  "Java.Mail.CA@gmail.com";           // specify your email id here (sender's email id)
            String password = "javamail";                                      // specify your password here
            return new PasswordAuthentication(username, password);
        }
  }

Save the file and compile it.
Now add another JSP, name it sendMail.jsp
Add the following code to it that instantiates JavaBean Object and set properties of JavaBean using the parameters passed to it using index.jsp
<jsp:useBean id="mail" scope="session" class="jMail.Mail" />
<jsp:setProperty name="mail" property="to" value="to" />
<jsp:setProperty name="mail" property="from" value="Java.Mail.CA@gmail.com" />
<jsp:setProperty name="mail" property="smtpServ" value="smtp.gmail.com" />
<jsp:setProperty name="mail" property="subject" param="subject" />
<jsp:setProperty name="mail" property="message" param="message" />

The main point to note here is the value of smtpServ that we have passed. Here, we are using a gmail id, so its smtp server name should be used, which is "smtp.gmail.com". If you want to use your own email id, then you have to make few changes as specified above and also change the value of smtpServ property to your smtp server name.
Add the following code to sendMail.jsp that calls the sendMail() method of the bean. Yes, a bean can have other methods except getter and setter methods. Its perfectly legal. :-)

 <%
String to = mail.getTo();
int result;
result = mail.sendMail();
if(result == 0){
    out.println(" Mail Successfully Sent to "+to);
}
else{
    out.println(" Mail NOT Sent to "+to);
}  
%>

       
Save your project and Run it to see that it actually works :-)
The whole project is available here for download. 

Notes:
There is much to JavaMail than what is mentioned here. For more read on
JavaMail & Glassfish
Read the following links to understand what's actually happening in the code given above
JavaMail Quick Start
jGuru : Fundamentals of JavaMail API

Related & Advanced :
Creating JavaMail Client On NB

Please do not modify the password for the account Java.Mail.CA@gmail.com I created it only for demo purposes and have given out the account details as on all tutorials/demos about JavaMail that i have seen online leave these fields empty and also leave smtp server name fields empty, which only adds to confusion for novices.
Any comments, suggestions and corrections are welcome.       


Friday May 02, 2008

I have been bugged with this question many a times so finally i have decided to write a small blog entry on the same. :-)

An Application Server (like Glassfish) is more sophisticated and complex (read intelligent) when compared with a Web Server (like Tomcat). A Web server is based on HTTP request-response model and generally acts as a web container for JSP's and Servlets. You give it a request and back comes the reply.

On the other hand, an Application Server can be used to serve business logic to applications programs, generally in a n-tier architecture (n>2), through any number of protocols (HTTP, HTTPS, IIOS/SSL). It is this capability of an appserver to cater the needs of a separate business layer in a 3-tier architecture through a component API (like EJB's) that makes enterprise level applications far more scalable. By separating the business logic from presentation layer, we make the business logic reusable between and within applications. Moreover, an application server manages its own resources. It takes care of other important issues like Transaction Management, Security, Database Connection Pooling, Clustering, Scalability and Messaging etc. A web server cannot provide these.

An Application server like Glassfish also provides the administrator with something known as Glassfish Admin Console, using which he/she can easily manage and utilize various resources like Connection Pools, JavaMail Sessions. More on this coming up soon.

Generally, all application servers contain a web server in them or you can say that a web server is a small subset of what comprises of an Application Server. Generally, all application server comes with two types of containers:

  • Web Container
  • EJB(Enterprise JavaBeans) Container

Difference b/w Glassfish & Tomcat in Arun Gupta's words,

- Tomcat is only a JSP/Servlet container. Everything else such as Web services, all the "Web 2.0" style processing, etc need to be installed in the container. Because it's only JSP/Servlet container, it's light-weight.
- Glassfish is a full Java EE 5 compliant App server. JSP/Servlet is just one component of Java EE 5, then there is Enterprise Java Beans, Web services, XML Binding, Security, Reliability, Transactions, Clustering, High Availability, Fault Tolerance and such enterprise features. GlassFish comes pre-bundled and pre-configured to handled those. In case of Tomcat, you need to install additional software for each of these components.

As a matter of fact, i'm an avid follower of Glassfish and strongly recommend Glassfish to developers worldwide, various reasons pamper me to do so:

  • It is Open Source
  • It's supported, maintained & developed by Sun Microsystems and others too.
  • It is fully Java EE 5 compliant and any new technology as and when introduced (even in future), GF will support that also.