Sunday 12 August 2012

upload image in java

import java.io.*;
import java.net.*;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.*;
import javax.servlet.http.*;

/**
*
* @author mkarthik
* @version
*/
public class ImageServlet extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request
* servlet request
* @param response
* servlet response
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection(
"jdbc:sqlserver://sql:1433;databaseName=karthik",
"karthik", "karthik");
PreparedStatement pstmt = con
.prepareStatement("insert into image(image) " + "values(?)");
File f = new File("C:/image.jpg");
FileInputStream fis = new FileInputStream(f);
pstmt.setBinaryStream(1, fis, (int) f.length());
pstmt.execute();
con.commit();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT image from image");
System.out.println("Image is inserted successfully!");
Blob b = null;
while (rs.next()) {
b = rs.getBlob("image");
}
byte b1[] = new byte[(int) b.length()];
b1 = b.getBytes(1, (int) b.length());
FileOutputStream fos = new FileOutputStream("D:/a.jpg");
fos.write(b1);
fos.close();
System.out.println("Image is retrieved successfully!");

} catch (Exception e) {
e.printStackTrace();
}
}

}

Insert,Update,Delete in single servlet


<<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<h1 align="center" style="color:red;"><u> Registration form </u></h1>

<script type="text/javascript">
function validateForm()
{
var p=document.forms["myForm"]["id"].value;
if (p==null || p=="")
{
alert("Id must be filled out");
document.myForm.id.focus();
return false;
}
var x=document.forms["myForm"]["firstname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
document.myForm.firstname.focus();
return false;
}

var y=document.forms["myForm"]["fathersname"].value;
if (y==null || y=="")
{
alert("Fathers name must be filled out");
document.myForm.fathersname.focus();
return false;
}
var a=document.forms["myForm"]["age"].value;
if (a==null || a=="")
{
alert("age must be filled out");
document.myForm.age.focus();
return false;
}

var c=document.forms["myForm"]["email"].value;
var atpos=c.indexOf("@");
var dotpos=c.lastIndexOf(".");

if (atpos<1 || dotpos<atpos+2 || dotpos+2>=c.length)
{
alert("Not a valid e-mail address");
document.myForm.email.focus();
return false;
}

var d=document.forms["myForm"]["phonenum"].value;
if (d==null || d=="")
{
alert("phone number must be filled out");
document.myForm.phonenum.focus();
return false;
}
var f=document.forms["myForm"]["qualification"].value;
if (f==null || f=="")
{
alert("Language must be filled out");
document.myForm.qualification.focus();
return false;
}
}

</script>
</head>

<body style="background-color:skyblue;">
<form name="myForm" onsubmit="return validateForm()" action=RegistrationServlet method="post">
<table align="center">
<tr><td> Id:</td><td><input type="text" name="id" /><br /></td></tr>
<tr><td> First name:</td><td><input type="text" name="firstname" /><br /></td></tr>
<tr><td> Fathersname:</td><td> <input type="text" name="fathersname" /><br/></td></tr>
<tr><td> Age:</td><td><input type="text" name="age" /></br></td></tr>

<tr><td> Gender:</td><td></br>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female</br></td></tr>
<tr><td> Emailid:</td><td><input type="text" name="email"/><br /></td></tr>
<tr><td>
Phone Number:</td><td><input type="text" name="phonenum"/><br /></td></tr>
<tr><td> Qualification:</td><td> <select name="qualification"/>
<option value="Btech">Btech</option>
<option value="Mtech">Mtech</option>
<option value="MCA">MCA</option>
<option value="MBA">MBA</option>
</select></br></td></tr>
<tr><td> <input type="Submit" value="submit" name="s1" >
<input type="reset" value="reset" /></td>
<td> <input type="Submit" value="insert" name="s1">
<input type="Submit" value="update" name="s1"></td>
<td> <input type="Submit" value="delete" name="s1"> </td></tr>
</form>
</body>
</html>


RegistrationServlet.java

package com;
import java.io.*;
import java.net.*;
import java.sql.*;
import javax.servlet.*;

import javax.servlet.http.*;


/**
*
* @author mkarthik
* @version
*/


