Trying to read tiff file using jai_imageio - servlets

I'm having some issue trying to create a subimage through a doGet method. I'm using jai_imageio, the same method "getInvoiceNumberTif()" works fine when using the main method.But when I try to call the method from servlet I get an exception.
Heres the GET:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h1>Hello Servlet Get </h1>");
out.println("</body>");
out.println("</html>");
FileHandler fh = new FileHandler();
fh.getInvoiceNumberTif();
}
Here is the method:
public void getInvoiceNumberTif() throws IOException{
File file = new File("C:\\Users\\gideon\\Desktop\\tmp\\invoice.tif");
BufferedImage img = ImageIO.read(file);
BufferedImage subImage = img.getSubimage(1600, 355, 220, 50);
OutputStream out = new FileOutputStream(new File("C:\\Users\\gideon\\Desktop\\tmp\\img_invoice_nr.tif"));
ImageIO.write(subImage, "tif", out);
out.flush();
out.close();
}
the exception:
java.lang.NullPointerException
at se.visma.servlet.FileHandler.getInvoiceNumberTif(FileHandler.java:145)
at se.visma.servlet.InvoiceServlet.doGet(InvoiceServlet.java:126)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:744)

Related

i am trying to work on this piece of code but its not working and flashing error on the line mentioned

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
/* TODO output your page here. You may use following sample code. */
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Existing</title>");
out.println("</head>");
out.println("<body>");
HttpSession session=request.getSession(true);
String id,password;
id=request.getParameter("t1");
password=request.getParameter("t2");
session.setAttribute("t1",id);
int f=0;
Class.forName("org.sqlite.JDBC");
Connection c;
c=DriverManager.getConnection("jdbc:sqlite:c:/java/project");//ERROR COMES HERE java.lang.UnsatisfiedLinkError: org.sqlite.core.NativeDB._open(Ljava/lang/String;I)V
/* PreparedStatement ps;
ps=c.prepareStatement("select id,password from id where id='tirjss' password='020'");
String id2,pswrd;
ResultSet r;
r=ps.executeQuery();
if(r.next()==true)
{*/ response.sendRedirect("existing_user.html");
out.println("</body>");
out.println("</html>");
}catch(Exception e){}
}

Tomcat error 500 on page load

I am getting the following error on Tomcat.
The code is given below
message Servlet execution threw an exception
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet execution threw an exception
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpher
DBChart.doGet(DBChart.java:68)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.ClassNotFoundException: net.sf.ezmorph.Morpher
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
DBChart.doGet(DBChart.java:68)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Below is my Java file
//imported all the required packages here
class DBChart extends HttpServlet
{
Connection c = null;
Statement st = null;
ResultSet rs = null;
String query = null;
JSONObject obj = null;
JSONObject resobj = null;
PreparedStatement pst = null;
DatabaseMetaData dbmd = null;
String dbURL = "jdbc:sqlserver://localhost:1433; databaseName = EMPLOYEE";
String user = "username";
String password = "mypassword";
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
List<JSONObject> Details = new LinkedList<JSONObject>();
PrintWriter out = response.getWriter();
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
c = DriverManager.getConnection(dbURL, user, password);
query = " select DeptName, NumberOfEmployess from Departments";
pst = c.prepareStatement(query);
rs = pst.executeQuery();
while (rs.next())
{
String dept = rs.getString(1);
int empnumber = rs.getInt(2);
obj = new JSONObject();
obj.put("DepartmentName", dept);
obj.put("EmployeesinNumbers", empnumber);
Details.add(obj);
}
resobj.put("RelativeDetails", Details);
out.write(resobj.toString());
}
catch (Exception e)
{
System.out.println("Exception " + e);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doGet(request, response);
}
}
I made sure that I have mentioned the correct name in XMl file and using the url as follows:
http://localhost:8080/DBCHART/db
Your class needs to be public:
public class DBChart extends HttpServlet

GWT RequestBuilder file download

