I'm uploading an image to a servlet through an ajax post request (provided by a complex html5 drag and drop plugin's javascript code..which i won't show now)
In a first image upload everything is fine (i'm also sending some data within the ajax post for cropping the image in the server-side and this is the reason for which i had to convert the InputStream
gotten from the uploaded image to a BufferedImage (the conversion as following :
BufferedImage imBuff = ImageIO.read(fi.getContent());
This is the whole FileUploadServlet servlet :
package com.hmkcode;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmkcode.vo.FileMeta;
import java.io.FileOutputStream;
import java.io.File;
//this to be used with Java Servlet 3.0 API
#MultipartConfig
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// this will store uploaded files
private static List<FileMeta> files = new LinkedList<FileMeta>();
/***************************************************
* URL: /upload
* doPost(): upload the files and other parameters
****************************************************/
private BufferedImage cropImage(BufferedImage src, int x, int y, int w, int h) {
BufferedImage dest = src.getSubimage(x, y, w, h);
return dest;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
// 1. Upload File Using Java Servlet API
//files.addAll(MultipartRequestHandler.uploadByJavaServletAPI(request));
HttpServletRequest rq = request;
// 1. Upload File Using Apache FileUpload
files.addAll(MultipartRequestHandler.uploadByApacheFileUpload(rq));
// Remove some files
while(files.size() > 20)
{
files.remove(0);
}
//////////////////////////////////////////
System.out.println("Begin:::mytestsmytestsmytestsmytestsmytestsmytestsmytestsmytestsmytests");
if(files.size()==0)
System.out.println("files is empty !");
else
for(FileMeta fi : files){
System.out.println("------->>>> file name : "+fi.getFileName());
System.out.println("------->>>> file size : "+fi.getFileSize());
System.out.println("------->>>> file type : "+fi.getFileType());
System.out.println("------->>>> file Class : "+fi.getClass());
System.out.println("------->>>> file Content : "+fi.getContent());
System.out.println("______________________________________________");
///////////////// /////////////////////////////// /////////////////////////
// java cropping test :
BufferedImage imBuff = ImageIO.read(fi.getContent());
File outputfile = new File("C:\\uploadedimgs\\"+UUID.randomUUID()+".jpg");
ImageIO.write(cropImage(imBuff,
// 0,0,200,200
Integer.parseInt(MultipartRequestHandler.cropx1),
Integer.parseInt(MultipartRequestHandler.cropy1),
Integer.parseInt(MultipartRequestHandler.cropw),
Integer.parseInt(MultipartRequestHandler.croph)
), "jpg", outputfile);
////////////////////////////////
}
System.out.println("fin:::mytestsmytestsmytestsmytestsmytestsmytestsmytestsmytestsmytests");
// 2. Set response type to json
response.setContentType("application/json");
// 3. Convert List<FileMeta> into JSON format
ObjectMapper mapper = new ObjectMapper();
// 4. Send resutl to client
mapper.writeValue(response.getOutputStream(), files);
}
/***************************************************
* URL: /upload?f=value
* doGet(): get file of index "f" from List<FileMeta> as an attachment
****************************************************/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
// 1. Get f from URL upload?f="?"
String value = request.getParameter("f");
// 2. Get the file of index "f" from the list "files"
FileMeta getFile = files.get(Integer.parseInt(value));
try {
// 3. Set the response content type = file content type
response.setContentType(getFile.getFileType());
// 4. Set header Content-disposition
response.setHeader("Content-disposition", "attachment; filename=\""+getFile.getFileName()+"\"");
// 5. Copy file inputstream to response outputstream
InputStream input = getFile.getContent();
OutputStream output = response.getOutputStream();
byte[] buffer = new byte[1024*10];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
output.close();
input.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
Now the problem, which is a NPE, happens in a second upload try.It is the BufferedImage imBuff which is null. this is the exception log :
10:10:40,818 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/gencarservces-web].[upload]] (http-localhost-127.0.0.1-8080-6) "Servlet.service()" pour la servlet upload a généré une exception: java.lang.NullPointerException
at com.hmkcode.FileUploadServlet.cropImage(FileUploadServlet.java:40) [classes:]
at com.hmkcode.FileUploadServlet.doPost(FileUploadServlet.java:95) [classes:]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:754) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:]
at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]
at java.lang.Thread.run(Thread.java:724) [rt.jar:1.7.0_40]
Related
Exception when writing the response back using jackson. Unable to find any solutions on the net. I am not sure what is the cause of error. Tried flushing the response but still the same error
import com.In10s.DBProperties.OracleDBConnection;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
public class GetTable extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
JSONObject jsonResponse = new JSONObject();
try {
JSONArray data = new JSONArray();
Connection con = OracleDBConnection.getConnection();
String query = "Select * from CREDIT_CARD_TRANSACTIONS";
Statement st = con.createStatement();
ResultSet rSet = st.executeQuery(query);
List<Map<String, Object>> result = new ArrayList<>();// JDK7++
while (rSet.next()) {
Map<String, Object> row = new HashMap<>();
row.put("CARD_NUMBER", rSet.getString("CARD_NUMBER"));
row.put("FIRST_NAME", rSet.getString("FIRST_NAME"));
row.put("OPENING_BALANCE", rSet.getString("OPENING_BALANCE"));
row.put("WITHDRAWAL", rSet.getString("WITHDRAWAL"));
row.put("DEPOSIT", rSet.getString("DEPOSIT"));
row.put("CLOSING_BAL", rSet.getString("CLOSING_BAL"));
row.put("TXDATE", rSet.getString("TXDATE"));
row.put("USAGE_TYPE", rSet.getString("USAGE_TYPE"));
result.add(row);
}
} catch (Exception e) {
e.printStackTrace();
}
ObjectMapper mapper = new ObjectMapper();
try {
response.getWriter().write(mapper.writeValueAsString(response));
response.getWriter().flush();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
Here is stack trace:
com.fasterxml.jackson.databind.JsonMappingException: getWriter() has already been called for this response (through reference chain: org.apache.catalina.connector.ResponseFacade["outputStream"])
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:210)
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:177)
at com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:190)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:671)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:156)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:129)
at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3383)
at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:2777)
at com.In10s.getTable.GetTable.doGet(GetTable.java:64)
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:504)
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:1074)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2466)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2455)
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)
Caused by: java.lang.IllegalStateException: getWriter() has already been called for this response
at org.apache.catalina.connector.Response.getOutputStream(Response.java:644)
at org.apache.catalina.connector.ResponseFacade.getOutputStream(ResponseFacade.java:196)
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 com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:536)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:663)
... 28 more
You're trying to transform the HttpServletResponse into JSON, and send it to the HttpServletResponse. You want to transform the result list to JSON instead:
response.getWriter().write(mapper.writeValueAsString(result));
I am really stuck at this exception from 3 days. It was working fine but suddenly it is throwing this exception.
I am trying to upload an image for cleaning from my android device to JAVA servlet in jboss which is like this :
Class Servlet extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("You need to post an image.");
PrintWriter out = response.getWriter();
out.println("Please post an image..");
out.flush();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
long time = System.currentTimeMillis(); // check the time, for file-naming and such
System.out.println("Got a post - " + time);
try{
// get the image from the app
ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
byte[] imageBytes = (byte[]) ois.readObject();
PlanarImage image = ImageUtil.getAsImage(imageBytes);
ois.close();
System.out.println("Read image from stream...");
// save a copy for inspection
ImageUtil.saveImage(image, time + "_y");
.......
And the ImageUtil.getasimage is like :
public static PlanarImage getAsImage(byte[] imageBytes){
BufferedImage bi = null;
InputStream in = null;
try {
in = new ByteArrayInputStream(imageBytes);
bi = ImageIO.read(in);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return PlanarImage.wrapRenderedImage(bi);
}
I am getting the following error on the line
PlanarImage image = ImageUtil.getAsImage(imageBytes);
Error :
[org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/VINCServer].[vinc]] (http--0.0.0.0-8080-2) Servlet.service() for servlet vinc threw exception: java.lang.ClassNotFoundException: javax.media.jai.ParameterBlockJAI from [Module "deployment.VINCServer.war:main" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:190)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:468)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:456)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:120)
at VinCapture.doPost(VinCapture.java:41) at javax.servlet.http.HttpServlet.service(HttpServlet.java:754) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:]
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]
at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_55]
I have also downloaded all the needed jars for the above.
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import javax.media.jai.ParameterBlockJAI;
import javax.media.jai.PlanarImage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.usaa.ar.deconvolution.Restore;
import com.usaa.ar.util.ImageUtil;
But still no luck.Please help me as I am not able to find anything on this exception.
I'm trying to generate pdf via button but my problem is this method
JasperRunManager.runReportToPdfStream(reportStream,servletOutputStream, new HashMap<Object, Object>(), resultSetDataSource);
it is not supporting Hashmap it gives following error
The method runReportToPdfStream(InputStream, OutputStream, Map<String,Object>, Connection) in the type JasperRunManager is
not applicable for the arguments (InputStream, ServletOutputStream, HashMap<Object,Object>, JRResultSetDataSource)
it Supports String parameter like Hashmap<String,Object> while generating pdf it gives following error
net.sf.jasperreports.engine.JRException: Error loading object from InputStream
at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:219)
at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:632)
at net.sf.jasperreports.engine.JasperRunManager.runToPdfStream(JasperRunManager.java:428)
at net.sf.jasperreports.engine.JasperRunManager.runReportToPdfStream(JasperRunManager.java:849)
at com.p41.jasper.Jasper.doPost(Jasper.java:103)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
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.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
at com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:546)
at com.sun.faces.application.view.JspViewHandlingStrategy.executePageToBuildView(JspViewHandlingStrategy.java:364)
at com.sun.faces.application.view.JspViewHandlingStrategy.buildView(JspViewHandlingStrategy.java:154)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:100)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:410)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.p41.setting.FacesFilter.doFilter(FacesFilter.java:153)
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:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
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:936)
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:1004)
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(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.io.StreamCorruptedException: invalid stream header: 3C3F786D
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at net.sf.jasperreports.engine.util.ContextClassLoaderObjectInputStream.<init>(ContextClassLoaderObjectInputStream.java:53)
at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:214)
Servlet
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.HashSet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperRunManager;
public class Jasper extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection connection;
Statement statement;
ResultSet resultSet;
response.setContentType("text/html");
String si = request.getParameter("input");
ServletOutputStream servletOutputStream = response.getOutputStream();
byte[] bytes = null;
InputStream reportStream = getServletConfig().getServletContext().getResourceAsStream("WEB-INF/HR/Jasp.jasper");
System.out.println("Print" + si);
try {
System.out.println("Second print" + si);
String query = "SELECT Where Empno = '" + si + "' ";
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/schemedb?user=root&password=root");
statement = connection.createStatement();
resultSet = statement.executeQuery(query);
JRResultSetDataSource resultSetDataSource = new JRResultSetDataSource(resultSet);
response.setContentType("application/pdf");
servletOutputStream.flush();
servletOutputStream.close();
System.out.println("print" + reportStream);
System.out.println("print" + servletOutputStream);
System.out.println("print" + resultSetDataSource);
JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, new HashMap<Object, Object>(), resultSetDataSource);
resultSet.close();
statement.close();
connection.close();
response.setContentType("application/pdf");
servletOutputStream.flush();
servletOutputStream.close();
} catch (Exception e) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
response.setContentType("text/plain");
response.getOutputStream().print(stringWriter.toString());
}
}
}
Solution is I Removed Run Report pdf stream and used method as exportReport to pdf Stream
JasperRunManager.runReportToPdfStream(reportStream,servletOutputStream, new HashMap<Object, Object>(), resultSetDataSource);
Coding:-
InputStream reportStream = getServletConfig().getServletContext().getResourceAsStream("WEB-INF/HR/Jasp.jrxml");
ByteArrayOutputStream baos =new ByteArrayOutputStream();
response.setContentType("application/pdf");
JasperDesign design = JRXmlLoader.load(reportStream);
JasperReport report = JasperCompileManager.compileReport(design);
JRResultSetDataSource jasperReports = new JRResultSetDataSource(rs);
JasperPrint print = JasperFillManager.fillReport(report, new HashMap(), jasperReports);
net.sf.jasperreports.engine.JasperExportManager.exportReportToPdfStream(print,baos);
response.setContentLength(baos.size());
ServletOutputStream out1 = response.getOutputStream();
baos.writeTo(out1);
out1.flush();
rs.close();
st.close();
conn.close();
I'm currently trying to develop a simple proof of concept for a REST application using CXF 2.6.4. I'm taking the non-spring approach. I'm using JBoss AS 7.1.1 Final as my web server.
The following is my web service class:
package restful.webservice;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import restful.entity.ControllerVersion;
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public class WebServiceRest implements WebServiceInterface
{
#Override
#POST
#GET
#Path("/getVersion")
public ControllerVersion getVersion(String deviceID, String[] macAddresses)
{
return new ControllerVersion();
}
}
ControllerVersion class:
package restful.entity;
#XmlRootElement(name = "ControllerVersion")
public class ControllerVersion {
private String version="R1.1.0.0";
public String getVersion() {
return version;
}
}
Now, when I try to make a REST call to my web service, I get the following exception on the server side:
18:51:52,913 WARNING [org.apache.cxf.jaxrs.utils.JAXRSUtils] (http--0.0.0.0-8080-1) No message body reader has been found for request class String[], ContentType : application/json.
18:51:52,927 WARNING [org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper] (http--0.0.0.0-8080-1) javax.ws.rs.WebApplicationException
at org.apache.cxf.jaxrs.utils.JAXRSUtils.readFromMessageBody(JAXRSUtils.java:1054)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameter(JAXRSUtils.java:614)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameters(JAXRSUtils.java:578)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:238)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:89)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:262)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:236)
at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:209)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:154)
at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:130)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:225)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:145)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:201)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930)
at java.lang.Thread.run(Thread.java:662)
The libraries that I have under WEB-INF/lib are:
cxf-api-2.6.4.jar
cxf-bundle-2.6.4.jar
cxf-rt-frontend-jaxrs-2.6.4.jar
cxf-rt-frontend-jaxrs.jar
cxf-rt-transports-http-2.6.4.jar
geronimo-servlet.jar
jaxb-api-2.2.5.jar
jaxb-impl-2.2.5.1.jar
jaxb-xjc-2.2.5.1.jar
jettison-1.3.4.jar
log4j-1.2.16.jar
neethi-3.0.2.jar
xmlschema-core-2.0.3.jar
The interesting thing is that I tried to do another project, but this time in the signature of my web service method, I included a custom class. I had no problem reading the contents of the custom class' instance, nor a problem while returning it to my client.
Am I missing something?
UPDATE:
I tried to add the following to my web.xml:
<init-param>
<param-name>jaxrs.providers</param-name>
<param-value>
org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider
(writeXsiType=false)
</param-value>
</init-param>
And added the following dependencies as well:
jackson-jaxrs-1.9.2.jar
jackson-mapper-asl-1.9.2.jar
jackson-xc-1.9.2.jar
Now I'm getting the following exception:
19:22:29,762 WARNING [org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper] (http--0.0.0.0-8080-1) javax.ws.rs.WebApplicationException: java.io.IOException: Stream closed
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:243)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:89)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:262)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:236)
at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:209)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:154)
at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:130)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:225)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:145)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:201)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.io.IOException: Stream closed
at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:377)
at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:193)
at java.io.FilterInputStream.read(FilterInputStream.java:116)
at org.codehaus.jackson.impl.ByteSourceBootstrapper.ensureLoaded(ByteSourceBootstrapper.java:507)
at org.codehaus.jackson.impl.ByteSourceBootstrapper.detectEncoding(ByteSourceBootstrapper.java:129)
at org.codehaus.jackson.impl.ByteSourceBootstrapper.constructParser(ByteSourceBootstrapper.java:224)
at org.codehaus.jackson.JsonFactory._createJsonParser(JsonFactory.java:785)
at org.codehaus.jackson.JsonFactory.createJsonParser(JsonFactory.java:561)
at org.codehaus.jackson.jaxrs.JacksonJsonProvider.readFrom(JacksonJsonProvider.java:414)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.readFromMessageBody(JAXRSUtils.java:1038)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameter(JAXRSUtils.java:614)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameters(JAXRSUtils.java:578)
Update 2:
I tried to implement a method with a different signature, and this time, I have omitted the String array from the method:
public ControllerVersion getVersion(String deviceID)
Everything is working perfectly without the String array. What do you think I should do?
I apparently misunderstood how REST works. What I did to finally solve the problem was the following:
1- Changed my web service signature:
#POST
#Path("/getVersion")
#Produces(MediaType.APPLICATION_JSON)
#Consumes({"application/xml", "application/json", "application/x-www-form-urlencoded"})
public ControllerVersion getVersion(#FormParam("deviceID") String deviceID,#FormParam("macAddresses") String macAddresses)
2- Now, make sure that the client is sending a request with content-type (application/x-www-form-urlencoded) and that the client correctly adds form parameters same as those you defined in the #FormParam annotations.
3- Now, you can use a library such as FlexJson, to deserialize your parameters from a JSon String. For instance, I'm now sending the macAddresses as a JSon String: ["mac1","mac2"] from the client. On the server side, I convert this JSon string to a String[] using the following method:
public static String[] parseStringArrayFromJSONArray(String jsonArray)
{
String[] stringArray = null;
try
{
JSONArray array = new JSONArray(jsonArray);
if (array != null)
{
stringArray = new String[array.length()];
for (int i = 0; i < array.length(); i++)
{
stringArray[i] = array.getString(i);
}
}
} catch (Exception e)
{
stringArray = null;
}
return stringArray;
}
I hope this will help someone out there.
You're using #Consumes(MediaType.APPLICATION_JSON). You need to add jackson-core (and maybe some more jackson dependencies) for the conversion to work.
cxf uses jettison by default. Why do you have #GET and #POST annotations?
But it say's
java.io.IOException: Stream closed
So there is most likely an inputstream that isn't being shut down.
i am developing a project KNOWLEDGE based community sharing system.
in which users can login and share their resources to other Users....
I'm getting a problem in uploading a file to mysql database....
PS..my Instructor strictly Says to use MVC architecture So, i have to use the same..
So i have created only one Servlet named Controller.java.
here i will redirect to other java programs for calculations...
Here is the code for Controller.java
package com.kbcss.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.kbcss.command.LoginCommand;
import com.kbcss.command.Commands;
import com.kbcss.command.ResourceCommand;
import com.kbcss.command.UserCommand;
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
public Controller() {super();}
#SuppressWarnings("rawtypes")
private Map commands = new HashMap();
#SuppressWarnings("unchecked")
public void init(ServletConfig config) throws ServletException{
super.init();
System.out.println("i am in init");
this.commands.put("login", new LoginCommand());
this.commands.put("user", new UserCommand());
this.commands.put("resource", new ResourceCommand());
System.out.println("i am about to exit init");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("i am in doget");
processCommand(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("i am in dopost");
processCommand(request, response);
}
private void processCommand(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("i am in processCommand");
String formAction = request.getParameter("form_action");
System.out.println("i am in processCommand state 2");
Commands command = (Commands) commands.get(formAction);
command.execute(request, response);
System.out.println("i am about to exit processCommand");
}
}
and here is the code for saving the resources to MY database table.... Named ResourceCommand .java
package com.kbcss.command;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.sql.DataSource;
import com.oreilly.servlet.MultipartRequest;
public class ResourceCommand extends HttpServlet implements Commands{
private static final long serialVersionUID = 1L;
public void execute(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//
// JNDI to connect to database
//
Connection conn = null;
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/tia");
conn = ds.getConnection();
//
// Save file(s) temporarily to filesystem
//
MultipartRequest multi = new MultipartRequest(request, "F:", 10*1024*1024);
Enumeration files = multi.getFileNames();
String filename = "";
File f = null;
while(files.hasMoreElements()) {
String name = (String)files.nextElement();
filename = multi.getFilesystemName(name);
String type = multi.getContentType(name);
f = multi.getFile(name);
}
//
// Insert file into database
//
InputStream is = new FileInputStream(f);
String sql = "INSERT INTO resource (`title`, `cat`, `user`, `filename`, `file`, `like`) VALUES (?, ?, ?, ?, ?, ?)"
;
PreparedStatement stmt = conn.prepareStatement(sql);
// Set some Title
stmt.setString(1, "some thing");
// Set some category
stmt.setString(2, ".net");
// Set some user
stmt.setString(3, "sri");
// Set Filename
stmt.setString(4, f.getName());
// Set the data
stmt.setBinaryStream(5, is, (int) f.length());
// Set Likes
stmt.setInt(6, 2);
stmt.executeUpdate();
is.close();
//
// Release connection
//
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) { ; }
stmt = null;
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) { ; }
conn = null;
}
} catch(Exception e) {
System.out.println(e);
}
}
}
And here is the jSP file where i will upload from....
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>UPLOAD FILE page</title></head>
<body>
<form method="post" action="Controller" enctype="multipart/form-data">
<input type="hidden" name="form_action" value="resource" />
<b>File to upload to database:</b>
<input type="file" name="attachment" size="36">
<input type="submit" value="Upload">
</form>
</body></html>
And this is the error i'm getting :(
INFO: Reloading Context with name [/KBCSS] is completed
i am in init
i am about to exit init
i am in dopost
i am in processCommand
i am in processCommand state 2
Oct 10, 2013 11:29:59 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Controller] in context with path [/KBCSS] threw exception
java.lang.NullPointerException
at com.kbcss.controller.Controller.processCommand(Controller.java:69)
at com.kbcss.controller.Controller.doPost(Controller.java:53)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
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:472)
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:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
and by the way..i have created a Command.java interface here it is.
package com.kbcss.command;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public interface Commands {
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
}
Can any one guide me PLZZZZZZZZZZZZZZZZZZZZ
i'm stuck for a day and Half and have no clue what i'm doing...
This is what happens if u ask an electrical engineering student to do a Java Project !!!!
GREAT GREAT thanks from My side.....
Chances are that commands.get(formAction); is returning null, so command is also null. When you call command.execute(request, response);, you're trying to access something within a null object. That's going to get you a NullPointerException.
Use your print statements to determine what the exact value of formAction is when you get the exception. Then verify that you're putting a key for that string into commands (if it isn't "login", "user", or "resource", since you're already entering those).
One other thing that may be causing the problem is that you need to add class-types to your Map. Change it to:
private Map<String,Command> commands = new HashMap<String,Command>();
After you do that, you shouldn't have to suppress the warning on the Map.