public class RegistrationServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html;charset=UTF-8");
try {
PrintWriter out = response.getWriter();
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:sqlserver://sql:1433;databaseName=karthik","karthik","karthik");
int id=Integer.parseInt(request.getParameter("id"));
String firstname=request.getParameter("firstname");
String fathersname=request.getParameter("fathersname");
int age=Integer.parseInt(request.getParameter("age"));
String sex=request.getParameter("sex");
String email=request.getParameter("email");
String phonenum=request.getParameter("phonenum");
String qualification=request.getParameter("qualification");
String s2=request.getParameter("s1");
if(s2.equals("insert")){
PreparedStatement pstmt = con.prepareStatement("insert into register values(?,?,?,?,?,?,?,?)");
pstmt.setInt(1,id);
pstmt.setString(2,firstname);
pstmt.setString(3,fathersname);
pstmt.setInt(4,age);
pstmt.setString(5,sex);
pstmt.setString(6,email);
pstmt.setString(7,phonenum);
pstmt.setString(8,qualification);
int a=pstmt.executeUpdate();
if(a>0) {
out.println("Values Are Inserted");
} else {
out.println("Values Are not Inserted");
}
} else if(s2.equals("delete")){
PreparedStatement pst = con.prepareStatement("delete from register where id =?");
pst.setInt(1,id);
pst.executeUpdate();
out.println("<body><h3>deleted with id " + id + "</h3></body></html>");
} else if(s2.equals("update")){
String query = "update register set id='"+id+"',firstname='"+firstname+"',fathersname='"+fathersname+"',age='"+age+"',sex='"+sex+"',email='"+email+"',phonenum='"+phonenum+"',qualification='"+qualification+"' where id="+id;
Statement stmt = con.createStatement();
int i = stmt.executeUpdate(query);
//out.println("query" + query);
out.println("update successfully");
}
out.println("<html>");
out.println("<head>");
out.println("<title>UserInfo</title>");
out.println("</head>");
out.println("<body>");
ResultSet rs;
out.println("<form>");
out.println("<table border='1' cellspacing='3' cellpadding='2'>");
out.println("<tr><td> ID </td> <td>FIRSTNAME</td> <td>FATHERSNAME</td><td>AGE</td><td>GENDER</td><td>EMAILID</td><td>PHONENUM</td><td>QUALIFICATION</td></tr>");
PreparedStatement pstmt = con.prepareStatement("select * from register");
ResultSet rs1 = pstmt.executeQuery();
while (rs1.next()) {
out.println("<tr><td>" + rs1.getString(1) + "</td><td>" + rs1.getString(2) + "</td><td>" + rs1.getString(3) + "</td><td>" + rs1.getString(4) + "</td><td>" + rs1.getString(5) + "</td><td>" + rs1.getString(6) + "</td><td>" + rs1.getString(7) + "</td><td>" + rs1.getString(8) + "</td></tr>");
}
out.println("</table>");
out.println("</form>");
out.println("<form name='f2' method='post' action=RegistrationServlet >");
out.println("<br><br><br>");
out.println("<br><br><br>");
out.println("<br><br>");
out.println("<form name='s' action='RegistrationServlet' method=post>");
out.println("<br>Enter ID : <input type='text' value=''name='search1'/> ");
out.println("<input type='hidden' value='" + id + "'name='id'/> ");
out.println("<input type='hidden' value='" + age + "'name='age'/> ");
out.println("<br><br>");
String s3 = request.getParameter("search1");
out.println("Click Here For Delete: <input type ='submit' value='Delete' name='s1'/>");
out.println("Click Here For Delete: <input type ='submit' value='Update1' name='s1'/>");
out.println("<br>");
out.println("Click Here For Search Details :<input type ='submit' value='Search Details' name='s1'/>");
out.println("</form>");
if (s2.equals("Delete")) {
PreparedStatement pst2 = con.prepareStatement("delete from register where ID =?");
pst2.setString(1, s3);
pst2.executeUpdate();
} // out.println("Click Here For Search Details :<input type ='submit' value='Search Details' name='search'/>");
else if (s2.equals("Search Details")) {
//out.println("Click Here For Search Details :<input type ='submit' value='Search Details' name='search'/>");
out.println("<table border='1' cellspacing='3' cellpadding='2'>");
String s23 = request.getParameter("search1");
out.println("<tr><td> ID </td> <td>FIRSTNAME</td> <td>FATHERSNAME</td><td>AGE</td><td>GENDER</td><td>EMAILID</td><td>PHONENUM</td><td>QUALIFICATION</td></tr>");
PreparedStatement pst1 = con.prepareStatement("select * from register where ID=? ");
pst1.setString(1, s23);
//System.out.println("hello");
rs = pst1.executeQuery();
while (rs.next()) {
out.println("<tr><td>" + rs.getString(1) + "</td><td>" + rs.getString(2) + "</td><td>" + rs.getString(3) + "</td><td>" + rs.getString(4) + "</td><td>" + rs.getString(5) + "</td><td>" + rs.getString(6) + "</td><td>" + rs.getString(7) + "</td><td>" + rs.getString(8) + "</td></tr>");
}
} else if (s2.equals("Update1")) {
PreparedStatement pst2 = con.prepareStatement("select * from register where ID =?");
pst2.setString(1, s3);
rs1 = pst2.executeQuery();
if (rs1.next()) {
out.println(" <form name=myForm method=post action=RegistrationServlet>");
out.println("<table bgcolor=skyblue align=center cellspacing=1 cellpadding=0 >");
out.println(" <tr><td> ID </td><td><input type=text name=id value='" + rs1.getInt(1) + "' readonly /><br /></td></tr>");
out.println("<tr><td> First name:</td><td> <input type=text name=firstname value='" + rs1.getString(2) + "'/><br /></td></tr>");
out.println("<tr><td> Fathersname:</td><td> <input type=text name=fathersname value='" + rs1.getString(3) + "'/><br/></td></tr>");
out.println("<tr><td> Age:</td><td> <input type=text name=age value='" + rs1.getString(4) + "'/></br></td></tr>");
out.println("<tr><td> Gender:</td><td>");
if(rs1.getString(5).equals("male")) {
out.println("<input type=radio name=sex value='male' checked /> Male");
out.println(" <input type=radio name=sex value='female' /> Female</td></tr>");
} else{
out.println("<input type=radio name=sex value='male' /> Male");
out.println(" <input type=radio name=sex value='female' checked/> Female</td></tr>");
}
out.println("<tr><td> Emailid: </td><td><input type=text name=email value='" + rs1.getString(6) + "'/><br /></td></tr>");
out.println(" <tr><td>Phone Number:</td><td> <input type=text name=phonenum value='" + rs1.getString(7) + "'/><br /></td></tr>");
out.println(" <tr><td> Qualification :</td><td>");
if(rs1.getString(8).equals("Btech")) {
out.println(" <select name=qualification><option value=-1/>Btech</option><option value='Btech' select/>Btech</option> ");
out.println(" <option value='Mtech'>Mtech</option> ");
out.println(" <option value='MCA'>MCA</option> ");
out.println(" <option value='MBA'>MBA</option></select>");
} else if(rs1.getString(8).equals("Mtech")) {
out.println("<select name=qualification><option value=-1/>Mtech</option><option value='Mtech' select/>Mtech</option> ");
out.println(" <option value='Btech' checked/>Mtech</option>");
out.println(" <option value='MCA'>MCA</option> ");
out.println(" <option value='MBA'>MBA</option></select>");
} else if(rs1.getString(8).equals("MCA")) {
out.println(" <select name=qualification><option value=-1/>MCA</option><option value='MCA' select/>MCA</option> ");
out.println(" <option value='Mtech' checked/>Mtech</option> ");
out.println(" <option value='Btech'>Btech</option> ");
out.println(" <option value='MBA'>MBA</option></select>");
} else if(rs1.getString(8).equals("MBA")) {
out.println(" <select name=qualification><option value=-1/>MBA</option><option value='MBA' select/>MBA</option> ");
out.println(" <option value='Mtech' checked/>Mtech</option> ");
out.println(" <option value='MCA'>MCA</option> ");
out.println(" <option value='Btech'>Btech</option></select>");
}
//out.println("</select></br></td></tr>");
out.println("<tr><td><br></td><td<br></td></tr>");
out.println("<tr><td></td><td>");
out.println("<input type=reset value=Reset />");
out.println(" <input type=Submit value=insert name=s1>");
out.println("<input type=Submit value=update name=s1>");
out.println("<input type=Submit value=delete name=s1> </td></tr></table>");
}
}
out.println("</table>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
} catch (Exception ex) {
ex.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}


Sunday 1 July 2012

Java Features


The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important key feature of java language that makes java as the most powerful language.
Java Features
Platform Independent
The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important key feature of java language that makes java as the most powerful language. Not even a single language is idle to this feature but java is more closer to this feature. The programs written on one platform can run on any platform provided the platform must have the JVM. 
Simple
There are various features that makes the java as a simple language. Programs are easy to write and debug because java does not use the pointers explicitly. It is much harder to write the java programs that can crash the system but we can not say about the other programming languages. Java provides the bug free system due to the strong memory management. It also has the automatic memory allocation and deallocation system.
Object Oriented
To be an Object Oriented language, any language must follow at least the four characteristics.
  • Inheritance   :   It is the process of creating the new classes and using the behavior of the existing classes by extending them just to        reuse  the existing code and adding the additional features as needed.
  • Encapsulation:  :   It is the mechanism of combining the information and providing the abstraction.
  • Polymorphism    :   As the name suggest one name multiple form, Polymorphism is the way of providing the different functionality by the
       functions  having the same name based on the signatures of the methods.
  • Dynamic binding  :   Sometimes we don't have the knowledge of objects about their specific types while writing our code. It is the way     of providing the maximum functionality to a program about the specific type at runtime.  
As the languages like Objective C, C++ fulfills the above four characteristics yet they  are not fully object oriented languages because they are structured as well as object oriented languages. But in case of java,  it is a fully Object Oriented language because object is at the outer most level of data structure in java. No stand alone methods, constants, and variables are there in java. Everything in java is object even the primitive data types can also be converted into object by using the wrapper class.
Robust
Java has the strong memory allocation and automatic garbage collection mechanism. It provides the powerful exception handling and type checking mechanism as compare to other programming languages. Compiler checks the program whether there any error and interpreter checks any run time error and makes the system secure from crash. All of the above features makes the java language robust.
Distributed
The widely used protocols like HTTP and FTP are developed in java. Internet programmers can call functions on these protocols and can get access the files from any remote machine on the internet rather than writing codes on their local system.
Portable
The feature Write-once-run-anywhere  makes the java language portable provided that the system must have interpreter for the JVM. Java also have the standard data size irrespective of operating system or the processor. These features makes the java as a portable language.
Dynamic
While executing the java program the user can get the required files dynamically from a local drive or from a computer thousands of miles away from the user just by connecting with the Internet.
Secure
Java does not use memory pointers explicitly. All the programs in java are run under an area known as the sand box. Security manager determines the accessibility options of a class like reading and writing a file to the local disk. Java uses the public key encryption system to allow the java applications to transmit over the internet in the secure encrypted form. The bytecode Verifier checks the classes after loading. 
Performance
Java uses native code usage, and lightweight process called  threads. In the beginning interpretation of bytecode resulted the performance slow but the advance version of JVM uses the adaptive and just in time compilation technique that improves the performance. 

Multithreaded
As we all know several features of Java like Secure, Robust, Portable, dynamic etc; you will be more delighted to know another feature of Java which is Multithreaded.Java is also a Multithreaded programming language. Multithreading means a single program having different threads executing independently at the same time. Multiple threads execute instructions according to the program code in a process or a program. Multithreading works the similar way as multiple processes run on one computer.
Multithreading programming is a very interesting concept in Java. In multithreaded programs not even a single thread disturbs the execution of other thread. Threads are obtained from the pool of available ready to run threads and they run on the system CPUs. This is how Multithreading works in Java which you will soon come to know in details in later chapters.
Interpreted
We all know that Java is an interpreted language as well. With an interpreted language such as Java, programs run directly from the source code.
The interpreter program reads the source code and translates it on the fly into computations. Thus, Java as an interpreted language depends on an interpreter program.
The versatility of being platform independent makes Java to outshine from other languages. The source code to be written and distributed is platform independent.
Another advantage of Java as an interpreted language is its error debugging quality. Due to this any error occurring in the program gets traced. This is how it is different to work with Java.
Architecture Neutral
The term architectural neutral seems to be weird, but yes Java is an architectural neutral language as well. The growing popularity of networks makes developers think distributed. In the world of network it is essential that the applications must be able to migrate easily to different computer systems. Not only to computer systems but to a wide variety of hardware architecture and Operating system architectures as well.  The Java compiler does this by generating byte code instructions, to be easily interpreted on any machine and to be easily translated into native machine code on the fly. The compiler generates an architecture-neutral object file format to enable a Java application to execute anywhere on the network and then the compiled code is executed on many processors, given the presence of the Java runtime system. Hence Java was designed to support applications on network. This feature of Java has thrived the programming language