Sending E-mail Using Google SMTP and JBoss AS 7

If you don’t have your own SMTP server, you can use Google’s in a pinch. This tutorial will show you how to do that using JBoss AS 7.

First, we will need to configure a mail session. Stop JBoss if it is running. Open JBOSS/standalone/configuration/standalone.xml. Search for smtp. You will see a sample mail session defined like this:

<mail-session jndi-name="java:jboss/mail/Default">
  <smtp-server outbound-socket-binding-ref="mail-smtp"/>
</mail-session>

Change it like this. I have highlighted the relevant changes.

<mail-session jndi-name="java:jboss/mail/Default">
 <smtp-server ssl="true" outbound-socket-binding-ref="mail-smtp">
  <login name="your_google_user_id@gmail.com" password="your_google_password"/>
 </smtp-server>
</mail-session>

Basically, you are enabling SSL and entering your Google account information.

Keep searching for smtp and you will see how the SMTP server address is defined.

<outbound-socket-binding name="mail-smtp">
 <remote-destination host="localhost" port="25"/>
</outbound-socket-binding>

Change it as follows.

<outbound-socket-binding name="mail-smtp">
 <remote-destination host="smtp.gmail.com" port="465"/>
</outbound-socket-binding>

Save changes. Start the server.

Write a small Servlet to test things out. Of course, use valid e-mail addresses.

import java.io.IOException;
import java.io.PrintWriter;
import javax.annotation.Resource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/MailTest")
public class MailTest extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Resource(lookup = "java:jboss/mail/Default")
    private Session mailSession;

    public void service(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
        PrintWriter out = res.getWriter();
        try {
            MimeMessage m = new MimeMessage(mailSession);
            Address from = new InternetAddress("bibhas@monkeyman.com");
            Address[] to = new InternetAddress[] { new InternetAddress(
                "bibhas@example.com") };
            m.setFrom(from);
            m.setRecipients(Message.RecipientType.TO, to);
            m.setSubject("Google JavaMail Test");
            m.setContent("Test from inside JBoss AS7 Server", "text/plain");
            Transport.send(m);

            out.println("Mail Sent Successfully.");
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace(out);
        }
    }
}

Note, Google will ignore the from address set in the code and always use your account as the from field.

Spring DI and CDI Comparative Study

This article shows how to perform basic Dependency Injection (DI) using Spring 3.2 and Context and Dependency Injection (CDI) of Java EE 6. Basically, this will help someone quickly learn one of the technologies when she knows the other.

Note: For Spring, we assume that the application is Spring MVC based. Also, for the sake of brevity I don’t create interfaces for Spring beans.

Basic Setup

For CDI, a file called beans.xml must be present in WEB-INF folder of a WAR file or META-INF folder of a JAR file. The file may be completely empty. If this file is absent, CDI is disabled at runtime. This is a common rookie mistake.

In a Spring MVC application, specify the location of the configuration file in web.xml as a part of the Spring dispatcher servlet definition. It is common to break up configuration in multiple files. For example:

<servlet>
<servlet-name>spring-servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>/WEB-INF/spring-mvc.xml,/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

To enable annotation based DI, the configuration file must specify the Java packages that will be scanned for injection points. You need to specify the parent package only. Spring will scan all child packages. For example:

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context" ...>
  <context:component-scan base-package="com.my.spring,com.other.package"/>
</beans>

In contrast, CDI will scan all classes at deployment time for injection points. Both will undeploy the application if an injection point can not be resolved for whatever reason.

Defining a Managed Bean

A bean must be managed by a DI container for all the magic (like injection and method interception) to happen.

In CDI, any POJO class can be managed without any modification. For example:

public class MyClass {
    public void doIt() {
    }
}

Use the @Named annotation only if you must give the class an EL name. This is something we need to do for JSF controllers so that we can refer to it from a XHTML view file.

@Named
public class MyClass {
    public void doIt() {
    }
}

In addition to above, a few classes are implicitly managed:

  • All EJB business classes (annotated with @Stateless, @Stateful etc) are also managed beans without the need to use the @Named annotation.
  • JSF controller classes can be annotated with either @Named or @ManagedBean. In either case, they are managed by CDI.
  • Servlets are implicitly managed by CDI.

In Spring, use @Component or one of its derivatives like @Controller, @Service and @Repository to make a class managed by DI. It is recommended that you use the appropriate specialized annotations for added benefits. For example, for a Spring MVC controller, use @Controller. Example:

@Controller
public class MyClass{
}

@Component
public class AnotherClass {
}

Injecting a Managed Bean

