From 8662870179eed5ca6e2b7b10fd1912f922fce67b Mon Sep 17 00:00:00 2001 From: pdanner Date: Mon, 6 Dec 2010 16:59:57 +0000 Subject: Moved to pdf-as-web project git-svn-id: https://joinup.ec.europa.eu/svn/pdf-as/trunk@678 7b5415b0-85f9-ee4d-85bd-d5d0c3b42d1c --- src/main/java/at/gv/egiz/pdfas/itext/IText.java | 111 ------- .../java/at/gv/egiz/pdfas/utils/TempDirHelper.java | 357 ++++++++++++++++++++ src/main/java/at/gv/egiz/pdfas/utils/WebUtils.java | 100 ------ .../gv/egiz/pdfas/web/CurrentLocalOperation.java | 87 ----- .../gv/egiz/pdfas/web/SignSessionInformation.java | 139 -------- .../egiz/pdfas/web/VerifySessionInformation.java | 195 ----------- .../gv/egiz/pdfas/web/filter/EncodingFilter.java | 123 ------- .../at/gv/egiz/pdfas/web/helper/SessionHelper.java | 47 --- .../egiz/pdfas/web/helper/SignServletHelper.java | 309 ------------------ .../egiz/pdfas/web/helper/SigningTimeHelper.java | 83 ----- .../at/gv/egiz/pdfas/web/helper/TempDirHelper.java | 362 --------------------- .../pdfas/web/i18n/LanguageDecoratorMapper.java | 125 ------- .../gv/egiz/pdfas/web/i18n/LocaleParamFilter.java | 96 ------ 13 files changed, 357 insertions(+), 1777 deletions(-) delete mode 100644 src/main/java/at/gv/egiz/pdfas/itext/IText.java create mode 100644 src/main/java/at/gv/egiz/pdfas/utils/TempDirHelper.java delete mode 100644 src/main/java/at/gv/egiz/pdfas/utils/WebUtils.java delete mode 100644 src/main/java/at/gv/egiz/pdfas/web/CurrentLocalOperation.java delete mode 100644 src/main/java/at/gv/egiz/pdfas/web/SignSessionInformation.java delete mode 100644 src/main/java/at/gv/egiz/pdfas/web/VerifySessionInformation.java delete mode 100644 src/main/java/at/gv/egiz/pdfas/web/filter/EncodingFilter.java delete mode 100644 src/main/java/at/gv/egiz/pdfas/web/helper/SessionHelper.java delete mode 100644 src/main/java/at/gv/egiz/pdfas/web/helper/SignServletHelper.java delete mode 100644 src/main/java/at/gv/egiz/pdfas/web/helper/SigningTimeHelper.java delete mode 100644 src/main/java/at/gv/egiz/pdfas/web/helper/TempDirHelper.java delete mode 100644 src/main/java/at/gv/egiz/pdfas/web/i18n/LanguageDecoratorMapper.java delete mode 100644 src/main/java/at/gv/egiz/pdfas/web/i18n/LocaleParamFilter.java (limited to 'src/main/java/at/gv') diff --git a/src/main/java/at/gv/egiz/pdfas/itext/IText.java b/src/main/java/at/gv/egiz/pdfas/itext/IText.java deleted file mode 100644 index 767dbbc..0000000 --- a/src/main/java/at/gv/egiz/pdfas/itext/IText.java +++ /dev/null @@ -1,111 +0,0 @@ -package at.gv.egiz.pdfas.itext; - -import java.awt.color.ICC_Profile; -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.io.output.ByteArrayOutputStream; -import org.apache.log4j.Logger; - -import com.lowagie.text.Document; -import com.lowagie.text.DocumentException; -import com.lowagie.text.Font; -import com.lowagie.text.PageSize; -import com.lowagie.text.Paragraph; -import com.lowagie.text.Rectangle; -import com.lowagie.text.pdf.BaseFont; -import com.lowagie.text.pdf.PdfArray; -import com.lowagie.text.pdf.PdfDictionary; -import com.lowagie.text.pdf.PdfICCBased; -import com.lowagie.text.pdf.PdfName; -import com.lowagie.text.pdf.PdfString; -import com.lowagie.text.pdf.PdfWriter; - -public final class IText { - - private IText() { - } - - private static final Logger LOG = Logger.getLogger(IText.class); - - private static final Font DEFAULT_FONT = new Font(Font.HELVETICA, 12, Font.NORMAL); - private static final String DEFAULT_TTF_FONT_RESOURCE = "DejaVuSansCondensed.ttf"; - private static final String DEFAULT_ICC_PROFILE_RESOURCE = "srgb.profile"; - private static final Rectangle DEFAULT_PAGE_SIZE = PageSize.A4; - private static final int[] DEFAULT_MARGINS_MM = { 25, 25, 25, 25 }; // top, right, bottom, left - public static final String DEFAULT_FILENAME = "text"; - - private static Font DEFAULT_TTF_FONT; - private static PdfICCBased DEFAULT_ICC_COLOR_SPACE; - - static { - try { - byte[] ttfFontData = IOUtils.toByteArray(IText.class.getResourceAsStream(DEFAULT_TTF_FONT_RESOURCE)); - DEFAULT_TTF_FONT = new Font(BaseFont.createFont(DEFAULT_TTF_FONT_RESOURCE, BaseFont.WINANSI, true, true, ttfFontData, null)); - } catch (Exception e) { - LOG.error(e); - DEFAULT_TTF_FONT = DEFAULT_FONT; - } - try { - byte[] iccData = IOUtils.toByteArray(IText.class.getResourceAsStream(DEFAULT_ICC_PROFILE_RESOURCE)); - DEFAULT_ICC_COLOR_SPACE = new PdfICCBased(ICC_Profile.getInstance(iccData)); - DEFAULT_ICC_COLOR_SPACE.remove(PdfName.ALTERNATE); - } catch (Exception e) { - LOG.error(e); - DEFAULT_ICC_COLOR_SPACE = null; - } - } - - public static byte[] createPDF(String content, boolean pdfa) throws DocumentException, IOException { - ByteArrayOutputStream baOut = new ByteArrayOutputStream(); - createPDF(content, pdfa, baOut); - return baOut.toByteArray(); - } - - public static byte[] createPDF(String content) throws DocumentException, IOException { - return createPDF(content, false); - } - - - private static void addContent(Document document, boolean pdfa, String content) throws DocumentException { - Paragraph p = new Paragraph(content, pdfa ? DEFAULT_TTF_FONT : DEFAULT_FONT); - document.add(p); - } - public static void createPDF(String content, OutputStream outputStream) throws DocumentException, IOException { - createPDF(content, false, outputStream); - } - - public static void createPDF(String content, boolean pdfa, OutputStream outputStream) throws DocumentException, IOException { - final float factor = (float) 72 / (float) 25.4; - Document document = new Document( - DEFAULT_PAGE_SIZE, - (float) DEFAULT_MARGINS_MM[3] * factor, // left - (float) DEFAULT_MARGINS_MM[1] * factor, // right - (float) DEFAULT_MARGINS_MM[0] * factor, // top - (float) DEFAULT_MARGINS_MM[2] * factor // bottom - ); - - PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream); - if (pdfa) { - pdfWriter.setPDFXConformance(PdfWriter.PDFA1B); - } - document.open(); - if (pdfa) { - PdfDictionary pdfOutputIntent = new PdfDictionary(PdfName.OUTPUTINTENT); - pdfOutputIntent.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString("sRGB IEC61966-2.1")); - pdfOutputIntent.put(PdfName.INFO, new PdfString("sRGB IEC61966-2.1")); - pdfOutputIntent.put(PdfName.S, PdfName.GTS_PDFA1); - if (DEFAULT_ICC_COLOR_SPACE != null) { - pdfOutputIntent.put(PdfName.DESTOUTPUTPROFILE, pdfWriter.addToBody(DEFAULT_ICC_COLOR_SPACE).getIndirectReference()); - } - pdfWriter.getExtraCatalog().put(PdfName.OUTPUTINTENTS, new PdfArray(pdfOutputIntent)); - } - addContent(document, pdfa, content); - if (pdfa) { - pdfWriter.createXmpMetadata(); - } - document.close(); - } - -} diff --git a/src/main/java/at/gv/egiz/pdfas/utils/TempDirHelper.java b/src/main/java/at/gv/egiz/pdfas/utils/TempDirHelper.java new file mode 100644 index 0000000..59b8953 --- /dev/null +++ b/src/main/java/at/gv/egiz/pdfas/utils/TempDirHelper.java @@ -0,0 +1,357 @@ +/** + * + */ +package at.gv.egiz.pdfas.utils; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStreamWriter; +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import at.gv.egiz.pdfas.framework.input.DataSource; +import at.gv.egiz.pdfas.framework.input.PdfDataSource; +import at.gv.egiz.pdfas.framework.input.TextDataSource; +import at.gv.egiz.pdfas.framework.output.DataSink; +import at.gv.egiz.pdfas.impl.input.ByteArrayPdfDataSourceImpl; +import at.gv.egiz.pdfas.impl.input.FileBased; +import at.gv.egiz.pdfas.impl.input.FileBasedTextDataSourceImpl; +import at.gv.egiz.pdfas.impl.input.TextDataSourceImpl; +import at.gv.egiz.pdfas.impl.input.helper.DataSourceHelper; +import at.gv.egiz.pdfas.impl.output.ByteArrayDataSink; +import at.knowcenter.wag.egov.egiz.cfg.SettingsReader; +import at.knowcenter.wag.egov.egiz.pdf.SignatureHolder; +import at.knowcenter.wag.egov.egiz.pdf.TextualSignatureHolder; + +/** + * @author wprinz + * + */ +public class TempDirHelper +{ + /** + * The log. + */ + private static Log log = LogFactory.getLog(TempDirHelper.class); + + protected static long runningIndex = 0; + + /** + * Assembles the File of the temporary directory without checking if it really + * exists. + */ + public static File assembleTemporaryDirectoryFile() + { + File temp_dir = new File(SettingsReader.TMP_PATH); + return temp_dir; + } + + /** + * Returns the directory where temporary files should be stored. + * + *

