Saturday, 29 April 2017

Send jFreeChart to jsp page

In my previous post, I explained how to send jfreeChart as servlet response. In this post, I am going to explain how to send jFreeChart as response to jsp page.


Step 1: Create new dynamic web project ‘jFreeChartDemo’
Give the project name as ‘jFreeChartDemo’.

Press Next.

Press Next.

Select the check box ‘Generate web.xml deployment descriptor’.

Press Finish.

Step 2: Mavenize the project. Right click on the project ‘jFreeChartDemo’ -> Configure -> Convert To Maven project

Use the defaults and press Finish.

Step 2: Create new package ‘com.sample. Define Hello.java like below.

Hello.java
package com.sample;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;

public class Hello extends HttpServlet {

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  /*
          * Get the output stream from the response
          * object
          */
  try {
   DefaultCategoryDataset dataset = new DefaultCategoryDataset();
   dataset.addValue(500, "Company A Revenue", "2009");
   dataset.addValue(550, "Company A Revenue", "2010");
   dataset.addValue(450, "Company A Revenue", "2011");
   dataset.addValue(650, "Company A Revenue", "2012");
   dataset.addValue(550, "Company A Revenue", "2013");
   dataset.addValue(700, "Company A Revenue", "2014");

   dataset.addValue(200, "Company B Revenue", "2009");
   dataset.addValue(450, "Company B Revenue", "2010");
   dataset.addValue(398, "Company B Revenue", "2011");
   dataset.addValue(425, "Company B Revenue", "2012");
   dataset.addValue(770, "Company B Revenue", "2013");
   dataset.addValue(810, "Company B Revenue", "2014");

   /* create chart */
   JFreeChart chart = ChartFactory.createLineChart("", "Year", "Revenue in M$", dataset,
     PlotOrientation.VERTICAL, false, true, false);
   
   BufferedImage bufferedImage = chart.createBufferedImage(500, 500);
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   ImageIO.write(bufferedImage, "png", baos);
   baos.flush();
   byte[] imageInByte = baos.toByteArray();
   baos.close();
   
   request.setAttribute("image", imageInByte);
   
    request.getRequestDispatcher("/freeChart.jsp").forward(request, response);
  } catch (Exception e) {
   System.err
     .println(e.toString()); /* Throw exceptions to log files */
  } 
 }
}

Step 2: Define freeChart.jsp like below.


freeChart.jsp
<%@page import="java.io.*, javax.imageio.*, java.awt.image.*, javax.servlet.*, javax.servlet.http.*,org.jfree.chart.*, org.jfree.chart.plot.*, org.jfree.data.category.*"%>

<!DOCTYPE html>
<html>
<head>

<title>Insert title here</title>
</head>
<body>
 <%
   /* Set the HTTP Response Type */
   response.setContentType("image/png");
   
   byte[] imageInBytes = (byte[]) request.getAttribute("image");
   OutputStream outStream = response.getOutputStream();
   outStream.write(imageInBytes);
 %>

</body>
</html>

Update web.xml like below.


web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>jFreeChartDemo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
   <servlet>
        <servlet-name>Hello</servlet-name>
        <servlet-class>com.sample.Hello</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Hello</servlet-name>
        <url-pattern>/HelloWorld</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

Run the application on server and hit the url ‘http://localhost:8080/jFreeChartDemo/HelloWorld’.


You can able to see following output.









Previous                                                 Next                                                 Home

Spring: default-init-method & default-destroy-method Example

In my previous posts, I explained how to set the life cycle methods at bean level using init-method, destroy-method attributes. Suppose if you want to set the life cycle methods for all the beans at a time, you can do this by using the attributes default-init-method & default-destroy-method of beans element.

Example
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd"
         default-init-method="init" default-destroy-method="cleanup">
        
</beans>

You need to define the method init, cleanup in your application logic. Spring container call these methods on bean creation and destroy time. Following is the complete working application.

LifeCycleService.java
package com.sample.pojo;

public interface LifeCycleService {
 public void init();
 
 public void cleanup();
}

Student.java
package com.sample.pojo;

public class Student implements LifeCycleService{
 private String name;
 private int id;
 
 public Student(){
  System.out.println("Student constructor called");
 }

 public String getName() {
  return name;
 }

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

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Student [name=").append(name).append(", id=").append(id).append("]");
  return builder.toString();
 }

 @Override
 public void init() {
  System.out.println(this + " is initialized");
 }

 @Override
 public void cleanup() {
  System.out.println(this + " is about to destroy");
 }
 
}

Author.java
package com.sample.pojo;

public class Author implements LifeCycleService {
 private String firstName;
 private String lastName;
 private String dateOfBirth;
 private String country;

