I am getting a Java EE HTTP Status 500 - Permission Denied, when running my local project in a browser. But it can correctly read and write from the file with the same code when running it in Netbeans through a main method.
I have tried to look answers up on SO, and I have not found a solution specific enough.
My index.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="Servlet" method="post">
<input type="text" name="userInput">
<input type="submit" name="Servlet">
</form>
</body>
</html>
Servlet.java:
#WebServlet("/Servlet")
public class Servlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("lol", "lol");
req.getRequestDispatcher("index.jsp").forward(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (req.getParameter("userInput") != null) {
System.out.println("gotcha");
IO io = new IO(req.getParameter("userInput"));
//req.setAttribute("input", io.readFile());
//System.out.println(io.readFile());
}
req.getRequestDispatcher("tab.jsp").forward(req, resp);
}
}
IO.java:
public class IO {
final String FILENAME = "file.txt";
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("file.txt", true);
PrintWriter pw = new PrintWriter(fw);
pw.println("test");
pw.flush();
}
public IO() throws FileNotFoundException {
}
public IO(String text) throws IOException {
FileWriter fw = new FileWriter(FILENAME, true);
PrintWriter pw = new PrintWriter(fw);
pw.println(text + ",");
pw.flush();
}
public String readFile() throws IOException {
StringBuilder sb = new StringBuilder();
FileReader fr = new FileReader(FILENAME);
int data = fr.read();
while (data != -1) {
sb.append(fr.read());
data = fr.read();
}
return sb.toString();
}
}
It chrashes in the constructor on the following line
FileWriter fw = new FileWriter(FILENAME, true);
Full stacktrace
19-Aug-2018 20:10:29.265 SEVERE [http-nio-8084-exec-315] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [PresentationLayer.Servlet] in context with path [/web] threw exception
java.io.FileNotFoundException: file.txt (Permission denied)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:133)
at java.io.FileWriter.<init>(FileWriter.java:78)
at BusinessLayer.IO.<init>(IO.java:24)
at PresentationLayer.Servlet.doPost(Servlet.java:24)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
If you run something on a java ee application server, the current working directory is usually the /bin folder of that server.
Using a relative file position searches the file relative to the current working directory.
One way to display the current working directory is System.out.println( new File(".").getCanonicalPath());
Options:
use an absolute file location
put the file into the current working directory
load the file from the classpath/war
Related
I'm trying to send variables between jsp and servlets, but I got this error that I still can't figure out why. It keeps sending HTTP Status 500 error.
it sending HTTP status 500 eror and java.lang.NullPointerException
but when i test java class in junit it ran fine.
this is jsp:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page import="model.StudentDao"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Student</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Student</h1>
<table class="table">
<tr>
<th>Student ID</th>
<th>Student Name</th>
</tr>
<c:forEach items="${requestScope.students}" var="student">
<tr>
<td><c:out value="${student.getStudentId()}"/></td>
<td><c:out value="${student.getStudentName()}"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>
and this my servlet:
package controller;
import...
#WebServlet("/StudentListServlet")
public class StudentListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public StudentListServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DbConnect dbConnect = new DbConnect();
Connection connection = dbConnect.connect();
StudentDao studentDao = new StudentDao(connection);
ArrayList<Student> students = null;
try {
students = studentDao.findAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("students", students);
request.getRequestDispatcher("student.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
StudentDao :
package model;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class StudentDao {
private Connection connection;
public StudentDao(Connection connection) {
super();
this.connection = connection;
}
public ArrayList<Student> findAll() throws SQLException{
ArrayList<Student> students = new ArrayList<>();
Student student = null;
Statement statement = this.connection.createStatement();
String sqlText = "SELECT * FROM student";
ResultSet resultSet = statement.executeQuery(sqlText);
while(resultSet.next()){
student = new Student();
student.setStudentId(resultSet.getString("student_Id"));
student.setStudentName(resultSet.getString("student_Name"));
students.add(student);
}
resultSet.close();
statement.close();
return students;
}
}
DbConnect:
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnect {
private static final String URL = "jdbc:mysql://localhost:3306/university";
private static final String USER = "root";
private static final String PASSWORD = "";
private Connection connection;
public Connection connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
this.connection = DriverManager.getConnection(URL, USER, PASSWORD);
if(!this.connection.isClosed())
System.out.println("MySQL Connected");
else
System.out.println("MySQL Connect fail!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return this.connection;
}
public void close() throws SQLException {
this.connection.close();
}
}
Stack Trace :
SEVERE: Servlet.service() for servlet [controller.StudentListServlet] in context with path [/MySQLDemo] threw exception
java.lang.NullPointerException
at model.StudentDao.findAll(StudentDao.java:21)
at controller.StudentListServlet.doGet(StudentListServlet.java:34)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Sorry for the long post.
anyone with an idea why this get error?
You are not loading the jdbc driver in your servelet
you can the jdbc driver as follows:
String driver = "com.mysql.jdbc.Driver";
// Load the JDBC driver
Class driver_class = Class.forName(driver);
Hi am new to java so facing some issue,i am hitting servlet from a html page where it is calling different method from different class, but while executing method of class from servlet it is throwing the file not found exception.but everything is present in correct path. while running method of class separately its working fine but from servlet it is not
SEVERE: Servlet.service() for servlet [Search] in context with path [/AutomationTest] threw exception
java.io.FileNotFoundException: WebContent\prop\html.txt (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at com.helix.etl.automation.dao.test.read(test.java:24)
at com.helix.etl.automation.controller.Search.doGet(Search.java:45)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
my test.java
public class test {
//String filenaame="WebContent/prop/html.txt";
/*public static void main(String[] args) throws IOException{
test t= new test();
t.read(filenaame);
}*/
String line="";
public List<String> read(String filename) throws IOException
{
File file =new File(filename);
FileReader fi = new FileReader(file);
BufferedReader in = new BufferedReader(fi);
List<String> tokens = new ArrayList<String>();
while((line=in.readLine())!=null){
tokens.add(line);
System.out.println("entering");
}
return tokens;
}
my servlet
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String Filename="WebContent/prop/html.txt";
test t = new test();
List<String> line=t.read(Filename);
for (String s : line) {
System.out.println(s);
out.print(s);}
}
This question already has answers here:
How to add JAR libraries to WAR project without facing java.lang.ClassNotFoundException? Classpath vs Build Path vs /WEB-INF/lib
(5 answers)
Closed 6 years ago.
I am trying to create an html page which takes some input and saves that data in oracle database using jdbc and servlet.
This is the HTML file
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="HelloServlet" method="post">
<input type="text" placeholder="ID" name="id">
<input type="text" placeholder="NAME" name="name">
<input type="text" placeholder="SALARY" name="salary">
<input type="submit" value="submit">
</form>
</body>
</html>
Here is javafile contains the servlet
package com.gaurav;
import java.sql.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
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.jasper.tagplugins.jstl.core.Out;
#WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Set response content type
// Actual logic goes here.
//String name=request.getParameter("name");
//out.println(name);
}
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String url="jdbc:oracle:thin:#localhost:1521:xe";
String user="system";
String pass="inception";
try{
int id=Integer.parseInt(request.getParameter("id"));
String name=request.getParameter("name");
int salary=Integer.parseInt(request.getParameter("salary"));
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(url,user,pass);
String query="INSERT INTO employee VALUES(?,?,?)";
PreparedStatement stm=con.prepareStatement(query);
stm.setInt(1, id);
stm.setString(2, name);
stm.setInt(3, salary);
stm.executeUpdate();
con.close();
}
catch(ClassNotFoundException e){
out.println("class not found ");
}
catch(SQLException e){
out.println("SQL Exception");
}
}
#Override
public void destroy() {
// resource release
super.destroy();
}
}
file hierarchy
whenever i tries to run the above program,it doesn't shows any error but when i write some data and press the submit button it thorws a ClassNotFound Exception.I don't have any idea whats happening.so someone help me.
Stack Trace:
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1285)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1119)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.gaurav.HelloServlet.doPost(HelloServlet.java:50)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
It looks like you are using Oracle 10g. From Oracle 9i onwards, support for oracle.jdbc.driver.OracleDriver is deprecated (documentation here). Could you try using oracle.jdbc.OracleDriver instead?
Check if you loaded the correct oracle jar driver on your project.
I try to create a restful service that uploads a file. I followed the steps of:
http://examples.javacodegeeks.com/enterprise-java/rest/jersey/jersey-file-upload-example/
http://www.mkyong.com/webservices/jax-rs/file-upload-example-in-jersey/
But, when I upload a file (for example, a .pdf), the input FormDataMultiPart is always NULL and I don´t understand why. I use the libs "jersey-multipart" and "jersey-core". My code:
Restful service:
#Path("/reservation")
public class ReservationWs {
/** The Constant log. */
private static final Logger LOGGER = LoggerFactory.getLogger(ReservationWs.class.getName());
private static final String SERVER_UPLOAD_LOCATION_FOLDER = "C://opt/share/reservation/";
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) {
String uploadedFileLocation = SERVER_UPLOAD_LOCATION_FOLDER
+ fileDetail.getFileName();
// save it
saveFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
return Response.status(200).entity(output).build();
}
#POST
#Path("/upload2")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile2(FormDataMultiPart form) {
FormDataBodyPart filePart = form.getField("file");
ContentDisposition headerOfFilePart = filePart.getContentDisposition();
InputStream fileInputStream = filePart.getValueAs(InputStream.class);
String filePath = SERVER_UPLOAD_LOCATION_FOLDER + headerOfFilePart.getFileName();
// save the file to the server
saveFile(fileInputStream, filePath);
String output = "File saved to server location using FormDataMultiPart : " + filePath;
System.out.println(output);
return Response.status(200).entity(output).build();
}
}
My client:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Form Page</title>
</head>
<body>
<h1>Upload a File</h1>
<form action="reservation/upload" method="post" enctype="multipart/form-data">
<p>
Select a file : <input type="file" name="file" size="55" />
</p>
<input type="submit" value="Upload It" />
</form>
</body>
</html>
When I try to call to "upload", the input is null and the error logs:
GRAVE: El Servlet.service() para el servlet [rest_1288520529] en el
contexto con ruta [/checking] lanzó la excepción [Error processing
webservice request] con causa raíz java.lang.NullPointerException at
com.checking.reservation.ws.ReservationWs.uploadFile(ReservationWs.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497) at
org.apache.openejb.server.cxf.rs.PojoInvoker.performInvocation(PojoInvoker.java:43)
at
org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:165)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:89) at
org.apache.openejb.server.cxf.rs.AutoJAXRSInvoker.invoke(AutoJAXRSInvoker.java:68)
at
org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:57)
at
org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:93)
at
org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
at
org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at
org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:240)
at
org.apache.openejb.server.cxf.rs.CxfRsHttpListener.onMessage(CxfRsHttpListener.java:187)
at
org.apache.openejb.server.rest.RsServlet.service(RsServlet.java:53)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:198)
at
net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:176)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at
org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
When I try to call to "upload2", the input is null and the error logs:
sep 11, 2015 9:12:21 AM org.apache.catalina.core.StandardWrapperValve
invoke GRAVE: El Servlet.service() para el servlet [rest_348842263] en
el contexto con ruta [/checking] lanzó la excepción [Error processing
webservice request] con causa raíz java.lang.NullPointerException at
com.checking.reservation.ws.ReservationWs.uploadFile2(ReservationWs.java:90)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497) at
org.apache.openejb.server.cxf.rs.PojoInvoker.performInvocation(PojoInvoker.java:43)
at
org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:165)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:89) at
org.apache.openejb.server.cxf.rs.AutoJAXRSInvoker.invoke(AutoJAXRSInvoker.java:68)
at
org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:57)
at
org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:93)
at
org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
at
org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at
org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:240)
at
org.apache.openejb.server.cxf.rs.CxfRsHttpListener.onMessage(CxfRsHttpListener.java:187)
at
org.apache.openejb.server.rest.RsServlet.service(RsServlet.java:53)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:198)
at
net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:176)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at
org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Any idea?
I found a not good solution for now.
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(#FormDataParam("file") InputStream file, #FormDataParam("file") FormDataContentDisposition fileDetail, #QueryParam("fileName") String fileName){
...
...
String uploadedFileLocation = SERVER_UPLOAD_LOCATION_FOLDER+ fileName;//fileDetail.getFileName();
// save it
saveFile(file, uploadedFileLocation);
...
//Logic of the service.
...
//Delete file from local.
}
private void saveFile(InputStream uploadedInputStream, String serverLocation) throws IOException {
OutputStream outpuStream=null;
try {
outpuStream = new FileOutputStream(new File(serverLocation));
int read = 0;
byte[] bytes = new byte[1024];
outpuStream = new FileOutputStream(new File(serverLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
outpuStream.write(bytes, 0, read);
}
outpuStream.flush();
outpuStream.close();
} catch( IOException e){
LOGGER.debug("[UploadWs - saveFile] - error: "+e);
} finally{
if(outpuStream!=null){
outpuStream.close();
}
}
}
"fileDetail" is always null and I don´t know why (if anyone knows the solution, say it) so I add the parameter "fileName" (name of the file) that the client send me. I build the location, I save the file in local, the logic of the service is executed (in my case, I send an email with this file) and I delete the file from local.
It's not a good solution because I add an unnecesarry parameter and I save the file in local.
We are using Wicket 6+ and have a strange error on FileUpload.writeTo(file).
It's happening only to certain types of files (docx,xlsx,java) and only in one form. The same exact code works to attach files just fine in other places. Any help? Thank you.
HTML:
<div wicket:id="filesInput"/>
Java:
add(new org.apache.wicket.markup.html.form.upload.MultiFileUploadField("filesInput",
new PropertyModel<Collection<FileUpload>>(this, "uploads"), 5));
Error thrown on line fileUpload.writeTo(file); when called from form onSubmit.
private void writeToFile(FileUpload fileUpload, Attachment attachment) {
if (fileUpload == null) {
return;
}
File file = AttachmentUtils.getFile(attachment, jtracHome);
try {
fileUpload.writeTo(file);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
Error log:
2013-05-03 12:57:23,731 [http-bio-8084-exec-9] ERROR [org.apache.wicket.DefaultExceptionMapper] - Unexpected error occurred
org.apache.wicket.WicketRuntimeException: Method onFormSubmitted of interface org.apache.wicket.markup.html.form.IFormSubmitListener targeted at [SpaceItemViewForm [Component id = form]] on component [SpaceItemViewForm [Component id = form]] threw an exception
at org.apache.wicket.RequestListenerInterface.internalInvoke(RequestListenerInterface.java:268)
at org.apache.wicket.RequestListenerInterface.invoke(RequestListenerInterface.java:216)
at org.apache.wicket.core.request.handler.ListenerInterfaceRequestHandler.invokeListener(ListenerInterfaceRequestHandler.java:240)
at org.apache.wicket.core.request.handler.ListenerInterfaceRequestHandler.respond(ListenerInterfaceRequestHandler.java:226)
at org.apache.wicket.request.cycle.RequestCycle$HandlerExecutor.respond(RequestCycle.java:840)
at org.apache.wicket.request.RequestHandlerStack.execute(RequestHandlerStack.java:64)
at org.apache.wicket.request.cycle.RequestCycle.execute(RequestCycle.java:254)
at org.apache.wicket.request.cycle.RequestCycle.processRequest(RequestCycle.java:211)
at org.apache.wicket.request.cycle.RequestCycle.processRequestAndDetach(RequestCycle.java:282)
at org.apache.wicket.protocol.http.WicketFilter.processRequestCycle(WicketFilter.java:244)
at org.apache.wicket.protocol.http.WicketFilter.processRequest(WicketFilter.java:188)
at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:267)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:75)
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)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.wicket.RequestListenerInterface.internalInvoke(RequestListenerInterface.java:258)
... 31 more
Caused by: java.lang.RuntimeException: java.io.FileNotFoundException: C:\Users\aeb\AppData\Roaming\NetBeans\7.2.1\apache-tomcat-7.0.27.0_base\temp\upload_9108b655_6177_4450_8e82_a767f101dd40_1997755963.tmp (The system cannot find the file specified)
at info.jtrac.JtracImpl.writeToFile(JtracImpl.java:405)
at info.jtrac.JtracImpl.storeScopeOfWork(JtracImpl.java:2053)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:301)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:198)
at $Proxy11.storeScopeOfWork(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:301)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy12.storeScopeOfWork(Unknown Source)
at info.jtrac.wicket.SpaceItemViewFormPanel$SpaceItemViewForm.onSubmit(SpaceItemViewFormPanel.java:433)
at org.apache.wicket.markup.html.form.Form$9.component(Form.java:1246)
at org.apache.wicket.markup.html.form.Form$9.component(Form.java:1240)
at org.apache.wicket.util.visit.Visits.visitPostOrderHelper(Visits.java:274)
at org.apache.wicket.util.visit.Visits.visitPostOrder(Visits.java:245)
at org.apache.wicket.markup.html.form.Form.delegateSubmit(Form.java:1239)
at org.apache.wicket.markup.html.form.Form.process(Form.java:921)
at org.apache.wicket.markup.html.form.Form.onFormSubmitted(Form.java:767)
at org.apache.wicket.markup.html.form.Form.onFormSubmitted(Form.java:700)
... 36 more
Caused by: java.io.FileNotFoundException: C:\Users\aib\AppData\Roaming\NetBeans\7.2.1\apache-tomcat-7.0.27.0_base\temp\upload_9108b655_6177_4450_8e82_a767f101dd40_1997755963.tmp (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at org.apache.wicket.util.upload.DiskFileItem.write(DiskFileItem.java:439)
at org.apache.wicket.markup.html.form.upload.FileUpload.writeTo(FileUpload.java:234)
at info.jtrac.JtracImpl.writeToFile(JtracImpl.java:402)
So this is the code where the exception is coming from:
if (!outputFile.renameTo(file))
{
BufferedInputStream in = null;
BufferedOutputStream out = null;
try
{
in = new BufferedInputStream(new FileInputStream(outputFile));
out = new BufferedOutputStream(new FileOutputStream(file));
Streams.copy(in, out);
}
finally
{
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
javadoc:
This method is only guaranteed to work once, the first time it is invoked for a
particular item. This is because, in the event that the method renames a temporary file, that
file will no longer be available to copy or rename again at a later time.
The exception is coming from the opening of the "outputFile" File - as if it is no longer there. Is it possible the renameTo succeeded to do something with the file, but the renameTo method still returned with false? Can you set a breakpoint there and see what is happening? Maybe somehow you DO call it twice?
From renameTo's javadoc:
Many aspects of the behavior of this method are inherently
platform-dependent: The rename operation might not be able to move a
file from one filesystem to another, it might not be atomic, and it
might not succeed if a file with the destination abstract pathname
already exists. The return value should always be checked to make sure
that the rename operation was successful.
I just ran the wicket MultiUploadPage example and everything is working.
Give us more details about your page structure, what's different about your page?
WicketApplication.java
public class WicketApplication extends WebApplication {
private Folder uploadFolder = null;
#Override
public Class<? extends WebPage> getHomePage(){
return HomePage.class;
}
public Folder getUploadFolder(){
return uploadFolder;
}
#Override
public void init(){
super.init();
getResourceSettings().setThrowExceptionOnMissingResource(false);
uploadFolder = new Folder(System.getProperty("java.io.tmpdir"), "wicket-uploads");
uploadFolder.mkdirs();
getApplicationSettings().setUploadProgressUpdatesEnabled(true);
}
}
HomePage.java
public class HomePage extends WebPage {
private static final long serialVersionUID = 1L;
private final FileListView fileListView;
public HomePage(final PageParameters parameters){
Folder uploadFolder = getUploadFolder();
final FeedbackPanel uploadFeedback = new FeedbackPanel("uploadFeedback");
add(uploadFeedback);
final FileUploadForm simpleUploadForm = new FileUploadForm("simpleUpload");
add(simpleUploadForm);
add(new Label("dir", uploadFolder.getAbsolutePath()));
fileListView = new FileListView("fileList", new LoadableDetachableModel<List<File>>(){
private static final long serialVersionUID = 1L;
#Override
protected List<File> load(){
return Arrays.asList(getUploadFolder().listFiles());
}
});
add(fileListView);
}
private class FileListView extends ListView<File>{
private static final long serialVersionUID = 1L;
public FileListView(String name, final IModel<List<File>> files){
super(name, files);
}
#Override
protected void populateItem(ListItem<File> listItem){
final File file = listItem.getModelObject();
listItem.add(new Label("file", file.getName()));
listItem.add(new Link<Void>("delete"){
private static final long serialVersionUID = 1L;
#Override
public void onClick(){
Files.remove(file);
info("Deleted " + file);
}
});
}
}
private class FileUploadForm extends Form<Void>{
private static final long serialVersionUID = 1L;
private final Collection<FileUpload> uploads = new ArrayList<FileUpload>();
public FileUploadForm(String name){
super(name);
setMultiPart(true);
add(new MultiFileUploadField("fileInput", new PropertyModel<Collection<FileUpload>>(this, "uploads"), 5, true));
setMaxSize(Bytes.kilobytes(100000));
}
#Override
protected void onSubmit(){
for (FileUpload upload : uploads){
File newFile = new File(getUploadFolder(), upload.getClientFileName());
try{
newFile.createNewFile();
upload.writeTo(newFile);
HomePage.this.info("saved file: " + upload.getClientFileName());
} catch (Exception e){
throw new IllegalStateException("Unable to write file");
}
}
}
}
private Folder getUploadFolder(){
return ((WicketApplication) Application.get()).getUploadFolder();
}
}
HomePage.html
<!DOCTYPE html>
<html xmlns:wicket="http://wicket.apache.org">
<head>
<meta charset="utf-8" />
<title>Apache Wicket Quickstart</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" title="Stylesheet" />
</head>
<body>
The multi upload field is based on javascript found
<a target="_blank" href="http://the-stickman.com/web-development/javascript/upload-multiple-files-with-a-single-file-element/">here</a>.
<br />
<br /> Wicket can also handle file uploads via AJAX, please see AJAX
examples section. AJAX Functionality is not included in this example to
keep things simple.
<br />
<br />
<form wicket:id="simpleUpload">
<fieldset>
<legend>Upload form</legend>
<p>
<div wicket:id="fileInput" class="mfuex" />
</p>
<input type="submit" value="Upload!" />
</fieldset>
</form>
<div><span wicket:id="uploadFeedback" /></div>
<div>
<h4>Current files in <span wicket:id="dir">(dir)</span>:</h4>
<table>
<tr wicket:id="fileList">
<td width="200"><span wicket:id="file">(file)</span></td>
<td><img src="delete.gif" border="0" /></td>
</tr>
</table>
</div>
</body>
</html>