Wednesday, July 7, 2010

Customized TableModel

import java.util.Vector;

import javax.swing.table.AbstractTableModel;

public class CustomizedTableModel extends AbstractTableModel
{
private String[] columnNames;
Vector cache;
String[] headers;
int colCount;
int dataLength;
private Object[][] data;
Class type[] = null;
public CustomizedTableModel(Class [] coltype, String [] columnNames)
{
type = coltype;
this.columnNames = columnNames;
headers = columnNames;
colCount = coltype.length;
cache = new Vector();

}

public int getColumnCount() {

return colCount;
}

public int getRowCount() {
return dataLength;

}


public String getColumnName(int col) {

return headers[col];
}

public Object getValueAt(int row, int col) {
return data[row][col];

}


public Class getColumnClass(int col) { return type[col]; }



public boolean isCellEditable(int row, int col) {
return false;
}


public void setValueAt(Object value, int row, int col) {

data[row][col] = value;
fireTableCellUpdated(row, col);

}

public void setDataSet(String[][] data)
{
dataLength = data.length;
try {
this.data = new Object[data.length][colCount];
for (int i = 0; i < data.length; i++)
{
for(int j = 0; j < colCount; j++)
{
this.data[i][j] = data[i][j];
}
}
}
catch(Exception e)
{
cache = new Vector();
e.printStackTrace();
}
fireTableChanged(null);

}
}



///calling of it///////////////

Class coltype [] = {String.class,String.class,String.class};
String colNames [] = {"EmpId","First Name","Last Name"};
CustomizedTableModel ctm = new CustomizedTableModel(coltype,colNames);

Tuesday, July 6, 2010

make a unsigned jar to a signed jar

http://wiki.plexinfo.net/index.php?title=How_to_sign_JAR_files


Signing with a Test Certificate

1. Make sure that you have a Java SDK keytool and jarsigner in your path. These tools are located in the Java SDK bin directory.

2. Create a new key in a new keystore as follows:

keytool -genkey -keystore myKeystore -alias myself

You will be prompted for information regarding the new key, such as password, name, etc. This will create the myKeystore file on disk.

3. Then create a self-signed test certificate as follows:

keytool -selfcert -alias myself -keystore myKeystore

This will prompt you for a password. Generating the certificate may take a few minutes.

4. Check to make sure that everything is okay. To list the contents of the keystore, use this command:

keytool -list -keystore myKeystore

It should list something like:

Keystore type: jks
Keystore provider: SUN


Your keystore contains 1 entry:
myself, Tue Jan 23 19:29:32 PST 2001, keyEntry,
Certificate fingerprint (MD5):
C2:E9:BF:F9:D3:DF:4C:8F:3C:5F:22:9E:AF:0B:42:9D

5. Finally, sign the JAR file with the test certificate as follows:

jarsigner -keystore myKeystore test.jar myself

6. Repeat these steps for all your JAR files.

Note that a self-signed test certificate should only be used for internal testing, since it does not guarantee the identity of the user and therefore cannot be trusted. A trustworthy certificate can be obtained from a certificate authority, such as VeriSign orThawte, and should be used when the application is put into production

Make sure you add the following tag to your .jnlp file:



Wednesday, May 5, 2010

Another Id generater method

//////////call method//////////////
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");

String reqid = new IdGenerator().getDateFormatedNextId("tbl_travel_package_req", "TPR-"+sdf.format(new Date()), "req_id", 3);


////////////////////////////



/////Method defination//////////////
public String getDateFormatedNextId(String tableName,String prefix,String columnName, int padlen)throws Exception
{
//create the connection of database.
int temp=0;
Connection con = null;
try{
con=new DBConnection().getDBConnection();
con.setAutoCommit(false);
Statement stmt=con.createStatement(); // getCon() is the return type of created Connection.
ResultSet rs=stmt.executeQuery("Select max(cast(SUBSTRING_INDEX("+columnName.trim()+",'/',-1) as unsigned int )) from "+tableName.trim()+" where SUBSTRING_INDEX("+columnName.trim()+",'/',1)='"+prefix.trim()+"'");

if(rs.next())
{
String str = rs.getString(1);
if(str != null)
{
temp=Integer.parseInt(str);
}

}

++temp;

String new_no = ""+temp;
prefix +="/";
for(int i = new_no.trim().length();i<padlen;i++)
{
prefix =prefix.trim()+"0";
}
rs.close();
stmt.close();
con.commit();
}catch(Exception e){
if(con != null){
con.rollback();
}
throw e;
}
finally
{
con.setAutoCommit(true);
}

con.close();
next_id=prefix.trim()+(temp);

return next_id;
}