I implemented servlet, that creates XLS file. I am making a request from UI (GWT, RequestBuilder). I get the response, but is it possible to get ready file (with auto "save as" dialog box)?
Should I somehow set headers or something?
Here is my code:
Request implementation
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, GWT.getModuleBaseURL() + "downloadLimitsFile");
try {
rb.setHeader("Content-type", "text/html");
Request response = rb.sendRequest("", new RequestCallback() {
public void onError(Request request, Throwable exception) {
Window.alert("fail");
}
public void onResponseReceived(Request request, Response response) {
Window.alert("file downloaded " + response.getText());
}
});
} catch (RequestException e) {
Window.alert("Failed to send the request: " + e.getMessage());
}
My servlet implementation
public void handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setHeader("Content-Disposition", "attachment; filename=File.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
try {
workbook = fileExporter.prepareExcellFile();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
response.setStatus(HttpServletResponse.SC_OK);
OutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
response.flushBuffer();
}
It was working fine (auto file download) when I was using eg. Anchor with servlet URL, but I have to use RequestBuilder now to make a request.
Can someone help?
I am afraid it is not possible, at least you can use a third party library.
Adding the header "Content-Disposition" won't work.

Upload file to my application on host by using servlet

I have a serlvet to upload file ... It work on my server, i upload to "http://localhost:8084/TestAmazon" and it work ... but we deploy my web application to host and upload file it not work ... please help me
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String relativeWebPath = "/image";
String absoluteFilePath = getServletContext().getRealPath(relativeWebPath);
if (ServletFileUpload.isMultipartContent(request)) {
try {
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File(absoluteFilePath + File.separator + name));
}
}
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception e) {
request.setAttribute("message", "File Upload Failed due to " + e);
}
} else {
request.setAttribute("message",
"Sorry this Servlet only handles file upload request");
}
request.getRequestDispatcher("result.jsp").forward(request, response);
}
i got an error:
exception
javax.servlet.ServletException: Servlet execution threw an exception
root cause
java.lang.NoSuchMethodError: org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload.parseRequest(Ljavax/servlet/http/HttpServletRequest;)Ljava/util/List;
sample.ProcessServlet.doPost(ProcessServlet.java:73)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

Write Glassfish output into servlet html page

How to redirect Glassfish server output into HttpServletResponse.out? I am making servlet in NetBeans.
here is a working example, just expose this as a servlet
public class ReadLogs extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=UTF-8";
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
public void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.append("<html>\n<head>\n\n");
out.append("<script>function toBottom()" + "{"
+ "window.scrollTo(0, document.body.scrollHeight);" + "}");
out.append("\n</script>");
out.append("\n</head>\n<body onload=\"toBottom();\">\n<pre>\n");
try {
File file = new File("C:\\pathToServerLogFile");
BufferedReader in = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
while (in.ready()) {
String x = in.readLine();
sb.append(x).append("<br/>");
}
in.close();
out.append("\n</pre>\n</body>\n</html>");
out.close();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
UPDATE
If you need to print only the last portion of the file use this after line "in.close();"
//print only 1MB Oof data
if(sb.length()>1000000){
out.append(sb.substring(sb.length()-1000000, sb.length()));
}else{
out.append(sb.toString());
}
So.. to print only lines which appeared after invoking script I've made such code:
BufferedReader reader = new BufferedReader(new FileReader("/path/to/server/log/server.log"));
int lines = 0;
while (reader.readLine() != null) {
lines++;
}
reader.close();
BufferedReader reader2 = new BufferedReader(new FileReader("/path/to/server/log/server.log"));
String strLine;
int i = 0;
while (i != lines) {
reader2.readLine();
i++;
}
while ((strLine = reader2.readLine()) != null) {
out.println(stringToHTMLString(strLine));
out.println("<br>");
}
reader2.close();
When servlet starts it counts lines in server log (saves it in variable i), then after clicking on action form it read lines which indexes are higher than i and displays it on html page. I've used function stringToHTMLString which I found somewhere on stackoverflow.
Greets.

Resources