Tuesday, January 10, 2012

Outlook Meeting Mail in Java

MimetypesFileTypeMap mimetypes = (MimetypesFileTypeMap)MimetypesFileTypeMap.getDefaultFileTypeMap();
mimetypes.addMimeTypes("text/calendar ics ICS");
//register the handling of text/calendar mime type
MailcapCommandMap mailcap = (MailcapCommandMap) MailcapCommandMap.getDefaultCommandMap();
mailcap.addMailcap("text/calendar;; x-java-content-handler=com.sun.mail.handlers.text_plain");
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setSubject(subject);
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

// Create an alternative Multipart
Multipart multipart = new MimeMultipart("alternative");
//part 1, html text
BodyPart messageBodyPart = buildHtmlTextPart();
multipart.addBodyPart(messageBodyPart);
// Add part two, the calendar
BodyPart calendarPart = buildCalendarPart();
multipart.addBodyPart(calendarPart);
//Put the multipart in message
message.setContent(multipart);

// send the message
Transport transport = session.getTransport("smtp");
transport.connect();
transport.sendMessage(message, message.getAllRecipients());
transport.close();


private BodyPart buildHtmlTextPart() throws MessagingException {

MimeBodyPart descriptionPart = new MimeBodyPart();

//Note: even if the content is spcified as being text/html, outlook won't read correctly tables at all
// and only some properties from div:s. Thus, try to avoid too fancy content
String content = "simple meeting invitation";
descriptionPart.setContent(content, "text/html; charset=utf-8");

return descriptionPart;
}

//define somewhere the icalendar date format
private static SimpleDateFormat iCalendarDateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmm'00'");

private BodyPart buildCalendarPart() throws Exception {

BodyPart calendarPart = new MimeBodyPart();

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, 1);
Date start = cal.getTime();
cal.add(Calendar.HOUR_OF_DAY, 3);
Date end = cal.getTime();

//check the icalendar spec in order to build a more complicated meeting request
String calendarContent =
"BEGIN:VCALENDAR\n" +
"METHOD:REQUEST\n" +
"PRODID: BCP - Meeting\n" +
"VERSION:2.0\n" +
"BEGIN:VEVENT\n" +
"DTSTAMP:" + iCalendarDateFormat.format(start) + "\n" +
"DTSTART:" + iCalendarDateFormat.format(start)+ "\n" +
"DTEND:" + iCalendarDateFormat.format(end)+ "\n" +
"SUMMARY:test request\n" +
"UID:324\n" +
"ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:organizer@yahoo.com\n" +
"ORGANIZER:MAILTO:organizer@yahoo.com\n" +
"LOCATION:on the net\n" +
"DESCRIPTION:learn some stuff\n" +
"SEQUENCE:0\n" +
"PRIORITY:5\n" +
"CLASS:PUBLIC\n" +
"STATUS:CONFIRMED\n" +
"TRANSP:OPAQUE\n" +
"BEGIN:VALARM\n" +
"ACTION:DISPLAY\n" +
"DESCRIPTION:REMINDER\n" +
"TRIGGER;RELATED=START:-PT00H15M00S\n" +
"END:VALARM\n" +
"END:VEVENT\n" +
"END:VCALENDAR";

calendarPart.addHeader("Content-Class", "urn:content-classes:calendarmessage");
calendarPart.setContent(calendarContent, "text/calendar;method=CANCEL");

return calendarPart;
}

Tuesday, February 8, 2011

Spring Controller-simple Controller

Controller
SimpleFormController

To handle forms in Spring you need to extend your controller class from SimpleFormController class. Here we will create a user registration form to understand how this works. The SimpleFormController is deprecated as of Spring 3.0 so if you are using Spring 3.0 or above use the annotate controllers instead.

package com.vaannila.web;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.vaannila.domain.User;
import com.vaannila.service.UserService;

@SuppressWarnings("deprecation")
public class UserController extends SimpleFormController {

private UserService userService;
public UserController() {
setCommandClass(User.class);
setCommandName("user");
}

public void setUserService(UserService userService) {
this.userService = userService;
}

@Override
protected ModelAndView onSubmit(Object command) throws Exception {
User user = (User) command;
userService.add(user);
return new ModelAndView("userSuccess","user",user);
}

}
I am using Spring 3.0 so you see the SuppressWarnings annotation there. Here we extend the UserController from SimpleFormController, this makes the controller class capable of handling forms. Usually a form will be associated with a particular domain object, in our case it is the User class. In Spring this domain object is called command object by default. To refer the command object in the jsp page you need to set the command class using the setCommandClass() method in the constructor. Let say the User class has a name property, and to refer this in the jsp page you will use "command.name". You can also change this name by using the setCommandName() method. Here we set the name to user, so to access the user name in the jsp page we use "user.name".
You need to have a method to handle the form when the form is submitted, here the onSubmit() method is used for this purpose. The onSubmit() method has access to the command object, we first typecast the command object to User (our domain object) and then to register the user we call the add() method of the service class and finally return the ModelandView object.
All the forms field values will be submitted as Strings to the form controller. Spring has several pre registered property editors to convert the String values to common data types. Incase you have a custom data type you need to create custom property editors to handle them.
The User domain object has the following attributes.

