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.");
  }
 }
}

Wednesday, March 27, 2013

JSP Response setHeader

In JSP header can be set to the response by using the setHeader() method of HttpServletResponse interface. However addHeader() method of this interface is also used for this purpose but in perspective of setHeader() method it sets the header by overwrites over the header if the header is already existed and the addHeader() method adds the new header. To check whether the header is already set or not response.containsHeader() method can be used.

Syntax of setHeader() :

void setHeader(String name, String value)
Both argument is of String type, where the first argument specifies the name of the header and second specifies the value of the corresponding header name.

Example :

An example that is being given here will help in understanding how to set response header. In this example I have created a JSP page where I have designed a form to take input through the user. Then wrote the java code using scriptlets into which at first I have checked for the header name I want to add to the response header, then adds the header by name "Author" and again used the containsHeader() method for checking the existence of currently added response header.

jspResponseSetHeader.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.net.URL"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP Response setHeader</title>
</head>
<body>
<form>
<table>
<tr>
<td>Enter your Name :</td>
<td><input type="text" name="name" />
</td>
</tr>
<tr>
<tr>
<td></td>
<td><input type="submit" value="submit" />
</td>
</tr>
</table>
</form>
<%
String nm = request.getParameter("name");

if (nm != null) {
out.println("The Header <b>" + nm + "</b> has been already set : "
+ response.containsHeader("Author")+"<br>");
response.setHeader("Author", nm);
out.println("Author : " + nm+"<br>");
out.println("The Header <b>" + nm + "</b> has been already set : "
+ response.containsHeader("Author"));
}
%>
</body>
</html>

JSP implicit object out


Out object denotes the Output stream in the context of page. The class or the interface name of the object out is "jsp.JspWriter".This object is instantiated implicitly from JSP Writer class and can be used for displaying anything within delimiters. 
Methods in out object
  • print
  • println
  • newLine
  • clear
  • clearBuffer
  • flush
  • isAutoFlush
  • getBufferSize
  • getRemaining.
(1)print() : The print method of out object writes the value to the output without a newline character.
Example :
If a JSP program has the following statements :
  out.print("Welcome!!!");
  out.print("Guests");
Output :
  Welcome!!! Guests
(2)println() : The println method of out object writes the value to the output with a newline character.
  out.println("Welcome!!!");
  out.println("Guests");
Output :
  Welcome!!!
  Guests
(3)newLine : The 'newLine' method of out object is used to write a newline character to the output.
Example : If a JSP program has the following statements :
out.write("Welcome!!!");
out.newLine();
out.write("Guests");
Output :
  Welcome!!!
  Guests

(4)clear :

The clear method of out object is used to clear the output buffer. This method does not write any contents to the client. An exception is thrown by this method if the buffer was flushed.
Syntax :  out.clear() ;  

(5)clearBuffer :

The 'clearBuffer' method of out object is used to clear the output buffer. This method does not write any contents to the client. The only difference between the 'clear' method of out object and 'clearBuffer' method is
  • 'clear' method throws an exception when the buffer is flushed.
  • 'clearBuffer' method does not throw an exception when the buffer is flushed.
Example : 
if (out.getBufferSize() != 0)
                out.clearBuffer();
(6)flush : Two methods of out object, 'clear' and 'clearBuffer' are used to clear the output buffer without writing any contents to the client. The 'flush' method of out object is used to flush the buffer by writing the contents to the client.
Example :
 out.flush();
 <jsp:forward page="roseindia.jsp&">
In the above example, no forwarding will take place. This is because of the "out.flush()" method. This method will flush the "JspWriter" buffer. Once the content is written to the browser, a forward cannot be invoked.
(7)isAutoFlush() : The "isAutoFlush" method of 'out' object returns a 'true' value if the output buffer is automatically flushed otherwise returns 'false'.
Syntax:     out.isAutoFlush() ;
(8)getBufferSize : The "getBufferSize" method of 'out' object is used to return the size of the buffer. The returned value of the size of the buffer is in bytes. If the output is not buffered, then the "getBufferSize" method returns a 0 byte.
Example :
if (out.getBufferSize() != 0)
    out.getBufferSize()
(9)getRemaining() : The "getRemaining" method of out object is used to return the number of empty bytes in the buffer.
Syntax :  out.getRemaining() ;
EXAMPLE USING "out" OBJECT
<HTML>
<BODY>
<%
// This scriptlet declares and initializes "date"
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>
Hello! The time is now
<%
out.println( date );
out.println( "<BR>Your machine's address is " );
out.println( request.getRemoteHost());
%>
</BODY>
</HTML>

What is interface in Java



Interface in java is core part of Java programming language and one of the way to achieve abstraction in Java along with abstract class. Even though interface is fundamental object oriented concept ; Many Java programmers thinks Interface in Java as advanced concept and refrain using interface from early in programming career. At very basic level  interface  in java is a keyword  but same time it is an object oriented term to define contracts and abstraction , This contract is followed by any implementation of Interface in Java. Since multiple inheritance is not allowed in Java,  interface is only way to implement multiple inheritance at Type level. In this Java tutorial we will see What is an interface in Java, How to use interface in Java and where to use interface in Java and some important points related to Java interfaceWhat is an interface in Java is also a common core Java question which people asked on various programming exams and interviews.



In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:
interface Bicycle {

    //  wheel revolutions per minute
    void changeCadence(int newValue);

    void changeGear(int newValue);

    void speedUp(int increment);

    void applyBrakes(int decrement);
}
To implement this interface, the name of your class would change (to a particular brand of bicycle, for example, such as ACMEBicycle), and you'd use theimplements keyword in the class declaration:
class ACMEBicycle implements Bicycle {

    // remainder of this class 
    // implemented as before
}
Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.


Tuesday, March 26, 2013

Upload and Download video in mysql databse using jsp

1)page.jsp
<%@ page language="java" %><Html>
<HEAD><TITLE>Display file upload form to the user</TITLE></HEAD>
<BODY>
<FORM ENCTYPE="multipart/form-data" ACTION="upload.jsp" METHOD=POST>
<br><br><br>
<center><table border="2" >
<tr><center><td colspan="2"><p align="center"><B>UPLOAD THE FILE</B><center></td></tr>
<tr><td><b>Choose the file To Upload:</b>
</td>
<td><INPUT NAME="file" TYPE="file"></td></tr>
<tr><td colspan="2">
<p align="right"><INPUT TYPE="submit" VALUE="Send File" ></p></td></tr>
<table>
</center>
</FORM>
</BODY>
</HTML>
2)upload.jsp
<%@ page import="java.io.*" %><%@ page import="java.sql.*" %>
<%
String contentType = request.getContentType();
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
out.println(saveFile);
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
FileOutputStream fileOut = new FileOutputStream(saveFile);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();

%><Br><table border="2"><tr><td><b>You have successfully upload the file by the name of:</b>
<% out.println(saveFile);%></td></tr></table>
<%
Connection connection = null;
String connectionURL = "jdbc:mysql://192.168.10.112:3306/file";;;
ResultSet rs = null;
PreparedStatement psmnt = null;
FileInputStream fis;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "root");
File f = new File(saveFile);
psmnt = connection.prepareStatement("insert into file(file_data) values(?)");
fis = new FileInputStream(f);
psmnt.setBinaryStream(1, (InputStream)fis, (int)(f.length()));
int s = psmnt.executeUpdate();
if(s>0) {
System.out.println("Uploaded successfully !");
}
else {
System.out.println("unsucessfull to upload file.");
}
}
catch(Exception e){e.printStackTrace();}
}
%> <a href="download.jsp">Download File</a>
3)download.jsp:
<%@page import="java.sql.*"%><%@page import="java.io.*"%><%@page import="javax.servlet.*"%><%
ServletOutputStream output = response.getOutputStream();
String connectionURL = "jdbc:mysql://192.168.10.112:3306/file";;;;;
String Content=new String("");
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection(connectionURL,"root","root");
Statement st=con.createStatement();
ResultSet rst= st.executeQuery("select * from file");
if(rst.last())
{
Content=rst.getString("file_data");
}
con.close();
}catch(Exception e){
System.out.println("Exception caught"+e.getMessage());
}
byte requestBytes[] = Content.getBytes();
ByteArrayInputStream bis = new ByteArrayInputStream(requestBytes);
response.reset();
response.setContentType("mime/flv");
response.setHeader("Content-disposition","attachment; filename=" +"file.flv");
byte[] buf = new byte[1024];
int len;
while ((len = bis.read(buf)) > 0){
output.write(buf, 0, len);
}
bis.close();
response.getOutputStream().flush();
%>