For both Spring and CDI, the class where injection is performed must itself be a managed bean. In other words, both the bean being injected and the bean receiving the injection are managed beans.

In CDI, use @Inject to perform injection (define an injection point).

@Named
public class MyClass {
  @Inject
  AnotherClass obj;
}

public class AnotherClass {
}

In the example above, we used @Named with MyClass because we intend to use it as a JSF controller. Where as, AnotherClass has no special decoration and can still be managed and injected by CDI.

In addition to @Inject, you can use @EJB to inject EJB and @Resource to inject resources like data source. @EJB and @Resource become necessary when you must refer to the injected item by some kind of a string name.

In Spring, use the @Autowired annotation to define an injection point.

@Controller
public class MyClass {
  @Autowired
  AnotherClass obj;
}

@Component
public class AnotherClass{
}

What is described above is field level injection. Instances can be injected in many other places, like in method parameter and constructor. We will not discuss them here.

Bean Lifecycle Events

Both Spring and CDI use the @PostConstruct and @PreDestroy annotations to mark lifecycle callback methods. A @PostConstruct method is called after all the injection points have been satisfied. This happens sometime after the costructor and as a result a better place to perform initialization than the constructor. @PreDestroy is called when a bean’s scope is about to be destroyed. For example, if a bean is in session scope and the session is about to expire.

CDI example:

public class AnotherClass{
    @PostConstruct
    public void init() {
    }
}

Spring Example:

@Component
public class AnotherClass{
    @PostConstruct
    public void init() {
    }
}

Bean Scope

In CDI, you can put a bean in dependent, request, conversation, session, and application scopes. The default is dependent scope (except JSF controllers are in request scope by default). With dependent scope, a new instance is created to satisfy every injection point. The remaining scopes have a larger lifespan. For example a bean in session scope is created only once per user session. The bean is destroyed when the session expires. CDI provides an annotation for each scope. For example, the following sets the scope of a managed bean to request.

@Named
@RequestScoped
public class AnotherClass {
}

CDI gives complete flexibility about mixing of scopes. That means, a bean of any scope can inject another bean in any other scope. For example, a session scoped bean can inject a request scoped bean.

@Named
@SessionScoped
public class MyClass {
    @Inject
    AnotherClass obj;
}

Spring works in a very similar way. But, be aware of subtle differences. First, let’s map the CDI scopes with Spring.

CDI Scope            Spring Scope
=================================
Dependent (default)  Prototype
Request              Request
Conversation         (No equivalent exists)
Session              Session
Application          Singleton (default)

The default scope in Spring is singleton.

Spring provides the @Scope annotation to set the scope of a bean. But, it’s usage is less straightforward and you need to be aware of a few things. The scope of a @Controller is fixed as a singleton and you can’t change it. A single instance of a controller is used to serve all requests from any user. So, be aware of thread safety and information leakage across users.

Spring supports mixing of scopes. For example, a controller that is always a singleton can inject a request scoped bean. But, this takes a little extra work.

@Controller
public class MyClass {
  @Autowired
  AnotherClass obj;
}
@Component
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = "request")
public class AnotherClass {
}

The extra work I was talking about is setting the proxyMode attribute. With proxy enabled, Spring wraps the actual bean instance in a dynamic proxy. This is necessary for injecting a bean with a shorter lifespan (request) in a longer lifespan (singleton) bean.

In the example above, the injected instance of AnotherClass is created in the request scope. As a result, it is safe as a member variable of the controller which itself is a singleton. This is not your usual Java programming and takes a little getting used to. The same magic happens in CDI, which uses proxy in all cases, except for dependent scope. Basically, with a proxy, a bean is instantiated lazily on demand. Consider a method of the controller:

@Controller
public class MyClass {
  @Autowired
  AnotherClass obj;

  public String doIt() {
      System.out.println("Controller doing it");
      obj.doSomething(); //Injected instance created here
  }
}

An instance of AnotherClass is created very late just prior to calling the doSomething() method. Once again, this instance is created in request scope and completely distinct for every request. So, the code above is completely safe without any worry for thread safety or information leakage between users. The principles are exactly the same for CDI. Except, there, proxy is always used and there is no need to set a proxyMode type flag anywhere.

Proxy mode does not need to be set when a bean injects another bean that has the same or longer lifespan. For example, a bean in request scope can inject a bean in session scope without setting the proxy.

@Component
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = "request")
public class AnotherClass {
    @Autowired
    ClassB obj;
}
@Component
@Scope(value = "session")
public class ClassB {
}

Alternative Bean Resolution

