iText working Google App engine - java

I'm trying create pdf in java with google app engine but it doesn't work yet:
#SuppressWarnings("serial")
public class GuestbookServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("application/pdf");
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
document.open();
document.add(new Paragraph("Hello World"));
document.close();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is the error:
HTTP ERROR 500
Problem accessing /guestbook. Reason:
com/itextpdf/text/DocumentException
Caused by:
java.lang.NoClassDefFoundError: com/itextpdf/text/DocumentException
I have read the incompatibility with java.awt and java.nio with google appengine. But I don't know how to do it. Is there any special version of itext to google app engine? Or do you know any clue that can help me?

Yes, there's a GAE version of iText. See http://lowagie.com/iPadSchools to watch a demo. The GAE port is distributed by iText Software. There's no link to get it online.

package mx.gob.campeche.sit.web.reportes;
import java.io.IOException;
import java.io.OutputStream;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import mx.gob.campeche.sit.doc.recibo_oficial.ReciboOficial;
#WebServlet("/reciboOficial")
public class ReporteReciboOficialServlet extends HttpServlet {
#Inject
ReciboOficial reciboOficial;
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpServletRequestWrapper srw = new HttpServletRequestWrapper(request);
String folio = "";
if (request.getParameterMap().containsKey("folio")) {
folio = request.getParameter("folio");
System.out.println("contenido" + folio);
}else
if (request.getParameterMap().containsKey("numero")) {
folio = request.getParameter("numero");
System.out.println("contenido" + folio);
}else{
throw new ServletException("No ingreso parametro");
}
byte[] pdfData = reciboOficial.crearReciboOFicialCajas(folio, srw.getRealPath(""));
response.setContentType("application/pdf");
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "inline; filename=\"" +"samplePDF2.pdf" +"\"");
OutputStream output = response.getOutputStream();
output.write(pdfData);
output.close();
}
this is small example, this help

Related

java.lang.ClassCastException: Servlet.Telnet cannot be cast to javax.servlet.Servlet

I want to implement a servlet and call it in a WebApp.
I am constantly get java.lang.ClassCastException: Servlet.Telnet cannot be cast to javax.servlet.Servlet from the Apache Tomcat Server. I made sure my class extends HttpServlet this is my code:
package Servlet;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.net.telnet.TelnetClient;
public class Servlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
TelnetClient telnet = new TelnetClient();
telnet.connect(request.getParameter("router"), 23);
PrintStream output = new PrintStream(telnet.getOutputStream());
output.println(request.getParameter("login"));
output.flush();
output.println(request.getParameter("password"));
output.flush();
out.printf("SUCCESS");
telnet.disconnect();
} catch (Exception e) {
e.printStackTrace();
out.printf("ERROR");
}
}
I renamed the package and the class and it works perfectly.

Jetty servlet override extension reading file

I'm trying to make a servlet on Jetty that overrides a file extension but that still needs to read the file being accessed.
I've been trying with resources but I could achieve nothing yet. I've tryed this code so far and, as you'll see, the resources are there but I somehow can't access them:
package valarionch.lab0.webapp.todo;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#SuppressWarnings("serial")
#WebServlet(urlPatterns = { "*.ToDo" })
public class ToDoHandler extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
String s = req.getParameter("s");
boolean small = (s != null && s.equals("1"));
PrintWriter out = resp.getWriter();
if (!small) {
out.println("<html><head><title>ToDo list</title></head>"
+ "<body>");
}
for (String res : getServletContext().getResourcePaths("/")) {
System.out.println("Resource: " + res);
System.out.println("ResourceURL: " + getServletContext().getResource(res));
System.out.println("ResourceStream: " + getServletContext().getResourceAsStream(res));
}
InputStream input = getServletContext().getResourceAsStream(req.getRequestURI());
System.out.println(input);
ToDoFormatter.parse(input, out, req.getParameter("q"));
if (!small) {
out.println("</body></html>");
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
this code prints this:
Resource: /META-INF/
ResourceURL: null
ResourceStream: null
Resource: /WEB-INF/
ResourceURL: null
ResourceStream: null
Resource: /index.html
ResourceURL: null
ResourceStream: null
Resource: /ToDoList.ToDo
ResourceURL: null
ResourceStream: null
null
I tryed with the next code too but also didn't worked:
getClass().getClassLoader().getResource(".").toString()+"../.."+req.getRequestURI()
so getClass().getClassLoader().getResource(".").toString() goes to WEB-INF/classess and +"../.."+req.getRequestURI() picks the actual file.
Am I missing something about how resources work? Is there another way to read the file?
You can use getServletContext().getRealPath() for such task. Let's imagine that you have the file myText.txt in the webapps folder:
#SuppressWarnings("serial")
#WebServlet(urlPatterns = { "*.ToDo" })
public class UseGetRealPath extends HttpServlet {
public void doGet( HttpServletRequest req, HttpServletResponse res )
throws ServletException, IOException {
String todoFile = getServletContext().getRealPath("/myText.txt");
FileReader fr = new FileReader( todoFile );
for( int c = fr.read(); c != -1; c = fr.read() ) {
System.out.print( (char) c );
}
fr.close();
res.getWriter().println( "check the console!" );
}
}
The code will open the file and dump its content in the console.

NullPointerException on Apache Server Servlet using JPA

Im trying to display contents of table (test_dept) which is in SQLSERVER
I have created a connection profile also.
I have written a Servlet like below... But Im getting this error.
import java.io.IOException;
import java.io.PrintWriter;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
//import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#SuppressWarnings("serial")
#WebServlet(urlPatterns = "/ServletClient")
public class ServletClient extends HttpServlet
{
#PersistenceUnit
EntityManagerFactory factory;
#SuppressWarnings("rawtypes")
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
//ServletOutputStream out = resp.getOutputStream();
PrintWriter pw = resp.getWriter();
java.util.List list = factory.createEntityManager().createQuery("select f from test_dept f;").getResultList();
pw.println("<html><body bgcolor=silver text=green><table>");
for (Object tdp : list)
{
pw.println("In The Loop");
pw.println("<tr><td>" + ((TestDept) tdp).getDptnam() + "</td></tr>");
}
pw.println("</table>");
pw.println("<font size=35><b>List created AdapChain</b></font>");
pw.println("</body></html>");
}
}
I don't think any version of Apache Tomcat supports injection of EntityManager or EntityManagerFactory objects out of the box.
You need to choose a server platform that supports more of the JavaEE specification.