package com.vaannila.domain;
public class User {

private String name;
private String password;
private String gender;
private String country;
private String aboutYou;
private String[] community;
private Boolean mailingList;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getAboutYou() {
return aboutYou;
}
public void setAboutYou(String aboutYou) {
this.aboutYou = aboutYou;
}
public String[] getCommunity() {
return community;
}
public void setCommunity(String[] community) {
this.community = community;
}
public Boolean getMailingList() {
return mailingList;
}
public void setMailingList(Boolean mailingList) {
this.mailingList = mailingList;
}


}
Our User Service interface.
package com.vaannila.service;

import com.vaannila.domain.User;

public interface UserService {

public void add(User user);
}
Our User Service Implementation class.
package com.vaannila.service;

import com.vaannila.domain.User;

public class UserServiceImpl implements UserService {

@Override
public void add(User user) {
//Persist the user object here.
System.out.println("User added successfully");

}

}
Let's now create the user registration form using the Spring form tags. To use the form tags you need to first import the Spring's form tag library.
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>


Registration Page



09.10.
User Name :
Password :
Gender :
Country :
About you :
Community :



Here the path attribute is used to bind the form fields to the domain object. Here we use the HTTP POST method to submit the form. Inorder to bind the form fields to the domain object successfully the command object should be set to the same name in the jsp page and the controller class. To set the command object name in the jsp page, use the commandName attribute of the form tag.
The web.xml file.


SpringExample6

dispatcher
org.springframework.web.servlet. DispatcherServlet

1


dispatcher
*.htm


redirect.jsp


Next create the Spring Bean Configuration file.








As you can see, we use "p" namespace here. The "p" namespace is simple and easy to use. Using "p" namespace the properties can be supplied using attributes, rather than elements.
For injecting the simple types we use property name in the "p" namespace and for injecting references we add "-ref" suffix to it. For example we use p:formView for injecting the form view property and p:userService-ref for injecting the user service.
During the HTTP GET request the formView will be rendered. When the form is submitted (during the HTTP POST request) the onSubmit() method of the UserController class will be called, on successful execution of the method the successView will be rendered. Incase of any type conversion errors or validation errors the formView will be automatically displayed the user.
Run the example by executing the redirect.jsp file. The redirect.jsp file, redirect the request to "userRegistration.htm".
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<% response.sendRedirect("userRegistration.htm"); %>
The following user registration page will be displayed.

Fill the form and submit it.

The onSubmit() method of the UserController class will be called and the control will be transfered to the view "userSuccess". We use InternalResourceViewResolver here, so the userSuccess.jsp page will be dispalyed. In the userSuccess.jsp page we dispaly all the user details using the jstl tags.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>


Success Page


User Details

User Name : ${user.name}

Gender : ${user.gender}

Country : ${user.country}

About You : ${user.aboutYou}

Community : ${user.community[0]} ${user.community[1]} ${user.community[2]}

Mailing List: ${user.mailingList}


The userSuccess.jsp page.

Spring IOC step-by-steps


1.     IOC

Inversion of Control or IoC is one of the techniques used to wire services or components to an application program. By definition, IoC is “A software design pattern and set of associated programming techniques in which the flow of control of a system is inverted in comparison to the traditional interaction mode.” Simply stated, in IoC, instead of an application calling the framework, it is the framework that calls the components specified by the application.
This approach is similar to the one that Hollywood agents adopt with their clients. It is sometimes known as “Don’t call me, I will call you.” This is why IoC is also known as the Hollywood approach.
However, IOC is a broad and generic term. The aspect of IoC that the Spring Framework uses is "Injection of required resources or dependency at Run-time into the dependent resource," which is also known as Dependency Injection. Hence, the service provided by the IoC container of Spring is Dependency Injection. Therefore, I will be using the terms IoC and Dependency Injection in a lax way.
There are three forms or styles of Dependency Injection. They are:
1.      Constructor Injection
2.      Setter Injection
3.      Interface Injection
Of these, the Spring Framework directly supports the first and second forms whereas the third form is supported indirectly. Between the first and the second, the Spring Framework prefers the use of second rather than the first. Here are the details.
1.1  Constructor Injection: In Constructor Injection, an IoC container uses the constructor to inject the dependency. All the dependencies, whether they are simple values or references to other objects, are declared in the constructor. One of the advantages of Constructor Injection is that all the dependencies are declared in one go. This also helps in understanding whether the class depends on too many services.
   <constructor-arg index="0" type="java.lang.String" value="MyName"/>

The above code is an example for how to pass dependency arguments to the constructor. Index attribute is useful when you have multiple arguments with the same type, you can inform the IOC container about the order of the arguments. You can pass bean reference using the ref element.