Languge translate using google translation api

///// Use google-api-translate-java-0.92.jar ////////////////

import com.google.api.translate.Language;
import com.google.api.translate.Translate;



Translate.setHttpReferrer("http://kmainfonet.in");
String translatedText = Translate.execute(line, Language.ENGLISH, Language.FRENCH);
System.out.println(translatedText);

Getting text containt out of a web page and translate it in any other language

///// Use google-api-translate-java-0.92.jar ////////////////



import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.List;
import java.util.ArrayList;

import javax.swing.text.html.parser.ParserDelegator;
import javax.swing.text.html.HTMLEditorKit.ParserCallback;
import javax.swing.text.html.HTML.Tag;
import javax.swing.text.MutableAttributeSet;

import com.google.api.translate.Language;
import com.google.api.translate.Translate;

public class HTMLUtils {
private HTMLUtils() {}

public static List<String> extractText(Reader reader) throws IOException {
final ArrayList<String> list = new ArrayList<String>();

ParserDelegator parserDelegator = new ParserDelegator();
ParserCallback parserCallback = new ParserCallback() {
public void handleText(final char[] data, final int pos) {
list.add(new String(data));
}
public void handleStartTag(Tag tag, MutableAttributeSet attribute, int pos) { }
public void handleEndTag(Tag t, final int pos) { }
public void handleSimpleTag(Tag t, MutableAttributeSet a, final int pos) { }
public void handleComment(final char[] data, final int pos) { }
public void handleError(final java.lang.String errMsg, final int pos) { }
};
parserDelegator.parse(reader, parserCallback, true);
return list;
}

public final static void main(String[] args) throws Exception{

URL url = new URL("http://en.wikipedia.org/wiki/Hello");
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
BufferedWriter writer = new BufferedWriter(new FileWriter("c:\\data.html"));

String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
writer.write(line);
writer.newLine();
}


FileReader freader = new FileReader("c:\\data.html");
List<String> flines = HTMLUtils.extractText(freader);
System.out.println("Original Text");
for (String fline : flines) {
System.out.println(fline);
}

System.out.println("\n\n\nTranslated Text");
Translate.setHttpReferrer("http://en.wikipedia.org/wiki/Hello");
for (String fline : flines) {
String translatedText = Translate.execute(fline, Language.ENGLISH, Language.FRENCH);
System.out.println(translatedText);
}
}
}

Saturday, April 24, 2010

Randum String generate

public class RandomString {

public void getRamdomString()
{
java.util.Random r = new java.util.Random();
//System.out.print(r.nextInt());
int i = 1, n = 0;
char c;
String str="";
for (int t = 0; t < 5; t++) {
//number of alfabat characters added in front of String token
while (true) {
i = r.nextInt(10);
if (i > 5 && i < 10) {

if (i == 9) {
i = 90;
n = 90;
break;
}
if (i != 90) {
n = i * 10 + r.nextInt(10);
while (n < 65) {
n = i * 10 + r.nextInt(10);
}
}
break;
}
}
c=(char)n;

str= String.valueOf(c)+str;
}
while(true){
i = r.nextInt(100000);// number of integer padded at last
if(i>9999) // number of integer padded at last
{
break;
}
}
str=str+i;
System.out.println(str);
}

public static void main(String[] args) {

RandomString obj=new RandomString();
while(true)
{
obj.getRamdomString();
}

}


}

Friday, April 23, 2010

Sending mail with attachment from java code

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package success;