One of the biggest benefits of DI is that you can switch the implementation of a bean throughout an application without making mass changes. For example, we can switch a data access class that fetches data from a  SQL database to another class that uses Web Service. The basic mechanism is same for Spring and CDI. Your application contains multiple classes that are candidates for injection at an injection point. Then you use some kind of configuration to narrow down the choice to a single candidate.

There are several ways of doing alternative bean resolution in CDI. One way is to disable a non-candidate bean using @Alternative.

public interface MyService {
	public void doIt();
}

@Alternative //Disable this class
public class ServiceA implements MyService {
    @Override
    public void doIt() {
    }
}

public class ServiceB implements MyService {
    @Override
    public void doIt() {
    }
}

@Named
public class HomeController {
	@Inject
	MyService obj; //ServiceB will be injected
}

In Spring, mark the preferred injection candidate with @Primary.

public interface MyService {
	public void doIt();
}

@Component
public class ServiceA implements MyService {
    @Override
    public void doIt() {
    }
}

@Primary
@Component
public class ServiceB implements MyService {
    @Override
    public void doIt() {
    }
}

@Controller
public class HomeController {
	@Autowired
	MyService obj; //ServiceB will be injected
}

Custom Bean Creation

By default, the DI container (Spring or CDI) is responsible for instantiating an injected bean instance. It uses the zero argument constructor to create the object. Some classes may not have a zero arg constructor or may need special initialization sequence. These beans can not be managed by the container. The solution is to provide one’s own bean creation routine.

In CDI, this is done using a producer method. A producer method returns an instance of a bean. It becomes the source of the bean at an injection point. To avoid ambiguity, we must declare the bean itself as an alternative.

@Alternative
public class Person {
  private String name;
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public Person(String name) {
    super();
    this.name = name;
  }
}

Then, we can define a producer class that acts as a factory.

public class PersonFactory {
  @Produces
  @RequestScoped
  public Person createPerson() {
    return new Person("Daffy Duck");
  }
}

Note, you can set the scope of the bean. Similarly, if you need to give the bean an EL name, you can use @Named.

The bean can be injected as usual:

@Named
public class MyClass {
    @Inject
    Person person;
}

Now, at the point of injection, the createPerson() method will be called. If we did not designate the Person class as an alternative, there will be two potential sources for the bean’s instance. This leads to ambiguity and error during deployment.

In Spring, if a bean is created by a factory class, there is no need to designate the bean class using @Component.

public class Person {
  private String name;
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public Person(String name) {
    super();
    this.name = name;
  }
}

The factory class and its producer method is declared as follows.

@Configuration
public class PersonFactory {
	@Bean
	@Scope(value = "request")
	public Person createPerson() {
		return new Person("Daffy Duck");
	}
}

Note, just as in CDI, you can set the scope with the producer method.

Summary

Spring and CDI are both very capable DI containers. As we have seen here, they work in a very similar manner. Unfortunately, bulk of Spring documentation still uses the old XML syntax. Finding information about annotation based processing is unusually difficult. Hopefully, this article will be useful for someone who want to do apples to apples comparison of the two technologies.

My Thoughts on Spring vs. Java EE6

The relationship between Spring and Java EE has aspects of real human drama. There is the powerful giant that refused innovation for years (J2EE). There is the contrarian crusader that wanted to set things right (Spring). Development shops abandoned J2EE ship in droves and took shelter with Spring. Then the giant woke up and changed its ways (Java EE6). And with that response, the world became much less black and white. What is the role of Spring now? How will it react to the new ground realities?

Answering these questions is not easy. Any kind of blanket statement about Spring or Java EE will be a folly. They are both collections of different frameworks and technologies. A far better conversation will involve analyzing these frameworks and technologies separately. This will give one a better picture about where Java EE 6 has done well and where Spring is still beating it.

Before I delve into the technical details, I must address the issue of human emotion, especially in relation to trust. It is a fact that people have been burnt by Java’s lack of innovation in the server space for far too long. Spring became a savior for them. People will not forget that so easily. Java EE 6 implementations (JBoss, WebSphere etc.) are more than a year old now. Spring continues to be very much in the hearts and minds of the developers. I make that statement based on two observations:

  1. Have a look at the job postings in Monster or Dice. A very large proportion of Java jobs require Spring experience.
  2. There has been a lot of innovation lately in the cloud space. None of the major Platform as a Service (PaaS) providers, like Amazon Beanstalk and Google App Engine, support Java EE 6. They all support Spring effortlessly. The fact that Spring works in the highly restrictive Google App Engine environment is nothing less than stunning.

The continued dominance of Spring, as I conclude by the end of this article, is largely due to emotional inertia and some technical advantages.