+ * If the directory doesn't exist, it is created. + *

+ * + * @return Returns the directory where temporary files should be stored. + */ + public static File getTemporaryDirectory() + { + File temp_dir = assembleTemporaryDirectoryFile(); + if (!temp_dir.exists()) + { + temp_dir.mkdirs(); + } + return temp_dir; + } + + /** + * Deletes all files in the temporary directory, if it exists. + * + *

+ * This should be used to clear temporary files when the application shuts + * down. + *

+ */ + public static void clearTemporaryDirectory() + { + File temp_dir = assembleTemporaryDirectoryFile(); + log.debug("Clearing temporary directory: " + temp_dir); + + if (!temp_dir.exists()) + { + return; + } + + File[] files = temp_dir.listFiles(); + for (int i = 0; i < files.length; i++) + { + // added by tknall: do not try to remove svn-metadata + if (files[i].getName().endsWith(".svn")) { + continue; + } + log.debug(" Clearing temporary file: " + files[i]); + boolean delete_success = files[i].delete(); + if (!delete_success) + { + log.error("Couldn't delete the temporary file: " + files[i]); + } + } + } + + public static void storeTextSignatureHoldersIfApplicable(List shs, String fileNameSuffix) throws IOException + { + Iterator it = shs.iterator(); + while (it.hasNext()) + { + SignatureHolder sh = (SignatureHolder) it.next(); + if (sh instanceof TextualSignatureHolder) + { + TextualSignatureHolder tsh = (TextualSignatureHolder) sh; + if (!(tsh.getDataSource() instanceof FileBased)) + { + TextDataSource tds = (TextDataSource) tsh.getDataSource(); + if (isReasonableToStore(tds.getText().length())) + { + TextDataSource fbtds = placeTextIntoTempDir(tds.getText(), fileNameSuffix); + tsh.exchangeDataSource(fbtds); + } + } + } + } + } + + /** + * Places the text into the temp dir if reasonable. + * + *

+ * Reasonable means that the text is longer than a certain threshold. + * Otherwise a short text is simply held in memory. + *

+ * + * @param text + * The text to be stored. + * @param fileNameSuffix + * A file name suffix so that the temp file gets a more "readable" + * name. + * @return Returns the TextDataSource. + * @throws IOException + * F.e. + */ + public static TextDataSource placeTextIntoTempDir(String text, String fileNameSuffix) throws IOException + { + if (isReasonableToStore(text.length())) + { + String fileName = formatFileName(fileNameSuffix); + + File tmpFile = createTempFileInDir(fileName); + + FileOutputStream fos = new FileOutputStream(tmpFile); + OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); + osw.write(text); + osw.close(); + + FileBasedTextDataSourceImpl textDataSource = new FileBasedTextDataSourceImpl(tmpFile, "UTF-8"); + return textDataSource; + } + else + { + return new TextDataSourceImpl(text); + } + } + + /** + * Tells, if it is reasonable to store the text of the given length onto the + * disk. + * + * @param textLength + * The length of the text under question. + * @return Returns true if the text should be stored on the disk. + */ + public static boolean isReasonableToStore(int textLength) + { + return false; +// return textLength >= 10000; + } + + public static PdfDataSource placePdfIntoTempDir(InputStream pdfInput, String fileNameSuffix) throws IOException + { + log.debug("PERF: placing pdf into memory cache"); + + byte [] pdfData = DataSourceHelper.convertInputStreamToByteArray(pdfInput); + PdfDataSource pdfDataSource = new ByteArrayPdfDataSourceImpl(pdfData); + +// File pdfFile = placeInputIntoTempDirFile(pdfInput, fileNameSuffix); +// +// FileBasedPdfDataSourceImpl pdfDataSource = new FileBasedPdfDataSourceImpl(pdfFile, (int) pdfFile.length()); + return pdfDataSource; + } + + public static File placeInputIntoTempDirFile(InputStream input, String fileNameSuffix) throws IOException + { + String fileName = formatFileName(fileNameSuffix); + + File tmpFile = createTempFileInDir(fileName); + + FileOutputStream fos = new FileOutputStream(tmpFile); + + byte[] buffer = new byte[2048]; + int read = -1; + while ((read = input.read(buffer)) > 0) + { + fos.write(buffer, 0, read); + } + fos.close(); + input.close(); + + return tmpFile; + } + + public static File formTempFile(String fileNameSuffix) + { + String fileName = formatFileName(fileNameSuffix); + File tmpFile = getFileInTempDir(fileName); + + return tmpFile; + } + + protected static File getFileInTempDir (String fileName) + { +// File tempDir = new File(new File(SettingsReader.RESOURCES_PATH), "pdfastmp"); + File tempDir = assembleTemporaryDirectoryFile(); + + File tmpFile = new File(tempDir, fileName); + + return tmpFile; + } + + protected static String formatFileName(String fileNameSuffix) + { + // double check so that file name is always correct. + fileNameSuffix = extractFileNameSuffix(fileNameSuffix); + String fileName = "tmp" + formatIndex(runningIndex) + "_" + fileNameSuffix; + runningIndex++; + + return fileName; + } + + protected static String formatIndex(long index) + { + NumberFormat nf = new DecimalFormat("00000000"); + + return nf.format(index); + } + + protected static File createTempFileInDir(String fileName) throws IOException + { + File tmpFile = getFileInTempDir(fileName); + + tmpFile.createNewFile(); + + tmpFile.deleteOnExit(); + + return tmpFile; + } + + public static DataSink createTempDataSink(String fileNameSuffix) throws IOException + { + log.debug("PERF: placing pdf into memory cache"); + + DataSink ds = new ByteArrayDataSink(); + +// String fileName = formatFileName(fileNameSuffix); +// +// File tmpFile = createTempFileInDir(fileName); +// +// FileBasedDataSink ds = new FileBasedDataSink(tmpFile); + + return ds; + } + +// public static void writeDataSinkToHttpResponse(DataSink ds, HttpServletResponse response) throws IOException +// { +// +// response.setContentType(ds.getMimeType()); +// response.setCharacterEncoding(ds.getCharacterEncoding()); +// +// OutputStream os = response.getOutputStream(); +// +// if (ds instanceof FileBasedDataSink) +// { +// FileBasedDataSink fbds = (FileBasedDataSink)ds; +// byte[] buffer = new byte[2048]; +// FileInputStream fis = new FileInputStream(fbds.getFile()); +// int n = -1; +// while ((n = fis.read(buffer)) > 0) +// { +// os.write(buffer, 0, n); +// } +// fis.close(); +// } +// else +// { +// ByteArrayDataSink bads = (ByteArrayDataSink)ds; +// os.write(bads.getByteArray()); +// os.flush(); +// +// } +// +// os.close(); +//} + + /** + * Deletes the underlying file of the FileBased DataSource. + * + *

+ * If the DataSource is not FileBased, nothing is done. + *

+ *

+ * This is usually used by the application to delete temporary files. + *

+ * + * @param dataSource + */ + public static void deleteDataSourceIfFileBased(DataSource dataSource) + { + if (dataSource instanceof FileBased) + { + FileBased fb = (FileBased) dataSource; + log.debug("Deleting temp file " + fb.getFile()); + boolean deleted = fb.getFile().delete(); + log.debug("deleted = " + deleted); + } + } + + public static void deleteDataSinkIfFileBased(DataSink dataSink) + { + if (dataSink instanceof FileBased) + { + FileBased fb = (FileBased) dataSink; + log.debug("Deleting temp file " + fb.getFile()); + boolean deleted = fb.getFile().delete(); + log.debug("deleted = " + deleted); + } + } + + /** + * Given a file (maybe with path), extracts the file name suffix. + * @param file The file and maybe path. + * @return Returns the file name. + */ + public static String extractFileNameSuffix (String file) + { + if (file == null || file.trim().length() == 0) + { + return "nofilename"; + } + File f = new File(file); + return f.getName(); + } +} diff --git a/src/main/java/at/gv/egiz/pdfas/utils/WebUtils.java b/src/main/java/at/gv/egiz/pdfas/utils/WebUtils.java deleted file mode 100644 index 4bca486..0000000 --- a/src/main/java/at/gv/egiz/pdfas/utils/WebUtils.java +++ /dev/null @@ -1,100 +0,0 @@ -package at.gv.egiz.pdfas.utils; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import at.knowcenter.wag.egov.egiz.cfg.SettingsReader; -import at.knowcenter.wag.egov.egiz.exceptions.SettingNotFoundException; -import at.knowcenter.wag.egov.egiz.exceptions.SettingsException; -import at.knowcenter.wag.egov.egiz.web.LocalRequestHelper; - -/** - * @author tknall - */ -public final class WebUtils { - - private WebUtils() { - } - - /** - * The log. - */ - private final static Log LOG = LogFactory.getLog(WebUtils.class); - - /** - * The configuration key that replaces a dynamically generated retrieve signature data url. - */ - private final static String RETRIEVE_SIGNATURE_DATA_URL_OVERRIDE_KEY = "retrieve_signature_data_url_override"; - - /** - * Unlike {@link HttpServletResponse#encodeURL(String)} that adds only a - * {@code JSESSIONID} entry to the given url if needed, this method always - * adds the session id (except if already present within the url. - * - * @param url - * The given url. - * @param session - * The {@link HttpSession}. - * @return The given url plus a session id. - */ - public static String addJSessionID(String url, HttpSession session) { - if (url == null) { - return null; - } - if (!StringUtils.containsIgnoreCase(url, ";jsessionid=")) { - url = url + ";jsessionid=" + session.getId(); - LOG.debug("Adding jsessionid " + session.getId()); - } else { - LOG.debug("No need to add a jsessionid."); - } - LOG.debug("Returning url " + url); - return url; - } - - /** - * Unlike {@link HttpServletResponse#encodeURL(String)} that adds only a - * {@code JSESSIONID} entry to the given url if needed, this method always - * adds the session id (except if already present within the url. - * - * @param url - * The given url. - * @param request - * The {@link HttpServletRequest}. - * @return The given url plus a session id. - */ - public static String addJSessionID(String url, HttpServletRequest request) { - return addJSessionID(url, request.getSession()); - } - - /** - * Either dynamically creates locref content url or uses a url provides by the pdf-as - * configuration (key {@code retrieve_signature_data_url_override}). - * @param request The {@link HttpServletRequest}. - * @param response The {@link HttpServletResponse}. - * @return The retrieve signature data url. - */ - public static String buildRetrieveSignatureDataURL(HttpServletRequest request, HttpServletResponse response) { - String override = null; - LOG.debug("Building retrieve signature data url."); - try { - override = SettingsReader.getInstance().getSetting(RETRIEVE_SIGNATURE_DATA_URL_OVERRIDE_KEY, null); - } catch (SettingsException e) { - LOG.error(e); - } - String result; - if (override == null) { - result = WebUtils.addJSessionID(LocalRequestHelper.getLocalContextAddress(request, response) + "/RetrieveSignatureData", request); - } else { - LOG.debug("Override url found: " + override); - result = WebUtils.addJSessionID(override, request); - } - LOG.debug("RetrieveSignatureDataURL = " + result); - return result; - } - -} diff --git a/src/main/java/at/gv/egiz/pdfas/web/CurrentLocalOperation.java b/src/main/java/at/gv/egiz/pdfas/web/CurrentLocalOperation.java deleted file mode 100644 index 83d214c..0000000 --- a/src/main/java/at/gv/egiz/pdfas/web/CurrentLocalOperation.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * - */ -package at.gv.egiz.pdfas.web; - -import java.util.List; -import java.util.Properties; - -import at.knowcenter.wag.egov.egiz.pdf.SignatureHolder; -import at.knowcenter.wag.egov.egiz.web.LocalRequest; - -/** - * Encapsulates a local operation. - * - *

- * A local operation is a sequence of successive local verifications. - *

- *

- * This is held on the VerifySessionInformation so that the DataURLServlet and RetrieveSignatureDataServlet - * can provide their data to the local service easily. - *

- * - * @author wprinz - */ -public class CurrentLocalOperation -{ - - /** - * The signature holders to be verified in the current local operation. - */ - public List holders_to_be_verified; - - - /** - * An array of local requests to be processed. - */ - public LocalRequest[] requests = null; - - /** - * An array of response strings of the local requests. - */ - public Properties[] response_properties = null; - - /** - * The index of the holder/request to be processed. - */ - public int current_operation = 0; - -// /** -// * Tells, if the current local request has been finished. -// */ -// public boolean finished = false; - - /** - * @see at.gv.egiz.pdfas.web.LocalOperation#isFinished() - */ - public boolean isFinished() - { - return this.current_operation >= this.requests.length; - } - - /** - * @see at.gv.egiz.pdfas.web.LocalOperation#getCurrentLocalRequest() - */ - public LocalRequest getCurrentLocalRequest() - { - return this.requests[this.current_operation]; - } - - /** - * @see at.gv.egiz.pdfas.web.LocalOperation#getCurrentSignatureHolder() - */ - public SignatureHolder getCurrentSignatureHolder() - { - return (SignatureHolder) this.holders_to_be_verified.get(this.current_operation); - } - - /** - * @see at.gv.egiz.pdfas.web.LocalOperation#finishCurrentOperation(java.util.Properties) - */ - public void finishCurrentOperation(Properties response_properties) - { - this.response_properties[this.current_operation] = response_properties; - - this.current_operation++; - } -} diff --git a/src/main/java/at/gv/egiz/pdfas/web/SignSessionInformation.java b/src/main/java/at/gv/egiz/pdfas/web/SignSessionInformation.java deleted file mode 100644 index 65015e1..0000000 --- a/src/main/java/at/gv/egiz/pdfas/web/SignSessionInformation.java +++ /dev/null @@ -1,139 +0,0 @@ -/** - * - */ -package at.gv.egiz.pdfas.web; - -import java.io.Serializable; -import java.util.Properties; - -import javax.servlet.http.HttpSessionBindingEvent; -import javax.servlet.http.HttpSessionBindingListener; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import at.gv.egiz.pdfas.framework.input.PdfDataSource; -import at.gv.egiz.pdfas.framework.output.DataSink; -import at.gv.egiz.pdfas.framework.signator.SignatorInformation; -import at.gv.egiz.pdfas.web.helper.TempDirHelper; -import at.knowcenter.wag.egov.egiz.pdf.TablePos; -import at.knowcenter.wag.egov.egiz.web.ExternAppInformation; -import at.knowcenter.wag.egov.egiz.web.LocalRequest; - -/** - * @author wprinz - * - */ -public class SignSessionInformation implements HttpSessionBindingListener, Serializable -{ - /** - * SVUID. - */ - private static final long serialVersionUID = 2739944460007369626L; - - /** - * The log. - */ - private static Log log = LogFactory.getLog(SignSessionInformation.class); - - /** - * The connector. - */ - public String connector = null; - - /** - * For local requests, tells the application (sign, verify). - */ - public String application = null; - - /** - * Tells the operation mode (binary, textual). - */ - public String mode = null; - - /** - * The original, uploaded pdf. - */ - public PdfDataSource pdfDataSource = null; - - /** - * The type/profile of the signature. - */ - public String type = null; - - /** - * The suggested filename. - */ - public String filename; - - /** - * Tells, if the file download should be done inline or as attachment. - */ - public boolean download_inline; - - /** - * Object containing information about the calling webapplication. - * - * @author: Thomas Zefferer - */ - public ExternAppInformation exappinf; - - /** - * Information about the signature position - * - * @author: Thomas Zefferer - */ - public TablePos pos; - - /** - * The SignatorInformation. - */ - public SignatorInformation si = null; - - /** - * The DataSink to write the output data to. - */ - public DataSink output = null; - - /** - * The local request to be sent to the device. - */ - public LocalRequest localRequest = null; - - /** - * The response properties of the local request. - */ - public Properties response_properties = null; - - /** - * Tells if the sign request has been processed and the signed document is - * available in the DataSink. - */ - public boolean outputAvailable = false; - - - /** - * @see javax.servlet.http.HttpSessionBindingListener#valueBound(javax.servlet.http.HttpSessionBindingEvent) - */ - public void valueBound(HttpSessionBindingEvent event) - { - log.debug("Bound SignSessionInformation to session (ID=" + event.getSession().getId() + ")."); - } - - /** - * @see javax.servlet.http.HttpSessionBindingListener#valueUnbound(javax.servlet.http.HttpSessionBindingEvent) - */ - public void valueUnbound(HttpSessionBindingEvent event) - { - log.debug("Unbound SignSessionInformation from session (ID=" + event.getSession().getId() + ")."); - - if (this.pdfDataSource != null) - { - TempDirHelper.deleteDataSourceIfFileBased(this.pdfDataSource); - } - if (this.output != null) - { - TempDirHelper.deleteDataSinkIfFileBased(this.output); - } - } -} diff --git a/src/main/java/at/gv/egiz/pdfas/web/VerifySessionInformation.java b/src/main/java/at/gv/egiz/pdfas/web/VerifySessionInformation.java deleted file mode 100644 index e998ded..0000000 --- a/src/main/java/at/gv/egiz/pdfas/web/VerifySessionInformation.java +++ /dev/null @@ -1,195 +0,0 @@ -/** - * Copyright (c) 2006 by Know-Center, Graz, Austria - * - * This software is the confidential and proprietary information of Know-Center, - * Graz, Austria. You shall not disclose such Confidential Information and shall - * use it only in accordance with the terms of the license agreement you entered - * into with Know-Center. - * - * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF - * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR - * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY - * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. - * - * $Id: SessionInformation.java,v 1.2 2006/08/25 17:06:11 wprinz Exp $ - */ -package at.gv.egiz.pdfas.web; - -import java.io.Serializable; -import java.util.Iterator; -import java.util.List; - -import javax.servlet.http.HttpSessionBindingEvent; -import javax.servlet.http.HttpSessionBindingListener; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import at.gv.egiz.pdfas.framework.input.DataSource; -import at.gv.egiz.pdfas.web.helper.TempDirHelper; -import at.knowcenter.wag.egov.egiz.pdf.SignatureHolder; -import at.knowcenter.wag.egov.egiz.pdf.TablePos; -import at.knowcenter.wag.egov.egiz.web.ExternAppInformation; - -/** - * This class is a collection of various session parameters that are passed - * between the servlets and jsps. - * - *

- * The SessionInformation class contains type safe references to the objects. - *

- * - * @author wprinz - */ -public class VerifySessionInformation implements HttpSessionBindingListener, Serializable -{ - - /** - * SVUID. - */ - private static final long serialVersionUID = -7413884936584659150L; - - /** - * The log. - */ - private static Log log = LogFactory.getLog(VerifySessionInformation.class); - - /** - * The connector. - */ - public String connector = null; - - /** - * For local requests, tells the application (sign, verify). - */ - public String application = null; - - /** - * Tells the operation mode (binary, textual). - */ - public String mode = null; - - /** - * The original, uploaded pdf. - */ - //public FileBasedPdfDataSourceImpl pdfDataSource = null; - public DataSource inputDataSource = null; - - /** - * The type/profile of the signature. - */ - public String type = null; - -// /** -// * The user name. -// */ -// public String user_name = null; -// -// /** -// * The password. -// */ -// public String user_password = null; - - /** - * All SignatureHolders extracted from the document. - */ - public List signature_holders; - - /** - * Keeps track of the currently running local operation. - * - *

- * Only valid during local verify. - *

- */ - public CurrentLocalOperation currentLocalOperation = null; - - /** - * This is used only for MOA loc-ref web verify. - */ - public SignatureHolder moa_holder; - - -// /** -// * The incremental update information that has been extracted from the given -// * PDF document. -// */ -// public IncrementalUpdateInformation iui; - -// public SignatorInformation si = null; - -// public FileBasedDataSink output = null; - - -// /** -// * Copy of signature holders. It's needed by BKU when we try to verify single by single -// * signature. -// */ -// public List copy_of_signature_holders; - -// /** -// * The suggested filename. -// */ -// public String filename; -// -// /** -// * Tells, if the file download should be done inline or as attachment. -// */ -// public boolean download_inline; - -//// /** -//// * The sign result to be passed back to the user. -//// */ -//// public SignResult sign_result; -// -// public boolean isSignFinished = false; - - - - /** - * Object containing information about the calling webapplication. - * @author: Thomas Zefferer - */ - public ExternAppInformation exappinf; - - /** - * Information about the signature position - * @author: Thomas Zefferer - */ - public TablePos pos ; - - - - /** - * @see javax.servlet.http.HttpSessionBindingListener#valueBound(javax.servlet.http.HttpSessionBindingEvent) - */ - public void valueBound(HttpSessionBindingEvent event) - { - log.debug("Bound SignSessionInformation to session."); - } - - /** - * @see javax.servlet.http.HttpSessionBindingListener#valueUnbound(javax.servlet.http.HttpSessionBindingEvent) - */ - public void valueUnbound(HttpSessionBindingEvent event) - { - log.debug("Unbound SignSessionInformation from session."); - - if (this.inputDataSource != null) - { - TempDirHelper.deleteDataSourceIfFileBased(this.inputDataSource); - } - if (this.signature_holders != null) - { - Iterator it = this.signature_holders.iterator(); - while (it.hasNext()) - { - SignatureHolder sh = (SignatureHolder) it.next(); - TempDirHelper.deleteDataSourceIfFileBased(sh.getDataSource()); - } - } - } - -} diff --git a/src/main/java/at/gv/egiz/pdfas/web/filter/EncodingFilter.java b/src/main/java/at/gv/egiz/pdfas/web/filter/EncodingFilter.java deleted file mode 100644 index 5267918..0000000 --- a/src/main/java/at/gv/egiz/pdfas/web/filter/EncodingFilter.java +++ /dev/null @@ -1,123 +0,0 @@ -package at.gv.egiz.pdfas.web.filter; - -import java.io.IOException; -import java.nio.charset.Charset; - -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.log4j.Logger; - -/** - * @author Thomas Knall - */ -public class EncodingFilter implements javax.servlet.Filter { - - private static final String SERVLET_INIT_PARAM_ENCODING = "encoding"; - - private static final String SERVLET_INIT_PARAM_SET_REQUEST_ENCODING = "setRequestEncoding"; - private static final String SERVLET_INIT_PARAM_FORCE_REQUEST_ENCODING = "forceRequestEncoding"; - - private static final String SERVLET_INIT_PARAM_SET_RESPONSE_ENCODING = "setResponseEncoding"; - private static final String SERVLET_INIT_PARAM_FORCE_RESPONSE_ENCODING = "forceResponseEncoding"; - - private static final boolean DEFAULT_SET_REQUEST_ENCODING_VALUE = true; - private static final boolean DEFAULT_FORCE_REQUEST_ENCODING_VALUE = true; - private static final boolean DEFAULT_SET_RESPONSE_ENCODING_VALUE = false; - private static final boolean DEFAULT_FORCE_RESPONSE_ENCODING_VALUE = false; - - private Logger log = Logger.getLogger(getClass().getName()); - - private String encoding = null; - - private boolean setRequestEncoding; - private boolean forceRequestEncoding; - - private boolean setResponseEncoding; - private boolean forceResponseEncoding; - - private boolean enabled = false; - - private boolean parseBooleanInitParameter(final FilterConfig filterConfig, String parameterName, boolean defaultValue) { - String paramValue = filterConfig.getInitParameter(parameterName); - if (paramValue == null) { - return defaultValue; - } - paramValue = paramValue.trim(); - if (paramValue.equalsIgnoreCase("true")) { - return true; - } else if (paramValue.equalsIgnoreCase("false")){ - return false; - } else { - log.warn("Unknown value \"" + paramValue + "\" for init parameter \"" + parameterName + "\" detected. Should be \"true\" or \"false\". Using default value \"" + defaultValue + "\"."); - return defaultValue; - } - } - - public void init(final FilterConfig filterConfig) throws ServletException { - log.debug("Initializing encoding filter (" + getClass().getName() + ")."); - - // mandatory parameter encoding - String desiredEncoding = filterConfig.getInitParameter(SERVLET_INIT_PARAM_ENCODING); - if (StringUtils.isEmpty(desiredEncoding)) { - log.warn("Unable to initialize encoding filter (" + getClass().getName() + "). Init parameter \"" + SERVLET_INIT_PARAM_ENCODING + "\" empty or not supplied."); - } else if (!Charset.isSupported(desiredEncoding)) { - log.warn("Unable to initialize encoding filter (" + getClass().getName() + "). Encoding \"" + desiredEncoding + "\" is not supported."); - } else { - this.encoding = desiredEncoding; - this.enabled = true; - this.setRequestEncoding = this.parseBooleanInitParameter(filterConfig, SERVLET_INIT_PARAM_SET_REQUEST_ENCODING, DEFAULT_SET_REQUEST_ENCODING_VALUE); - this.forceRequestEncoding = this.parseBooleanInitParameter(filterConfig, SERVLET_INIT_PARAM_FORCE_REQUEST_ENCODING, DEFAULT_FORCE_REQUEST_ENCODING_VALUE); - this.setResponseEncoding = this.parseBooleanInitParameter(filterConfig, SERVLET_INIT_PARAM_SET_RESPONSE_ENCODING, DEFAULT_SET_RESPONSE_ENCODING_VALUE); - this.forceResponseEncoding = this.parseBooleanInitParameter(filterConfig, SERVLET_INIT_PARAM_FORCE_RESPONSE_ENCODING, DEFAULT_FORCE_RESPONSE_ENCODING_VALUE); - log.debug("Encoding filter \"" + getClass().getName() + "\" configured: " + this.toString(true)); - - } - } - - public String toString(boolean verbose) { - if (verbose) { - return new ToStringBuilder(this) - .append(SERVLET_INIT_PARAM_ENCODING, this.encoding) - .append(SERVLET_INIT_PARAM_SET_REQUEST_ENCODING, this.setRequestEncoding) - .append(SERVLET_INIT_PARAM_FORCE_REQUEST_ENCODING, this.forceRequestEncoding) - .append(SERVLET_INIT_PARAM_SET_RESPONSE_ENCODING, this.setResponseEncoding) - .append(SERVLET_INIT_PARAM_FORCE_RESPONSE_ENCODING, this.forceResponseEncoding) - .toString(); - } else { - return super.toString(); - } - } - - public void doFilter(ServletRequest request, ServletResponse response, final FilterChain filterChain) throws IOException, ServletException { - if (this.enabled) { - if (this.setRequestEncoding) { - if (this.forceRequestEncoding) { - log.trace("Forcing request encoding \"" + this.encoding + "\"."); - request.setCharacterEncoding(this.encoding); - } else if (request.getCharacterEncoding() == null) { - log.trace("Request character encoding not set. Setting to \"" + this.encoding + "\"."); - request.setCharacterEncoding("UTF8"); - } - } - if (this.setResponseEncoding) { - if (this.forceResponseEncoding) { - log.trace("Forcing response encoding \"" + this.encoding + "\"."); - response.setCharacterEncoding(this.encoding); - } else if (response.getCharacterEncoding() == null) { - log.trace("Response character encoding not set. Setting to \"" + this.encoding + "\"."); - response.setCharacterEncoding("UTF8"); - } - } - } - filterChain.doFilter(request, response); - } - - public void destroy() { - } -} diff --git a/src/main/java/at/gv/egiz/pdfas/web/helper/SessionHelper.java b/src/main/java/at/gv/egiz/pdfas/web/helper/SessionHelper.java deleted file mode 100644 index ca09871..0000000 --- a/src/main/java/at/gv/egiz/pdfas/web/helper/SessionHelper.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * - */ -package at.gv.egiz.pdfas.web.helper; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import at.gv.egiz.pdfas.exceptions.web.SessionExpiredException; -import at.knowcenter.wag.egov.egiz.web.SessionAttributes; - -/** - * @author wprinz - * - */ -public class SessionHelper -{ - /** - * The log. - */ - private static Log log = LogFactory.getLog(SessionHelper.class); - - public static Object getSession(HttpServletRequest request) throws SessionExpiredException - { - - HttpSession session = request.getSession(false); - if (session == null) - { - String msg = "There is no session associated with this request."; //$NON-NLS-1$ - log.error(msg); - throw new SessionExpiredException(msg); - } - - Object sessionObject = session.getAttribute(SessionAttributes.ATTRIBUTE_SESSION_INFORMATION); - if (sessionObject == null) - { - String msg = "Unable to find session data in session " + session.getId(); - log.error(msg); - throw new SessionExpiredException(msg); - } - - return sessionObject; - } -} diff --git a/src/main/java/at/gv/egiz/pdfas/web/helper/SignServletHelper.java b/src/main/java/at/gv/egiz/pdfas/web/helper/SignServletHelper.java deleted file mode 100644 index 7e121b9..0000000 --- a/src/main/java/at/gv/egiz/pdfas/web/helper/SignServletHelper.java +++ /dev/null @@ -1,309 +0,0 @@ -/** - * - */ -package at.gv.egiz.pdfas.web.helper; - -import java.io.FileInputStream; -import java.io.IOException; -import java.net.URL; - -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import at.gv.egiz.pdfas.api.commons.Constants; -import at.gv.egiz.pdfas.framework.SignatorFactory; -import at.gv.egiz.pdfas.framework.signator.Signator; -import at.gv.egiz.pdfas.impl.output.ByteArrayDataSink; -import at.gv.egiz.pdfas.impl.output.FileBasedDataSink; -import at.gv.egiz.pdfas.utils.WebUtils; -import at.gv.egiz.pdfas.web.SignSessionInformation; -import at.knowcenter.wag.egov.egiz.PdfASID; -import at.knowcenter.wag.egov.egiz.exceptions.PDFDocumentException; -import at.knowcenter.wag.egov.egiz.exceptions.PresentableException; -import at.knowcenter.wag.egov.egiz.framework.signators.DetachedSignator_1_0_0; -import at.knowcenter.wag.egov.egiz.sig.ConnectorFactory; -import at.knowcenter.wag.egov.egiz.sig.connectors.Connector; -import at.knowcenter.wag.egov.egiz.sig.connectors.ConnectorChooser; -import at.knowcenter.wag.egov.egiz.sig.connectors.bku.SignSignatureObject; -import at.knowcenter.wag.egov.egiz.web.FormFields; -import at.knowcenter.wag.egov.egiz.web.LocalRequestHelper; -import at.knowcenter.wag.egov.egiz.web.PDFContainer; -import at.knowcenter.wag.egov.egiz.web.SessionAttributes; -import at.knowcenter.wag.egov.egiz.web.servlets.ProvidePDFServlet; - -/** - * @author wprinz - * - */ -public class SignServletHelper -{ - /** - * The log. - */ - private static Log log = LogFactory.getLog(SignServletHelper.class); - - public static void dispatch(HttpServletRequest request, HttpServletResponse response, String resource, ServletContext context) throws ServletException, IOException - { - response.setContentType("text/html"); - response.setCharacterEncoding("UTF-8"); - - RequestDispatcher disp = context.getRequestDispatcher(resource); - disp.forward(request, response); - } - - - /** - * Prepares the sign. - * - *

- * This prepares the data for both being signed or being previewed. - *

- * - * @param si - * The SessionInformation to be prepared. - * @throws PresentableException - * f.e. - */ - public static void prepareSign(SignSessionInformation si) throws PresentableException - { - log.debug("prepareSign:"); //$NON-NLS-1$ - - PdfASID algorithm = FormFields.translateSignatureModeToPdfASID(si.mode); - Signator signator = SignatorFactory.createSignator(algorithm); - - // tzefferer: modified - // si.iui = signator.prepareSign(si.pdf, si.type, null, - // ConnectorFactory.needsSIG_ID(si.connector)); - si.si = signator.prepareSign(si.pdfDataSource, si.type, si.pos, null); - // end modify - log.debug("prepareSign finished."); //$NON-NLS-1$ - } - - /** - * Finishes the sign. - * - *

- * For non local connectors this concludes the sign process, signs the - * document and returns the result. For local connectors this initializes the - * local sign process and redirects to following servlets. - *

- * - * @param si - * The SessionInformation. - * @param request - * The servlet request for dispatching. - * @param response - * The servlet response for dispatching. - * @param context - * The servlet context for dispatching. - * @throws PresentableException - * f.e. - * @throws IOException - * f. e. - * @throws ServletException - * f. e. - */ - public static void finishSign(SignSessionInformation si, HttpServletRequest request, HttpServletResponse response, ServletContext context) throws PresentableException, IOException, ServletException - { - log.debug("finishSign:"); //$NON-NLS-1$ - - // check if document is empty - if (si.si.getSignatureData() == null || si.si.getSignatureData().getDataSource().getLength() == 0) { - throw new PDFDocumentException(251, "Unable to extract and textual content."); - } - - log.debug("connector = " + si.connector); //$NON-NLS-1$ - if (ConnectorFactory.isConnectorLocal(si.connector)) - { - log.debug("Connector is local -> dispatching to local processing."); //$NON-NLS-1$ - - String dispatch_to = LocalRequestHelper.processLocalSign(si, request, response); - dispatch(request, response, dispatch_to, context); - return; - } - log.debug("Connector is not local -> finishing the sign."); //$NON-NLS-1$ - - PdfASID algorithm = FormFields.translateSignatureModeToPdfASID(si.mode); - Signator signator = SignatorFactory.createSignator(algorithm); - - log.debug("RequestURL = " + request.getRequestURL()); - log.debug("ContextPath = " + request.getContextPath()); - String host = request.getServerName(); - - // TODO TR: Web-Applikation verwendet in Loc-Ref-Variante ext. Referenz, um performanter zu sein; - // nachfolend auskommentieren, wenn anstatt SwA-Connector LocRef-Connector verwendet wird -// URL signature_data_URL = new URL(WebUtils.addJSessionID(LocalRequestHelper.getLocalContextAddress(request, response) + "/RetrieveSignatureData", request)); - URL signature_data_URL = new URL(WebUtils.buildRetrieveSignatureDataURL(request, response)); - String signature_data_url = response.encodeURL(signature_data_URL.toString()); - - Connector c = ConnectorChooser.chooseWebConnectorForSign(si.connector, si.type, signature_data_url); - SignSignatureObject signSignatureObject = c.doSign(si.si.getSignatureData()); - - si.si.setSignSignatureObject(signSignatureObject); - - si.output = TempDirHelper.createTempDataSink(si.filename + "_signed.pdf"); - signator.finishSign(si.si, si.output); - - returnSignResponse(si, request, response); - log.debug("finishSign finished."); //$NON-NLS-1$ - - } - - /** - * Returns the data in the SignResult with proper content disposition. - * - * @param si - * SessionInformation. - * @parem request The servlet request. - * @param response - * The servlet response. - * @throws IOException - * The IO Exception. - */ - public static void returnSignResponse(SignSessionInformation si, HttpServletRequest request, HttpServletResponse response) throws IOException - { -// SignResult sign_result = si.sign_result; - - String file_name = formatFileNameForSignResult(si.filename, si.output.getMimeType()); - - // tzefferer: added condition - if (si.exappinf == null) - { - - // The name parameter is actually deprecated in favour of - // Content-Disposition filename - // Unfortunately Acrobat reader does recognize neither of these parameters - // with its inline save-as. It always takes the page name. - response.setContentType(si.output.getMimeType() + "; name=\"" + file_name + "\""); - if (si.download_inline) - { - response.addHeader("Content-Disposition", "inline; filename=\"" + file_name + "\""); - } - else - { - response.addHeader("Content-Disposition", "attachment; filename=\"" + file_name + "\""); - } - - TempDirHelper.writeDataSinkToHttpResponse(si.output, response); - //response.getOutputStream().write(sign_result.getData()); - - // tzefferer: added else-block - } - else - { - /** - * The following code handles an external invocation of pdf-as. External invocation is done by - * redirecting the user to the Sign-Servlet using the parameters defined in class - * at.knowcenter.wag.egov.egiz.web.FormFields. - * e.g. http://localhost:48080/pdf-as/Sign?preview=false&connector=bku&mode=textual&sig_type=SIGNATURBLOCK_DE&inline=false&filename=test.pdf&num-bytes=45916&pdf-url=http%3A%2F%2Flocalhost%3A8080%2Fmyapp%2FProvidePDF&pdf-id=1956507909008215134&invoke-app-url=https%3A%2F%2Flocalhost%3A8443%2Fmyapp%2FReturnSignedPDF&invoke-app-error-url=https%3A%2F%2Flocalhost%3A8443%2Fmyapp%2Fpdfaserror.do&session-id=9085B85B364BEC31E7D38047FE54577D&locale=de - */ - log.debug("External webapp invocation detected."); - byte [] signed_pdf = null; - if (si.output instanceof FileBasedDataSink) - { - FileBasedDataSink fbds = (FileBasedDataSink)si.output; - signed_pdf = new byte [(int)fbds.getFile().length()]; - FileInputStream fis = new FileInputStream(fbds.getFile()); - fis.read(signed_pdf); - fis.close(); - } - else - { - ByteArrayDataSink bads = (ByteArrayDataSink)si.output; - signed_pdf = bads.getByteArray(); - } - HttpSession session = request.getSession(); - - PDFContainer entry = new PDFContainer(signed_pdf, si.exappinf.pdf_id); - ProvidePDFServlet.signedDocuments.add(entry); - - // notify webapp... - String invoke_url = si.exappinf.invoke_url; - - String providePDFServlet = "ProvidePDF"; - String pdf_id = String.valueOf(si.exappinf.pdf_id); - String session_id = si.exappinf.session_id; - - log.debug("External application has to be notified. Building url from callback url \"" + invoke_url + "\"."); - - // build URL - int ind = invoke_url.indexOf("?"); - - // fixed by tknall: must not presume that invoke_url contains "?" - String sep = "&"; - if (ind == -1) { - ind = invoke_url.length(); - sep = "?"; - } - - String query = invoke_url.substring(0, ind) + ";jsessionid=" + session_id + invoke_url.substring(ind) - + sep + FormFields.FIELD_PDF_URL + "=" + providePDFServlet + "&" + FormFields.FIELD_PDF_ID - + "=" + pdf_id + "&" + FormFields.FIELD_FILE_LENGTH + "=" + signed_pdf.length - + "&" + FormFields.FIELD_PDFAS_SESSION_ID + "=" + session.getId(); - - /* - * Using the external web-interface of pdf-as (as described above) pdf-as should be run within - * an iframe. In case of a signature performed with a local citizen card software or with the - * server bku the result has to be provided outside the iframe. To break out of the iframe a - * helper jsp (redirect_to_parent) has to be used that redirects the user to the parent - * window. - */ - disableBrowserCacheForResponse(response); - if (Constants.SIGNATURE_DEVICE_BKU.equals(si.connector) || Constants.SIGNATURE_DEVICE_MOC.equals(si.connector)) { - log.debug("Pdf-as is supposed to run within an iframe."); - log.debug("Putting external application notify url (\"" + query + "\") in session (" + session.getId() + ") for later use."); - session.setAttribute(SessionAttributes.PARENT_WEBAPP_REDIRECT_URL, query); - String redirectHelper = response.encodeRedirectURL(request.getContextPath() + "/jsp/redirect_to_parent.jsp"); - - log.debug("Redirecting to " + redirectHelper); - log.debug("The browser will finally be redirected outside the iframe to " + query + " in order to notify the external application."); - - response.sendRedirect(redirectHelper); - - } else { - log.debug("Notifying external application by redirecting to \"" + query + "\"."); - response.sendRedirect(query); - } - - } - - } - - public static void disableBrowserCacheForResponse(HttpServletResponse response) { - log.debug("Disabling browser cache for HttpServletResponse."); - response.setHeader("Cache-Control", "no-cache"); - response.setHeader("Pragma","no-cache"); - response.setDateHeader("Expires", -1); - } - - /** - * Formats the file name according to the SignResult. - * - * @param file_name - * The file name. - * @param sign_result - * The sign result. - * @return Returns the formatted file name. - */ - public static String formatFileNameForSignResult(String file_name, String mimeType) - { - String output = file_name + "_signed"; - if (mimeType.equals(DetachedSignator_1_0_0.MIME_TYPE)) - { - output += ".xml"; - } - else - { - output += ".pdf"; - } - - return output; - } -} diff --git a/src/main/java/at/gv/egiz/pdfas/web/helper/SigningTimeHelper.java b/src/main/java/at/gv/egiz/pdfas/web/helper/SigningTimeHelper.java deleted file mode 100644 index 673c197..0000000 --- a/src/main/java/at/gv/egiz/pdfas/web/helper/SigningTimeHelper.java +++ /dev/null @@ -1,83 +0,0 @@ -package at.gv.egiz.pdfas.web.helper; - -import java.util.Date; - -import org.apache.commons.lang.time.DateFormatUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import at.gv.egiz.pdfas.exceptions.ErrorCode; -import at.gv.egiz.pdfas.framework.signator.SignatorInformation; -import at.knowcenter.wag.egov.egiz.cfg.SettingsReader; -import at.knowcenter.wag.egov.egiz.exceptions.SettingsException; -import at.knowcenter.wag.egov.egiz.exceptions.SignatureException; -import at.knowcenter.wag.egov.egiz.pdf.EGIZDate; -import at.knowcenter.wag.egov.egiz.sig.connectors.bku.SignSignatureObject; - -/** - * This class deals with invalid signing times. - * @author tknall - */ -public final class SigningTimeHelper { - - private SigningTimeHelper() { - } - - private static Integer tolerance = null; - - /** - * The log. - */ - private final static Log LOG = LogFactory.getLog(SigningTimeHelper.class); - - private final static String SIGNING_TIME_TOLERANCE_KEY = "signing_time_tolerance"; - private final static String FORMAT_UTC_DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"; - - public static void checkSigningTimeAgainstHostTime(SignatorInformation si) throws SignatureException { - checkSigningTimeAgainstHostTime(si.getSignSignatureObject()); - } - - public static synchronized void checkSigningTimeAgainstHostTime(SignSignatureObject sso) throws SignatureException { - if (tolerance == null) { - try { - String toleranceString = SettingsReader.getInstance().getSetting(SIGNING_TIME_TOLERANCE_KEY, "-1"); - tolerance = new Integer(Integer.parseInt(toleranceString)); - } catch (NumberFormatException e) { - LOG.warn("Invalid configuration key = " + SIGNING_TIME_TOLERANCE_KEY + ". Disabling signing time check."); - tolerance = new Integer(-1); - } catch (SettingsException e) { - LOG.error("Error reading settings. Disabling signing time check.", e); - tolerance = new Integer(-1); - } - } - if (tolerance.intValue() == -1) { - return; - } - - // signing time - Date signingTime = EGIZDate.parseDateFromString(sso.getDate()); - - // current time - Date currentTime = new Date(); - - // lower limit - Date lowerLimit = new Date(currentTime.getTime() - tolerance.intValue()*1000); - - // upper limit - Date upperLimit = new Date(currentTime.getTime() + tolerance.intValue()*1000); - - String signingTimeString = DateFormatUtils.formatUTC(signingTime, FORMAT_UTC_DATE_PATTERN); - - if (LOG.isDebugEnabled()) { - String lower = DateFormatUtils.formatUTC(lowerLimit, FORMAT_UTC_DATE_PATTERN); - String upper = DateFormatUtils.formatUTC(upperLimit, FORMAT_UTC_DATE_PATTERN); - LOG.debug("Checking if signing time " + signingTimeString + " is valid according to the given time frame [ " + lower + ", " + upper + " ]."); - } - - if (signingTime.before(lowerLimit) || signingTime.after(upperLimit)) { - throw new SignatureException(ErrorCode.INVALID_SIGNING_TIME, "The signing time " + signingTimeString + " is out of the given tolerance of " + tolerance.intValue() + " seconds."); - } - - } - -} diff --git a/src/main/java/at/gv/egiz/pdfas/web/helper/TempDirHelper.java b/src/main/java/at/gv/egiz/pdfas/web/helper/TempDirHelper.java deleted file mode 100644 index e7ce3ac..0000000 --- a/src/main/java/at/gv/egiz/pdfas/web/helper/TempDirHelper.java +++ /dev/null @@ -1,362 +0,0 @@ -/** - * - */ -package at.gv.egiz.pdfas.web.helper; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.Iterator; -import java.util.List; - -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import at.gv.egiz.pdfas.framework.input.DataSource; -import at.gv.egiz.pdfas.framework.input.PdfDataSource; -import at.gv.egiz.pdfas.framework.input.TextDataSource; -import at.gv.egiz.pdfas.framework.output.DataSink; -import at.gv.egiz.pdfas.impl.input.ByteArrayPdfDataSourceImpl; -import at.gv.egiz.pdfas.impl.input.FileBased; -import at.gv.egiz.pdfas.impl.input.FileBasedTextDataSourceImpl; -import at.gv.egiz.pdfas.impl.input.TextDataSourceImpl; -import at.gv.egiz.pdfas.impl.input.helper.DataSourceHelper; -import at.gv.egiz.pdfas.impl.output.ByteArrayDataSink; -import at.gv.egiz.pdfas.impl.output.FileBasedDataSink; -import at.knowcenter.wag.egov.egiz.cfg.SettingsReader; -import at.knowcenter.wag.egov.egiz.pdf.SignatureHolder; -import at.knowcenter.wag.egov.egiz.pdf.TextualSignatureHolder; - -/** - * @author wprinz - * - */ -public class TempDirHelper -{ - /** - * The log. - */ - private static Log log = LogFactory.getLog(TempDirHelper.class); - - protected static long runningIndex = 0; - - /** - * Assembles the File of the temporary directory without checking if it really - * exists. - */ - public static File assembleTemporaryDirectoryFile() - { - File temp_dir = new File(SettingsReader.TMP_PATH); - return temp_dir; - } - - /** - * Returns the directory where temporary files should be stored. - * - *

- * If the directory doesn't exist, it is created. - *

- * - * @return Returns the directory where temporary files should be stored. - */ - public static File getTemporaryDirectory() - { - File temp_dir = assembleTemporaryDirectoryFile(); - if (!temp_dir.exists()) - { - temp_dir.mkdirs(); - } - return temp_dir; - } - - /** - * Deletes all files in the temporary directory, if it exists. - * - *

- * This should be used to clear temporary files when the application shuts - * down. - *

- */ - public static void clearTemporaryDirectory() - { - File temp_dir = assembleTemporaryDirectoryFile(); - log.debug("Clearing temporary directory: " + temp_dir); - - if (!temp_dir.exists()) - { - return; - } - - File[] files = temp_dir.listFiles(); - for (int i = 0; i < files.length; i++) - { - // added by tknall: do not try to remove svn-metadata - if (files[i].getName().endsWith(".svn")) { - continue; - } - log.debug(" Clearing temporary file: " + files[i]); - boolean delete_success = files[i].delete(); - if (!delete_success) - { - log.error("Couldn't delete the temporary file: " + files[i]); - } - } - } - - public static void storeTextSignatureHoldersIfApplicable(List shs, String fileNameSuffix) throws IOException - { - Iterator it = shs.iterator(); - while (it.hasNext()) - { - SignatureHolder sh = (SignatureHolder) it.next(); - if (sh instanceof TextualSignatureHolder) - { - TextualSignatureHolder tsh = (TextualSignatureHolder) sh; - if (!(tsh.getDataSource() instanceof FileBased)) - { - TextDataSource tds = (TextDataSource) tsh.getDataSource(); - if (isReasonableToStore(tds.getText().length())) - { - TextDataSource fbtds = placeTextIntoTempDir(tds.getText(), fileNameSuffix); - tsh.exchangeDataSource(fbtds); - } - } - } - } - } - - /** - * Places the text into the temp dir if reasonable. - * - *

- * Reasonable means that the text is longer than a certain threshold. - * Otherwise a short text is simply held in memory. - *

- * - * @param text - * The text to be stored. - * @param fileNameSuffix - * A file name suffix so that the temp file gets a more "readable" - * name. - * @return Returns the TextDataSource. - * @throws IOException - * F.e. - */ - public static TextDataSource placeTextIntoTempDir(String text, String fileNameSuffix) throws IOException - { - if (isReasonableToStore(text.length())) - { - String fileName = formatFileName(fileNameSuffix); - - File tmpFile = createTempFileInDir(fileName); - - FileOutputStream fos = new FileOutputStream(tmpFile); - OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); - osw.write(text); - osw.close(); - - FileBasedTextDataSourceImpl textDataSource = new FileBasedTextDataSourceImpl(tmpFile, "UTF-8"); - return textDataSource; - } - else - { - return new TextDataSourceImpl(text); - } - } - - /** - * Tells, if it is reasonable to store the text of the given length onto the - * disk. - * - * @param textLength - * The length of the text under question. - * @return Returns true if the text should be stored on the disk. - */ - public static boolean isReasonableToStore(int textLength) - { - return false; -// return textLength >= 10000; - } - - public static PdfDataSource placePdfIntoTempDir(InputStream pdfInput, String fileNameSuffix) throws IOException - { - log.debug("PERF: placing pdf into memory cache"); - - byte [] pdfData = DataSourceHelper.convertInputStreamToByteArray(pdfInput); - PdfDataSource pdfDataSource = new ByteArrayPdfDataSourceImpl(pdfData); - -// File pdfFile = placeInputIntoTempDirFile(pdfInput, fileNameSuffix); -// -// FileBasedPdfDataSourceImpl pdfDataSource = new FileBasedPdfDataSourceImpl(pdfFile, (int) pdfFile.length()); - return pdfDataSource; - } - - public static File placeInputIntoTempDirFile(InputStream input, String fileNameSuffix) throws IOException - { - String fileName = formatFileName(fileNameSuffix); - - File tmpFile = createTempFileInDir(fileName); - - FileOutputStream fos = new FileOutputStream(tmpFile); - - byte[] buffer = new byte[2048]; - int read = -1; - while ((read = input.read(buffer)) > 0) - { - fos.write(buffer, 0, read); - } - fos.close(); - input.close(); - - return tmpFile; - } - - public static File formTempFile(String fileNameSuffix) - { - String fileName = formatFileName(fileNameSuffix); - File tmpFile = getFileInTempDir(fileName); - - return tmpFile; - } - - protected static File getFileInTempDir (String fileName) - { -// File tempDir = new File(new File(SettingsReader.RESOURCES_PATH), "pdfastmp"); - File tempDir = assembleTemporaryDirectoryFile(); - - File tmpFile = new File(tempDir, fileName); - - return tmpFile; - } - - protected static String formatFileName(String fileNameSuffix) - { - // double check so that file name is always correct. - fileNameSuffix = extractFileNameSuffix(fileNameSuffix); - String fileName = "tmp" + formatIndex(runningIndex) + "_" + fileNameSuffix; - runningIndex++; - - return fileName; - } - - protected static String formatIndex(long index) - { - NumberFormat nf = new DecimalFormat("00000000"); - - return nf.format(index); - } - - protected static File createTempFileInDir(String fileName) throws IOException - { - File tmpFile = getFileInTempDir(fileName); - - tmpFile.createNewFile(); - - tmpFile.deleteOnExit(); - - return tmpFile; - } - - public static DataSink createTempDataSink(String fileNameSuffix) throws IOException - { - log.debug("PERF: placing pdf into memory cache"); - - DataSink ds = new ByteArrayDataSink(); - -// String fileName = formatFileName(fileNameSuffix); -// -// File tmpFile = createTempFileInDir(fileName); -// -// FileBasedDataSink ds = new FileBasedDataSink(tmpFile); - - return ds; - } - - public static void writeDataSinkToHttpResponse(DataSink ds, HttpServletResponse response) throws IOException - { - - response.setContentType(ds.getMimeType()); - response.setCharacterEncoding(ds.getCharacterEncoding()); - - OutputStream os = response.getOutputStream(); - - if (ds instanceof FileBasedDataSink) - { - FileBasedDataSink fbds = (FileBasedDataSink)ds; - byte[] buffer = new byte[2048]; - FileInputStream fis = new FileInputStream(fbds.getFile()); - int n = -1; - while ((n = fis.read(buffer)) > 0) - { - os.write(buffer, 0, n); - } - fis.close(); - } - else - { - ByteArrayDataSink bads = (ByteArrayDataSink)ds; - os.write(bads.getByteArray()); - os.flush(); - - } - - os.close(); -} - - /** - * Deletes the underlying file of the FileBased DataSource. - * - *

- * If the DataSource is not FileBased, nothing is done. - *

- *

- * This is usually used by the application to delete temporary files. - *

- * - * @param dataSource - */ - public static void deleteDataSourceIfFileBased(DataSource dataSource) - { - if (dataSource instanceof FileBased) - { - FileBased fb = (FileBased) dataSource; - log.debug("Deleting temp file " + fb.getFile()); - boolean deleted = fb.getFile().delete(); - log.debug("deleted = " + deleted); - } - } - - public static void deleteDataSinkIfFileBased(DataSink dataSink) - { - if (dataSink instanceof FileBased) - { - FileBased fb = (FileBased) dataSink; - log.debug("Deleting temp file " + fb.getFile()); - boolean deleted = fb.getFile().delete(); - log.debug("deleted = " + deleted); - } - } - - /** - * Given a file (maybe with path), extracts the file name suffix. - * @param file The file and maybe path. - * @return Returns the file name. - */ - public static String extractFileNameSuffix (String file) - { - if (file == null || file.trim().length() == 0) - { - return "nofilename"; - } - File f = new File(file); - return f.getName(); - } -} diff --git a/src/main/java/at/gv/egiz/pdfas/web/i18n/LanguageDecoratorMapper.java b/src/main/java/at/gv/egiz/pdfas/web/i18n/LanguageDecoratorMapper.java deleted file mode 100644 index 42e6b03..0000000 --- a/src/main/java/at/gv/egiz/pdfas/web/i18n/LanguageDecoratorMapper.java +++ /dev/null @@ -1,125 +0,0 @@ -package at.gv.egiz.pdfas.web.i18n; - -import java.io.File; -import java.util.Locale; -import java.util.Properties; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -import org.apache.log4j.Logger; - -import com.opensymphony.module.sitemesh.Config; -import com.opensymphony.module.sitemesh.Decorator; -import com.opensymphony.module.sitemesh.DecoratorMapper; -import com.opensymphony.module.sitemesh.Page; -import com.opensymphony.module.sitemesh.mapper.AbstractDecoratorMapper; -import com.opensymphony.module.sitemesh.mapper.DefaultDecorator; - -public class LanguageDecoratorMapper extends AbstractDecoratorMapper { - - - private String decoratorParameter = null; - - private static final Logger LOG = Logger.getLogger(LanguageDecoratorMapper.class); - - public void init(Config config, Properties properties, DecoratorMapper parent) throws InstantiationException { - super.init(config, properties, parent); - } - - public static Object getFirstNotNull(Object[] objects) { - if (objects == null) { - return null; - } - for (int i = 0; i < objects.length; i++) { - if (objects[i] != null) { - return objects[i]; - } - } - return null; - } - - public static Locale getLocale(HttpServletRequest request, String decoratorParameter) { - Locale locale = null; - HttpSession session = request.getSession(); - - LOG.trace("Looking for locale in session (ID=" + session.getId() + ")."); - locale = (Locale) session.getAttribute(LocaleParamFilter.LOCALE_SESSION_KEY); - if (locale == null) { - LOG.debug("Unable to find locale in session. Trying to create new locale based on Accept-Language header entry."); - String acceptLanguage = request.getHeader("Accept-Language"); - if (acceptLanguage != null) { - LOG.trace("Accept-Language header entry: " + acceptLanguage); - } else { - LOG.trace("No header entry found."); - } - if (acceptLanguage != null && acceptLanguage.length() >= 2) { - locale = new Locale(acceptLanguage.substring(0, 2)); - LOG.debug("New Locale created: " + locale); - LOG.trace("Setting language to " + locale.getDisplayLanguage() + "."); - session.setAttribute(LocaleParamFilter.LOCALE_SESSION_KEY, locale); - } - } else { - LOG.trace("Locale found: " + locale); - } - - return locale; - } - - public Decorator getDecorator(HttpServletRequest request, Page page) { - LOG.trace("SiteMesh language resource decorator mapper invoked."); - - try { - Decorator result = null; - final Decorator d = super.getDecorator(request, page); - Locale locale = getLocale(request, this.decoratorParameter); - - String path; - if (locale != null) { - path = modifyPath(d.getPage(), locale.getLanguage()); - } else { - path = d.getPage(); - } - - File decFile = new File(config.getServletContext().getRealPath(path)); - - LOG.trace("Looking for decorator \"" + path + "\"."); - if (decFile.isFile()) { - result = new DefaultDecorator(d.getName(), path, null) { - public String getInitParameter(String paramName) { - return d.getInitParameter(paramName); - } - }; - } - - if (result != null) { - LOG.trace("Decorator found (\"" + result.getName() + "\", \"" + getFirstNotNull(new Object[] { result.getURIPath(), result.getPage(), ""}) + "\")."); - return result; - } else { - LOG.trace("No decorator found. Delegating to super class."); - result = super.getDecorator(request, page); - if (result != null) { - LOG.trace("Super class returned decorator (\"" + result.getName() + "\", \"" + getFirstNotNull(new Object[] { result.getURIPath(), result.getPage(), ""}) + "\")."); - } else { - LOG.trace("Super class did not return a decorator."); - } - return result; - } - } catch (NullPointerException e) { - return super.getDecorator(request, page); - } - } - - private static String modifyPath(String path, String ext) { - if (ext == null || ext.length() == 0) { - return path; - } - int dot = path.lastIndexOf('.'); - if (dot > -1) { - return path.substring(0, dot) + '-' + ext + path.substring(dot); - } else { - return path + '-' + ext; - } - } - -} diff --git a/src/main/java/at/gv/egiz/pdfas/web/i18n/LocaleParamFilter.java b/src/main/java/at/gv/egiz/pdfas/web/i18n/LocaleParamFilter.java deleted file mode 100644 index 598b23b..0000000 --- a/src/main/java/at/gv/egiz/pdfas/web/i18n/LocaleParamFilter.java +++ /dev/null @@ -1,96 +0,0 @@ -package at.gv.egiz.pdfas.web.i18n; - -import java.io.IOException; -import java.util.Locale; -import java.util.StringTokenizer; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -import org.apache.commons.lang.LocaleUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.log4j.Logger; - -public class LocaleParamFilter implements Filter { - - private static final Logger LOG = Logger.getLogger(LocaleParamFilter.class); - public static final String LOCALE_SESSION_KEY = "at.gv.egiz.pdfas.web.i18n:currentLocale"; - public static final String LOCALE_PARAM_KEY = "locale"; - - public void destroy() { - } - - public static String normalizeLocaleString(String localeString) { - if (localeString == null) { - return null; - } - int jsessionIdIndex = localeString.toLowerCase().indexOf(";jsessionid"); - if (jsessionIdIndex != -1) { - localeString = localeString.substring(0, jsessionIdIndex); - } - StringTokenizer tokenizer = new StringTokenizer(localeString, "_", false); - StringBuffer buffer = new StringBuffer(); - int index = 0; - while (tokenizer.hasMoreTokens()) { - String token = tokenizer.nextToken(); - switch (++index) { - case 1: - buffer.append(token.toLowerCase()); - break; - case 2: - buffer.append(token.toUpperCase()); - break; - default: - buffer.append(token); - break; - } - if (tokenizer.hasMoreTokens()) { - buffer.append("_"); - } - } - return buffer.toString(); - } - - public static Locale getLocale(HttpServletRequest request) { - Locale locale = null; - HttpSession session = request.getSession(); - - LOG.trace("Looking for locale parameter \"" + LOCALE_PARAM_KEY + "\"."); - String language = request.getParameter(LOCALE_PARAM_KEY); - if (!StringUtils.isEmpty(language)) { - LOG.debug("Locale parameter \"" + language + "\" found."); - String code = normalizeLocaleString(language.trim()); - LOG.debug("Normalizing locale -> " + code); - try { - locale = LocaleUtils.toLocale(code); - LOG.info("Setting locale flag in session (ID=" + session.getId() + ") to \"" + locale.toString() + "\"."); - session.setAttribute(LOCALE_SESSION_KEY, locale); - } catch (IllegalArgumentException e) { - LOG.error("Locale \"" + code + "\" is not valid. Flag will not be set."); - } - } else { - LOG.trace("No locale parameter found."); - } - - return locale; - } - - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { - HttpServletRequest request = (HttpServletRequest) servletRequest; - - LOG.trace("LocaleParamFilter invoked."); - getLocale(request); - - filterChain.doFilter(servletRequest, servletResponse); - } - - public void init(FilterConfig filterConfig) throws ServletException { - } - -} -- cgit v1.2.3