import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendMail
{
String mailhost = "smtp.gmail.com"; //it is googles mail host use proper mail host for proper server
String senderid = "senderid@gmail.com"; ///authentication mail id
String password = ""; //password
String smtpport = "587";

String messagetype = "text/plain";
SendMail( String to, String message,String subject,String Username)
{

Properties props = new Properties();
props.put("mail.smtp.host", mailhost);
props.put("mail.smtp.port", smtpport);
props.put("mail.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.localhost", "gamil.com");



Session s = Session.getInstance(props, null);
s.setDebug(true);

MimeMessage message1 = new MimeMessage(s);
try
{
InternetAddress from1 = new InternetAddress(senderid, Username);
InternetAddress to1 = new InternetAddress(to);

message1.setSentDate( new Date() );
message1.setFrom( from1 );
message1.addRecipient(javax.mail.Message.RecipientType.TO, to1);

message1.setSubject(subject);
message1.setContent(message, messagetype);

Transport tr = s.getTransport("smtp");
tr.connect(mailhost, senderid, password);
message1.saveChanges();
tr.sendMessage(message1, message1.getAllRecipients());
tr.close();

}
catch (Exception e)
{
System.out.println(e.toString());
}

}

SendMail( String to, String message,String subject,String Username, String[] attachments)
{

Properties props = new Properties();
props.put("mail.smtp.host", mailhost);
props.put("mail.smtp.port", smtpport);
props.put("mail.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.localhost", "gamil.com");



Session s = Session.getInstance(props, null);
s.setDebug(true);

MimeMessage message1 = new MimeMessage(s);
try
{
InternetAddress from1 = new InternetAddress(senderid, Username);
InternetAddress to1 = new InternetAddress(to);

message1.setSentDate( new Date() );
message1.setFrom( from1 );
message1.addRecipient(javax.mail.Message.RecipientType.TO, to1);

message1.setSubject(subject);

// Create a message part to represent the body text
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(message);

//use a MimeMultipart as we need to handle the file attachments
Multipart multipart = new MimeMultipart();

//add the message body to the mime message
multipart.addBodyPart(messageBodyPart);

// add any file attachments to the message
addAtachments(attachments, multipart);

// Put all message parts in the message
message1.setContent(multipart);

// Send the message
Transport tr = s.getTransport("smtp");
tr.connect(mailhost, senderid, password);
message1.saveChanges();
tr.sendMessage(message1, message1.getAllRecipients());
tr.close();
}
catch (Exception e)
{
System.out.println(e.toString());
}

}

protected void addAtachments(String[] attachments, Multipart multipart)
throws MessagingException, AddressException
{
for (int i = 0; i <= attachments.length - 1; i++) {
String filename = attachments[i];
MimeBodyPart attachmentBodyPart = new MimeBodyPart();

//use a JAF FileDataSource as it does MIME type detection
DataSource source = new FileDataSource(filename);
attachmentBodyPart.setDataHandler(new DataHandler(source));

//assume that the filename you want to send is the same as the
//actual file name - could alter this to remove the file path
attachmentBodyPart.setFileName(filename);

//add the attachment
multipart.addBodyPart(attachmentBodyPart);
}
}



public static void main(String[] args) {
// TODO code application logic here
//Text Mail Sending................
SendMail sm = new SendMail("reciverid@yahoo.co.in", "Java mail sending test", "test", "debmalya");


//Attachment mail sending................
String[] filenames = {"d:\\B2.JPG"};
SendMail sm1 = new SendMail("reciverid@gmail.com", "Java mail sending test", "test", "debmalya",filenames);
}
}

Tuesday, April 20, 2010

getvalue from servlet and set in page field using ajax

servelet side


String str = containt.trim().replaceAll(" ", "`");
str = str.replaceAll("\r\n", "~");



javascript side

document.getElementById("prtype").value=prtype.replace(/`/g,' ').replace(/~/g,'\n');

Wednesday, April 7, 2010

some javascript input field checking

function flatnoValidation(e)
{
var unicode = e.charCode? e.charCode : e.keyCode;

if (unicode== 32)
{
return false; //if the key is the backspace key (which we should not allow)
}
else if (unicode== 96)
{
return false; //if the key is the backspace key (which we should not allow)
}
else if (unicode== 126)
{
return false; //if the key is the backspace key (which we should not allow)
}
else
{
return true;
}

}

function blockUsedSymbols(e)
{
var unicode = e.charCode? e.charCode : e.keyCode;
if (unicode== 96)
{
return false; //if the key is the ` key (which we should not allow)
}
else if (unicode== 39)
{
return false; //if the key is the ' key (which we should not allow)
}
else if (unicode== 126)
{
return false; //if the key is the ~ key (which we should not allow)
}
else
{
return true;
}
}
function nameonly(e)
{
var unicode = e.charCode? e.charCode : e.keyCode;

if (unicode== 8)
{
return true; //if the key is the backspace key (which we should allow)
}
else if (unicode== 9)
{
return true;//if the key is the tab key (which we should allow)
}
else if (unicode== 46)
{
return true;//if the key is the delete key (which we should allow)
}
else if(unicode==32)
{
return true;//if the key is the space key (which we should allow)

}
else if(unicode<65||unicode>90&&unicode<97||unicode>122)
{
return false; //if not a letter
}
return true;
}