Let’s now have a look at the technical aspects of Spring and Java EE 6. I will limit this article to the areas where I can claim some expertise and experience. Even in those areas, I can not claim absolute knowledge. These are then, my personal opinions. They are open to correction based on your feedback and my own learning.

Dependency Injection (DI)

Context and Dependency Injection (CDI) feature of Java EE 6 has been very well put together. It is easy to learn and use. I think, for most common tasks, CDI is just as good a DI tool as Spring.

A down side of CDI is that it needs a full Java EE container. Technically, CDI will not work in plain Tomcat. Although, others have found simple workarounds to getting Weld working in Tomcat. Last time I checked, Weld is still not supported by Google App Engine.

Web Model View Controller (MVC) Framework

JavaServer Faces (JSF) is the official out-of-the box MVC framework in Java EE. JSF 2.0 has been a major improvement. Unfortunately, JSF is still a big mess. It is a fine framework for building a 90’s web site. But, a pain in the neck for building a modern HTML5 web site with complex Ajax interactions and SEO friendly URL. I will almost always suggest Spring MVC framework over JSF for most projects.

Time has come to completely rethink Java’s MVC strategy. My own Pink framework leverages all that is great about Java EE 6, like CDI and Bean Validation (JSR 303). It practically matches Spring MVC feature by feature. We need something similar out of the box from Java EE.

SOAP and RESTful Web Service

Java has done a tremendous job with JAX-WS and JAX-RS. I have used both extensively. Just like CDI, they are very well put together, easy to learn and use. At the same time, they support proper programming practices like contract first design.

I had a brief look at Spring-WS. I really fail to see why Spring even bothered to create this module. For all practical purposes, I will recommend using JAX-RS and JAX-WS.

Component Model

The preferred component model for Java EE is EJB. In the past, EJB had been cumbersome and pain to work with. A lot has changed since then. In Java EE 6, you can:

  1. Create EJBs right inside a web module. There is no need for a separate EJB module.
  2. Define local EJBs without any business interface.
  3. Lifecycle methods are completely optional.

In other words, EJBs are now just as easy to develop as Spring components. Spring documentation continues to say things like “The negatives of EJB in general are so great that this is not an attractive proposition”. Really? I can’t really agree to that. Neither can I agree that Spring’s transaction management is any better or worse than EJBs.

Runtime Environment

This is an area where Spring enjoys an undisputed advantage. Spring, in all it’s glory, will work in plain Tomcat, Google App Engine and Amazon Beanstalk. This includes, DI, JPA, transaction (local only) and the whole deal. Tomcat, GAE and the likes do not care much for Java EE certification. They live happily in a symbiotic relationship with Spring.

Unlike Spring, different Java EE specifications are implemented separately. For example, CDI comes from Weld, Bean Validation comes from Apache BVal, JPA from Open JPA and so on. Getting these to work together is a Herculean task. In fact, that is what the fine folks at TomEE are trying to do. It has taken a number of developers almost a year to put all the pieces together on top of Tomcat to create a full Java EE 6 web profile.

Summary and Conclusions

Spring has made tremendous contributions to the development community. One indirect contribution is the competition that it gave to Java EE. Java finally woke up and responded with Java EE 6. Unfortunately, one of the most critical pieces of Java EE – the MVC framework – remains deeply flawed. In all honesty, I will always steer my clients to frameworks like Spring MVC, Struts 2 and Stripes. The second advantage of Spring is its support for almost any web container, including the awkward ones like GAE. These two advantages will continue to cause Spring’s dominance in development projects.

Out of the two main disadvantages of Java EE 6, JSF 2.0 is more critical. Java badly needs a modern MVC framework. Startup companies avoid Java like plague. Enterprises prefer Spring MVC (based on what I have seen in the job listing sites).  If this gap is somehow filled, either from Java EE (which is highly unlikely at this time) or from third party (like my own Pink framework or something like Struts 2), then Java EE will pose a formidable challenge to Spring.

Page Templating Using JSP Custom Tag

Templating greatly simplifies management of layout of pages in a large site. Simply put, a template captures the page layout and defines content placeholder areas. Actual individual pages provide content for these placeholders. This has two advantages:

  1. Individual page files become very simple since they contain dynamic content only. Common items like, importing CSS files, scripts, header, footer, side-bar etc. are all isolated in the template file.
  2. If you change the page layout in the template file, the change is immediately reflected site wide for hundreds of pages.

Java has several templating tools. JSF comes with Facelet. You can also use Tiles. But, did you know that JSP now has built-in templating mechanism? Yes, that’s true. You get a fine templating engine hidden within the custom JSP tag mechanism. In this article, we will learn how to build templates using basic JSP.