 public Author() {
  System.out.println("Author Constructor called");
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getDateOfBirth() {
  return dateOfBirth;
 }

 public void setDateOfBirth(String dateOfBirth) {
  this.dateOfBirth = dateOfBirth;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Author [firstName=").append(firstName).append(", lastName=").append(lastName)
    .append(", dateOfBirth=").append(dateOfBirth).append(", country=").append(country).append("]");
  return builder.toString();
 }

 @Override
 public void init() {
  System.out.println(this + " is initialized");
 }

 @Override
 public void cleanup() {
  System.out.println(this + " is about to destroy");
 }

}

myConfiguration.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"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd"
 default-init-method="init" default-destroy-method="cleanup">

 <bean id="osho" class="com.sample.pojo.Author">
  <property name="firstName" value="Chandra Mohan" />
  <property name="lastName" value="Jain" />
  <property name="dateOfBirth" value="11 December 1931" />
  <property name="country" value="India" />
 </bean>

 <bean id="krishna" class="com.sample.pojo.Student">
  <property name="name" value="Hari krishna" />
  <property name="id" value="553" />
 </bean>

</beans>

HelloWorld.java
package com.sample.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sample.pojo.Author;
import com.sample.pojo.Student;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  Author osho = context.getBean("osho", Author.class);
  Student krishna = context.getBean("krishna", Student.class);

  System.out.println(osho);
  System.out.println(krishna);
  
  ((ClassPathXmlApplicationContext) context).close();
 }
}


Output
Author Constructor called
Author [firstName=Chandra Mohan, lastName=Jain, dateOfBirth=11 December 1931, country=India] is initialized
Student constructor called
Student [name=Hari krishna, id=553] is initialized
Author [firstName=Chandra Mohan, lastName=Jain, dateOfBirth=11 December 1931, country=India]
Student [name=Hari krishna, id=553]
Student [name=Hari krishna, id=553] is about to destroy
Author [firstName=Chandra Mohan, lastName=Jain, dateOfBirth=11 December 1931, country=India] is about to destroy







Previous                                                 Next                                                 Home

Wednesday, 26 April 2017

Spring: InitializingBean and DisposableBean example

Spring provides InitializingBean and DisposableBean interfaces to handle bean life cycle call backs.

InitializingBean interface
InitializingBean interface provides 'afterPropertiesSet' method, it is called by the bean factory after it has set all bean properties supplied.

DisposableBean interface
DisposableBean interface provides destroy method, it is called by a BeanFactory on destruction of a singleton bean.

Following is the complete working application.