function floorNoValidation(e)
{
var unicode = e.charCode? e.charCode : e.keyCode;
if (unicode== 8)
{
return true; //if the key is the backspace key (which we should allow)
}
else if (unicode== 9)
{
return true;//if the key is the tab key (which we should allow)
}
else if (unicode== 46)
{
return true;//if the key is the delete key (which we should allow)
}
else if (unicode== 32)
{
return false;//if the key is the space key (which we should not allow)
}
else if(unicode<48||unicode>57)
{
return false;
}
return true;
}

function numberonly(e)
{
var unicode = e.charCode? e.charCode : e.keyCode;
if (unicode== 8)
{
return true; //if the key is the backspace key (which we should allow)
}
else if (unicode== 9)
{
return true;//if the key is the tab key (which we should allow)
}
else if (unicode== 46)
{
return true;//if the key is the delete key (which we should allow)
}
else if (unicode== 32)
{
return true;//if the key is the space key (which we should allow)
}
else if(unicode<48||unicode>57)
{
return false;
}
return true;
}
function passwordonly(e)
{
var unicode = e.charCode? e.charCode : e.keyCode;
if (unicode== 8)
{
return true; //if the key is the backspace key (which we should allow)
}
else if (unicode== 9)
{
return true;//if the key is the tab key (which we should allow)
}
else if (unicode== 46)
{
return true;//if the key is the delete key (which we should allow)
}
else if(unicode==95)
{
return true;//if the key is the _ underscore key (which we should allow)
}
else if (unicode==32)
{
return false;//if the key is the space key (which we should not allow)
}
else if(unicode<48||unicode>57&&unicode<65||unicode>90&&unicode<97||unicode>122)
{
return false;
}
return true;
}

function trimThis(value1)
{
value1= value1.replace(/^\s+|\s+$/, '');
return value1;
}

function emailcheck(str) {

var at="@"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1){

return false
}

if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){

return false
}

if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){

return false
}

if (str.indexOf(at,(lat+1))!=-1){

return false
}

if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){

return false
}

if (str.indexOf(dot,(lat+2))==-1){

return false
}

if (str.indexOf(" ")!=-1){

return false
}

return true
}

function validateTextAreaLen(e,txt,len)
{
var unicode = e.charCode? e.charCode : e.keyCode;
var addrs = txt.value;
if(addrs.toString().length >= len)
{
if (unicode== 8)
{
return true; //if the key is the backspace key (which we should allow)
}
else if (unicode== 9)
{
return true;//if the key is the tab key (which we should allow)
}
else if (unicode== 46)
{
return true;//if the key is the delete key (which we should allow)
}
else
{
return false;
}
}
else
{
if (unicode== 96)
{
return false; //if the key is the ` key (which we should not allow)
}
else if (unicode== 39)
{
return false; //if the key is the ' key (which we should not allow)
}
else if (unicode== 126)
{
return false; //if the key is the ~ key (which we should not allow)
}
else
{
return true;
}

}
}

function onblurMonyonly(txtf)
{
if(trimThis(txtf.value).toString().length == 0)
{
txtf.value='0.00';
}
else if(txtf.value == '.')
{
txtf.value='0.00';
}
else if(txtf.value.toString().indexOf('.') != -1)
{
if(txtf.value.toString().indexOf('.') == txtf.value.toString().length-1)
{
txtf.value = txtf.value.toString()+'00';
}
else if(txtf.value.toString().indexOf('.') == txtf.value.toString().length-2)
{
txtf.value = txtf.value.toString()+'0';
}
}
else
{
txtf.value = txtf.value.toString()+'.00';
}

}

