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>
Related
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
I am migrating an application from older version of wicket to wicket 8. Some pages are working ok (simple pages such as login). These pages does not use the extension mechanism.
When I access to a page that has the mechanism it doesn't work. I don't know if this is a bug but I tried everything and couldn't find a solution.
I am using wicket 8.0.0-M5 (i kwnow that is not a stable release). Anybody had the same problem?
Here is my code:
WerklijstPageXXX.html
<html xmlns:wicket>
<body>
<wicket:extend>
<div wicket:id="panelXXX"></div>
</wicket:extend>
</body>
WerklijstPanelXXX.html
<wicket:head xmlns:wicket>
</wicket:head>
<wicket:panel xmlns:wicket>
<div wicket:id="filter">
<div wicket:id="label"></div>
</div>
</wicket:panel>
WerklijstPageXXX.java
public class WerklijstPageXXX extends BasePage {
private WerklijstPanelXXX werklijstPanel;
public WerklijstPageXXX() {
werklijstPanel = new WerklijstPanelXXX("panelXXX"){};
add(werklijstPanel);
}
#Override
public Panel getContextPanel(String id)
{
return werklijstPanel.getWerklijstFilterPanel();
}
WerklijstPanelXXX.java
public abstract class WerklijstPanelXXX extends Panel {
private static final Logger LOG = LoggerFactory
.getLogger(WerklijstPanelXXX.class);
private Panel filterPanel;
public WerklijstPanelXXX(String id) {
super(id);
WebMarkupContainer upperPanel = new WebMarkupContainer("filter");
filterPanel = new Panel("filterPanel") {
};
add(upperPanel);
upperPanel.add(new Label("label"));
}
public Panel getWerklijstFilterPanel() {
return filterPanel;
}
EDIT:
BasePage.html (part of it)
<div id="body" class="body">
<div id="aside" class="aside">
<div wicket:id="contextPanel"></div>
</div>
<div id="content" class="content">
<div class="padding">
<wicket:child></wicket:child>
</div>
</div>
</div>
BasePage.java
#Override
protected void onInitialize() {
super.onInitialize();
add(getContextPanel("contextPanel"));
addTabMenu();
addMenu();
addPatientBar();
}
Error:
Root cause:
org.apache.wicket.WicketRuntimeException: The component(s) below failed to render. Possible reasons could be that:
1) you have added a component in code but forgot to reference it in the markup (thus the component will never be rendered),
2) if your components were added in a parent container then make sure the markup for the child container includes them in .
[WerklijstPanelXXX [Component id = panelXXX, page = nl.philips.raris.web.werklijst.WerklijstPageXXX, path = panelXXX, type = nl.philips.raris.web.werklijst.WerklijstPanelXXX, isVisible = true, isVersioned = true], children = [WebMarkupContainer [Component id = filter]]]
[WebMarkupContainer [Component id = filter, page = nl.philips.raris.web.werklijst.WerklijstPageXXX, path = panelXXX:filter, type = org.apache.wicket.markup.html.WebMarkupContainer, isVisible = true, isVersioned = true], children = [Component id = label]]
[Component id = label, page = nl.philips.raris.web.werklijst.WerklijstPageXXX, path = panelXXX:filter:label, type = org.apache.wicket.markup.html.basic.Label, isVisible = true, isVersioned = true]
[Panel [Component id = filterPanel, page = nl.philips.raris.web.werklijst.WerklijstPageXXX, path = filterPanel, type = org.apache.wicket.markup.html.panel.Panel, isVisible = true, isVersioned = true]]
at org.apache.wicket.Page.checkRendering(Page.java:662)
at org.apache.wicket.Page.onAfterRender(Page.java:805)
at org.apache.wicket.markup.html.WebPage.onAfterRender(WebPage.java:209)
at org.apache.wicket.Component.afterRender(Component.java:919)
at org.apache.wicket.Component.render(Component.java:2335)
at org.apache.wicket.Page.renderPage(Page.java:987)
at org.apache.wicket.request.handler.render.WebPageRenderer.renderPage(WebPageRenderer.java:124)
at org.apache.wicket.request.handler.render.WebPageRenderer.respond(WebPageRenderer.java:236)
at org.apache.wicket.core.request.handler.RenderPageRequestHandler.respond(RenderPageRequestHandler.java:175)
at org.apache.wicket.request.cycle.RequestCycle$HandlerExecutor.respond(RequestCycle.java:912)
at org.apache.wicket.request.RequestHandlerExecutor.execute(RequestHandlerExecutor.java:65)
at org.apache.wicket.request.cycle.RequestCycle.execute(RequestCycle.java:283)
at org.apache.wicket.request.cycle.RequestCycle.processRequest(RequestCycle.java:253)
at org.apache.wicket.request.cycle.RequestCycle.processRequestAndDetach(RequestCycle.java:221)
at org.apache.wicket.protocol.http.WicketFilter.processRequestCycle(WicketFilter.java:262)
at org.apache.wicket.protocol.http.WicketFilter.processRequest(WicketFilter.java:204)
at org.apache.wicket.protocol.http.WicketServlet.doGet(WicketServlet.java:137)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:808)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669)
at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:387)
at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:151)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
The Java and HTML component trees should match.
Your HTML states: <div wicket:id="*contextPanel*"></div>, but your Java code returns a Panel with id filterPanel instead.
public WerklijstPageXXX() {
werklijstPanel = new WerklijstPanelXXX("panelXXX"){};
add(werklijstPanel);
}
#Override
public Panel getContextPanel(String id) // HERE id is ignored
{
return werklijstPanel.getWerklijstFilterPanel(); // This returns a panel with id `filterPanel`
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Working on a Spring MVC based project, I am getting the following code while I try to save review (Bean). I am able to get the data into controller successfully but for some reason getting a NULL pointer exception while saving.
Here is the code
-- JSP--
<div class="col-md-12">
<div class="p-b">
<cf:form action="${pageContext.request.contextPath}/reviews/add" id="reviewAction" modelAttribute="review" method="post" accept-charset="utf-8">
<div style="display:none">
<cf:input path="tutorId" type="hidden" name="tutorId" id="tutorId" value="" />
<cf:input path="studentId" type="hidden" name="studentId" id="studentId" value="${sessionScope.user.userId}" />
</div>
<label>Your Comment / Review</label>
<cf:textarea path="reviewMessage" name="reviewMessage" required="required"/>
<p class="text-right"><input type="submit" class="btn btn-default btn-sm" name="submit" value="Post"> </p>
</cf:form>
</div>
</div>
<cf:hidden path="userId" id="userId"/>
<script type="text/javascript">
$(document).ready(function () {
console.log("Calling getTutorId()");
getTutorId();
});
function getTutorId()
{
$('#tutorId').attr('value',$('#userId').val());
}
</script>
-- Controller --
#RequestMapping (value = "/add" , method = RequestMethod.POST)
public String addReview(#Valid #ModelAttribute Review review , BindingResult bindingResult, Model model) {
try {
if (bindingResult.hasErrors()) {
System.out.println(bindingResult.getAllErrors().iterator().next().toString());
return "FindTutor";
}
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
String newDate = dateFormat.format(date); //06/08/2016 15:59:48
review.setDate(newDate);
review.setReviewStatus("Disapproved");
//Just for testing purposes
System.out.println(review.getStudentId());
System.out.println(review.getTutorId());
System.out.println(review.getDate());
System.out.println(review.getReviewMessage());
System.out.println(review.getReviewStatus());
//Just for testing purposes
reviewBL.saveReview(review);
List<Subject> subjectList = subjectBL.getAllSubjects();
List<User> userList = manageUserBL.getAllUsers();
model.addAttribute("subjectList", subjectList);
model.addAttribute("userList", userList);
} catch (Exception e) {
e.printStackTrace();
}
return "FindTutor";
}
-- Business Logic Class --
#Service
public class ReviewBL {
private ReviewsMongoRepository reviewsMongoRepository;
public void saveReview(Review review)
{
if (StringUtils.isEmpty(review.getId())) {
review.setId(null);
}
reviewsMongoRepository.save(review);
}
}
-- Bean Class --
#Document (collection = "reviews")
public class Review {
#Id
private String Id;
private String tutorId;
private String studentId;
private String date;
private String reviewMessage;
private String reviewStatus;
// plus constructors also all of the getters and setters
}
I am getting the following error message, and as you can see the data (Model Attribute is successfully been captured in the controller but is not being saved in the database due to a NULL pointer exception error that I can't seem to find out why
2016-05-28 13:16:59 [http-bio-8080-exec-6] INFO e.b.fyp.stp.web.filter.SessionFilter - Filtering: /reviews/add
java.lang.NullPointerException
at edu.bnu.fyp.stp.bl.ReviewBL.saveReview(ReviewBL.java:23)
at edu.bnu.fyp.stp.web.controller.student.ReviewController.addReview(ReviewControll er.java:66)
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:606)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
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 edu.bnu.fyp.stp.web.filter.SessionFilter.doFilter(SessionFilter.java:59)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
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 org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
574939f19fcf9da523b63f8b // ID 1 (String)
57493a3e9fcf9da523b63f8c // ID 2 (String)
28/05/2016 13:16:59 //Date (String)
Great Tutor // Message (String)
Disapproved //Status (String)
2016-05-28 13:16:59 [http-bio-8080-exec-6] INFO e.b.fyp.stp.web.filter.SessionFilter - Filtering: /WEB-INF/jsp/FindTutor.jsp
I was able to resolve this issue. It was because I didn't apply #Autowired on reviewsMongoRepository so it wasn't linked with the review bean. I corrected this and now it is working. Thank you
Inside ReviewBL.saveReview you are calling reviewsMongoRepository.save(review)
But I can see you havent initialized reviewsMongoRepository, this is just a reference type reffering to "nothhing." It might be the cause of your Null Pointer exception
I am working with canvas.js charts.I need to populate date from servlet into the chart.I have tried a process but data is not coming to the Chart.I am posting the code i have tried..
In the Jsp end
<html>
<head>
<title>Chart JS Library Demo</title>
<style>
</style>
</head>
<body>
<canvas id="canvas" height="500" width="500"></canvas>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="Chart.min.js"></script>
<script type="text/javascript" src="ts-chart-script.js"></script>
</body>
</html>
The js i am using for fetching the servlet
var TUTORIAL_SAVVY ={
/*Makes the AJAX calll (synchronous) to load a Student Data*/
loadStudentData : function(){
var formattedstudentListArray =[];
$.ajax({
async: false,
url: "StudentJsonDataServlet",
dataType:"json",
success: function(studentJsonData) {
console.log(studentJsonData);
$.each(studentJsonData,function(index,aStudent){
formattedstudentListArray.push([aStudent.mathematicsMark,aStudent.computerMark,aStudent.historyMark,aStudent.litratureMark,aStudent.geographyMark]);
});
}
});
return formattedstudentListArray;
},
/*Crate the custom Object with the data*/
createChartData : function(jsonData){
console.log(jsonData);
return {
labels : ["Mathematics", "Computers", "History","Literature", "Geography"],
datasets : [
{
fillColor : "rgba(255,0,0,0.3)",
strokeColor : "rgba(0,255,0,1)",
pointColor : "rgba(0,0,255,1)",
pointStrokeColor : "rgba(0,0,255,1)",
/*As Ajax response data is a multidimensional array, we have 'student' data in 0th position*/
data : jsonData[0]
}
]
};
},
/*Renders the Chart on a canvas and returns the reference to chart*/
renderStudenrRadarChart:function(radarChartData){
var context2D = document.getElementById("canvas").getContext("2d"),
myRadar = new Chart(context2D).
Radar(radarChartData,{
scaleShowLabels : false,
pointLabelFontSize : 10
});
return myRadar;
},
/*Initalization Student render chart*/
initRadarChart : function(){
var studentData = TUTORIAL_SAVVY.loadStudentData();
chartData = TUTORIAL_SAVVY.createChartData(studentData);
radarChartObj = TUTORIAL_SAVVY.renderStudenrRadarChart(chartData);
}
};
$(document).ready(function(){
TUTORIAL_SAVVY.initRadarChart();
});
Servlet i am using
package com.servlet;
#WebServlet("/StudentJsonDataServlet")
public class StudentJsonDataServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public StudentJsonDataServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
List<Student> listOfStudent = getStudentData();
Gson gson = new Gson();
String jsonString = gson.toJson(listOfStudent);
response.setContentType("application/json");
response.getWriter().write(jsonString);
}
private List<Student> getStudentData() {
List<Student> listOfStudent = new ArrayList<Student>();
Student s1 = new Student();
s1.setName("Sandeep");
s1.setComputerMark(75);
s1.setMathematicsMark(26);
s1.setGeographyMark(91);
s1.setHistoryMark(55);
s1.setLitratureMark(36);
listOfStudent.add(s1);
return listOfStudent;
}
}
Student Class
public class Student {
private String name;
private int ComputerMark;
private int MathematicsMark;
private int GeographyMark;
private int HistoryMark;
private int LitratureMark;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getComputerMark() {
return ComputerMark;
}
public void setComputerMark(int computerMark) {
ComputerMark = computerMark;
}
public int getMathematicsMark() {
return MathematicsMark;
}
public void setMathematicsMark(int mathematicsMark) {
MathematicsMark = mathematicsMark;
}
public int getGeographyMark() {
return GeographyMark;
}
public void setGeographyMark(int geographyMark) {
GeographyMark = geographyMark;
}
public int getHistoryMark() {
return HistoryMark;
}
public void setHistoryMark(int historyMark) {
HistoryMark = historyMark;
}
public int getLitratureMark() {
return LitratureMark;
}
public void setLitratureMark(int litratureMark) {
LitratureMark = litratureMark;
}
}
This codes i am using as my chart and servlet interaction but getting error in the log that ,it is not finding the Gson.But i have included the jar .I am using gson-2.2.4.jar for it.
SEVERE: Servlet.service() for servlet [com.servlet.StudentJsonDataServlet] in context with path [/jQueryMenu] threw exception [Servlet execution threw an exception] with root cause
java.lang.ClassNotFoundException: com.google.gson.Gson
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
at com.servlet.StudentJsonDataServlet.doGet(StudentJsonDataServlet.java:29)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
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 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: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:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:722)
Put the Gson jar where Tomcat will find it and load it.
From the Apache Tomcat documentation:
A class loader is created for each web application that is deployed in
a single Tomcat instance. All unpacked classes and resources in the
/WEB-INF/classes directory of your web application, plus classes and
resources in JAR files under the /WEB-INF/lib directory of your web
application, are made visible to this web application, but not to
other ones.
How can i initialized Multipart request..? I am uploading file using multipart/form-data content type but i can't get multipart request in my controller.So how can i get multipart request in my controller ..
Thanks in Advance.
I am getting error like this..
Jun 13, 2012 2:01:05 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/Login] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Multipart request not initialized] with root cause
java.lang.IllegalStateException: Multipart request not initialized
at org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest.initializeMultipart(AbstractMultipartHttpServletRequest.java:107)
at org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest.getMultipartFiles(AbstractMultipartHttpServletRequest.java:97)
at org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest.getFile(AbstractMultipartHttpServletRequest.java:60)
at com.mpm.common.controller.FileUploadController.create(FileUploadController.java:62)
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.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:585)
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:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:279)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)
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)
And my JSP code is :
<body>
<h1>Please upload a file</h1>
<form method="post" action="upload.action" enctype="multipart/form-data">
<input type="text" name="name"/></br>
<input type="file" name="file"/></br>
<input type="submit"/>
</form>
</body>
and my servlet-context.xml code is :
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
</bean>
<bean id="fileUploadController" class="com.mpm.common.controller.FileUploadController" ></bean>
You seem to use Spring. In that case, I usually manage multipart requests like this:
#RequestMapping("/url")
public String method(HttpServletRequest request) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// do stuff with multipartRequest
return "/jsp";
}
You simply need to cast your HttpServletRequest request.
public void upload(HttpServletRequest request) {
File up = new File("C:\\temp"); // path where u need to upload
// Create object of MultipartRequest to upload file
MultipartRequest m;
try {
m = new MultipartRequest(request, up.toString());
Enumeration files = m.getFileNames();
// Get the files to be uploaded from enumeration
while (files.hasMoreElements()) {
String upload = (String) files.nextElement();
filename = m.getFilesystemName(upload);
// out.println("<br/><br/><br/><br/>");
}
} catch (IOException e) {
System.out.println("Error in Uploading files...");
}
xsdName = filename.substring(0, filename.lastIndexOf('.'));
}
it was my code to do the same in servlet. Hope it helps.