aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/at/gv/egiz/pdfas/utils
diff options
context:
space:
mode:
authorpdanner <pdanner@7b5415b0-85f9-ee4d-85bd-d5d0c3b42d1c>2010-12-06 16:59:57 +0000
committerpdanner <pdanner@7b5415b0-85f9-ee4d-85bd-d5d0c3b42d1c>2010-12-06 16:59:57 +0000
commit8662870179eed5ca6e2b7b10fd1912f922fce67b (patch)
treef6184f2006fd2ccc1995e54d08770eab0c5885c8 /src/main/java/at/gv/egiz/pdfas/utils
parent12e08e6bc47592045f54e3b46274f0231e88d369 (diff)
downloadpdf-as-3-8662870179eed5ca6e2b7b10fd1912f922fce67b.tar.gz
pdf-as-3-8662870179eed5ca6e2b7b10fd1912f922fce67b.tar.bz2
pdf-as-3-8662870179eed5ca6e2b7b10fd1912f922fce67b.zip
Moved to pdf-as-web project
git-svn-id: https://joinup.ec.europa.eu/svn/pdf-as/trunk@678 7b5415b0-85f9-ee4d-85bd-d5d0c3b42d1c
Diffstat (limited to 'src/main/java/at/gv/egiz/pdfas/utils')
-rw-r--r--src/main/java/at/gv/egiz/pdfas/utils/TempDirHelper.java357
-rw-r--r--src/main/java/at/gv/egiz/pdfas/utils/WebUtils.java100
2 files changed, 357 insertions, 100 deletions
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.
+ *
+ * <p>
+ * If the directory doesn't exist, it is created.
+ * </p>
+ *
+ * @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.
+ *
+ * <p>
+ * This should be used to clear temporary files when the application shuts
+ * down.
+ * </p>
+ */
+ 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.
+ *
+ * <p>
+ * Reasonable means that the text is longer than a certain threshold.
+ * Otherwise a short text is simply held in memory.
+ * </p>
+ *
+ * @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.
+ *
+ * <p>
+ * If the DataSource is not FileBased, nothing is done.
+ * </p>
+ * <p>
+ * This is usually used by the application to delete temporary files.
+ * </p>
+ *
+ * @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;
- }
-
-}