function resetMoneyOnly(txtf)
{
txtf.value = '';
}
function moneyonly(e,txtf)
{
var unicode=e.charCode? e.charCode : e.keyCode;
var st = txtf.value;
//alert(unicode)
if (unicode== 8)
{
return true;
//if the key isn't the backspace key (which we should allow)
}
else if (unicode== 8)
{
return true; //if the key is the backspace key (which we should allow)
}
else if (unicode== 9)
{
return true;//if the key is the tab key (which we should allow)
}

else if(unicode == 46)
{
if(st.toString().indexOf(".",0) != -1)
{
return false;
}

}
else if (unicode<48||unicode>57) //if not a number
{

return false //disable key press
}
else if(st.toString().indexOf(".",0) != -1)
{
if(st.toString().length - st.toString().indexOf(".",0) > 2)
{
return false;
}
}

return true;
}

Wednesday, March 31, 2010

Piocture View from database revised

<%@page contentType="text/html" pageEncoding="UTF-8" import="java.sql.*,dbmodel.DBConnection,model.ExceptionLogger,java.io.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<%

try
{
String seproname = request.getParameter("proname");
String seblocknm = request.getParameter("block");
String valfloor=request.getParameter("floorno");
Connection con=new DBConnection().getDBConnection();

PreparedStatement pst=con.prepareStatement("select floor_pic from tbl_floor_picture where pro_name=? and block_name =? and floorno =?");

pst.setString(1, seproname.trim());
pst.setString(2, seblocknm.trim());
pst.setString(3, valfloor.trim());

ResultSet rs = pst.executeQuery();
if(rs.next())
{
int len =10485760;
byte [] rb = new byte[len];
InputStream readImg = rs.getBinaryStream(1);
int index=readImg.read(rb);


response.reset();
response.setContentType("image/jpg");
response.setHeader("Content-disposition","attachment; filename=img");


response.getOutputStream().write(rb,0,rb.length);
response.getOutputStream().flush();
out.write("image");
}
rs.close();
pst.close();
con.close();
}
catch(Exception e)
{
ExceptionLogger.writeToDB(this.getClass().getName()+": "+e);

//session.setAttribute("resmsg", "Sorry! Some Exception Occurred");
//response.sendRedirect("floor_pic_Upload.jsp");
}

%>

picture upload revised

///////////Servlet//////////////////////


package controler.project;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.ExceptionLogger;
import model.UploadProjectPictureReleted;

public class UploadProjectPicture extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String errormsg="";
int flag=0;
String fileName="",lastFileName="";
String err = "";
String sno ="1";

