Unable to upload file : code doesn't enter the while loop - java

I am unable to upload file. There is no exception,no error but when the code is run, file doesn't uploaded. What could be the reason for it?
As debugged :
iterator.hasNext() returns false
`
<form action='UploadMatch' method='post' enctype="multipart/form-data">
<input type='file' />
<input type='submit' class='btn btn-default' id='uploadmatch' />upload
</form>
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
/**
*
* #author user
*/
public class UploadMatch extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter writer = response.getWriter();
String path = request.getParameter("Data");
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if( !isMultipart ) {
writer.println("File cannot be uploaded !");
} else {
DiskFileItemFactory diskFileItem = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(diskFileItem);
List list = null;
try {
list = fileUpload.parseRequest(request);
}catch(Exception exc) {
writer.println(exc);
}
Iterator iterator = list.iterator();
while(iterator.hasNext()) { // WHILE LOOP (DOESN'T ENTER)
FileItem fileItem = (FileItem)iterator.next();
if(fileItem.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
} else {
// Process form file field (input type="file").
String fieldName = fileItem.getFieldName();
String fileName = FilenameUtils.getName(fileItem.getName());
File file = new File(request.getServletContext().getContextPath(),fileName);
writer.println(">>>>>>>>>>W:/" + " " + fileName);
fileItem.write(file);
}
}
}
}catch(Exception exc) {
writer.println(exc);
}
}
}
Note : The code doesn't enter the while loop

Related

How can I read a dynamic file from servlets and printout to the browser

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.util.Calendar;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class SSEServlet
*/
#WebServlet("/SSE")
public class SSE extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/event-stream");
response.setCharacterEncoding("UTF-8");
PrintWriter printwriter = response.getWriter();
File file= new File("/home/user/Documents/new.txt");
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
long length = randomAccessFile.length();
String temp;
int foundLine = 0;
while (length > 0 && foundLine < 10) {
randomAccessFile.seek(length--);
if (randomAccessFile.read() == 10) {
foundLine++;
}
}
while(true)
while((temp = randomAccessFile.readLine()) != null)
{
printwriter.println(temp);
response.flushBuffer();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
In my code I am trying to get the last 10 lines and also the one that is written to file dynamically after tht 10 lines but while running my pgm am only getting the last 10 lines and not the ones written after that....in short am not able to watch the file dynamically is there any solution for this

commons fileupload(Apache)

I am getting null pointer exception here:
List fileItems = upload.parseRequest(req);
That happens if the number of line in the file is greater the 2000 approx, as I could upload the file of lines above 1000. Someone please help me out. The form is below.
<form name="fos_picks" id="fos_picks" action="<%=path%>/fos_upld" method="post" enctype="multipart/form-data" >
<br/><br/><br/><br/>
<p align="center">
<input type="file" name="file" size="50" /><br/>
<br/>
<input type="submit" class="buttons" value="Upload File" />
</p>
</form>
Upload controller code...
package file_proc;
import DBConn.DBConn;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.PreparedStatement;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
#WebServlet(name="file_upld", urlPatterns = {"/file_upld"})
public class file_upld extends HttpServlet {
private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 10 * 1024;
private File file ;
/* public void init( ){
// Get the file location where it would be stored.
filePath =
getServletContext().getInitParameter("file-upload");
}*/
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, java.io.IOException {
// Check that we have a file upload request
java.io.PrintWriter out = res.getWriter( );
// out.println("entered");
isMultipart = ServletFileUpload.isMultipartContent(req);
res.setContentType("text/html");
if( !isMultipart ){
out.println("!multipart");
System.out.println("here");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:/temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
ServletContext servletContext = getServletContext();
String path = servletContext.getRealPath("/");
BufferedReader br=null;
String fileName="";
DBConn db = new DBConn();
try{
// Parse the request to get file items.
System.out.println("here1"+req);
List fileItems = upload.parseRequest(req);
// Process the uploaded file items
Iterator i = fileItems.iterator();
/* out.println("<html>");
out.println("<head>");
out.println("<title>Upload</title>");
out.println("</head>");
out.println("<body>");*/
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( "c:/Temp/" +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( "c:/Temp/"+
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
if(!file.exists())
{
File fold=new File(file.getParent());
fold.mkdirs();
}
fi.write( file ) ;
System.out.println("Uploaded Filename: " + fileName + "<br>");
}
}
}catch(Exception ce)
{
out.println("<font size='30' color='red'>Error Code 016</font>");
//out.println("Exception1: "+ce);
}
//read uploaded file and insert into table********************************************
// String newline = System.getProperty("line.separator");
// File file = new File(path+"//"+fileName);
// file.createNewFile();
try{
if(file.isFile())
{
br = new BufferedReader(new FileReader(file));
String str="";
String temp[]=null;
file.canWrite();
file.canRead();
file.setWritable(true);
db.conn.setAutoCommit(false);
while((str=br.readLine())!=null)
{
temp=str.split(" ");
// PreparedStatement ps = db.conn.prepareStatement("INSERT INTO file_proc VALUES(?,?,?,?,?,?,?,?,?,STR_TO_DATE(?,'%m/%d/%Y'))");
PreparedStatement ps = db.conn.prepareStatement("INSERT INTO file_proc(run_date,zone,location,bank,file_type,num_rec,ex_sett_date,ex_stat_date) "
+ "VALUES(STR_TO_DATE(?,'%m/%d/%Y'),?,?,?,?,?,STR_TO_DATE(?,'%m/%d/%Y'),STR_TO_DATE(?,'%m/%d/%Y'))");
ps.setString(1,temp[0]);
ps.setString(2,temp[1]);
ps.setString(3,temp[2]);
ps.setString(4,temp[3]);
ps.setString(5,temp[4]);
ps.setInt(6,Integer.parseInt(temp[5]));
ps.setString(7,temp[6]);
ps.setString(8,temp[7]);
ps.executeUpdate();
ps.close();
}
db.conn.commit();
db.conn.setAutoCommit(true);
db.conn.close();
br.close();
file.delete();
// RequestDispatcher rd = req.getRequestDispatcher("./status/status.jsp");
// rd.forward(req, res);
out.print("success");
// out.println("</html>");
}
else
{
out.println(file+" is not a file");
}
}catch(Exception ex) {
out.println("file name= "+fileName);
// out.println("DBEX= "+ex );
out.println("<font size='30' color='red'>Error Code 017 - Recommended date format = m/d/yyyy.</font>");
out.println("<font size='30' color='red'>Check the column order</font>"+ex);
//file.delete();
// RequestDispatcher rd = req.getRequestDispatcher("./status/error.jsp");
// rd.forward(req, res);
}finally{
try{
db.conn.close();
br.close();
}catch(Exception e){}
}
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, java.io.IOException {
doPost(request, response);
}
}
**** Here is form ******
<form name="file_proc" id="file_proc" method = "post" action="../file_upld" enctype="multipart/form-data">
<br/><br/><br/><br/>
<p align="center">
<input type="file" id="file" name="file" size="50" /><br/>
<br/>
<input type="submit" class="buttons" value="Upload File" />br/><br/><br/>
</p>
</form>
Upload controller code...
package file_proc;
import DBConn.DBConn;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.PreparedStatement;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
#WebServlet(name="file_upld", urlPatterns = {"/file_upld"})
public class file_upld extends HttpServlet {
private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 10 * 1024;
private File file ;
/* public void init( ){
// Get the file location where it would be stored.
filePath =
getServletContext().getInitParameter("file-upload");
}*/
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, java.io.IOException {
// Check that we have a file upload request
java.io.PrintWriter out = res.getWriter( );
// out.println("entered");
isMultipart = ServletFileUpload.isMultipartContent(req);
res.setContentType("text/html");
if( !isMultipart ){
out.println("!multipart");
System.out.println("here");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:/temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
ServletContext servletContext = getServletContext();
String path = servletContext.getRealPath("/");
BufferedReader br=null;
String fileName="";
DBConn db = new DBConn();
try{
// Parse the request to get file items.
System.out.println("here1"+req);
List fileItems = upload.parseRequest(req);
// Process the uploaded file items
Iterator i = fileItems.iterator();
/* out.println("<html>");
out.println("<head>");
out.println("<title>Upload</title>");
out.println("</head>");
out.println("<body>");*/
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( "c:/Temp/" +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( "c:/Temp/"+
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
if(!file.exists())
{
File fold=new File(file.getParent());
fold.mkdirs();
}
fi.write( file ) ;
System.out.println("Uploaded Filename: " + fileName + "<br>");
}
}
}catch(Exception ce)
{
out.println("<font size='30' color='red'>Error Code 016</font>");
//out.println("Exception1: "+ce);
}
//read uploaded file and insert into table********************************************
// String newline = System.getProperty("line.separator");
// File file = new File(path+"//"+fileName);
// file.createNewFile();
try{
if(file.isFile())
{
br = new BufferedReader(new FileReader(file));
String str="";
String temp[]=null;
file.canWrite();
file.canRead();
file.setWritable(true);
db.conn.setAutoCommit(false);
while((str=br.readLine())!=null)
{
temp=str.split(" ");
// PreparedStatement ps = db.conn.prepareStatement("INSERT INTO file_proc VALUES(?,?,?,?,?,?,?,?,?,STR_TO_DATE(?,'%m/%d/%Y'))");
PreparedStatement ps = db.conn.prepareStatement("INSERT INTO file_proc(run_date,zone,location,bank,file_type,num_rec,ex_sett_date,ex_stat_date) "
+ "VALUES(STR_TO_DATE(?,'%m/%d/%Y'),?,?,?,?,?,STR_TO_DATE(?,'%m/%d/%Y'),STR_TO_DATE(?,'%m/%d/%Y'))");
ps.setString(1,temp[0]);
ps.setString(2,temp[1]);
ps.setString(3,temp[2]);
ps.setString(4,temp[3]);
ps.setString(5,temp[4]);
ps.setInt(6,Integer.parseInt(temp[5]));
ps.setString(7,temp[6]);
ps.setString(8,temp[7]);
ps.executeUpdate();
ps.close();
}
db.conn.commit();
db.conn.setAutoCommit(true);
db.conn.close();
br.close();
file.delete();
// RequestDispatcher rd = req.getRequestDispatcher("./status/status.jsp");
// rd.forward(req, res);
out.print("success");
// out.println("</html>");
}
else
{
out.println(file+" is not a file");
}
}catch(Exception ex) {
out.println("file name= "+fileName);
// out.println("DBEX= "+ex );
out.println("<font size='30' color='red'>Error Code 017 - Recommended date format = m/d/yyyy.</font>");
out.println("<font size='30' color='red'>Check the column order</font>"+ex);
//file.delete();
// RequestDispatcher rd = req.getRequestDispatcher("./status/error.jsp");
// rd.forward(req, res);
}finally{
try{
db.conn.close();
br.close();
}catch(Exception e){}
}
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, java.io.IOException {
doPost(request, response);
}
}
**** Here is form ******
<form name="file_proc" id="file_proc" method = "post" action="../file_upld" enctype="multipart/form-data">
<br/><br/><br/><br/>
<p align="center">
<input type="file" id="file" name="file" size="50" /><br/>
<br/>
<input type="submit" class="buttons" value="Upload File" />br/><br/><br/>
</p>
</form>
here is the log4j stuff, it shows the error at filter.java, which i am not using in the current servlet.
[ERROR] 29:05(file_upld.java:doPost:172) failed!
java.lang.NullPointerException at
file_proc.file_upld.doPost(file_upld.java:120) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:641) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at filter.filter.doFilter(filter.java:16) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Here goes the filter.javapackage filter;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
public class filter implements Filter{
private FilterConfig config=null;
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException
{
HttpServletResponse hsr = (HttpServletResponse) res;
hsr.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
hsr.setHeader("Pragma", "no-cache"); // HTTP 1.0.
hsr.setDateHeader("Expires", 0); // Proxies.
chain.doFilter(req, res);
}
#Override
public void destroy() { }
#Override
public void init(FilterConfig config) {
this.config = config;
}
}
Your concrete problem is caused by bad exception handling and tight-coupling view with the controller.
After filtering noise from your code, it goes roughly like:
File file = null;
try {
// ...
file = new File(...);
// ...
} catch (Exception e) {
out.println("...");
}
try {
if (file.isFile())
// ...
} else {
// ...
}
} catch (Exception e) {
out.println("...");
}
The NullPointerException is been thrown at the line with the if (file.isFile()) block. This thus means that the first try block threw an exception, hereby leaving the file as null.
The cause of the problem is two-fold:
The first try block is not returning from the servlet method on exception, but incorrectly continuing the code flow.
The second try block is not checking beforehand if the file is not null.
Your concrete problem is however much bigger. You're completely swallowing exceptions and printing irrelevant HTML code instead of throwing them through and/or logging the exceptions.
Replace your catch blocks as follows:
} catch (Exception e) {
throw new ServletException(e);
}
By default, this way the exception will be logged and be displayed in its full glory, complete with the stacktrace, in a HTTP 500 error page. The stacktrace gives you a wealth of information to understand the problem and fix it.
Unrelated to the concrete problem, there are many other conceptual and design mistakes in the code, but they are so far not directly related to the concrete problem. I would however recommend to take a pause and go through some sane Servlet books/tutorials/resources. This code seems to be just cobbled together based on snippets found in Google instead of being well thought out written. The first step would be understanding how servlets actually work: How do servlets work? Instantiation, sessions, shared variables and multithreading

Servlet method is not getting called?

I am trying to upload a file to web server and read the same. file uploading is working and the file is uploaded but when i call some methods to manipulate saved file the method is not getting called.
in the following file i call readFile method from post method.
I am using tomcat 7.0. Please save me from this. the code is :
package org.slingemp.fileupload;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slingemp.bean.setNotification;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
/**
* Servlet implementation class Fileupload
*/
#WebServlet("/Fileupload")
public class Fileupload extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Fileupload() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("file upload started....Antony");
// TODO Auto-generated method stub
List fileItemsList = null;
float filesize = 0;
String _fileLink;
String _fileName = null;
String _uploadDir = getServletContext().getRealPath("/accesscarddata/");
// Change upload with your directory
HttpSession session = request.getSession(true);
try {
if (ServletFileUpload.isMultipartContent(request)) {
ServletFileUpload servletFileUpload = new ServletFileUpload(
new DiskFileItemFactory());
try {
fileItemsList = servletFileUpload.parseRequest(request);
} catch (FileUploadException ex) {
Logger.getLogger(Fileupload.class.getName()).log(
Level.SEVERE, null, ex);
// Change above line replace FileUploadExample with your
// file name
}
String optionalFileName = "";
FileItem fileItem = null;
Iterator it = fileItemsList.iterator();
while (it.hasNext()) {
FileItem fileItemTemp = (FileItem) it.next();
if (fileItemTemp.isFormField()) {
if (fileItemTemp.getFieldName().equals("filename")) {
optionalFileName = fileItemTemp.getString();
}
/*
* If you want to pass some other data from JSP page.
* You can access then in this way. For each field you
* have do create if like below. if
* (fileItemTemp.getFieldName
* ().equals("Name of other field like:Firstname")) {
* String Firstname = fileItemTemp.getString(); }
*/
} else {
fileItem = fileItemTemp;
}
}
if (fileItem != null) {
long size_long = fileItem.getSize();
filesize = size_long / 1024;
filesize = filesize / 1000;
// If you want to limit the file size. Here 30MB file size
// is allowed you can change it
//if (filesize > 30.0) {
// Pass error message in session.
//setNotification _sN = new setNotification();
//_sN.setError("File size can't be more than 30MB");
//session.setAttribute("error", _sN);
//} else {
_fileName = fileItem.getName();
if (fileItem.getSize() > 0) {
if (optionalFileName.trim().equals("")) {
_fileName = FilenameUtils.getName(_fileName);
} else {
_fileName = optionalFileName;
}
_fileLink = "../accesscarddata/" + _fileName;
try {
File file = new File(new File(_uploadDir + "/"),fileItem.getName());
fileItem.write(file);
} catch (Exception e) {
e.printStackTrace();
}
setNotification _sN = new setNotification();
_sN.setError("File Uploaded to : " + _fileLink + "");
session.setAttribute("accesscardDatafileNname", _fileName);
session.setAttribute("error", _sN);
}
//}
}
//SELECT * FROM leave_application WHERE from_date >= '2004-01-01' AND to_date <'2004-01-30' and emp_id=128
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("before calling readFile");
readFile(request,response);
System.out.println("after calling readFile");
response.sendRedirect("index.jsp");
}
protected void readFile(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.out.println("readFile is called..");
Map employeeMap = null;
String fileName = "",employeeAttendanceFilePath="";
String _uploadDir = getServletContext().getRealPath("/accesscarddata/");
HttpSession session = request.getSession(true);
if(session.getAttribute("accesscardDatafileNname") != null)
fileName = (String) session.getAttribute("accesscardDatafileNname");
employeeAttendanceFilePath = _uploadDir+fileName;
System.out.println("File Path : "+employeeAttendanceFilePath);
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
fis = new FileInputStream(employeeAttendanceFilePath);
// Create an excel workbook from the file system.
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);// gets the first sheet on workbook
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
//count=count+1;
List data = new ArrayList();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
data.add(cell);
}
sheetData.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
session.setAttribute("sheetData", sheetData);
processEmployeeAttendance(request,response);
System.out.println("employeeMap : "+employeeMap);
if(session.getAttribute("employeeMap")!=null)
employeeMap = (LinkedHashMap) session.getAttribute("sheetData");
Iterator<Map.Entry> entries = employeeMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
protected void processEmployeeAttendance(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.out.println("processEmployeeAttendance is called...");
String tempEmpid="",strdepartment="";
int j=1;
List sheetData =null;
HttpSession session = request.getSession(true);
if(session.getAttribute("sheetData")!=null)
sheetData = (ArrayList) session.getAttribute("sheetData");
Map employeeMap = new LinkedHashMap();
Map tempEmployeeMap = new LinkedHashMap();
for (int i = 0; i < sheetData.size(); i++) {
List list = (List) sheetData.get(i);
HSSFCell employeeid = (HSSFCell) list.get(0);
HSSFCell department = (HSSFCell) list.get(3);
HSSFCell date = (HSSFCell) list.get(5);
strdepartment = department.getRichStringCellValue().getString();
if(!tempEmpid.equals("")){
if(tempEmpid.equals(employeeid.getRichStringCellValue().getString()) && !(employeeid.getRichStringCellValue().getString().equals("EmpID") || date.getRichStringCellValue().getString().equals("Date") || department.getRichStringCellValue().getString().equals("Department"))){
if(!(strdepartment.equals("Temporary Card") || strdepartment.equals("Contractor"))){
employeeMap.put(employeeid.getRichStringCellValue().getString()+"_"+j,date.getRichStringCellValue().getString());
// System.out.println("j value : "+j+":"+employeeid.getRichStringCellValue().getString()+"_"+j+","+date.getRichStringCellValue().getString());
j++;
}
}else{
tempEmpid = employeeid.getRichStringCellValue().getString();
j=0;
}
}else{
tempEmpid = employeeid.getRichStringCellValue().getString();
}
// System.out.println("");
}
session.setAttribute("employeeMap", employeeMap);
}
}
I wanted to put it as a comment, but somehow I am unable to comment.
My suggestion would be to debug the code using your IDE. Put breakpoints at relevant positions and see where its going.

How to upload a excel file using tomcat 5.5?

how to update file to tomcat 5.5.
i tried with the follwoing code but the code does not run with tomcat5.5 and shows
Tomcat version 5.5 only supports J2EE 1.2, 1.3, and 1.4 Web module
the code is:
package org.slingemp.fileupload;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slingemp.bean.setNotification;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
/**
* Servlet implementation class Fileupload
*/
#WebServlet("/Fileupload")
public class Fileupload extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Fileupload() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("file upload started....");
// TODO Auto-generated method stub
List fileItemsList = null;
float filesize = 0;
String _fileLink;
String _fileName = null;
String _uploadDir = getServletContext().getRealPath("/accesscarddata/");
System.out.println("_uploadDir :"+_uploadDir);
// Change upload with your directory
HttpSession session = request.getSession(true);
try {
if (ServletFileUpload.isMultipartContent(request)) {
ServletFileUpload servletFileUpload = new ServletFileUpload(
new DiskFileItemFactory());
try {
fileItemsList = servletFileUpload.parseRequest(request);
} catch (FileUploadException ex) {
Logger.getLogger(Fileupload.class.getName()).log(Level.SEVERE, null, ex);
// Change above line replace FileUploadExample with your
// file name
}
String optionalFileName = "";
FileItem fileItem = null;
Iterator it = fileItemsList.iterator();
while (it.hasNext()) {
FileItem fileItemTemp = (FileItem) it.next();
if (fileItemTemp.isFormField()) {
if (fileItemTemp.getFieldName().equals("filename")) {
optionalFileName = fileItemTemp.getString();
System.out.println("optionalFileName : "+optionalFileName);
}
/*
* If you want to pass some other data from JSP page.
* You can access then in this way. For each field you
* have do create if like below. if
* (fileItemTemp.getFieldName
* ().equals("Name of other field like:Firstname")) {
* String Firstname = fileItemTemp.getString(); }
*/
} else {
fileItem = fileItemTemp;
}
}
if (fileItem != null) {
long size_long = fileItem.getSize();
filesize = size_long / 1024;
filesize = filesize / 1000;
// If you want to limit the file size. Here 30MB file size
// is allowed you can change it
//if (filesize > 30.0) {
// Pass error message in session.
//setNotification _sN = new setNotification();
//_sN.setError("File size can't be more than 30MB");
//session.setAttribute("error", _sN);
//} else {
_fileName = fileItem.getName();
if (fileItem.getSize() > 0) {
if (optionalFileName.trim().equals("")) {
_fileName = FilenameUtils.getName(_fileName);
} else {
_fileName = optionalFileName;
}
_fileLink = "../accesscarddata/" + _fileName;
try {
File file = new File(new File(_uploadDir + "/"),fileItem.getName());
fileItem.write(file);
} catch (Exception e) {
e.printStackTrace();
}
setNotification _sN = new setNotification();
_sN.setError("File Uploaded to : " + _fileLink + "");
session.setAttribute("accesscardDatafileNname", _fileName);
session.setAttribute("error", _sN);
}
//}
}
//SELECT * FROM leave_application WHERE from_date >= '2004-01-01' AND to_date <'2004-01-30' and emp_id=128
}
} catch (Exception e) {
e.printStackTrace();
} finally{
}
System.out.println("before calling readFile");
readFile(request,response);
System.out.println("after calling readFile");
response.sendRedirect("index.jsp");
}
protected void readFile(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.out.println("readFile is called..");
Map employeeMap = null;
String fileName = "",employeeAttendanceFilePath="";
String _uploadDir = getServletContext().getRealPath("/accesscarddata/");
HttpSession session = request.getSession(true);
if(session.getAttribute("accesscardDatafileNname") != null)
fileName = (String) session.getAttribute("accesscardDatafileNname");
employeeAttendanceFilePath = _uploadDir+fileName;
System.out.println("File Path : "+employeeAttendanceFilePath);
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
fis = new FileInputStream(employeeAttendanceFilePath);
// Create an excel workbook from the file system.
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);// gets the first sheet on workbook
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
//count=count+1;
List data = new ArrayList();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
data.add(cell);
}
sheetData.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
session.setAttribute("sheetData", sheetData);
processEmployeeAttendance(request,response);
System.out.println("employeeMap : "+employeeMap);
if(session.getAttribute("employeeMap")!=null)
employeeMap = (LinkedHashMap) session.getAttribute("sheetData");
Iterator<Map.Entry> entries = employeeMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
protected void processEmployeeAttendance(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.out.println("processEmployeeAttendance is called...");
String tempEmpid="",strdepartment="";
int j=1;
List sheetData =null;
HttpSession session = request.getSession(true);
if(session.getAttribute("sheetData")!=null)
sheetData = (ArrayList) session.getAttribute("sheetData");
Map employeeMap = new LinkedHashMap();
Map tempEmployeeMap = new LinkedHashMap();
for (int i = 0; i < sheetData.size(); i++) {
List list = (List) sheetData.get(i);
HSSFCell employeeid = (HSSFCell) list.get(0);
HSSFCell department = (HSSFCell) list.get(3);
HSSFCell date = (HSSFCell) list.get(5);
strdepartment = department.getRichStringCellValue().getString();
if(!tempEmpid.equals("")){
if(tempEmpid.equals(employeeid.getRichStringCellValue().getString()) && !(employeeid.getRichStringCellValue().getString().equals("EmpID") || date.getRichStringCellValue().getString().equals("Date") || department.getRichStringCellValue().getString().equals("Department"))){
if(!(strdepartment.equals("Temporary Card") || strdepartment.equals("Contractor"))){
employeeMap.put(employeeid.getRichStringCellValue().getString()+"_"+j,date.getRichStringCellValue().getString());
// System.out.println("j value : "+j+":"+employeeid.getRichStringCellValue().getString()+"_"+j+","+date.getRichStringCellValue().getString());
j++;
}
}else{
tempEmpid = employeeid.getRichStringCellValue().getString();
j=0;
}
}else{
tempEmpid = employeeid.getRichStringCellValue().getString();
}
// System.out.println("");
}
session.setAttribute("employeeMap", employeeMap);
}
}
when i run this code in tomcat 7 it says this error when uploading the file :
java.io.FileNotFoundException: D:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\Fileupload\accesscarddata\C:\Users\anthony.savarimut\Desktop\Map Iterate\SampleData.xls (The filename, directory name, or volume label syntax is incorrect)
Please save me form this.
You are running the tomcat in workspace. Please change location to where tomcat installed. I assuming that your are running with eclipse, click on server and set the location.

Servlet Issue - Index page not popping up

I am using spring framework and i am having Index.jsp like :
Code:
<html>
<head></head>
<body>
<p>File Upload</p>
<form action="ImportService" enctype="multipart/form-data" method="POST">
<input type="file" name="file1"><br>
<input type="Submit" value="Upload File"><br>
</form>
</body>
I have ImportService as
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class ImportService extends HttpServlet {
private static final String TMP_DIR_PATH = "c:\\tmp";
private File tmpDir;
private static final String DESTINATION_DIR_PATH = "c:\\files";
private File destinationDir;
public void init(ServletConfig config) throws ServletException {
super.init(config);
tmpDir = new File(TMP_DIR_PATH);
if (!tmpDir.isDirectory()) {
throw new ServletException(TMP_DIR_PATH + " is not a directory");
}
// String realPath =
// getServletContext().getRealPath(DESTINATION_DIR_PATH);
destinationDir = new File(DESTINATION_DIR_PATH);
if (!destinationDir.isDirectory()) {
throw new ServletException(DESTINATION_DIR_PATH
+ " is not a directory");
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String name = "param";
String value = request.getParameter(name);
String welcomeMessage = "Welcome " + value;
System.out.println("Message=" + welcomeMessage);
response.setContentType("text/html");
response.setContentType("text/plain");
System.out.println("Inside Get Method");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("Inside Post Method");
PrintWriter out = response.getWriter();
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
/*
* Set the size threshold, above which content will be stored on disk.
*/
fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
/*
* Set the temporary directory to store the uploaded files of size above
* threshold.
*/
fileItemFactory.setRepository(tmpDir);
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
/*
* Parse the request
*/
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
/*
* Handle Form Fields.
*/
if (item.isFormField()) {
out.println("File Name = " + item.getFieldName()
+ ", Value = " + item.getString());
} else {
// Handle Uploaded files.
out.println("Field Name = " + item.getFieldName()
+ ", File Name = " + item.getName()
+ ", Content type = " + item.getContentType()
+ ", File Size = " + item.getSize());
}
out.close();
}
} catch (FileUploadException ex) {
log("Error encountered while parsing the request", ex);
} catch (Exception ex) {
log("Error encountered while uploading file", ex);
}
// doGet(request, response);
}
}
In my web.xml, I have
<servlet>
<servlet-name>ImportService</servlet-name>
<servlet-class>com.service.ImportService</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImportService</servlet-name>
<url-pattern>/ImportService/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/jsp/Index.jsp</welcome-file>
</welcome-file-list>
Now when I try to hit the url: http://localhost:8080/delta-webapp/ImportService/jsp/Index.jsp then it gives me blank message and html form is not rendered.
Any suggestions or pointers?
change your entry URL from http://localhost:8080/delta-webapp/ImportService/jsp/Index.jsp
to http://localhost:8080/delta-webapp/jsp/Index.jsp
You've mapped ImportService servlet to handle all requests to /ImportService/*.
Your index.jsp is located at /jsp/Index.jsp. If instead you just put /delta-webapp It /may/ work.
In general though, I don't think welcome files have hard coded paths. Typically you specify something like index.jsp as your welcome file and if nothing handles the request at a particular location, it will fall back to see if one of the welcome files listed is available and will render that.

Categories

Resources