Saturday, March 30, 2013

What is difference between JDK,JRE and JVM

JVM is acronym for  Java Virtual machine,it is an  abstract machine which  provides the runtime environment in  which java bytecode can be executed.

JVMs are available  for many hardware and software platform (so JVM is platforms dependent).



JRE  is  java runtime environment . it is used to  provide  runtime environment. it is  the implementation of JVM.  it is physically exists.



JDK  is acronym of java development kit. it is physically exist.

ServletOutputStream Class in java

It is  an abstract class . which is provide stream to write binary data into the response

  ServletOutputStream fout = response.getOutputStream()



Example :   to down load video in jsp page


String url = request.getParameter("url");
    String title = request.getParameter("title");
    URL tU = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) tU.openConnection();
    String type = conn.getContentType();
    InputStream ins = conn.getInputStream();
    ServletOutputStream fout = response.getOutputStream();
    response.setContentType("mime/flv");
    response.setHeader("Content-disposition","attachment; filename=\""+title+".flv\"");
    byte[] outputByte = new byte[conn.getContentLength()];
    int bytesRead;
    int length = conn.getContentLength();
    int read = 0;
    while((bytesRead = ins.read(outputByte, 0, length)) != -1){
         //read += bytesRead;
         //System.out.println(read + " out of " + length);
         fout.write(outputByte, 0, bytesRead);
    }
     fout.flush();
     fout.close();
     out.clear(); // where out is a JspWriter
     out = pageContext.pushBody();
     response.getOutputStream().flush();



Friday, March 29, 2013

Create a 3D bar chart in JSP page using JFreeChart

This Example shows you how to create a 3D bar chart in jsp page using JFreeChart. Code given below creates a bar chart of scores of two teams in matches.
In the code given below we have extended class ApplicationFrame to create a frame and also pass a string value to the constructor of ApplicationFrame class by using super keyword that will be name of the created frame.

Methods used in this example are described below:
pack(): This method invokes the layout manager.

centerFrameOnScreen(): This method is used for the position of the frame in the middle of the screen.

setVisible(): This method is used for display frame on the screen.

createCategoryDataset(): This method is used to create the instance of CategoryDataset Interface and that contains a copy of the data in an array.

saveChartAsPNG(): This method is used to save chart in to png format.

jsp3Dbarchart.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
 
 
<%page  import="java.awt.*" %>
<%page  import="java.io.*" %>
<%page  import="org.jfree.chart.*" %>
<%page  import="org.jfree.chart.axis.*" %>
<%page  import="org.jfree.chart.entity.*" %>
<%page  import="org.jfree.chart.labels.*" %>
<%page  import="org.jfree.chart.plot.*" %>
<%page  import="org.jfree.chart.renderer.category.*" %>
<%page  import="org.jfree.chart.urls.*" %>
<%page  import="org.jfree.data.category.*" %>
<%page  import="org.jfree.data.general.*" %>

<%
  final double[][] data = new double[][]{
 {210300320265299},
 {200304201201340}
 };

 final CategoryDataset dataset =
   DatasetUtilities.createCategoryDataset
("Team """, data);

 JFreeChart chart = null;
 BarRenderer renderer3D = null;
 CategoryPlot plot = null;


 final CategoryAxis3D categoryAxis = new CategoryAxis3D("Match");
 final ValueAxis valueAxis = new NumberAxis3D("Run");
 renderer3D = new BarRenderer3D();

 plot = new CategoryPlot(dataset, categoryAxis, valueAxis, renderer3D);
 plot.setOrientation(PlotOrientation.VERTICAL);
 chart = new JFreeChart("Srore Bord", JFreeChart.DEFAULT_TITLE_FONT,
  plot, 
true);

 chart.setBackgroundPaint(new Color(249231236));

  try {
 final ChartRenderingInfo info = new ChartRenderingInfo
 (
new StandardEntityCollection());
 
final File file1 = new File("../webapps/jspchart/web/3dbarchart.png");
 ChartUtilities.saveChartAsPNG(file1, chart, 600400, info);
  catch (Exception e) {
 out.println(e);
 }
%>

<html>
  <head>
  <meta http-equiv="Content-Type"
  
content="text/html; charset=UTF-8">
  <title>JSP Page</title>
  </head>
  <body>
  <IMG SRC="3dbarchart.png"
  
WIDTH="600" HEIGHT="400" BORDER="0" USEMAP="#chart">
  </body>
</html>

Create area chart in JSP page using JFreeChart

This Example shows you how to create a area chart in JSP page using JFreeChart. Code given below creates a area chart of runs of two teams in different matches. In the code given below we have extended class ApplicationFrame to create a frame and also pass a string value to the constructor of ApplicationFrame class by using super keyword that will be name of the created frame.

Methods used in this example are described below:
pack(): This method invokes the layout manager.

centerFrameOnScreen(): This method is used for the position of the frame in the middle of the screen.

setVisible(): This method is used for display frame on the screen.

createCategoryDataset(): This method is used to create the instance of CategoryDataset Interface and that contains a copy of the data in an array.

createAreaChart(): This method is used to create bar chart for given values. It takes title, category axis label, value axis label, dataset, Plot Orientation, legend, tool tips and urls as parameters.

saveChartAsPNG(): This method is used to save chart in to png format.

jspareachart.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<%page  import="java.awt.*" %>
<%page  import="java.io.*" %>
<%page  import="org.jfree.chart.*" %>
<%page  import="org.jfree.chart.axis.*" %>
<%page  import="org.jfree.chart.entity.*" %>
<%page  import="org.jfree.chart.labels.*" %>
<%page  import="org.jfree.chart.plot.*" %>
<%page  import="org.jfree.chart.renderer.category.*" %>
<%page  import="org.jfree.chart.urls.*" %>
<%page  import="org.jfree.data.category.*" %>
<%page  import="org.jfree.data.general.*" %>

<%
  final double[][] data = new double[][]{
  {210300320265299},
  {200304201201340}
  };

 final CategoryDataset dataset =
  DatasetUtilities.createCategoryDataset
(
  "Team """, data);

 final JFreeChart chart = ChartFactory.createAreaChart(
  "Area Chart""""Value", dataset,
   PlotOrientation.VERTICAL,

  true, true, false);

 final CategoryPlot plot = chart.getCategoryPlot();
 plot.setForegroundAlpha(0.5f);

 chart.setBackgroundPaint(new Color(249231236));

 try {
  final ChartRenderingInfo info = new ChartRenderingInfo
   (
new StandardEntityCollection());



final File file1 = new File("../webapps/jspchart/web/
  areachart.png"
);
 ChartUtilities.saveChartAsPNG(file1, chart, 600400, info);
  catch (Exception e) {
  out.println(e);
  }

%>

<html>
  <head>
  <meta http-equiv="Content-Type" 
   content=
"text/html; charset=UTF-8">
  <title>JSP Page</title>
  </head>
  <body>
  <IMG SRC="areachart.png" WIDTH="600" HEIGHT="400" BORDER="0"
   
USEMAP="#chart">
  </body>
</html>




Thursday, March 28, 2013

Introduction to POJO (Plain Old Java Object) Programming Model


One of the new features of added by Sun Microsystems in EJB 3.0 is POJO (Plain Old Java Object). It is a Java object that doesn't extend or implement some specialized classes and interfaces respectively require by the EJB framework. Therefore, all normal Java objects are POJO?s only. The following classes are not POJO classes shown as:
class MyServlet extends HttpServlet {} 
class MyRemote implements SessionBean {}
In POJO model, it is recommended that, interfaces should be explicitly implemented whenever you want to pick and choose the methods of the interface. The interfaces are optional for entity beans but required for session beans and message-driven beans. In this model, both the interface and the bean class do not have to throw unnecessary exceptions such as RemoteException.

The interface class in POJO model is a Plain Old Java Interface (POJI).
 The Benefits of POJOs: 
Decoupling: It decouples the application components from the infrastructure of the EJB framework that lets you construct an application from loosely coupled components. There are no longer need to write the tedious JNDI framework-specific lookup code. You can design and implement the business logic. Once that's working, and then you can deal with persistence and transactions.
Easier testing: You can test or run your business logic outside of the application server in a few seconds.
Flexible:
 A Java POJO code can be implemented with any type of enterprise bean such as Message Driven Bean and Entity Bean.  The POJO technology can be used with any type of Enterprise Java Beans(e.g Session Bean, Message Driven Bean or Entity Bean).

Let?s understand the POJO with Message Driven Bean:
Message Driven POJOs:
Message-driven POJOs offer the functionality like MDB to make a simple JavaBeans for the developers. Similar to a MDB in EJB, it acts as a receiver for JMS messages.
Writing a message-driven POJO is not much different than writing a message-driven EJB. The major difference between both is that, an message-driven POJO (MDP) must implement thejavax.jms.MessageListener interface. Like an MDB, you don't have to implementjavax.ejb.MessageDrivenBean and the EJB lifecycle methods defined by the interface.
The EJB 3.0 uses annotations to build completely POJO-based messaging applications.

 In EJB 3.0?s container application server, there is an easier way to implement message driven RPCs. You can use POJOs as message end-points (message driven POJO). The RPC caller retrieves an automatically generated stub of the POJO and makes regular calls against the POJO methods. The message driven POJO works much like a session bean of EJB3, except that all calls are tunneled via a message queue.


 Let?s see the structure of Message Driven POJO given below:
  




Overview of Threads


Process
process is an instance of a computer program that is executed sequentially. It is a collection of instructions which are executed simultaneously at the rum time. Thus several processes may be associated with the same program. For example, to check the spellingis a single process in the Word Processor program and you can also use other processes likeprinting, formatting, drawing, etc. associated with this program.
Thread
A thread is a lightweight process which exist within a program and executed to perform a special task.Several threads of execution may be associated with a single process. Thus a process that has only one thread is referred to as a single-threaded process, while a process with multiple threads is referred to as a multi-threaded process.
In Java Programming language,  thread is a sequential path of code execution within a program. Each thread has its own local variables, program counter and lifetime. In single threaded runtime environment, operations are executes sequentially i.e. next operation can execute only when the previous one is complete. It exists in a common memory space and can share both data and code of a program.Threading concept is very important in Java through which we can increase the speed of any application. You can see diagram shown below in which a thread is executed along with its several operations with in a single process. 

To make bar chart from excel sheet in java?


import java.io.*;
import java.util.*;
import org.jfree.data.*;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.plot.PlotOrientation;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jfree.data.category.DefaultCategoryDataset;

    public class ReadExcel{
        public static void main(String[]args){
    short a=0;  
    short b=1;  
     int i=0;   
    ArrayList<Integer> list1=new ArrayList<Integer>();
    ArrayList<Integer> list2=new ArrayList<Integer>();
        int   x=0, y=0;  
       String filename ="C:/data.xls";     
        if(filename != null && !filename.equals("")){
        try{    
        FileInputStream fs =new FileInputStream(filename);    
        HSSFWorkbook wb = new HSSFWorkbook(fs);   
        for(int k = 0; k < wb.getNumberOfSheets(); k++){    
         int j=i+1;    
         HSSFSheet sheet = wb.getSheetAt(k);    
         int rows  = sheet.getPhysicalNumberOfRows();    
         for(int r =     1; r < rows; r++){    
         HSSFRow row   = sheet.getRow(r);    
         int cells = row.getPhysicalNumberOfCells();    
            HSSFCell cell1  = row.getCell(a);      
            x =(int) cell1.getNumericCellValue();    
            HSSFCell cell2  = row.getCell(b);     
            y =(int) cell2.getNumericCellValue();     

            list1.add(new Integer(x));
            list2.add(new Integer(y));   
          }       
          i++;   
        }    }catch(Exception e){ 
    System.out.println(e);

 }

 }
 DefaultCategoryDataset dataset = new DefaultCategoryDataset();
  for(int j=0;j<list1.size();j++){
        dataset.setValue((double)list2.get(j), "Marks", list1.get(j).toString());
  }
        JFreeChart chart = ChartFactory.createBarChart("BarChart using JFreeChart","ID", "Marks", dataset, 
        PlotOrientation.VERTICAL, false,true, false);
               try {
               ChartUtilities.saveChartAsJPEG(new File("C:/chart.jpg"), chart,400, 300);
               } catch (IOException e) {
               System.out.println("Problem in creating chart.");
  }
 }
}