try
{
String proname= "";
String lastentryby = session.getAttribute("cur_userid").toString().trim();


String contentType = request.getContentType();
String boundary = "";
final int BOUNDARY_WORD_SIZE = "boundary=".length();
//out.println("ss");

if(contentType == null || !contentType.startsWith("multipart/form-data"))
{
err = "Ilegal ENCTYPE : must be multipart/form-data\n";
err += "ENCTYPE set = " + contentType;
session.setAttribute("resmsg", err);
response.sendRedirect("project/project_pic_upload.jsp?pno="+sno.trim());
}
else
{
//out.println("tttttttttttttttttt");
boundary = contentType.substring(contentType.indexOf("boundary=") + BOUNDARY_WORD_SIZE);
boundary = "--" + boundary;


javax.servlet.ServletInputStream sis = request.getInputStream();
//out.println("kkkkkkkkkkkkkkkk");
double len=request.getContentLength();
if(len>10485760)
{
errormsg="Picture larger than 10 MB Upload Not Supported";
session.setAttribute("resmsg", errormsg);
response.sendRedirect("project/project_pic_upload.jsp?pno="+sno.trim());
flag=0;
}
else
{
byte[] b = new byte[1048576];
int x=0;
int state=0;
String name=null, contentType2=null;
java.io.FileOutputStream buffer = null;
//out.println("mmmmmmmmmmmmmmmmmmmmmm");
while((x=sis.readLine(b,0,1048576))>-1)
{
String s = new String(b,0,x);
if(s.startsWith(boundary))
{
state = 0;
name = null;
contentType2 = null;
fileName = null;
}
else if(s.startsWith("Content-Disposition") && state==0)
{
//out.println("22222");
state = 1;
if(s.indexOf("filename=") == -1)
{
name = s.substring(s.indexOf("name=") + "name=".length(),s.length()-2);
}
else
{
name = s.substring(s.indexOf("name=") + "name=".length(),s.lastIndexOf(";"));
fileName = s.substring(s.indexOf("filename=") + "filename=".length(),s.length()-2);
if(fileName.equals("\"\""))
{
fileName = null;
}
else
{
String userAgent = request.getHeader("User-Agent");
String userSeparator="/"; // default
if (userAgent.indexOf("Windows")!=-1)
userSeparator="\\";
if (userAgent.indexOf("Linux")!=-1)
userSeparator="/";
fileName = fileName.substring(fileName.lastIndexOf(userSeparator)+1,fileName.length()-1);
if(fileName.startsWith( "\""))
fileName = fileName.substring( 1);
}
}
name = name.substring(1,name.length()-1);
if (name.equals("file")) {

if (buffer!=null)
buffer.close();
lastFileName = fileName;

// out.println(fileName);
// un=fileName;
buffer = new java.io.FileOutputStream(fileName);
}
}
else if(s.startsWith("Content-Type") && state==1)
{
state = 2;
contentType2 = s.substring(s.indexOf(":")+2,s.length()-2);
}
else if(s.equals("\r\n") && state != 3)
{
state = 3;
}
else
{
if (name.equals("file"))
{
buffer.write(b,0,x);
}
if(name.equals("projnm"))
{
proname=s;
}
if(name.equals("cpno"))
{
sno=s;
}
}
}
sis.close();
buffer.flush();
buffer.close();

UploadProjectPictureReleted uppr = new UploadProjectPictureReleted();
uppr.setProname(proname.trim());
uppr.setFile(lastFileName);
uppr.setLastentryby(lastentryby.trim());
uppr.setData();
errormsg="Picture Upload Successfully";
session.setAttribute("resmsg", errormsg);
response.sendRedirect("project/project_pic_upload.jsp?pno="+sno.trim());
}
}
}
catch(Exception e)
{
ExceptionLogger.writeToDB(this.getClass().getName()+": "+e);
session.setAttribute("resmsg", "Sorry! Some Exception Occured");
response.sendRedirect("project/project_pic_upload.jsp?pno="+sno.trim());
} finally {
out.close();
}
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

}

////////////end of Servlet////////////////////////////////



///model bean class////////////////////

package model;

import dbmodel.DBConnection;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UploadProjectPictureReleted {

private String proname;
private String file;
private String lastentryby;

public boolean setData() throws Exception
{
boolean flag=false;
File file1 =null;
file1 = new File(file);
FileInputStream fis = new FileInputStream(file1);
int len1 = (int)file1.length();

Connection con=new DBConnection().getDBConnection();
PreparedStatement pst = con.prepareStatement("select pro_name from tbl_project_picture where pro_name=?");
pst.setString(1,proname.trim());
ResultSet rs=pst.executeQuery();
if(rs.next())
{
PreparedStatement pst1 = con.prepareStatement("delete from tbl_project_picture where pro_name=?");
pst1.setString(1,proname.trim());

pst1.executeUpdate();

pst1.close();
}


PreparedStatement pstmt = con.prepareStatement("insert into tbl_project_picture VALUES(?,?,?,Now())");
pstmt.setString(1,proname.trim());
pstmt.setBinaryStream(2, fis, len1);
pstmt.setString(3,lastentryby.trim());
if(pstmt.executeUpdate()>0)
{
flag=true;
}
fis.close();
pstmt.close();

rs.close();
pst.close();
con.close();

try{
file1.delete();
}catch(Exception e){

}

return flag;
}

/**
* @return the proname
*/
public String getProname() {
return proname;
}

/**
* @param proname the proname to set
*/
public void setProname(String proname) {
this.proname = proname;
}

/**
* @return the file
*/
public String getFile() {
return file;
}

/**
* @param file the file to set
*/
public void setFile(String file) {
this.file = file;
}

/**
* @return the lastentryby
*/
public String getLastentryby() {
return lastentryby;
}

/**
* @param lastentryby the lastentryby to set
*/
public void setLastentryby(String lastentryby) {
this.lastentryby = lastentryby;
}

}