Skip to content

Instantly share code, notes, and snippets.

@theresajayne
Created July 1, 2011 10:28
Show Gist options
  • Save theresajayne/1058258 to your computer and use it in GitHub Desktop.
Save theresajayne/1058258 to your computer and use it in GitHub Desktop.
package uk.co.inbrand.inline;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import uk.co.inbrand.dto.LicencesBase;
import uk.co.inbrand.dto.TemplatesBase;
import uk.co.inbrand.fopengine.FopEngine;
import uk.co.inbrand.service.Service;
import uk.co.inbrand.utilities.MD5Utils;
/**
* Servlet to call fop with input/output command line arguments as url params
*
* @web.servlet-mapping
* url-pattern="/InLine/*"
*/
public class InLine extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(InLine.class);
private URL xslUrl;
private URL httpUrl;
private boolean embed = true; //we embed by default
private static final Logger LOGGER = Logger.getLogger(InLine.class);
private Service appservice;
private String key;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
appservice = webApplicationContext.getBean(Service.class);
}
public void doRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.info("Processing Incoming Request..");
key = null;
//Check licence first;
if(request.getParameter("xsl")== null ) {
//lets see if they have a template ID instead
if(request.getParameter("template")!= null) {
//this is a true inline call so we need to bypass the licence check as we know the template is in our system.
key = MD5Utils.getMD5(request.getParameter("url") + request.getParameter("template"), LOGGER);
processTemplate(Integer.parseInt(request.getParameter("template")),request,response);
}
} else {
//we have a template as url so need to check its not a rival trying to use our engine to create their own files.
key = MD5Utils.getMD5(request.getParameter("url") + request.getParameter("xsl"), LOGGER);
if(checkLicence(key,request.getParameter("url"),request.getParameter("xsl"))) {
processTemplate(request, response);
}
}
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doRequest(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doRequest(request, response);
}
private void processTemplate(int templateId,HttpServletRequest request, HttpServletResponse response) throws IOException {
byte[] result = checkCache(key);
ServletOutputStream outstream = response.getOutputStream();
if(result.length >0) {
//output from cache so quick
try {
byte[] outputbytes = appservice.retrievePDFFromCache(key);
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment; filename=output.pdf");
response.setContentLength((int) outputbytes.length);
outstream.write(outputbytes);
} finally {
if (outstream != null) {
outstream.flush();
}
outstream.close();
}
} else {
String filename = createPDF(request, response, templateId);
String masterkey = MD5Utils.getMD5(request.getParameter("url") + request.getParameter("template"), LOGGER);
BufferedInputStream buf = null;
TemplatesBase dto = appservice.getTemplateById(templateId);
appservice.storePDFInCache(masterkey,dto.getOrg_id(), new File(filename));
try {
File input = new File(filename);
InputStream instream = new FileInputStream(input);
byte[] outputbytes = new byte[(int)input.length()];
instream.read(outputbytes,0,(int)input.length());
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment; filename=output.pdf");
response.setContentLength((int) outputbytes.length);
outstream.write(outputbytes);
} finally {
if (outstream != null) {
outstream.flush();
}
outstream.close();
}
}
}
private void processTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {
byte[] result = checkCache(key);
ServletOutputStream outstream = response.getOutputStream();
if((result!= null) && (result.length >0)) {
//output from cache so quick
try {
byte[] outputbytes = appservice.retrievePDFFromCache(key);
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment; filename=output.pdf");
response.setContentLength((int) outputbytes.length);
outstream.write(outputbytes);
} finally {
if (outstream != null) {
outstream.flush();
}
outstream.close();
}
} else {
String filename = createPDF(request, response);
BufferedInputStream buf = null;
try {
File input = new File(filename);
InputStream instream = new FileInputStream(input);
byte[] outputbytes = new byte[(int)input.length()];
instream.read(outputbytes,0,(int)input.length());
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment; filename=output.pdf");
response.setContentLength((int) outputbytes.length);
outstream.write(outputbytes);
} finally {
if (outstream != null) {
outstream.flush();
}
outstream.close();
}
}
}
private String createPDF(HttpServletRequest request,HttpServletResponse response) {
File tempFile= null;
try {
FopEngine fope = new FopEngine();
String xmlContent = fope.tagsoupFile(request.getParameter("url"));
xslUrl = new URL(request.getParameter("xsl"));
//We have the urls so we need to now head out and get them via a HTTP request to the external location
byte[] xslContent = fope.fetchPage(xslUrl);
System.out.println("Ready to process FOP");
//Save the output files
File tempxsl = File.createTempFile("tmp", ".xsl");
File tempxml = File.createTempFile("tmp", ".xml");
BufferedWriter out = new BufferedWriter(new FileWriter(tempxsl));
out.write(new String(xslContent));
out.close();
out = new BufferedWriter(new FileWriter(tempxml));
out.write(xmlContent);
out.close();
Thread.sleep(3000);
tempFile = fope.generatePDFFromXml(tempxsl, tempxml);
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe ) {
ioe.printStackTrace();
} catch (InterruptedException ie) {
ie.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(tempFile != null) {
return tempFile.getAbsolutePath();
} else {
return null;
}
}
}
private String createPDF(HttpServletRequest request,HttpServletResponse response, int templateId) {
File tempfile= null;
try {
FopEngine fope = new FopEngine();
String xmlContent = fope.tagsoupFile(request.getParameter("url"));
//the template is in the database so need to get it.
TemplatesBase template = appservice.getTemplateById(templateId);
byte[] xslContent = template.getTemplate_body().getBytes();
LOGGER.info("Ready to process FOP");
//Save the output files
File tempxsl = File.createTempFile("tmp", ".xsl");
File tempxml = File.createTempFile("tmp", ".xml");
BufferedWriter out = new BufferedWriter(new FileWriter(tempxsl));
out.write(new String(xslContent));
out.close();
out = new BufferedWriter(new FileWriter(tempxml));
out.write(xmlContent);
out.close();
Thread.sleep(3000);
File tempFile = fope.generatePDFFromFO(fope.generateFOFromXml(tempxsl, tempxml));
} catch (MalformedURLException mue) {
} catch (IOException ioe ) {
} catch (InterruptedException ie) {
} catch (ClassNotFoundException cnfe) {
} finally {
return tempfile.getName();
}
}
private boolean checkLicence(String key,String url, String xsl) {
LicencesBase dto = appservice.getLicenceByKey(key);
if (dto == null) {
//Not got a licence so log error and die
LOGGER.info("No Licence for URLs " + url + " and " + xsl);
return false;
} else {
LOGGER.info("Licence Found for " + url + " and " + xsl);
return true;
}
}
private byte[] checkCache(String key) {
byte[] result = null;
if (appservice.isInCache(key)) {
result = appservice.retrievePDFFromCache(key);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment