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.
Related
So I need a unix command to be executed by clicking a button in a jsp.
Here's the jsp:
<body>
<div align="center">
<h2>Welcome to ETL Automation Testing Tool</h2>
<h3>Please select Graph:</h3>
<table border="1">
<th>Graph</th>
<tr>
<td>Graph 1</td>
<td><INPUT TYPE="radio" NAME="graph" VALUE="radio1"></td>
</tr>
</table>
<form action="${pageContext.request.contextPath}/myservlet" method="post">
<input type="submit" value="Submit" name="submit" />
</form>
</div>
</body>
All pretty straightforward there.
Here's the servlet:
#WebServlet("/myservlet")
public class MyServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UnixPrompt unixprompt = new UnixPrompt();
unixprompt.connect();
}
}
Here's the code to connect to ssh and execute a command:
import com.jcraft.jsch.*;
import java.io.*;
public class UnixPrompt{
public static void connect(){
try{
JSch jsch=new JSch();
String host=null;
String user="******";
host="*******";
String config =
"Port 22\n"+
"\n"+
"Host foo\n"+
" User "+user+"\n"+
" Hostname "+host+"\n"+
"Host *\n"+
" ConnectTime 30000\n"+
" PreferredAuthentications keyboard-interactive,password,publickey\n"+
" #ForwardAgent yes\n"+
" #StrictHostKeyChecking no\n"+
" #IdentityFile ~/.ssh/id_rsa\n"+
" #UserKnownHostsFile ~/.ssh/known_hosts";
ConfigRepository configRepository =
com.jcraft.jsch.OpenSSHConfig.parse(config);
jsch.setConfigRepository(configRepository);
Session session=jsch.getSession("foo");
String passwd ="*****";
session.setPassword(passwd);
UserInfo ui = new MyUserInfo(){
public boolean promptYesNo(String message){
int foo = 0;
return foo==0;
}
};
session.setUserInfo(ui);
session.connect();
String command="pwd";
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
System.out.print(new String(tmp, 0, i));
}
if(channel.isClosed()){
if(in.available()>0) continue;
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
}
catch(Exception e){
System.out.println(e);
}
}
public static void main(String arg[]){
connect();
}
public static abstract class MyUserInfo
implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return null; }
public boolean promptYesNo(String str){ return false; }
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return false; }
public boolean promptPassword(String message){ return false; }
public void showMessage(String message){ }
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
return null;
}
}
}
I am able to connect to the SSH and execute commands through the standalone UnixPrompt class but am not able to do so through the jsp.
This is the error I am getting:
SEVERE: Servlet.service() for servlet [unix.MyServlet] in context with
path [/Scratchpad] threw exception [Servlet execution threw an
exception] with root cause java.lang.ClassNotFoundException:
com.jcraft.jsch.ConfigRepository at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1858)
at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1709)
at unix.MyServlet.doPost(MyServlet.java:17) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:650) 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.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: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:956)
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: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:722)
The class the error refers to is present in the newer JSch jar having version 0.1.54 which I have included in the build path so I'm not sure what the problem is.
Any help would be appreciated
I am learning wicket framework and while working with ajax I tried one example in which I want to display a panel with selected radio button's company name. But while doing this I am getting some error. Here I mentioned all details from my coding:
Test.java
public class Test extends WebPage {
private static final List<String> companies = Arrays.asList(new String[] {"Google","Microsoft","Yahoo"});
private ArrayList<String> compSelected = new ArrayList<String>();
private Panel panel;
public Test(final PageParameters parameters) {
final RadioChoice<String> companyList =
new RadioChoice<String>("companyNames",new Model(compSelected),companies);
companyList.add(new AjaxFormChoiceComponentUpdatingBehavior() {
#Override
protected void onUpdate(AjaxRequestTarget target) {
if("Google".equals(companyList.getModelObject())){
panel = new Panel1("panel1","Google");
}
else if("Microsoft".equals(companyList.getModelObject())){
panel = new Panel1("panel1","Microsoft");
}
else{
panel = new Panel1("panel1","Yahoo");
}
panel.setOutputMarkupId(true);
target.addComponent(panel);
}});
Form<?> form = new Form<Void>("form");
add(form);
form.add(companyList);
form.add(panel);
this.add(form);
}
}
Test.html
<form wicket:id="form">
<label><b>Company List:</b></label><br>
<span wicket:id="companyNames">radio button list will goes here</span><br>
<span wicket:id = "panel1" class="panel">panel goes here</span>
</form>
Panel1.java
#SuppressWarnings("serial")
public class Panel1 extends Panel{
public Panel1(String id,String cName) {
super(id);
add(new Label("msg", "selected company is:"+ cName));
}
}
Panel1.html
<body>
<wicket:panel>
<span wicket:id="msg">message goes here</span>
</wicket:panel>
</body>
WicketMessage: Can't instantiate page using constructor public demo.wicket.ajax.Test(org.apache.wicket.PageParameters) and argument Root cause:java.lang.IllegalArgumentException: argument child may not be null at org.apache.wicket.MarkupContainer.add(MarkupContainer.java:131) at demo.wicket.ajax.Test.(Test.java:46) at java.lang.reflect.Constructor.newInstance(Unknown Source) at org.apache.wicket.session.DefaultPageFactory.createPage(DefaultPageFactory.java:188) at org.apache.wicket.session.DefaultPageFactory.newPage(DefaultPageFactory.java:65) at org.apache.wicket.request.target.component.BookmarkablePageRequestTarget.newPage(BookmarkablePageRequestTarget.java:299) at org.apache.wicket.request.target.component.BookmarkablePageRequestTarget.getPage(BookmarkablePageRequestTarget.java:321) at org.apache.wicket.request.target.component.BookmarkablePageRequestTarget.processEvents(BookmarkablePageRequestTarget.java:234) at org.apache.wicket.request.AbstractRequestCycleProcessor.processEvents(AbstractRequestCycleProcessor.java:92) at org.apache.wicket.RequestCycle.processEventsAndRespond(RequestCycle.java:1250) at org.apache.wicket.RequestCycle.step(RequestCycle.java:1329) at org.apache.wicket.RequestCycle.steps(RequestCycle.java:1428) at org.apache.wicket.RequestCycle.request(RequestCycle.java:545) at org.apache.wicket.protocol.http.WicketFilter.doGet(WicketFilter.java:468) at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:301) 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:503) 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:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421) 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:314) 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)
I am not sure what I did wrong here. can someone please help me to figure it out?
The problem is form.add(panel);. panel is null at that time. You initialize it in #onUpdate() but it is executed only after a click(?) on the radio buttons.
Solution:
Change panel type to WebMarkupContainer and initialize it in the page's constructor. Call panel.setOutputMarkupId(true) also in the constructor so the <span wicket:id="panel1"...> has an id in the rendered HTML and being able to be referenced later with JS to replace/update it. In #onUpdate() use something like panel = panel.replaceWith(new Panel1(panel.getId(), choice.getModelObject())); target.add(panel);
I have the following dependencies for jersey in my web application
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.8</version>
</dependency>
when I use #Consumes(MediaType.APPLICATION_JSON) or #Produces(MediaType.APPLICATION_JSON) i get a server error . Similarly if I try and use XML . Is it because of the libraries I am using ?
my java class
import org.apache.log4j.Logger;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("/test")
public class test {
private static Logger logger = Logger.getLogger(test.class);
#GET
#Produces(MediaType.TEXT_PLAIN) // works perfectly
public Response getMsg()
{
logger.info("Inside getMsg()");
String output = "hello world";
return Response.status(200).entity(output).build();
}
/* #GET // I get a HTTP 500 , server error
#Path("/get")
#Produces(MediaType.APPLICATION_JSON)
public Track getTrackInJSON() {
Track track = new Track();
track.setTitle("Enter Sandman");
track.setSinger("Metallica");
return track;
}
*/
#GET
#Path("/get")
#Produces(MediaType.APPLICATION_JSON)
public Response getTrackInJSON() {
Track track = new Track();
track.setTitle("Enter Sandman");
track.setSinger("Metallica");
//String test = " hello world";
return Response.status(201).entity(track).build();
}
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
// #Produces(Me)
public Response createTrackInJSON(Track track) {
String result = "Track saved : " + track;
return Response.status(201).entity(result).build();
}
#POST
#Path("/getValue")
#Produces(MediaType.APPLICATION_XML)
public void createXML()
{
String result = " get the track";
// return result.createXML();
// check this line
}
}
when I use a rest client to access the #GET resource I get this error :
<u>Internal Server Error</u></p><p><b>description</b> <u>The server encountered an internal error that prevented it from fulfilling this request.</u>
when I use the rest client to access the #POST resource I get this error:
<u>Internal Server Error</u></p><p><b>description</b> <u>The server encountered an internal error that prevented it from fulfilling this request.</u>
this is what I get from the Tomcat error logs
Jan 29, 2014 11:00:21 AM com.sun.jersey.spi.container.ContainerResponse logException
SEVERE: Mapped exception to response: 500 (Internal Server Error)
javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class com.myProj.jsp.rest.Track, and Java type class com.gsipartners.apimgmtut
at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:285)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1437)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:662)
Caused by: com.sun.jersey.api.MessageException: A message body writer for Java class com.myProj.jsp.rest.Track, and Java type class com.myProj.jsp.rest.Track, and MIM
... 24 more
the Track class
public class Track {
String title;
String singer;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSinger() {
return singer;
}
public void setSinger(String singer) {
this.singer = singer;
}
#Override
public String toString() {
return "Track [title=" + title + ", singer=" + singer + "]";
}
}
You should annotate your Track class with JAXB annotations and Jersey will use its MessageBodyWriter to serialize/marshall the returned entity (track) into the response outputstream. Or you'll need to provide your own implementation of MessageBodyWriter for the Track type to write the serialized form in the response outputstream. Otherwise, Jersey doesn't know how to do it.
Form my client application (AngularJS), I am uploading a file and some other data as FormData.
var formData=new FormData();
formData.append("file",file.files[0]); //files
formData.append("docData", angular.toJson($scope.docdata)); //invoice
Value of angular.toJson($scope.docdata) is like {"configuration":20,"title":"invoicedata"}
This is my HTTP post
$http({
method: 'POST',
url: uploadurl,
headers: {'Content-Type': false},
data: formData,
transformRequest: function(data, headersGetterFunction) {
return data;
}
})
.success(function(data, status) {
alert("Error");
})
.error(function(data, status) {
alert("Error");
});
The request is getting in my Spring MVC controller and I am able to process with the file. But the other data (docData), I am not able to get.
Here is my UploadController.java
#Controller
public class UploadController {
#RequestMapping(value="/newDocument", method = RequestMethod.POST)
public void UploadFile(HttpServletRequest request, HttpServletResponse response) {
MultipartHttpServletRequest mRequest=(MultipartHttpServletRequest)request;
Iterator<String> itr=mRequest.getFileNames();
while(itr.hasNext()){
MultipartFile file=mRequest.getFile(itr.next());
String fileName=file.getOriginalFilename();
try {
File newFile = new File("/home/myHome/file-uploaded/"+fileName);
// if the directory does not exist, create it
if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdirs();
}
FileCopyUtils.copy(file.getBytes(), newFile);
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
Enumeration<String> parametrs = request.getParameterNames();
while(parametrs.hasMoreElements()) {
String param=parametrs.nextElement();
System.out.println("Param : " + param);
Object object=request.getAttribute(param);
System.out.println("Param Instance" + object.getClass().getName());
}
}
}
The first part is working perfectly. (Copying file to the directory). But the second part giving me an exception. First it prints the value of param which is docData the one I send form client app in FormData. Then it throws the exception
java.lang.NullPointerException
at com.serverapp.demoapp.web.UploadController.UploadFile(UploadController.java:63)
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.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:920)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
Line 63 refers to System.out.println("Param Instance" + object.getClass().getName());
which means the object is null
How to get the values?
When you use multipart then your form fields are included in request Stream. So you have to check whether they are form fields or not.
This is what I use in a servlet, you can make appropriate changes in it to work in Spring-MVC.
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart)
{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext())
{
FileItem item = (FileItem) iterator.next();
if (item.isFormField()) //your code for getting form fields
{
String name = item.getFieldName();
String value = item.getString();
System.out.println(name+value);
}
if (!item.isFormField())
{
//your code for getting multipart
}
}
}
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>