Author.java
package com.sample.pojo;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class Author implements InitializingBean, DisposableBean {
 private String firstName;
 private String lastName;
 private String dateOfBirth;
 private String country;

 public Author() {
  System.out.println("Constructor called");
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getDateOfBirth() {
  return dateOfBirth;
 }

 public void setDateOfBirth(String dateOfBirth) {
  this.dateOfBirth = dateOfBirth;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Author [firstName=").append(firstName).append(", lastName=").append(lastName)
    .append(", dateOfBirth=").append(dateOfBirth).append(", country=").append(country).append("]");
  return builder.toString();
 }

 @Override
 public void afterPropertiesSet() throws Exception {
  System.out.println("\n**************************");
  System.out.println("Following properties are set to author bean");
  System.out.println("firstName : " + firstName);
  System.out.println("lastName : " + lastName);
  System.out.println("dateOfBirth : " + dateOfBirth);
  System.out.println("country : " + country);
  System.out.println("**************************\n");
 }

 @Override
 public void destroy() throws Exception {
  System.out.println("\n**************************");
  System.out.println("Destroying bean " + this);
  System.out.println("**************************");
 }

}

myConfiguration.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"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="osho" class="com.sample.pojo.Author">
  <property name="firstName" value="Chandra Mohan" />
  <property name="lastName" value="Jain" />
  <property name="dateOfBirth" value="11 December 1931" />
  <property name="country" value="India" />
 </bean>

</beans>

HelloWorld.java
package com.sample.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sample.pojo.Author;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  Author osho = context.getBean("osho", Author.class);

  System.out.println(osho);

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Output
Constructor called

**************************
Following properties are set to author bean
firstName : Chandra Mohan
lastName : Jain
dateOfBirth : 11 December 1931
country : India
**************************

Author [firstName=Chandra Mohan, lastName=Jain, dateOfBirth=11 December 1931, country=India]

**************************
Destroying bean Author [firstName=Chandra Mohan, lastName=Jain, dateOfBirth=11 December 1931, country=India]
**************************

Note
a. It is recommended that you do not use the InitializingBean interface because it unnecessarily couples the code to Spring. Alternatively, use the @PostConstruct annotation or specify a POJO initialization method. In the case of XML-based configuration metadata, you use the init-method attribute to specify the name of the method that has a void no-argument signature. With Java config, you use the initMethod attribute of @Bean.

public class Author {

         public void initCheck() {
                 System.out.println("\n**************************");
                 System.out.println("Following properties are set to author bean");
                 System.out.println("firstName : " + firstName);
                 System.out.println("lastName : " + lastName);
                 System.out.println("dateOfBirth : " + dateOfBirth);
                 System.out.println("country : " + country);
                 System.out.println("**************************\n");

         }

}

         <bean id="osho" class="com.sample.pojo.Author" init-method="initCheck">
                 <property name="firstName" value="Chandra Mohan" />
                 <property name="lastName" value="Jain" />
                 <property name="dateOfBirth" value="11 December 1931" />
                 <property name="country" value="India" />
         </bean>

Update Author.java, myConfiguration.xml like below.

Author.java
package com.sample.pojo;

public class Author {
 private String firstName;
 private String lastName;
 private String dateOfBirth;
 private String country;

 public Author() {
  System.out.println("Constructor called");
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getDateOfBirth() {
  return dateOfBirth;
 }

 public void setDateOfBirth(String dateOfBirth) {
  this.dateOfBirth = dateOfBirth;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Author [firstName=").append(firstName).append(", lastName=").append(lastName)
    .append(", dateOfBirth=").append(dateOfBirth).append(", country=").append(country).append("]");
  return builder.toString();
 }

 public void initCheck() {
  System.out.println("\n**************************");
  System.out.println("Following properties are set to author bean");
  System.out.println("firstName : " + firstName);
  System.out.println("lastName : " + lastName);
  System.out.println("dateOfBirth : " + dateOfBirth);
  System.out.println("country : " + country);
  System.out.println("**************************\n");

 }

}

myConfiguration.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"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="osho" class="com.sample.pojo.Author" init-method="initCheck">
  <property name="firstName" value="Chandra Mohan" />
  <property name="lastName" value="Jain" />
  <property name="dateOfBirth" value="11 December 1931" />
  <property name="country" value="India" />
 </bean>

</beans>


HelloWorld.java
package com.sample.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sample.pojo.Author;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  Author osho = context.getBean("osho", Author.class);

  System.out.println(osho);

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Output
Constructor called

**************************
Following properties are set to author bean
firstName : Chandra Mohan
lastName : Jain
dateOfBirth : 11 December 1931
country : India
**************************

Author [firstName=Chandra Mohan, lastName=Jain, dateOfBirth=11 December 1931, country=India]

b. It is recommended that you do not use the DisposableBean callback interface because it unnecessarily couples the code to Spring. Alternatively, use the @PreDestroy annotation or specify a generic method that is supported by bean definitions. With XML-based configuration metadata, you use the destroy-method attribute on the <bean/>. With Java config, you use the destroyMethod attribute of @Bean.
public class Author {

         public void cleanup() {
                 System.out.println("\n**************************");
                 System.out.println("Cleaning up the bean " + this);
                 System.out.println("**************************\n");
         }

}

         <bean id="osho" class="com.sample.pojo.Author" destroy-method="cleanup">
                 <property name="firstName" value="Chandra Mohan" />
                 <property name="lastName" value="Jain" />
                 <property name="dateOfBirth" value="11 December 1931" />
                 <property name="country" value="India" />
         </bean>

Author.java
package com.sample.pojo;

public class Author {
 private String firstName;
 private String lastName;
 private String dateOfBirth;
 private String country;

 public Author() {
  System.out.println("Constructor called");
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getDateOfBirth() {
  return dateOfBirth;
 }

 public void setDateOfBirth(String dateOfBirth) {
  this.dateOfBirth = dateOfBirth;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Author [firstName=").append(firstName).append(", lastName=").append(lastName)
    .append(", dateOfBirth=").append(dateOfBirth).append(", country=").append(country).append("]");
  return builder.toString();
 }

 public void cleanup() {
  System.out.println("\n**************************");
  System.out.println("Cleaning up the bean " + this);
  System.out.println("**************************\n");
 }

}

myConfiguration.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"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="osho" class="com.sample.pojo.Author" destroy-method="cleanup">
  <property name="firstName" value="Chandra Mohan" />
  <property name="lastName" value="Jain" />
  <property name="dateOfBirth" value="11 December 1931" />
  <property name="country" value="India" />
 </bean>

</beans>

HelloWorld.java
package com.sample.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sample.pojo.Author;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  Author osho = context.getBean("osho", Author.class);

  System.out.println(osho);

  ((ClassPathXmlApplicationContext) context).close();
 }
}


Output
Constructor called
Author [firstName=Chandra Mohan, lastName=Jain, dateOfBirth=11 December 1931, country=India]

**************************
Cleaning up the bean Author [firstName=Chandra Mohan, lastName=Jain, dateOfBirth=11 December 1931, country=India]
**************************


Previous                                                 Next                                                 Home