Generate PDF file in an appropriate format

For my use, I created a PDF file using flying-saucer library. It was a legacy HTML so I cleaned out the XHTML using HTMLCleaner library.
After this I serialize the XML as string then pass it to the iText module of flying-saucer to render it and subsequently create the PDF.
This PDF I place it in the OutputStream. After the response is committed I get a dialog asking to save or open it. However it does not get saved as PDF file. I have to right-click and open it in Adobe or any PDF reader.
How do I make it display in the PDF reader. And make the file be saved as .pdf file. What would be an effective and user-friendly way to handle this issue? Help as always will be greatly appreciated!
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringBufferInputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.DomSerializer;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.PrettyXmlSerializer;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XmlSerializer;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xhtmlrenderer.resource.XMLResource;
public class MyPDF extends HttpServlet {
public MyPDF() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/pdf");
String html = request.getParameter("source");
try
{
HtmlCleaner cleaner = new HtmlCleaner();
CleanerProperties props = cleaner.getProperties();
TagNode node = cleaner.clean(html);
//String content = "<" + node.getName() + ">" + cleaner.getInnerHtml(node) + "</" + node.getName() + ">";
//System.out.println("content " +content);
OutputStream os = response.getOutputStream();
System.out.println("encoding " +response.getCharacterEncoding());
final XmlSerializer xmlSerializer = new PrettyXmlSerializer(props);
final String html1 = xmlSerializer.getAsString(node);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html1);
renderer.layout();
renderer.createPDF(os);
os.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public void init() throws ServletException {
}
}
Your MIME type is incorrect for PDF. It should be application/pdf.
Change
response.setContentType("text/pdf");
to
response.setContentType("application/pdf");
See https://www.rfc-editor.org/rfc/rfc3778 for the RFC for the PDF MIME type.
Edit: Totally overlooked the "Save as .pdf" question.
You'll also need to add something like:
response.setHeader("content-disposition", "attachment; filename=yourFileName.pdf");
to tell the browser what the default file name should be.

Java Servlet Downloading File

So I have two files, the servlet:
package com.servlets;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import com.java.DataDownloader;
/**
* Servlet implementation class downloaderServ
*/
public class DownloaderServ extends HttpServlet {
private static final long serialVersionUID = 1L;
DataDownloader dl;
/**
* #see HttpServlet#HttpServlet()
*/
public DownloaderServ() {
super();
dl = new DataDownloader();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
dl.download();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
The application which does the processing:
package com.java;
import java.io.*;
import java.net.*;
import org.apache.commons.io.*;
public class DataDownloader {
private static boolean get(String address, String fileName) {
try {
URL url = new URL(address);
File f = new File(fileName);
FileUtils.copyURLToFile(url, f);
}
catch(MalformedURLException e) {
System.out.println(e);
return false;
}
catch(IOException e) {
System.out.println(e);
return false;
}
return true;
}
public boolean download() {
String[][] urls = new String[3][2];
urls[0][0] = "http://data.london.gov.uk/datafiles/crime-community-safety/mps-recordedcrime-borough.csv";
urls[0][1] = "crimes.csv";
urls[1][0] = "http://data.london.gov.uk/datafiles/housing/average-house-prices-borough.xls";
urls[1][1] = "prices.xls";
urls[2][0] = "http://data.london.gov.uk/datastorefiles/datafiles/demographics/gla_2012rnd_SHLAA_based_borough_projections.xls";
urls[2][1] = "population.xls";
for (int i = 0; i < 3; i++) {
if (get(urls[i][0], urls[i][1]) == false) {
System.out.println(false);
return false;
}
}
return true;
}
}
I can run it with no problems but there does not seem to be any files downloaded. I have also printed out the return values (true or false) and it does print true. Is downloading a file not as simple as this?
Code looks fine, so if prints true and you don't see any exceptions as well while running the program, then your problem is you are not able to locate the files copied from url.
Since no directories are specified in destination File, it must be dumping your file in the folder at which you are invoking java program. If it's an IDE (Eclipse) etc with which program is being run, refresh and check the associated project folder.
Kevin, as you clearly didn't get any exception, here's what I suggest: please right click your Eclipse project root folder and click: Refresh. Your files will be there directly at that path.
Also, I'm removing the servlet tag from your question as the issue has totally nothing to do with servlets. It's just that you're using them inside a servlet, but this same code would work in isolation, even outside of Java EE in fact.
I added fileutils instead.
I changed the it so an absolute path is taken e.g.
File f = new File("C:\\data\\" + fileName);
This works. Does having it in a servlet change it so an absolute path is needed and render relative paths unusable? I tested the downloading part outside of a servlet and it works with relative paths or it just downloads into project folder if nothing is specified.

Categories