Employee.java
package javabeat.net.spring.ioc;

/**
 * Source : http://www.javabeat.net
 */
public class Employee {
    private String name;
    private String empId;
    private Address address;
    public Employee(String name, String empId, Address address){
        this.name = name;
        this.empId = empId;
        this.address = address;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }
    public String getEmpId() {
        return empId;
    }
    public void setEmpId(String empId) {
        this.empId = empId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }   
}
Address.java
package javabeat.net.spring.ioc;
/**
 * Source : http://www.javabeat.net
 */

public class Address {
    public Address(){

    }
    private String street;
    private String city;
    private String pincode;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getPincode() {
        return pincode;
    }

    public void setPincode(String pincode) {
        this.pincode = pincode;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }
}



ConstructorInjection.java
package javabeat.net.spring.ioc;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

/**
 * source : www.javabeat.net
 */
public class ConstructorInjection {
    public static void main(String args[]){
        Resource xmlResource = new FileSystemResource("applicationContext.xml");
        BeanFactory factory = new XmlBeanFactory(xmlResource);
        Employee employee = (Employee)factory.getBean("employeeBean");
        Address address = employee.getAddress();
        System.out.println(employee.getName());
        System.out.println(employee.getEmpId());
        System.out.println(address.getCity());
        System.out.println(address.getStreet());
        System.out.println(address.getPincode());       
    }}

applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
    <bean id="addressBean" class="javabeat.net.spring.ioc.Address">
        <property name="street">
            <value>Street</value>
        </property>
        <property name="city">
            <value>Bangalore</value>
        </property>
        <property name="pincode">
            <value>567456</value>
        </property>
    </bean>
    <bean id="employeeBean" class="javabeat.net.spring.ioc.Employee">
        <constructor-arg index="0" type="java.lang.String" value="MyName"/>
        <constructor-arg index="1" type="java.lang.String" value="001"/>
        <constructor-arg index="2">
            <ref bean="addressBean"/>
        </constructor-arg>
    </bean>
</beans>

1.2   Setter Injection: This form of Dependency Injection uses Setters, also known as mutators (because they change the value of the corresponding instance variables), to inject the required resources or dependencies. In other words, each of the objects that the class depends upon will have a setter and the IOC container will use the setters to provide the resource at run-time.

The main difference between Constructor Injection and Setter Injection is that in Constructor Injection, the handing over of the dependencies takes place during instantiation of the dependent object, whereas with Setter Injection, it takes place after the dependent object is instantiated. The Spring Framework favors Setter Injection over Constructor Injection.


Employee.java
package javabeat.net.spring.ioc;

/**
 *
Source : http://www.javabeat.net
 */

public class Employee {
    private String name;
    private String empId;
    private Address address;
    public Employee(){
    }

    public Address getAddress() {
       
return address;
    }
    public void setAddress(Address address) {
        this.address = address;
   }

    public String getEmpId() {
        return empId;
    }

    public void setEmpId(String empId) {
        this.empId = empId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }   
}
Address.java

package javabeat.net.spring.ioc;
/**
 * Source : http://www.javabeat.net
 */

public class Address {
    public Address(){

    }
    private String street;
    private String city;
    private String pincode;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getPincode() {
        return pincode;
    }

    public void setPincode(String pincode) {
        this.pincode = pincode;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

}


ConstructorInjection.java

package javabeat.net.spring.ioc;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

/**
 * source : www.javabeat.net
 */
public class ConstructorInjection {
    public static void main(String args[]){
        Resource xmlResource = new FileSystemResource("applicationContext.xml");
        BeanFactory factory = new XmlBeanFactory(xmlResource);
        Employee employee = (Employee)factory.getBean("employeeBean");
        Address address = employee.getAddress();
        System.out.println(employee.getName());
        System.out.println(employee.getEmpId());
        System.out.println(address.getCity());
        System.out.println(address.getStreet());
        System.out.println(address.getPincode());       
    }}

applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
    <bean id="addressBean" class="javabeat.net.spring.ioc.Address">
        <property name="street">
            <value>Street</value>
        </property>
        <property name="city">
            <value>Bangalore</value>
        </property>
        <property name="pincode">
            <value>567456</value>
        </property>
    </bean>
    <bean id="employeeBean" class="javabeat.net.spring.ioc.Employee">
        <property name="name" value="MyName"/>
        <property name="empId"  value="001"/>
        <property name="address" ref="addressBean"/>
    </bean>
</beans>

Note: 
The Following Jar files are needed to run the Above Code:
1.       commons-logging-1.0.4.jar
2.       org.springframework.beans-3.0.1.jar
3.       org.springframework.core-3.0.1.jar
Interface Injection provides the concrete implementations of an interface to the dependent object according to the configuration. The main difference between Interface Injection and the previous two is that in Interface Injection, any of the implementations of the interface can be injected, whereas with the other two, the object of the class specified is injected.

Note: Spring does not provide direct support for Interface Injection, Instead of that we can  use Auto Wiring.