Create the Template

A template is created as a custom tag. Each placeholder in the template is defined using an attribute. Here is a simple template. This is created as WEB-INF/tags/simple_layout.tag. (All custom tags in a web module go inside WEB-INF/tags and have .tag extension).

<!DOCTYPE html>
<%@tag description="Simple Template" pageEncoding="UTF-8"%>

<%@attribute name="title"%>
<%@attribute name="head_area" fragment="true" %>
<%@attribute name="body_area" fragment="true" %>

<html>
 <head>
 <title>${title}</title>
     <jsp:invoke fragment="head_area"/>
 </head>
 <body>
     <jsp:invoke fragment="body_area"/>
 </body>
</html>

In this template, we have defined three attributes for three content placeholders:

  1. title – This is a regular attribute. As its value, we can only supply simple text values or expressions that evaluate to text.
  2. head_area – This is a fragment attribute. We can supply any arbitrary HTML chunks as value of this placeholder.
  3. body_area – This is also a fragment attribute.

A regular attribute is rendered using EL, such as ${title} here. A fragment attribute is rendered using <jsp:invoke>.

Use the Template from a JSP

We can now provide content for the placehodlers from a JSP. Let’s say that we create a JSP called mypage.jsp as follows:

<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:simple_layout title="My page">

<jsp:attribute name="head_area">
  <script>
    function hello() {
        alert("Hello World");
    }
  </script>
</jsp:attribute>

<jsp:attribute name="body_area">
  <div>
    <button onclick="hello();">Hello There</button>
  </div>
</jsp:attribute>

</t:simple_layout>

When you execute the JSP, the following HTML markup will be generated.

<!DOCTYPE html>

<html>
<head>
<title>My page</title>
  <script>
    function hello() {
      alert("Hello World");
    }
  </script>
</head>
<body>
  <div>
    <button onclick="hello();">Hello There</button>
  </div>
</body>
</html>

Not all pages will have content to contribute for all placeholders. Which is OK, because, it is optional for JSPs to provide values for the attributes. For example, this page contributes nothing to the “head_area”.

<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:simple_layout title="My page">

<jsp:attribute name="body_area">
  <div>Hello World!</div>
</jsp:attribute>

</t:simple_layout>

You can make any attribute mandatory by setting required=”true”. For example: <%@attribute name=”body_area” fragment=”true” required=”true” %>. In this case, every JSP using the template must supply the body_area.

Uploading File Using XMLHttpRequest Level 2

This post will show how to do a file upload and show progress using XMLHttpRequest level 2 API. This is to gain fundamental understanding of the low level API only. In real life, I strongly recommend using a higher level API such as jQuery. For that, read my earlier article.

First, create the form:

<!DOCTYPE html>

<html>
<body>
<input type="file" id="fileInput"/>
<button onclick="startUpload();">Upload</button>
<br/>
<progress id="progressBar" max="100" value="0"/>

</body>
</html>

This create a very simple form with a file input, button and a progress bar.

image

. Pay attention to the DOCTYPE. We need that for HTML5.

Now, the script that does the upload:

<script>
function startUpload() {
    var fileInput = document.getElementById("fileInput");

    if (fileInput.files.length == 0) {
        alert("Please choose a file");
        return;
    }
    
    var progressBar = document.getElementById("progressBar");
    var xhr = new XMLHttpRequest();

    xhr.upload.onprogress = function(e) {
        var percentComplete = (e.loaded / e.total) * 100;
        progressBar.value = percentComplete;
    };

    xhr.onload = function() {
        if (xhr.status == 200) {
            alert("Sucess! Upload completed");
        } else {
            alert("Error! Upload failed");
        }
    };
    xhr.onerror = function() {
        alert("Error! Upload failed. Can not connect to server.");
    };
    
    progressBar.value = 0;
    xhr.open("POST", "ajax-upload", true);
    xhr.setRequestHeader("Content-Type", fileInput.files[0].type);
    xhr.send(fileInput.files[0]);
}
</script>

This will send the file contents as the body of the HTTP request. It is essential that you set the Content-Type header. Otherwise, some browsers will set it to “application/x-www-form-urlencoded”. The server will then treat the request body as form input parameter and will try to parse it. Which will fail.

The server side to read the file contents is easy. Here is a code snippet for a Java servlet.

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
  throws ... {
    InputStream is = request.getInputStream();
    //Read the file contents from the input stream
    byte buff[] = new byte[256];
    int len;

    while ((len = is.read(buff)) > 0) {
        //...
    }
}

When you upload the file, the progress bar should indicate the amount of data uploaded.

image