From 3d982813b34f6f230baf4a467cdc37ec92a77595 Mon Sep 17 00:00:00 2001
From: netconomy
+ * This scans the first 1000 bytes of the PDF for the pdf Header.
+ *
- * This algorithm tries to position the table between the end of the text and - * the footer line. - *
- * - * @deprecated - * @param pdf - * The PDF document. - * @param pdf_table - * The PDFPTable to be placed. - * @return Returns the position where the PDFPTable should be placed. - * @throws PDFDocumentException - * F.e. - */ - public static PositioningInstruction adjustTableAndCalculatePositionRegardingFooter( - final byte[] pdf, PdfPTable pdf_table, float footer_line) throws PDFDocumentException - { - boolean make_new_page = false; - - PdfReader reader = readInPdfDocument(pdf); - - int page = reader.getNumberOfPages(); - Rectangle psize = reader.getPageSizeWithRotation(page); - float page_width = psize.width(); - float page_height = psize.height(); - - final float width = page_width - SIGNATURE_BORDER; - pdf_table.setTotalWidth(width); - pdf_table.setLockedWidth(true); - - final float pos_x = SIGNATURE_BORDER / 2; - - final float table_height = pdf_table.getTotalHeight(); - - final float page_length = PDFUtilities.calculateLastPageLength(pdf, page_height - footer_line); - float pos_y = page_height - page_length - SIGNATURE_MARGIN; - - if (pos_y - footer_line <= table_height) - { - make_new_page = true; - page++; - - pos_y = page_height - SIGNATURE_BORDER / 2; - } - - return new PositioningInstruction(make_new_page, page, pos_x, pos_y); - } +// /** +// * Sets the width of the table according to the layout of the document and +// * calculates the y position where the PDFPTable should be placed. +// * +// * @deprecated +// * @param pdf +// * The PDF document. +// * @param pdf_table +// * The PDFPTable to be placed. +// * @return Returns the position where the PDFPTable should be placed. +// * @throws PDFDocumentException +// * F.e. +// */ +// public static PositioningInstruction adjustTableAndCalculatePosition(final byte[] pdf, PdfPTable pdf_table) throws PDFDocumentException +// { +// boolean make_new_page = false; +// +// PdfReader reader = readInPdfDocument(pdf); +// +// int page = reader.getNumberOfPages(); +// Rectangle psize = reader.getPageSizeWithRotation(page); +// float page_width = psize.width(); +// float page_height = psize.height(); +// +// final float width = page_width - SIGNATURE_BORDER; +// pdf_table.setTotalWidth(width); +// pdf_table.setLockedWidth(true); +// +// final float pos_x = SIGNATURE_BORDER / 2; +// +// final float table_height = pdf_table.getTotalHeight(); +// final float page_length = PDFUtilities.calculateLastPageLength(pdf, page_height); +// float pos_y = page_height - page_length - SIGNATURE_MARGIN; +// +// if (pos_y <= table_height) +// { +// make_new_page = true; +// page++; +// +// pos_y = page_height - SIGNATURE_BORDER / 2; +// } +// +// return new PositioningInstruction(make_new_page, page, pos_x, pos_y); +// } + +// /** +// * Sets the width of the table according to the layout of the document and +// * calculates the y position where the PDFPTable should be placed. +// * +// *+// * This algorithm tries to position the table between the end of the text and +// * the footer line. +// *
+// * +// * @deprecated +// * @param pdf +// * The PDF document. +// * @param pdf_table +// * The PDFPTable to be placed. +// * @return Returns the position where the PDFPTable should be placed. +// * @throws PDFDocumentException +// * F.e. +// */ +// public static PositioningInstruction adjustTableAndCalculatePositionRegardingFooter(final byte[] pdf, PdfPTable pdf_table, float footer_line) throws PDFDocumentException +// { +// boolean make_new_page = false; +// +// PdfReader reader = readInPdfDocument(pdf); +// +// int page = reader.getNumberOfPages(); +// Rectangle psize = reader.getPageSizeWithRotation(page); +// float page_width = psize.width(); +// float page_height = psize.height(); +// +// final float width = page_width - SIGNATURE_BORDER; +// pdf_table.setTotalWidth(width); +// pdf_table.setLockedWidth(true); +// +// final float pos_x = SIGNATURE_BORDER / 2; +// +// final float table_height = pdf_table.getTotalHeight(); +// +// final float page_length = PDFUtilities.calculateLastPageLength(pdf, page_height - footer_line); +// float pos_y = page_height - page_length - SIGNATURE_MARGIN; +// +// if (pos_y - footer_line <= table_height) +// { +// make_new_page = true; +// page++; +// +// pos_y = page_height - SIGNATURE_BORDER / 2; +// } +// +// return new PositioningInstruction(make_new_page, page, pos_x, pos_y); +// } /** * Creates an iText Reader that parses the document. @@ -1386,11 +1376,14 @@ public abstract class PdfAS * @throws PDFDocumentException * F.e. */ - public static PdfReader readInPdfDocument(final byte[] pdf) throws PDFDocumentException + public static PdfReader readInPdfDocument(final PdfDataSource pdfDataSource) throws PDFDocumentException { try { - return new PdfReader(pdf); + InputStream is = pdfDataSource.createInputStream(); + PdfReader reader = new PdfReader(is); + is.close(); + return reader; } catch (IOException e) { diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/PdfASID.java b/src/main/java/at/knowcenter/wag/egov/egiz/PdfASID.java index 0193368..0409bb7 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/PdfASID.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/PdfASID.java @@ -161,6 +161,36 @@ public class PdfASID implements Serializable { return this.version; } + + + + /** + * @see java.lang.Object#equals(java.lang.Object) + */ + //@override + public boolean equals(Object obj) + { + if (obj == null) + { + return false; + } + if (!(obj instanceof PdfASID)) + { + return false; + } + + PdfASID other = (PdfASID) obj; + + return this.toString().equals(other.toString()); + } + + /** + * @see java.lang.Object#hashCode() + */ + public int hashCode() + { + return toString().hashCode(); + } /** * @see java.lang.Object#toString() diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/cfg/ConfigLogger.java b/src/main/java/at/knowcenter/wag/egov/egiz/cfg/ConfigLogger.java index 3b32c22..e0a8a3d 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/cfg/ConfigLogger.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/cfg/ConfigLogger.java @@ -27,6 +27,8 @@ import org.apache.log4j.Logger; /** * This logger class is the main logger class for the pdf-as project. It holds static logger * instances with could be configured the level with one method. + * + * @deprecated use commons.logging instead */ public class ConfigLogger { diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/cfg/SettingsReader.java b/src/main/java/at/knowcenter/wag/egov/egiz/cfg/SettingsReader.java index 96286ad..a158729 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/cfg/SettingsReader.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/cfg/SettingsReader.java @@ -18,17 +18,17 @@ package at.knowcenter.wag.egov.egiz.cfg; -import java.io.FileInputStream; import java.io.File; +import java.io.FileInputStream; import java.io.IOException; import java.io.Serializable; -import java.util.Vector; import java.util.ArrayList; import java.util.Enumeration; import java.util.Properties; +import java.util.Vector; -import org.apache.log4j.Level; -import org.apache.log4j.Logger; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import at.knowcenter.wag.egov.egiz.exceptions.SettingNotFoundException; import at.knowcenter.wag.egov.egiz.exceptions.SettingsException; @@ -120,7 +120,7 @@ import at.knowcenter.wag.egov.egiz.exceptions.SettingsException; * * @author wlackner */ -public class SettingsReader implements Settings, Serializable +public class SettingsReader implements Serializable { /** @@ -252,9 +252,9 @@ public class SettingsReader implements Settings, Serializable private PropertyTree pTree_ = new PropertyTree(); /** - * The logger definition. + * The log. */ - private static final Logger logger_ = ConfigLogger.getLogger(SettingsReader.class); + private static final Log logger_ = LogFactory.getLog(SettingsReader.class); /** * Make this constructor private. Use the method @@ -321,7 +321,7 @@ public class SettingsReader implements Settings, Serializable } catch (IOException e) { - throw new SettingsException(e); + throw new SettingsException("Couldn't load settings from file " + settingsFile, e); } } @@ -385,11 +385,11 @@ public class SettingsReader implements Settings, Serializable if (result == null) { String log_message = "Configuration key not found: '" + key + "'! Check '" + settingsFile_ + "' file."; - if (logger_.isEnabledFor(Level.WARN)) + if (logger_.isWarnEnabled()) { logger_.warn(log_message); } - SettingNotFoundException snf = new SettingNotFoundException(100, log_message); + SettingNotFoundException snf = new SettingNotFoundException(log_message); throw snf; } // if (logger_.isDebugEnabled()) @@ -524,14 +524,14 @@ public class SettingsReader implements Settings, Serializable } catch (NumberFormatException e) { - if (logger_.isEnabledFor(Level.WARN)) + if (logger_.isWarnEnabled()) { logger_.warn("Can not convert " + value + " to int."); } } catch (SettingNotFoundException e) { - if (logger_.isEnabledFor(Level.WARN)) + if (logger_.isWarnEnabled()) { logger_.warn("Setting " + key + " not found, return default value:" + defaultValue); } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/commandline/Main.java b/src/main/java/at/knowcenter/wag/egov/egiz/commandline/Main.java index 65c30b9..ee12fff 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/commandline/Main.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/commandline/Main.java @@ -19,34 +19,44 @@ package at.knowcenter.wag.egov.egiz.commandline; import java.io.File; import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; +import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import org.apache.log4j.Logger; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.apache.log4j.PropertyConfigurator; +import at.gv.egiz.pdfas.commandline.CommandlineConnectorChooser; +import at.gv.egiz.pdfas.exceptions.ErrorCode; +import at.gv.egiz.pdfas.exceptions.ErrorCodeHelper; +import at.gv.egiz.pdfas.exceptions.external.ExternalErrorException; +import at.gv.egiz.pdfas.framework.config.SettingsHelper; +import at.gv.egiz.pdfas.framework.input.DataSource; +import at.gv.egiz.pdfas.framework.input.ExtractionStage; +import at.gv.egiz.pdfas.framework.input.PdfDataSource; +import at.gv.egiz.pdfas.framework.output.DataSink; +import at.gv.egiz.pdfas.framework.vfilter.VerificationFilterParameters; +import at.gv.egiz.pdfas.impl.input.FileBasedPdfDataSourceImpl; +import at.gv.egiz.pdfas.impl.input.TextDataSourceImpl; +import at.gv.egiz.pdfas.impl.output.FileBasedDataSink; +import at.gv.egiz.pdfas.impl.vfilter.VerificationFilterParametersImpl; import at.knowcenter.wag.egov.egiz.PdfAS; import at.knowcenter.wag.egov.egiz.PdfASID; -import at.knowcenter.wag.egov.egiz.cfg.ConfigLogger; import at.knowcenter.wag.egov.egiz.cfg.SettingsReader; import at.knowcenter.wag.egov.egiz.exceptions.ConnectorFactoryException; -import at.knowcenter.wag.egov.egiz.exceptions.ErrorCodeException; import at.knowcenter.wag.egov.egiz.exceptions.PDFDocumentException; import at.knowcenter.wag.egov.egiz.exceptions.PlaceholderException; import at.knowcenter.wag.egov.egiz.exceptions.PresentableException; import at.knowcenter.wag.egov.egiz.exceptions.SettingNotFoundException; import at.knowcenter.wag.egov.egiz.exceptions.SignatureException; import at.knowcenter.wag.egov.egiz.exceptions.SignatureTypesException; -import at.knowcenter.wag.egov.egiz.framework.SignResult; import at.knowcenter.wag.egov.egiz.framework.SignatorFactory; -import at.knowcenter.wag.egov.egiz.framework.VerificationFilter; import at.knowcenter.wag.egov.egiz.framework.signators.BinarySignator_1_0_0; -import at.knowcenter.wag.egov.egiz.framework.signators.DetachedSignator_1_0_0; import at.knowcenter.wag.egov.egiz.framework.signators.TextualSignator_1_0_0; import at.knowcenter.wag.egov.egiz.pdf.SignatureHolder; import at.knowcenter.wag.egov.egiz.pdf.TablePos; @@ -132,12 +142,12 @@ public abstract class Main /** * The application mode verify */ - public static final String VALUE_SIGNATURE_MODE_DETACHED_TEXt = "detachedtextual"; + public static final String VALUE_SIGNATURE_MODE_DETACHED_TEXT = "detachedtextual"; /** - * The logger definition. + * The log. */ - private static final Logger logger_ = ConfigLogger.getLogger(Main.class); + private static final Log logger_ = LogFactory.getLog(Main.class); /** * Main program entry point. @@ -152,9 +162,7 @@ public abstract class Main SettingsReader.initializeForCommandLine(); PropertyConfigurator.configure(SettingsReader.CONFIG_PATH + "log4j.properties"); - - try - { + // printUsage(System.out); String mode = null; @@ -170,7 +178,10 @@ public abstract class Main String input = null; String output = null; - + + try + { + // for (int i = 0; i < args.length; i++) // { // logger_.debug("arg[" + i + "] = " + args[i]); @@ -378,21 +389,31 @@ public abstract class Main return; } + if (mode.equals(VALUE_MODE_SIGN) && output == null) + { + output = generateOutputFileNameFromInput(input, signature_mode); + } + else + { + output = null; + } + carryOutCommand(mode, signature_mode, connector, signature_type, user_name, user_password, verify_which, input, output, pos_string); } catch (PresentableException e) { - if (e instanceof ErrorCodeException) - { - ErrorCodeException ece = (ErrorCodeException) e; - printErrorCodeException(ece); - } - else + printPresentableException(e); + + if (output != null) { - System.err.println("PresentableException:"); - System.err.println(e.getMessage()); - logger_.debug(e.toString()); + logger_.debug("Deleting output file on error."); + File oFile = new File(output); + boolean deleted = oFile.delete(); + if (!deleted) + { + logger_.error("Couldn't delete output file " + output); + } } } finally @@ -401,186 +422,226 @@ public abstract class Main } } - /** - * Carries out the actual command given via the commandline parameters. - * - *- * This is simply the procedure that is executed after the commandline - * parameters have been parsed successfully. - *
- * - * @param mode - * The operation mode (e.g. "sign", "verify"). - * @param signature_mode - * The signature mode (e.g. "binary", "textual"). - * @param connector - * The connector (e.g. "bku", "a1"). - * @param signature_type - * The signature type/profile. For signing only. - * @param user_name - * The user name. For signing only. - * @param user_password - * The user password. For signing only. - * @param verify_which - * The number of the signature to be verified. For verifying only. - * @param input - * The input file name. - * @param output - * The output file name. - * @throws PresentableException - */ - protected static void carryOutCommand(final String mode, - final String signature_mode, final String connector, - final String signature_type, final String user_name, - final String user_password, final int verify_which, final String input, - String output, final String pos_string) throws PresentableException + protected static void carryOutCommand(final String mode, final String signature_mode, final String connector, final String signature_type, final String user_name, final String user_password, + final int verify_which, final String input, String output, final String pos_string) throws PresentableException + { + // File file = new File(input); + // + // byte[] input_bytes = null; + // try + // { + // FileInputStream fis = new FileInputStream(file); + // input_bytes = new byte[(int) file.length()]; + // fis.read(input_bytes); + // fis.close(); + // } + // catch (IOException e) + // { + // throw new PDFDocumentException(201); + // } + + PrintWriter messageOutput = new PrintWriter(System.out); + + if (mode.equals(VALUE_MODE_SIGN)) + { + carryOutSign(input, connector, signature_mode, signature_type, pos_string, user_name, user_password, output, messageOutput); + } + else + { + carryOutVerify(input, connector, verify_which, messageOutput); + } + messageOutput.close(); + } + + public static void carryOutSign(String input, String connector, String signature_mode, String signature_type, String pos_string, String user_name, String user_password, String output, + PrintWriter messageOutput) throws PresentableException { - File file = new File(input); + messageOutput.println("Signing..."); - byte[] input_bytes = null; + PdfDataSource pdfDataSource; try { - FileInputStream fis = new FileInputStream(file); - input_bytes = new byte[(int) file.length()]; - fis.read(input_bytes); - fis.close(); + File file = new File(input); + pdfDataSource = new FileBasedPdfDataSourceImpl(file, (int)file.length()); } catch (IOException e) { - throw new PDFDocumentException(201); + throw new PDFDocumentException(201, e); } - if (mode.equals(VALUE_MODE_SIGN)) + FileBasedDataSink dataSink = null; + try { - System.out.println("Signing..."); + File outputFile = new File(output); + dataSink = new FileBasedDataSink(outputFile); + } + catch (IOException e) + { + throw new PDFDocumentException(ErrorCode.CANNOT_WRITE_PDF, e); + } - PdfAS.applyStrictMode(input_bytes); + processSign(pdfDataSource, connector, signature_mode, signature_type, pos_string, dataSink); - TablePos pos = null; - if (pos_string != null) + messageOutput.println("Signing was successful."); + } + + public static void carryOutVerify(String input, String connector, int verify_which, PrintWriter messageOutput) throws PresentableException + { + messageOutput.println("Verifying..."); + + DataSource dataSource = null; + try + { + File file = new File(input); + String extension = VerifyServlet.extractExtension(input); + if (extension != null && extension.equals("txt")) { try { - pos = PdfAS.parsePositionFromPosString(pos_string); + FileInputStream fis = new FileInputStream(file); + byte[] input_bytes = new byte[(int) file.length()]; + fis.read(input_bytes); + fis.close(); + + String text = new String(input_bytes, "UTF-8"); + dataSource = new TextDataSourceImpl(text); } - catch (PDFDocumentException e) + catch (UnsupportedEncodingException e) { - printUnrecognizedValue(PARAMETER_POS, pos_string); - return; - + throw new RuntimeException("Very strange: UTF-8 character encoding not supported.", e); } } - - PdfASID algorithm = translateSignatureModeToPdfASID(signature_mode); - - // TODO MOA detached signing is not allowed at the commandline - logger_.debug("Suggested sign algorithm = " + algorithm); - if (connector.equals("moa")) + else { - // TODO: possible new implementation of moa where is commandline call supported - // it should be checked in config file is it allowed to use MOA detached from command line. - String msg = "Hinweis: Der MOA Detached Connector ist für die Kommandozeile nicht geeignet. Die Signatur wird daher im alten Base64 enveloping Format ausgeführt."; - System.out.println(msg); - logger_.warn(msg); - - if (signature_mode.equals(VALUE_SIGNATURE_MODE_BINARY)) - { - algorithm = BinarySignator_1_0_0.MY_ID; - } - if (signature_mode.equals(VALUE_SIGNATURE_MODE_TEXTUAL)) - { - algorithm = TextualSignator_1_0_0.MY_ID; - } + dataSource = new FileBasedPdfDataSourceImpl(file, (int)file.length()); } - logger_.debug("Finally used sign algorithm = " + algorithm); + } + catch (IOException e) + { + throw new PDFDocumentException(ErrorCode.DOCUMENT_CANNOT_BE_READ, e); + } + + List results = processVerify(dataSource, connector, verify_which); - SignResult sign_result = PdfAS.sign(algorithm, input_bytes, signature_type, connector, user_name, user_password, pos); + messageOutput.println("Verification results:"); + formatVerifyResults(results, messageOutput); + } + + public static void processSign(PdfDataSource pdfDataSource, String connector, String signature_mode, String signature_type, String pos_string, DataSink dataSink) throws PresentableException + { + PdfAS.applyStrictMode(pdfDataSource); + TablePos pos = null; + if (pos_string != null) + { try { - if (output == null) - { - output = generateOutputFileNameFromInput(input, sign_result); - } - - FileOutputStream fos = new FileOutputStream(output); - fos.write(sign_result.getData()); - fos.close(); + pos = PdfAS.parsePositionFromPosString(pos_string); } - catch (IOException e) + catch (PDFDocumentException e) { - throw new PDFDocumentException(205); - } + printUnrecognizedValue(PARAMETER_POS, pos_string); + return; - System.out.println("Signing was successful."); + } } - else - { - System.out.println("Verifying..."); - - VerificationFilter vf = new VerificationFilter(); - List signature_holders = null; + PdfASID signatorId = translateSignatureModeToPdfASID(signature_mode); - String extension = VerifyServlet.extractExtension(input); - if (extension != null && extension.equals("txt")) + // TODO MOA detached signing is not allowed at the commandline + logger_.debug("Suggested sign algorithm = " + signatorId); + if (connector.equals("moa")) + { + // TODO: possible new implementation of moa where is commandline call + // supported + // it should be checked in config file is it allowed to use MOA detached + // from command line. + String msg = "Hinweis: Der MOA Detached Connector ist für die Kommandozeile nicht geeignet. Die Signatur wird daher im alten Base64 enveloping Format ausgeführt."; + System.out.println(msg); + logger_.warn(msg); + + if (signature_mode.equals(VALUE_SIGNATURE_MODE_BINARY)) { - try - { - String text = new String(input_bytes, "UTF-8"); - signature_holders = vf.extractSignaturesFromPlainText(text); - } - catch (UnsupportedEncodingException e) - { - throw new PresentableException(e); - } + signatorId = BinarySignator_1_0_0.MY_ID; } - else + if (signature_mode.equals(VALUE_SIGNATURE_MODE_TEXTUAL)) { - signature_holders = vf.extractSignaturesFromPdf(input_bytes); + signatorId = TextualSignator_1_0_0.MY_ID; } + } + logger_.debug("Finally used sign algorithm = " + signatorId); + + String connectorId = CommandlineConnectorChooser.chooseCommandlineConnectorForSign(connector); - if (signature_holders.isEmpty()) - { - throw new PDFDocumentException(206); - } + PdfAS.signCommandline(pdfDataSource, dataSink, signatorId, connectorId, signature_type, pos); - List holders_to_verify = signature_holders; +// PdfAS.sign(algorithm, pdfDataSource, dataSink, signature_type, connector, pos); + } + + public static List processVerify(DataSource dataSource, String connector, int verify_which) throws PresentableException + { + VerificationFilterParameters parameters = SettingsHelper.readVerificationFilterParametersFromSettings(); + ExtractionStage es = new ExtractionStage(); - // verify_which - optional argument in command line/web - if (verify_which >= 0) - { - if (verify_which >= signature_holders.size()) - { - throw new SignatureException(312, "The selected signature to be verified doesn't exist."); - } + List signature_holders = es.extractSignatureHolders(dataSource, parameters); - SignatureHolder holder = (SignatureHolder) signature_holders.get(verify_which); - holders_to_verify = new ArrayList(); - holders_to_verify.add(holder); + if (signature_holders.isEmpty()) + { + throw new PDFDocumentException(ErrorCode.DOCUMENT_NOT_SIGNED, "Document is unsigned."); + } + + List holders_to_verify = signature_holders; + + // verify_which - optional argument in command line/web + if (verify_which >= 0) + { + if (verify_which >= signature_holders.size()) + { + throw new SignatureException(312, "The selected signature to be verified doesn't exist."); } - List results = PdfAS.verifySignatureHolders(holders_to_verify, connector); - System.out.println("Verification results:"); - formatVerifyResults(results, System.out); + SignatureHolder holder = (SignatureHolder) signature_holders.get(verify_which); + holders_to_verify = new ArrayList(); + holders_to_verify.add(holder); } + + List results = PdfAS.verifySignatureHolders(holders_to_verify, connector); + + return results; } - /** - * Generates a suitable output file name for the output regarding the type of - * the sign_result. - * - * @param input - * The input file name. - * @param sign_result - * The sign result. - * @return Returns the output file name. - */ - protected static String generateOutputFileNameFromInput(String input, - SignResult sign_result) + // TODO old method - remove + // /** + // * Generates a suitable output file name for the output regarding the type + // of + // * the sign_result. + // * + // * @param input + // * The input file name. + // * @param sign_result + // * The sign result. + // * @return Returns the output file name. + // */ + // protected static String generateOutputFileNameFromInput(String input, + // SignResult sign_result) + // { + // String output = input + "_out"; + // if (sign_result.getMimeType().equals(DetachedSignator_1_0_0.MIME_TYPE)) + // { + // output += ".xml"; + // } + // else + // { + // output += ".pdf"; + // } + // + // return output; + // } + + protected static String generateOutputFileNameFromInput(String input, String sig_mode) { String output = input + "_out"; - if (sign_result.getMimeType().equals(DetachedSignator_1_0_0.MIME_TYPE)) + if (sig_mode.equals("detached")) { output += ".xml"; } @@ -628,8 +689,7 @@ public abstract class Main * @throws PresentableException * Forwarded exception. */ - protected static void printUnrecognizedValue(final String parameter, - final String value) throws PresentableException + protected static void printUnrecognizedValue(final String parameter, final String value) throws PresentableException { System.err.println("The parameter " + parameter + " doesn't recognize the provided value '" + value + "'."); printUsage(System.out); @@ -643,8 +703,7 @@ public abstract class Main * @throws PresentableException * Forwarded exception. */ - protected static void printUnrecognizedAdditionalCommandlineArgument( - final String argument) throws PresentableException + protected static void printUnrecognizedAdditionalCommandlineArgument(final String argument) throws PresentableException { System.err.println("Unrecognized additional commandline argument '" + argument + "'."); printUsage(System.out); @@ -660,8 +719,7 @@ public abstract class Main * @throws PresentableException * Forwarded exception. */ - protected static void printMissingParameter(final String missing_term, - final String parameter) throws PresentableException + protected static void printMissingParameter(final String missing_term, final String parameter) throws PresentableException { printMissing(missing_term + " ('" + parameter + "' parameter)"); } @@ -686,23 +744,32 @@ public abstract class Main * @param ece * The ErrorCodeException to be printed. */ - protected static void printErrorCodeException(final ErrorCodeException ece) + protected static void printPresentableException(final PresentableException e) { - if (ece instanceof PlaceholderException) + if (e.getErrorCode() == ErrorCode.PLACEHOLDER_EXCEPTION) { - PlaceholderException phe = (PlaceholderException) ece; + PlaceholderException phe = null; + if (e instanceof PlaceholderException) + { + phe = (PlaceholderException) e; + } + else + { + phe = (PlaceholderException) e.getCause(); + } System.err.println("Der Platzhalter des Feldes " + phe.getField() + " ist um " + phe.getMissing() + " Bytes zu kurz. "); } - System.err.println("Fehler " + ece.getErrorCode() + ": " + ece.getErrorCodeMessage()); + System.err.println("Fehler " + e.getErrorCode() + ": " + ErrorCodeHelper.getMessageForErrorCode(e.getErrorCode())); - if (ece.hasExternalErrorMessage()) + if (e instanceof ExternalErrorException) { - System.err.println("Externer Fehlergrund: " + ece.getExternalErrorCode() + ": " + ece.getExternalErrorMessage()); + ExternalErrorException eee = (ExternalErrorException) e; + System.err.println("Externer Fehlergrund: " + eee.getExternalErrorCode() + ": " + eee.getExternalErrorMessage()); } - logger_.debug(ece.toString()); + logger_.debug(e); } /** @@ -753,8 +820,8 @@ public abstract class Main writer.println(" " + PARAMETER_SIGNATURE_MODE + " <" + VALUE_SIGNATURE_MODE_BINARY + "|" + VALUE_SIGNATURE_MODE_TEXTUAL + ">"); writer.println(" " + VALUE_SIGNATURE_MODE_BINARY + " ... signs the complete binary document"); writer.println(" " + VALUE_SIGNATURE_MODE_TEXTUAL + " ... signs only the textual portion of the document"); - writer.println(" " + VALUE_SIGNATURE_MODE_DETACHED + " ... signs the document using the binary mode and returns the xml signature of it."); - writer.println(" " + VALUE_SIGNATURE_MODE_DETACHED_TEXt + " ... signs the document using the textual mode and returns the xml signature of it."); + //writer.println(" " + VALUE_SIGNATURE_MODE_DETACHED + " ... signs the document using the binary mode and returns the xml signature of it."); + writer.println(" " + VALUE_SIGNATURE_MODE_DETACHED_TEXT + " ... signs the document using the textual mode and returns the xml signature of it."); writer.print(" " + PARAMETER_SIGNATURE_TYPE + " <"); SignatureTypes sig_types = SignatureTypes.getInstance(); @@ -831,7 +898,8 @@ public abstract class Main */ protected static boolean checkSignatureMode(String signature_mode) { - return signature_mode.equals(VALUE_SIGNATURE_MODE_BINARY) || signature_mode.equals(VALUE_SIGNATURE_MODE_TEXTUAL) || signature_mode.equals(VALUE_SIGNATURE_MODE_DETACHED) || signature_mode.equals(VALUE_SIGNATURE_MODE_DETACHED_TEXt); + return signature_mode.equals(VALUE_SIGNATURE_MODE_BINARY) || signature_mode.equals(VALUE_SIGNATURE_MODE_TEXTUAL) || signature_mode.equals(VALUE_SIGNATURE_MODE_DETACHED) + || signature_mode.equals(VALUE_SIGNATURE_MODE_DETACHED_TEXT); } /** @@ -892,7 +960,7 @@ public abstract class Main { return SignatorFactory.MOST_RECENT_DETACHED_SIGNATOR_ID; } - if (signature_mode.equals(VALUE_SIGNATURE_MODE_DETACHED_TEXt)) + if (signature_mode.equals(VALUE_SIGNATURE_MODE_DETACHED_TEXT)) { return SignatorFactory.MOST_RECENT_DETACHEDTEXT_SIGNATOR_ID; } @@ -909,7 +977,7 @@ public abstract class Main * @throws SettingNotFoundException * Forwarded exception. */ - protected static void formatVerifyResults(List results, PrintStream writer) throws SettingNotFoundException + protected static void formatVerifyResults(List results, PrintWriter writer) throws SettingNotFoundException { Iterator it = results.iterator(); while (it.hasNext()) @@ -934,8 +1002,7 @@ public abstract class Main * @throws SettingNotFoundException * Forwarded exception. */ - public static void formatSignatureResponse(SignatureResponse result, - PrintStream writer) throws SettingNotFoundException + public static void formatSignatureResponse(SignatureResponse result, PrintWriter writer) throws SettingNotFoundException { writer.println(" Zertifikat:"); diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/ConnectorException.java b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/ConnectorException.java index e660bb7..34c27b2 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/ConnectorException.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/ConnectorException.java @@ -9,7 +9,7 @@ package at.knowcenter.wag.egov.egiz.exceptions; * * @author wprinz */ -public class ConnectorException extends SignatureException +public class ConnectorException extends PresentableException { /** @@ -45,12 +45,8 @@ public class ConnectorException extends SignatureException super(error_code, cause); } - /** - * @param error_code - */ - public ConnectorException(int error_code) + public ConnectorException(PresentableException cause) { - super(error_code); + super(cause.getErrorCode(), cause); } - } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/ConnectorFactoryException.java b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/ConnectorFactoryException.java index 733ccb6..924400f 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/ConnectorFactoryException.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/ConnectorFactoryException.java @@ -17,6 +17,8 @@ */ package at.knowcenter.wag.egov.egiz.exceptions; +import at.gv.egiz.pdfas.exceptions.ErrorCode; + /** * This exception is thrown when the connector factory encounters an error * during providing a connector. @@ -41,24 +43,24 @@ public class ConnectorFactoryException extends PresentableException */ public ConnectorFactoryException(String message) { - super(message); + super(ErrorCode.SETTINGS_EXCEPTION, message); } - /** - * @param message - * @param cause - */ - public ConnectorFactoryException(String message, Throwable cause) - { - super(message, cause); - } +// /** +// * @param message +// * @param cause +// */ +// public ConnectorFactoryException(String message, Throwable cause) +// { +// super(message, cause); +// } /** * @param cause */ public ConnectorFactoryException(Throwable cause) { - super(cause); + super(ErrorCode.SETTINGS_EXCEPTION, cause); } } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/ErrorCodeException.java b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/ErrorCodeException.java index 42fe597..ec21fb5 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/ErrorCodeException.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/ErrorCodeException.java @@ -44,6 +44,8 @@ import at.knowcenter.wag.egov.egiz.cfg.SettingsReader; * @author wlackner * @author wprinz (enforced error code) * + * @deprecated + * * @see at.knowcenter.wag.egov.egiz.cfg.SettingsReader */ public class ErrorCodeException extends PresentableException @@ -96,7 +98,7 @@ public class ErrorCodeException extends PresentableException */ public ErrorCodeException(final int error_code) { - super("error code " + error_code); + super(error_code, "just an error code"); this.error_code_ = error_code; loadSettings(); } @@ -112,7 +114,7 @@ public class ErrorCodeException extends PresentableException */ public ErrorCodeException(final int error_code, String message) { - super("error code " + error_code + ": " + message); + super(error_code, message); this.error_code_ = error_code; loadSettings(); } @@ -130,7 +132,7 @@ public class ErrorCodeException extends PresentableException */ public ErrorCodeException(final int error_code, String message, Throwable cause) { - super("error code " + error_code + ": " + message, cause); + super(error_code, message, cause); this.error_code_ = error_code; loadSettings(); } @@ -146,7 +148,7 @@ public class ErrorCodeException extends PresentableException */ public ErrorCodeException(final int error_code, Throwable cause) { - super("error code " + error_code, cause); + super(error_code, cause); this.error_code_ = error_code; loadSettings(); } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/InvalidIDException.java b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/InvalidIDException.java index 33d189b..15f30ca 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/InvalidIDException.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/InvalidIDException.java @@ -44,9 +44,4 @@ public class InvalidIDException extends SignatureException super(error_code, cause); } - public InvalidIDException(int error_code) - { - super(error_code); - } - } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/NormalizeException.java b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/NormalizeException.java index 3675edb..2dd6cd4 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/NormalizeException.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/NormalizeException.java @@ -19,13 +19,15 @@ */ package at.knowcenter.wag.egov.egiz.exceptions; +import at.gv.egiz.pdfas.exceptions.ErrorCode; + /** * This exception is thrown by the processing a normalizer. * * @author wlackner */ -public class NormalizeException extends ErrorCodeException { +public class NormalizeException extends PresentableException { /** * SVUID. @@ -37,36 +39,18 @@ public class NormalizeException extends ErrorCodeException { * @param message * @param cause */ - public NormalizeException(int error_code, String message, Throwable cause) + public NormalizeException(String message, Throwable cause) { - super(error_code, message, cause); + super(ErrorCode.NORMALIZER_EXCEPTION, message, cause); } /** * @param error_code * @param message */ - public NormalizeException(int error_code, String message) - { - super(error_code, message); - } - - /** - * @param error_code - * @param cause - */ - public NormalizeException(int error_code, Throwable cause) - { - super(error_code, cause); - } - - /** - * @param error_code - */ - public NormalizeException(int error_code) + public NormalizeException(String message) { - super(error_code); + super(ErrorCode.NORMALIZER_EXCEPTION, message); } - } \ No newline at end of file diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/PDFDocumentException.java b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/PDFDocumentException.java index a0cf56a..f7fd09d 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/PDFDocumentException.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/PDFDocumentException.java @@ -22,11 +22,11 @@ package at.knowcenter.wag.egov.egiz.exceptions; * * @author wlackner */ -public class PDFDocumentException extends ErrorCodeException +public class PDFDocumentException extends PresentableException { /** - * + * SVUID. */ private static final long serialVersionUID = -4595955288382226408L; @@ -58,12 +58,5 @@ public class PDFDocumentException extends ErrorCodeException super(error_code, cause); } - /** - * @param error_code - */ - public PDFDocumentException(int error_code) - { - super(error_code); - } } \ No newline at end of file diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/PlaceholderException.java b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/PlaceholderException.java index 1c82c3c..7fdc06b 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/PlaceholderException.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/PlaceholderException.java @@ -17,6 +17,8 @@ */ package at.knowcenter.wag.egov.egiz.exceptions; +import at.gv.egiz.pdfas.exceptions.ErrorCode; + /** * @author wprinz */ @@ -33,7 +35,7 @@ public class PlaceholderException extends PDFDocumentException public PlaceholderException(String field, int missing) { - super(700, field + ":" + missing); + super(ErrorCode.PLACEHOLDER_EXCEPTION, field + ":" + missing); this.field = field; this.missing = missing; diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/PresentableException.java b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/PresentableException.java index ab87002..218109d 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/PresentableException.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/PresentableException.java @@ -36,30 +36,47 @@ public class PresentableException extends Exception * SVUID. */ private static final long serialVersionUID = -102406558526000792L; + + protected int errorCode = -1; /** * @param message */ - public PresentableException(String message) + public PresentableException(int errorCode, String message) { super(message); + + this.errorCode = errorCode; } /** * @param message * @param cause */ - public PresentableException(String message, Throwable cause) + public PresentableException(int errorCode, String message, Throwable cause) { super(message, cause); + + this.errorCode = errorCode; } /** * @param cause */ - public PresentableException(Throwable cause) + public PresentableException(int errorCode, Throwable cause) { super(cause); + + this.errorCode = errorCode; + } + + /** + * Returns the error code of this exception. + * @return Returns the error code of this exception. + */ + public int getErrorCode () + { + return this.errorCode; } } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SettingNotFoundException.java b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SettingNotFoundException.java index 02a3b5b..b117fdb 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SettingNotFoundException.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SettingNotFoundException.java @@ -17,13 +17,15 @@ */ package at.knowcenter.wag.egov.egiz.exceptions; +import at.gv.egiz.pdfas.exceptions.ErrorCode; + /** * This exception is thrown by the SettingsReader if a property key is not * found. * * @author wlackner */ -public class SettingNotFoundException extends ErrorCodeException +public class SettingNotFoundException extends PresentableException { /** @@ -36,35 +38,32 @@ public class SettingNotFoundException extends ErrorCodeException * @param message * @param cause */ - public SettingNotFoundException(int error_code, String message, Throwable cause) + public SettingNotFoundException(String message, Throwable cause) { - super(error_code, message, cause); + super(ErrorCode.SETTING_NOT_FOUND, message, cause); } /** * @param error_code * @param message */ - public SettingNotFoundException(int error_code, String message) + public SettingNotFoundException(String message) { - super(error_code, message); + super(ErrorCode.SETTING_NOT_FOUND, message); } /** * @param error_code * @param cause */ - public SettingNotFoundException(int error_code, Throwable cause) + public SettingNotFoundException(Throwable cause) { - super(error_code, cause); + super(ErrorCode.SETTING_NOT_FOUND, cause); } - - /** - * @param error_code - */ - public SettingNotFoundException(int error_code) + + protected SettingNotFoundException(int errorCode, String message) { - super(error_code); + super(errorCode, message); } } \ No newline at end of file diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SettingsException.java b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SettingsException.java index c53e6f2..d781577 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SettingsException.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SettingsException.java @@ -17,6 +17,8 @@ */ package at.knowcenter.wag.egov.egiz.exceptions; +import at.gv.egiz.pdfas.exceptions.ErrorCode; + /** * Thrown when the settings couldn't be loaded. * @@ -40,7 +42,7 @@ public class SettingsException extends PresentableException */ public SettingsException(String message) { - super(message); + super(ErrorCode.SETTINGS_EXCEPTION, message); } /** @@ -49,15 +51,6 @@ public class SettingsException extends PresentableException */ public SettingsException(String message, Throwable cause) { - super(message, cause); - } - - /** - * @param cause - */ - public SettingsException(Throwable cause) - { - super(cause); + super(ErrorCode.SETTINGS_EXCEPTION, message, cause); } - } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SignatorFactoryException.java b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SignatorFactoryException.java index dea7cfc..53a88de 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SignatorFactoryException.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SignatorFactoryException.java @@ -17,6 +17,8 @@ */ package at.knowcenter.wag.egov.egiz.exceptions; +import at.gv.egiz.pdfas.exceptions.ErrorCode; + /** * Exception coming out of the SignatorFactory. * @author wprinz @@ -31,7 +33,7 @@ public class SignatorFactoryException extends PresentableException public SignatorFactoryException(String message) { - super(message); + super(ErrorCode.SETTINGS_EXCEPTION, message); } } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SignatureException.java b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SignatureException.java index f036f49..dc69722 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SignatureException.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SignatureException.java @@ -25,7 +25,7 @@ package at.knowcenter.wag.egov.egiz.exceptions; * * @author wlackner */ -public class SignatureException extends ErrorCodeException { +public class SignatureException extends PresentableException { /** * SVUID. @@ -62,10 +62,11 @@ public class SignatureException extends ErrorCodeException { /** * @param error_code + * @param cause */ - public SignatureException(int error_code) + public SignatureException(PresentableException cause) { - super(error_code); + super(cause.getErrorCode(), cause); } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SignatureTypesException.java b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SignatureTypesException.java index 4f51418..d8f46db 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SignatureTypesException.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/SignatureTypesException.java @@ -17,8 +17,11 @@ */ package at.knowcenter.wag.egov.egiz.exceptions; +import at.gv.egiz.pdfas.exceptions.ErrorCode; + /** * Exception for Signature Type problems. + * * @author wprinz */ public class SignatureTypesException extends PresentableException @@ -34,24 +37,31 @@ public class SignatureTypesException extends PresentableException */ public SignatureTypesException(String message) { - super(message); + super(ErrorCode.SIGNATURE_TYPES_EXCEPTION, message); } - /** - * @param message - * @param cause - */ - public SignatureTypesException(String message, Throwable cause) - { - super(message, cause); - } +// /** +// * @param message +// * @param cause +// */ +// public SignatureTypesException(String message, Throwable cause) +// { +// super(ErrorCode.SIGNATURE_TYPES_EXCEPTION, message, cause); +// } + + // /** + // * @param cause + // */ + // public SignatureTypesException(Throwable cause) + // { + // super(ErrorCode.SIGNATURE_TYPES_EXCEPTION, cause); + // } /** * @param cause */ - public SignatureTypesException(Throwable cause) + public SignatureTypesException(PresentableException cause) { - super(cause); + super(cause.getErrorCode(), cause); } - } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/WebException.java b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/WebException.java index 5f72211..7d06b6a 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/WebException.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/exceptions/WebException.java @@ -19,54 +19,48 @@ */ package at.knowcenter.wag.egov.egiz.exceptions; +import at.gv.egiz.pdfas.exceptions.ErrorCode; + /** * Exception for web problems. * @author wlackner */ -public class WebException extends ErrorCodeException { +public class WebException extends PresentableException { /** * SVUID. */ private static final long serialVersionUID = 4329890155872840492L; +// /** +// * @param error_code +// * @param message +// * @param cause +// */ +// public WebException(int error_code, String message, Throwable cause) +// { +// super(error_code, message, cause); +// } +// +// /** +// * @param error_code +// * @param message +// */ +// public WebException(int error_code, String message) +// { +// super(error_code, message); +// } +// + /** * @param error_code - * @param message * @param cause */ - public WebException(int error_code, String message, Throwable cause) + public WebException(Throwable cause) { - super(error_code, message, cause); + super(ErrorCode.WEB_EXCEPTION, cause); } - /** - * @param error_code - * @param message - */ - public WebException(int error_code, String message) - { - super(error_code, message); - } - - /** - * @param error_code - * @param cause - */ - public WebException(int error_code, Throwable cause) - { - super(error_code, cause); - } - - /** - * @param error_code - */ - public WebException(int error_code) - { - super(error_code); - } - - } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/framework/Signator.java b/src/main/java/at/knowcenter/wag/egov/egiz/framework/Signator.java index 8d1688c..2d90005 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/framework/Signator.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/framework/Signator.java @@ -17,6 +17,7 @@ */ package at.knowcenter.wag.egov.egiz.framework; +import at.gv.egiz.pdfas.framework.input.PdfDataSource; import at.knowcenter.wag.egov.egiz.PdfASID; import at.knowcenter.wag.egov.egiz.exceptions.PDFDocumentException; import at.knowcenter.wag.egov.egiz.exceptions.PresentableException; @@ -64,7 +65,7 @@ public interface Signator * @throws PresentableException * Forwarded exception. */ - public IncrementalUpdateInformation prepareSign(byte[] pdf, + public IncrementalUpdateInformation prepareSign(PdfDataSource pdfDataSource, String signature_type, TablePos pos, boolean has_SIG_ID) throws PresentableException; /** diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/framework/SignatorFactory.java b/src/main/java/at/knowcenter/wag/egov/egiz/framework/SignatorFactory.java index c26055f..01155a8 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/framework/SignatorFactory.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/framework/SignatorFactory.java @@ -82,7 +82,7 @@ public abstract class SignatorFactory /** * The most recent test algorithm this application provides. */ - public static final PdfASID MOST_RECENT_DETACHED_SIGNATOR_ID = DetachedSignator_1_0_0.MY_ID; + public static final PdfASID MOST_RECENT_DETACHED_SIGNATOR_ID = DetachedfTextualSignator_1_0_0.MY_ID; /** * The most recent test algorithm this application provides. diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/framework/VerificationFilter.java b/src/main/java/at/knowcenter/wag/egov/egiz/framework/VerificationFilter.java index da5a8dc..2631028 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/framework/VerificationFilter.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/framework/VerificationFilter.java @@ -17,6 +17,7 @@ */ package at.knowcenter.wag.egov.egiz.framework; +import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -24,6 +25,8 @@ import java.io.PrintStream; import java.util.ArrayList; import java.util.List; +import at.gv.egiz.pdfas.exceptions.ErrorCode; + import org.apache.log4j.Logger; import at.knowcenter.wag.egov.egiz.PdfAS; @@ -43,6 +46,7 @@ import at.knowcenter.wag.egov.egiz.pdf.BinarySignature; import at.knowcenter.wag.egov.egiz.pdf.Placeholder; import at.knowcenter.wag.egov.egiz.pdf.SignatureHolder; import at.knowcenter.wag.egov.egiz.pdf.StringInfo; +import at.knowcenter.wag.egov.egiz.pdf.TextualSignatureHolder; import at.knowcenter.wag.exactparser.ParseDocument; import at.knowcenter.wag.exactparser.parsing.IndirectObjectReference; import at.knowcenter.wag.exactparser.parsing.PDFUtils; @@ -64,6 +68,8 @@ import at.knowcenter.wag.exactparser.parsing.results.ObjectParseResult; * in the document. * * + * @deprecated use the new at.gv.egiz.framework instead + * * @author wprinz * @author amavriqi */ @@ -105,6 +111,7 @@ public class VerificationFilter return extractSignaturesFromPdf(pdf, false); } + //@deprecated public List extractSignaturesFromPdf(final byte[] pdf, boolean ignorePostSignModificationsRestriction) throws PresentableException { @@ -178,7 +185,7 @@ public class VerificationFilter } else { - // FIXME make better + // TODO: make better - already deprecated //amavriqi: skip checking for old sigs becouse of performance issues String old_text_sigs = SettingsReader.getInstance().getSetting("check_old_textual_sigs", "false"); @@ -201,7 +208,7 @@ public class VerificationFilter current_block_contains_signature = true; } - // FIXME make better + // TODO: make better - already deprecated //amavriqi: only if old textual signatures are checked for if(old_text_sigs.equalsIgnoreCase("true")){ if (prev_end == 0) @@ -209,7 +216,7 @@ public class VerificationFilter String rest_text = null; if (!text_holders.isEmpty()) { - SignatureHolder first_holder = (SignatureHolder) text_holders.get(0); + TextualSignatureHolder first_holder = (TextualSignatureHolder) text_holders.get(0); rest_text = first_holder.getSignedText(); } else @@ -218,7 +225,7 @@ public class VerificationFilter logger_.debug("Incemental block" + prev_end + " and there are " + text_holders.size() + " text holders"); logger_.debug("Checking for older textual Signatures"); logger_.debug("Extracting text to " + bpr.next_index); - rest_text = PdfAS.extractNormalizedTextTextual(pdf, bpr.next_index); + rest_text = PdfAS.extractNormalizedTextTextual(new ByteArrayInputStream(pdf), bpr.next_index); } List old_holders = PdfAS.extractSignatureHoldersTextual(rest_text, true); @@ -371,7 +378,7 @@ public class VerificationFilter String rest_text = normalized_text; if (!text_holders.isEmpty()) { - SignatureHolder holder = (SignatureHolder) text_holders.get(0); + TextualSignatureHolder holder = (TextualSignatureHolder) text_holders.get(0); rest_text = holder.getSignedText(); } @@ -492,7 +499,7 @@ public class VerificationFilter } catch (IOException e1) { - throw new PDFDocumentException(201); + throw new PDFDocumentException(ErrorCode.DOCUMENT_CANNOT_BE_READ, e1); } } @@ -530,23 +537,24 @@ public class VerificationFilter } - public static void main(String[] args) throws IOException, PresentableException - { - SettingsReader.initializeForCommandLine(); - - File in = new File(args[0]); - FileInputStream fis = new FileInputStream(in); - byte[] pdf = new byte[(int) in.length()]; - fis.read(pdf); - fis.close(); - - String text = PdfAS.extractNormalizedTextTextual(pdf, pdf.length);; - - VerificationFilter vf = new VerificationFilter(); - //List found = vf.extractSignaturesFromPdf(pdf); - - List found = vf.extractSignaturesFromPlainText(text); - - printFoundHolders("Final Holders", found, System.out); - } + // TODO old code - remove +// public static void main(String[] args) throws IOException, PresentableException +// { +// SettingsReader.initializeForCommandLine(); +// +// File in = new File(args[0]); +// FileInputStream fis = new FileInputStream(in); +// byte[] pdf = new byte[(int) in.length()]; +// fis.read(pdf); +// fis.close(); +// +// String text = PdfAS.extractNormalizedTextTextual(pdf, pdf.length);; +// +// VerificationFilter vf = new VerificationFilter(); +// //List found = vf.extractSignaturesFromPdf(pdf); +// +// List found = vf.extractSignaturesFromPlainText(text); +// +// printFoundHolders("Final Holders", found, System.out); +// } } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/framework/Verificator.java b/src/main/java/at/knowcenter/wag/egov/egiz/framework/Verificator.java index b17fc79..e70c44a 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/framework/Verificator.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/framework/Verificator.java @@ -28,6 +28,8 @@ import at.knowcenter.wag.exactparser.parsing.results.FooterParseResult; * extracts all Signatures of its type and returns them as valitatable * SignatureHolders. * + * @deprecated replaced by the one in framework + * * @author wprinz */ public interface Verificator diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/BinarySignator_1_0_0.java b/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/BinarySignator_1_0_0.java index 2c5ecf5..0ecff57 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/BinarySignator_1_0_0.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/BinarySignator_1_0_0.java @@ -17,11 +17,17 @@ */ package at.knowcenter.wag.egov.egiz.framework.signators; +import java.io.IOException; +import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import at.gv.egiz.pdfas.impl.input.CompoundPdfDataSourceImpl; +import at.gv.egiz.pdfas.impl.signator.IncrementalUpdateHelper; +import at.gv.egiz.pdfas.framework.input.DataSource; +import at.gv.egiz.pdfas.framework.input.PdfDataSource; import at.knowcenter.wag.egov.egiz.PdfAS; import at.knowcenter.wag.egov.egiz.PdfASID; import at.knowcenter.wag.egov.egiz.exceptions.PDFDocumentException; @@ -60,6 +66,8 @@ import com.lowagie.text.pdf.PdfPTable; * values according to the encoding. * * + * @deprecated movet to nc-framework + * * @author wprinz */ public class BinarySignator_1_0_0 implements Signator @@ -89,8 +97,7 @@ public class BinarySignator_1_0_0 implements Signator * @see at.knowcenter.wag.egov.egiz.framework.Signator#prepareSign(byte[], * String, TablePos, boolean) */ - public IncrementalUpdateInformation prepareSign(byte[] pdf, - String signature_type, TablePos pos, boolean has_SIG_ID) throws PresentableException + public IncrementalUpdateInformation prepareSign(PdfDataSource pdf, String signature_type, TablePos pos, boolean has_SIG_ID) throws PresentableException { try { @@ -117,13 +124,12 @@ public class BinarySignator_1_0_0 implements Signator variable_field_definitions.add(sfd); } } - IncrementalUpdateInformation iui = BinarySignature.writeIncrementalUpdate(pdf, pdf_table, pi, variable_field_definitions, all_field_definitions); + IncrementalUpdateInformation iui = IncrementalUpdateHelper.writeIncrementalUpdate(pdf, pdf_table, pi, variable_field_definitions, all_field_definitions); String temp_string = iui.temp_ir_number + " " + iui.temp_ir_generation + " obj"; //$NON-NLS-1$//$NON-NLS-2$ byte[] temp_bytes = temp_string.getBytes("US-ASCII"); //$NON-NLS-1$ int temp_start = ByteArrayUtils.lastIndexOf(iui.signed_pdf, temp_bytes); - byte[] stream_bytes = new byte[] { '>', '>', 's', 't', 'r', 'e', 'a', - 'm', 0x0A }; + byte[] stream_bytes = new byte[] { '>', '>', 's', 't', 'r', 'e', 'a', 'm', 0x0A }; int stream_start = ByteArrayUtils.indexOf(iui.signed_pdf, temp_start, stream_bytes); iui.content_stream_start = stream_start + stream_bytes.length; @@ -153,6 +159,8 @@ public class BinarySignator_1_0_0 implements Signator // byte [] old_signed_pdf = iui.signed_pdf; iui.signed_pdf = BinarySignature.prepareDataToSign(iui.signed_pdf, iui.byte_ranges); + reduceToIUBlock(iui); + iui.signature_data = formSignatureData(iui); return iui; @@ -170,8 +178,11 @@ public class BinarySignator_1_0_0 implements Signator */ public SignResult finishSign(IncrementalUpdateInformation iui) throws PresentableException { + restoreSignedPdf(iui); + // PdfAS.prefixID(iui.signed_signature_object, PdfAS.BINARY_ID); fillReplacesWithValues(iui); + BinarySignature.replaceCertificate(iui); BinarySignature.replacePlaceholders(iui); @@ -192,11 +203,38 @@ public class BinarySignator_1_0_0 implements Signator while (it.hasNext()) { ReplaceInfo ri = (ReplaceInfo) it.next(); - + ri.value = SignSignatureObjectHelper.retrieveStringValueFromSignatureObject(iui.signed_signature_object, ri.sfd.field_name); } } + protected void reduceToIUBlock(IncrementalUpdateInformation iui) + { + byte[] iu_block = new byte[iui.signed_pdf.length - iui.original_document.getLength()]; + System.arraycopy(iui.signed_pdf, iui.original_document.getLength(), iu_block, 0, iu_block.length); + + iui.signed_pdf = null; + iui.sign_iui_block = iu_block; + } + + protected void restoreSignedPdf(IncrementalUpdateInformation iui) + { + iui.signed_pdf = new byte[iui.original_document.getLength() + iui.sign_iui_block.length]; + + try + { + InputStream is = iui.original_document.createInputStream(); + is.read(iui.signed_pdf, 0, iui.original_document.getLength()); + is.close(); + } + catch (IOException e) + { + throw new RuntimeException(e); + } + + System.arraycopy(iui.sign_iui_block, 0, iui.signed_pdf, iui.original_document.getLength(), iui.sign_iui_block.length); + } + /** * Forms the SignatureData to be used for signing. * @@ -206,18 +244,22 @@ public class BinarySignator_1_0_0 implements Signator */ protected SignatureData formSignatureData(IncrementalUpdateInformation iui) { - String document_text = BinarySignature.retrieveSignableTextFromData(iui.signed_pdf, iui.signed_pdf.length); // signed_pdf.length); - - byte[] data; - try - { - data = document_text.getBytes("UTF-8"); //$NON-NLS-1$ - } - catch (UnsupportedEncodingException e) - { - throw new RuntimeException("Very strange: UTF-8 character encoding not supported.", e); //$NON-NLS-1$ - } - SignatureData signature_data = new SignatureDataImpl(data, PdfAS.PDF_MIME_TYPE); + // String document_text = + // BinarySignature.retrieveSignableTextFromData(iui.signed_pdf, + // iui.signed_pdf.length); // signed_pdf.length); + // + // byte[] data; + // try + // { + // data = document_text.getBytes("UTF-8"); //$NON-NLS-1$ + // } + // catch (UnsupportedEncodingException e) + // { + // throw new RuntimeException("Very strange: UTF-8 character encoding not + // supported.", e); //$NON-NLS-1$ + // } + DataSource ds = new CompoundPdfDataSourceImpl(iui.original_document, iui.sign_iui_block); + SignatureData signature_data = new SignatureDataImpl(ds, PdfAS.PDF_MIME_TYPE); return signature_data; } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/BinarySignator_1_1_0.java b/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/BinarySignator_1_1_0.java index 174f0b6..b6e18ed 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/BinarySignator_1_1_0.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/BinarySignator_1_1_0.java @@ -17,6 +17,12 @@ */ package at.knowcenter.wag.egov.egiz.framework.signators; +import java.io.ByteArrayInputStream; + +import at.gv.egiz.pdfas.impl.input.ByteArrayPdfDataSourceImpl; +import at.gv.egiz.pdfas.impl.input.CompoundPdfDataSourceImpl; +import at.gv.egiz.pdfas.framework.input.DataSource; + import at.knowcenter.wag.egov.egiz.PdfAS; import at.knowcenter.wag.egov.egiz.PdfASID; import at.knowcenter.wag.egov.egiz.framework.SignatorFactory; @@ -34,6 +40,8 @@ import at.knowcenter.wag.egov.egiz.sig.SignatureDataImpl; * * @see BinarySignator_1_0_0 * + * @deprecated moved to nc-framework + * * @author wprinz */ public class BinarySignator_1_1_0 extends BinarySignator_1_0_0 @@ -59,7 +67,8 @@ public class BinarySignator_1_1_0 extends BinarySignator_1_0_0 */ protected SignatureData formSignatureData(IncrementalUpdateInformation iui) { - SignatureData signature_data = new SignatureDataImpl(iui.signed_pdf, PdfAS.PDF_MIME_TYPE); + DataSource ds = new CompoundPdfDataSourceImpl(iui.original_document, iui.sign_iui_block); + SignatureData signature_data = new SignatureDataImpl(ds, PdfAS.PDF_MIME_TYPE); return signature_data; } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/DetachedSignator_1_0_0.java b/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/DetachedSignator_1_0_0.java index 5d0fd65..4ef1e15 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/DetachedSignator_1_0_0.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/DetachedSignator_1_0_0.java @@ -17,8 +17,14 @@ */ package at.knowcenter.wag.egov.egiz.framework.signators; +import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; +import at.gv.egiz.pdfas.impl.input.TextDataSourceImpl; +import at.gv.egiz.pdfas.impl.input.helper.DataSourceHelper; +import at.gv.egiz.pdfas.framework.input.DataSource; +import at.gv.egiz.pdfas.framework.input.PdfDataSource; + import at.knowcenter.wag.egov.egiz.PdfAS; import at.knowcenter.wag.egov.egiz.PdfASID; import at.knowcenter.wag.egov.egiz.exceptions.PDFDocumentException; @@ -73,7 +79,7 @@ public class DetachedSignator_1_0_0 implements Signator * @see at.knowcenter.wag.egov.egiz.framework.Signator#prepareSign(byte[], * String, TablePos, boolean) */ - public IncrementalUpdateInformation prepareSign(byte[] pdf, + public IncrementalUpdateInformation prepareSign(PdfDataSource pdf, String signature_type, TablePos pos, boolean has_SIG_ID) throws PresentableException { IncrementalUpdateInformation iui = new IncrementalUpdateInformation(); @@ -81,17 +87,11 @@ public class DetachedSignator_1_0_0 implements Signator iui.signature_type = signature_type; iui.pos = pos; - String document_text = PdfAS.extractNormalizedTextTextual(pdf); + String document_text = PdfAS.extractNormalizedTextTextual(pdf.createInputStream()); // logger_.debug("signed_text = " + document_text); - try - { - iui.signature_data = new SignatureDataImpl(document_text.getBytes("UTF-8"), MIME_TYPE, "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ - } - catch (UnsupportedEncodingException e) - { - throw new RuntimeException("Very strange: UTF-8 character encoding not supported???"); //$NON-NLS-1$ - } + DataSource ds = new TextDataSourceImpl(document_text); + iui.signature_data = new SignatureDataImpl(ds, MIME_TYPE, "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ return iui; } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/DetachedfTextualSignator_1_0_0.java b/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/DetachedfTextualSignator_1_0_0.java index 93f10ff..d7c79ea 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/DetachedfTextualSignator_1_0_0.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/DetachedfTextualSignator_1_0_0.java @@ -17,8 +17,14 @@ */ package at.knowcenter.wag.egov.egiz.framework.signators; +import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; +import at.gv.egiz.pdfas.impl.input.TextDataSourceImpl; +import at.gv.egiz.pdfas.impl.input.helper.DataSourceHelper; +import at.gv.egiz.pdfas.framework.input.DataSource; +import at.gv.egiz.pdfas.framework.input.PdfDataSource; + import at.knowcenter.wag.egov.egiz.PdfAS; import at.knowcenter.wag.egov.egiz.PdfASID; import at.knowcenter.wag.egov.egiz.exceptions.PDFDocumentException; @@ -81,7 +87,7 @@ public class DetachedfTextualSignator_1_0_0 implements Signator * @see at.knowcenter.wag.egov.egiz.framework.Signator#prepareSign(byte[], * String, TablePos, boolean) */ - public IncrementalUpdateInformation prepareSign(byte[] pdf, + public IncrementalUpdateInformation prepareSign(PdfDataSource pdf, String signature_type, TablePos pos, boolean has_SIG_ID) throws PresentableException { IncrementalUpdateInformation iui = new IncrementalUpdateInformation(); @@ -89,17 +95,11 @@ public class DetachedfTextualSignator_1_0_0 implements Signator iui.signature_type = signature_type; iui.pos = pos; - String document_text = PdfAS.extractNormalizedTextTextual(pdf); + String document_text = PdfAS.extractNormalizedTextTextual(pdf.createInputStream()); // logger_.debug("signed_text = " + document_text); - try - { - iui.signature_data = new SignatureDataImpl(document_text.getBytes("UTF-8"), MIME_TYPE, "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ - } - catch (UnsupportedEncodingException e) - { - throw new RuntimeException("Very strange: UTF-8 character encoding not supported???"); //$NON-NLS-1$ - } + DataSource ds = new TextDataSourceImpl(document_text); + iui.signature_data = new SignatureDataImpl(ds, MIME_TYPE, "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ return iui; } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/TextualSignator_1_0_0.java b/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/TextualSignator_1_0_0.java index 7fe9e4f..33de15e 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/TextualSignator_1_0_0.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/framework/signators/TextualSignator_1_0_0.java @@ -17,15 +17,16 @@ */ package at.knowcenter.wag.egov.egiz.framework.signators; -import java.io.UnsupportedEncodingException; - +import at.gv.egiz.pdfas.framework.input.DataSource; +import at.gv.egiz.pdfas.framework.input.PdfDataSource; +import at.gv.egiz.pdfas.impl.input.TextDataSourceImpl; +import at.gv.egiz.pdfas.impl.signator.IncrementalUpdateHelper; import at.knowcenter.wag.egov.egiz.PdfAS; import at.knowcenter.wag.egov.egiz.PdfASID; import at.knowcenter.wag.egov.egiz.exceptions.PresentableException; import at.knowcenter.wag.egov.egiz.framework.SignResult; import at.knowcenter.wag.egov.egiz.framework.Signator; import at.knowcenter.wag.egov.egiz.framework.SignatorFactory; -import at.knowcenter.wag.egov.egiz.pdf.BinarySignature; import at.knowcenter.wag.egov.egiz.pdf.IncrementalUpdateInformation; import at.knowcenter.wag.egov.egiz.pdf.PositioningInstruction; import at.knowcenter.wag.egov.egiz.pdf.TablePos; @@ -80,7 +81,7 @@ public class TextualSignator_1_0_0 implements Signator * @see at.knowcenter.wag.egov.egiz.framework.Signator#prepareSign(byte[], * String, TablePos, boolean) */ - public IncrementalUpdateInformation prepareSign(byte[] pdf, + public IncrementalUpdateInformation prepareSign(PdfDataSource pdf, String signature_type, TablePos pos, boolean has_SIG_ID) throws PresentableException { IncrementalUpdateInformation iui = new IncrementalUpdateInformation(); @@ -88,17 +89,11 @@ public class TextualSignator_1_0_0 implements Signator iui.signature_type = signature_type; iui.pos = pos; - String document_text = PdfAS.extractNormalizedTextTextual(pdf); + String document_text = PdfAS.extractNormalizedTextTextual(pdf.createInputStream()); // logger_.debug("signed_text = " + document_text); - try - { - iui.signature_data = new SignatureDataImpl(document_text.getBytes("UTF-8"), "text/plain", "UTF-8"); - } - catch (UnsupportedEncodingException e) - { - throw new RuntimeException("Very strange: UTF-8 character encoding not supported???"); //$NON-NLS-1$ - } + DataSource ds = new TextDataSourceImpl(document_text); + iui.signature_data = new SignatureDataImpl(ds, "text/plain", "UTF-8"); return iui; } @@ -118,7 +113,7 @@ public class TextualSignator_1_0_0 implements Signator PositioningInstruction pi = PdfAS.determineTablePositioning(iui.pos, iui.signature_type, iui.original_document, pdf_table); - IncrementalUpdateInformation signed_iui = BinarySignature.writeIncrementalUpdate(iui.original_document, pdf_table, pi, null, null); + IncrementalUpdateInformation signed_iui = IncrementalUpdateHelper.writeIncrementalUpdate(iui.original_document, pdf_table, pi, null, null); SignResult sign_result = new SignResult(PdfAS.PDF_MIME_TYPE, signed_iui.signed_pdf); return sign_result; diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/framework/verificators/BinaryVerificator_1_0_0.java b/src/main/java/at/knowcenter/wag/egov/egiz/framework/verificators/BinaryVerificator_1_0_0.java index 469fcee..b389a25 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/framework/verificators/BinaryVerificator_1_0_0.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/framework/verificators/BinaryVerificator_1_0_0.java @@ -22,6 +22,10 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import at.gv.egiz.pdfas.exceptions.ErrorCode; +import at.gv.egiz.pdfas.framework.input.PdfDataSource; +import at.gv.egiz.pdfas.impl.input.ByteArrayPdfDataSourceImpl; + import org.apache.log4j.Logger; import at.knowcenter.wag.egov.egiz.PdfASID; @@ -52,11 +56,12 @@ import at.knowcenter.wag.exactparser.parsing.results.NumberParseResult; import at.knowcenter.wag.exactparser.parsing.results.ObjectParseResult; import at.knowcenter.wag.exactparser.parsing.results.ParseResult; - /** * The BinaryVerificator parses the EGIT Dictionary and extracts the signature * holder from it. * + * @deprecated moved to the new framework + * * @author wprinz */ public class BinaryVerificator_1_0_0 implements Verificator @@ -66,6 +71,16 @@ public class BinaryVerificator_1_0_0 implements Verificator */ public static final PdfASID MY_ID = new PdfASID(SignatorFactory.VENDOR, SignatorFactory.TYPE_BINARY, SignatorFactory.VERSION_1_0_0); + /** + * Use this to override the MY_ID field. + * + * @return Returns the Id of this Verificator. + */ + protected PdfASID getMyId() + { + return MY_ID; + } + /** * The /ODS key in the EGIZ Dict. */ @@ -79,20 +94,17 @@ public class BinaryVerificator_1_0_0 implements Verificator /** * The /ByteRange key in the EGIZ Dict. */ - public static final byte[] EGIZ_BYTE_RANGE_NAME = new byte[] { 'B', 'y', 't', - 'e', 'R', 'a', 'n', 'g', 'e' }; + public static final byte[] EGIZ_BYTE_RANGE_NAME = new byte[] { 'B', 'y', 't', 'e', 'R', 'a', 'n', 'g', 'e' }; /** * The /replaces key in the EGIZ Dict. */ - public static final byte[] EGIZ_REPLACES_NAME = new byte[] { 'r', 'e', 'p', - 'l', 'a', 'c', 'e', 's' }; + public static final byte[] EGIZ_REPLACES_NAME = new byte[] { 'r', 'e', 'p', 'l', 'a', 'c', 'e', 's' }; /** * The /encodings key in the EGIZ Dict. */ - public static final byte[] EGIZ_ENCODINGS_NAME = new byte[] { 'e', 'n', 'c', - 'o', 'd', 'i', 'n', 'g', 's' }; + public static final byte[] EGIZ_ENCODINGS_NAME = new byte[] { 'e', 'n', 'c', 'o', 'd', 'i', 'n', 'g', 's' }; /** * The /Cert key in the EGIZ Dict. @@ -116,13 +128,12 @@ public class BinaryVerificator_1_0_0 implements Verificator * @see at.knowcenter.wag.egov.egiz.framework.Verificator#parseBlock(byte[], * at.knowcenter.wag.exactparser.parsing.results.FooterParseResult, int) */ - public List parseBlock(byte[] pdf, FooterParseResult block, - int start_of_whole_block) throws PresentableException + public List parseBlock(byte[] pdf, FooterParseResult block, int start_of_whole_block) throws PresentableException { int egiz_index = PDFUtils.indexOfName(pdf, block.tpr.dpr.names, VerificationFilter.EGIZ_DICT_NAME); if (egiz_index < 0) { - throw new PDFDocumentException(301, "egiz_index = " + egiz_index); + throw new PDFDocumentException(ErrorCode.COULDNT_VERIFY, "egiz_index = " + egiz_index); } IndirectObjectReferenceParseResult egiz_dict_iorpr = (IndirectObjectReferenceParseResult) block.tpr.dpr.values.get(egiz_index); @@ -140,7 +151,7 @@ public class BinaryVerificator_1_0_0 implements Verificator PdfASID kz = null; String kz_string = VerificationFilter.restoreKZ(pdf, kz_apr); kz = new PdfASID(kz_string); - if (!kz_string.equals(MY_ID.toString())) + if (!kz_string.equals(getMyId().toString())) { logger_.warn("Warning: Kennzeichnung not recognized:" + kz_string); } @@ -223,7 +234,9 @@ public class BinaryVerificator_1_0_0 implements Verificator // bbi); byte[] signed_pdf = BinarySignature.prepareDataToSign(pdf, byte_ranges); - //String signed_text = BinarySignature.retrieveSignableTextFromData(signed_pdf, signed_pdf.length); // has been moved into the BinarySignatureHolder + // String signed_text = + // BinarySignature.retrieveSignableTextFromData(signed_pdf, + // signed_pdf.length); // has been moved into the BinarySignatureHolder SignatureObject signature_object = new SignatureObject(); String default_type = SettingsReader.getInstance().getValueFromKey(SignatureTypes.DEFAULT_TYPE); @@ -300,8 +313,9 @@ public class BinaryVerificator_1_0_0 implements Verificator } } - // FIXME make better - BinarySignatureHolder signature_holder = new BinarySignatureHolder(signed_pdf, signed_pdf.length, signature_object); + // FIXME This blows up the session !!!!! + PdfDataSource ds = new ByteArrayPdfDataSourceImpl(signed_pdf, signed_pdf.length); + BinarySignatureHolder signature_holder = new BinarySignatureHolder(ds, signature_object); List holders = new ArrayList(); holders.add(signature_holder); @@ -322,8 +336,7 @@ public class BinaryVerificator_1_0_0 implements Verificator * @throws PDFDocumentException * Thrown, if the key doesn't exist in the dictionary. */ - protected ParseResult getRequiredValueOfKey(byte[] pdf, - DictionaryParseResult egiz_dict, byte[] name) throws PDFDocumentException + protected ParseResult getRequiredValueOfKey(byte[] pdf, DictionaryParseResult egiz_dict, byte[] name) throws PDFDocumentException { final int index = PDFUtils.indexOfName(pdf, egiz_dict.names, name); checkIndex(index); @@ -343,7 +356,7 @@ public class BinaryVerificator_1_0_0 implements Verificator { if (name_index < 0) { - throw new PDFDocumentException(301, "The name wasn't found in the egiz dict."); + throw new PDFDocumentException(ErrorCode.COULDNT_VERIFY, "The name wasn't found in the egiz dict."); } } @@ -359,8 +372,7 @@ public class BinaryVerificator_1_0_0 implements Verificator * @return Returns the key's value, or null if the dictionary didn't contain * that key. */ - protected ParseResult getValueOfKey(byte[] pdf, - DictionaryParseResult egiz_dict, byte[] name) + protected ParseResult getValueOfKey(byte[] pdf, DictionaryParseResult egiz_dict, byte[] name) { final int index = PDFUtils.indexOfName(pdf, egiz_dict.names, name); if (index < 0) diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/framework/verificators/BinaryVerificator_1_1_0.java b/src/main/java/at/knowcenter/wag/egov/egiz/framework/verificators/BinaryVerificator_1_1_0.java new file mode 100644 index 0000000..efbc4f8 --- /dev/null +++ b/src/main/java/at/knowcenter/wag/egov/egiz/framework/verificators/BinaryVerificator_1_1_0.java @@ -0,0 +1,24 @@ +/** + * + */ +package at.knowcenter.wag.egov.egiz.framework.verificators; + +import at.knowcenter.wag.egov.egiz.PdfASID; +import at.knowcenter.wag.egov.egiz.framework.SignatorFactory; + +/** + * @author wprinz + * + */ +public class BinaryVerificator_1_1_0 extends BinaryVerificator_1_0_0 +{ + public static final PdfASID MY_ID = new PdfASID(SignatorFactory.VENDOR, SignatorFactory.TYPE_BINARY, SignatorFactory.VERSION_1_1_0); + + /** + * @see at.knowcenter.wag.egov.egiz.framework.verificators.BinaryVerificator_1_0_0#getMyId() + */ + protected PdfASID getMyId() + { + return MY_ID; + } +} diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/framework/verificators/TextualVerificator_1_0_0.java b/src/main/java/at/knowcenter/wag/egov/egiz/framework/verificators/TextualVerificator_1_0_0.java index fccdfd0..176c0f0 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/framework/verificators/TextualVerificator_1_0_0.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/framework/verificators/TextualVerificator_1_0_0.java @@ -17,6 +17,7 @@ */ package at.knowcenter.wag.egov.egiz.framework.verificators; +import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.List; @@ -49,6 +50,8 @@ import at.knowcenter.wag.exactparser.parsing.results.FooterParseResult; * Note that it will not find old style blocks as they don't have the SIG_KZ. * * + * @deprecated moved to the new framework + * * @author wprinz */ public class TextualVerificator_1_0_0 implements Verificator @@ -78,7 +81,7 @@ public class TextualVerificator_1_0_0 implements Verificator public List parseBlock(byte[] pdf, FooterParseResult block, int start_of_whole_block) throws PresentableException { - String block_text = PdfAS.extractNormalizedTextTextual(pdf, block.next_index); + String block_text = PdfAS.extractNormalizedTextTextual(new ByteArrayInputStream(pdf), block.next_index); logger_.debug("Scanning block:"); //List signature_holders = PdfAS.extractSignatureHoldersTextual(block_text, false); @@ -97,7 +100,7 @@ public class TextualVerificator_1_0_0 implements Verificator { text_holder_candidates = new ArrayList(); - String prev_text = PdfAS.extractNormalizedTextTextual(pdf, start_of_whole_block); + String prev_text = PdfAS.extractNormalizedTextTextual(new ByteArrayInputStream(pdf), start_of_whole_block); logger_.debug("Scanning prev block:"); //List prev_signature_holders = PdfAS.extractSignatureHoldersTextual(prev_text, false); diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/framework/verificators/TextualVerificator_pdfasold.java b/src/main/java/at/knowcenter/wag/egov/egiz/framework/verificators/TextualVerificator_pdfasold.java index 5008ed3..ea84e7e 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/framework/verificators/TextualVerificator_pdfasold.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/framework/verificators/TextualVerificator_pdfasold.java @@ -17,6 +17,7 @@ */ package at.knowcenter.wag.egov.egiz.framework.verificators; +import java.io.ByteArrayInputStream; import java.util.List; import org.apache.log4j.Logger; @@ -60,7 +61,7 @@ public class TextualVerificator_pdfasold implements Verificator throw new PDFDocumentException(201, "The PDF-AS-old Verificator can only be applied on original documents."); } - String normalized_text = PdfAS.extractNormalizedTextTextual(pdf, block.next_index); + String normalized_text = PdfAS.extractNormalizedTextTextual(new ByteArrayInputStream(pdf), block.next_index); logger_.debug("Scanning block:"); List signature_holders = PdfAS.extractSignatureHoldersTextual(normalized_text, true); diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/AbsoluteTextSignature.java b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/AbsoluteTextSignature.java index a5d1be8..4219475 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/AbsoluteTextSignature.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/AbsoluteTextSignature.java @@ -75,7 +75,7 @@ public class AbsoluteTextSignature String current_text = text; for (;;) { - SignatureHolder signature_holder = extractLatestBlock(current_text); + TextualSignatureHolder signature_holder = extractLatestBlock(current_text); if (signature_holder == null) { break; @@ -99,7 +99,7 @@ public class AbsoluteTextSignature * @throws SignatureTypesException * F.e. */ - public static SignatureHolder extractLatestBlock(String text) throws SignatureException, SignatureTypesException + public static TextualSignatureHolder extractLatestBlock(String text) throws SignatureException, SignatureTypesException { FoundBlock latest_block = findLatestBlock(text); if (latest_block == null) diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/BinarySignature.java b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/BinarySignature.java index fb93fbd..d253393 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/BinarySignature.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/BinarySignature.java @@ -24,6 +24,7 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -35,17 +36,16 @@ import java.util.Comparator; import java.util.Iterator; import java.util.List; +import at.gv.egiz.pdfas.exceptions.ErrorCode; +import at.gv.egiz.pdfas.exceptions.pdf.KZSettingNotFoundException; +import at.gv.egiz.pdfas.framework.input.PdfDataSource; +import at.gv.egiz.pdfas.framework.output.DataSink; import at.knowcenter.wag.egov.egiz.exceptions.PDFDocumentException; import at.knowcenter.wag.egov.egiz.exceptions.PlaceholderException; import at.knowcenter.wag.egov.egiz.exceptions.PresentableException; import at.knowcenter.wag.egov.egiz.exceptions.SettingNotFoundException; -import at.knowcenter.wag.egov.egiz.exceptions.SignatureException; -import at.knowcenter.wag.egov.egiz.exceptions.SignatureTypesException; -import at.knowcenter.wag.egov.egiz.sig.SignatureBlock; import at.knowcenter.wag.egov.egiz.sig.SignatureFieldDefinition; -import at.knowcenter.wag.egov.egiz.sig.SignatureObject; import at.knowcenter.wag.egov.egiz.sig.SignatureTypes; -import at.knowcenter.wag.egov.egiz.sig.X509Cert; import at.knowcenter.wag.egov.egiz.tools.CodingHelper; import at.knowcenter.wag.exactparser.ByteArrayUtils; @@ -288,8 +288,7 @@ public abstract class BinarySignature * @return Returns the indirect reference of the Egiz Dictionary, or null, if * none exists. */ - public static PdfIndirectReference getEgizDictIndRefFromReader( - PdfReader reader) + public static PdfIndirectReference getEgizDictIndRefFromReader(PdfReader reader) { PdfDictionary catalog = reader.getCatalog(); PdfIndirectReference dict_ir = (PdfIndirectReference) catalog.get(EGIZ_DICT_NAME); @@ -369,12 +368,11 @@ public abstract class BinarySignature * The original document size. * @return Returns the signable text. */ - public static String retrieveSignableTextFromData(final byte[] data, - final int ods) + public static String retrieveSignableTextFromData(final byte[] data, final int ods) { // byte[] digest = buildDigest(data, ods); String raw_text = CodingHelper.encodeBase64(data);// digest); // data); - + return raw_text; } @@ -387,8 +385,7 @@ public abstract class BinarySignature * The byte ranges. * @return Returns the filled text. */ - public static byte[] prepareDataToSign(final byte[] data, - final List byte_ranges) + public static byte[] prepareDataToSign(final byte[] data, final List byte_ranges) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Iterator it = byte_ranges.iterator(); @@ -411,174 +408,176 @@ public abstract class BinarySignature return data_to_sign; } - /** - * Extracts the binary 'text' of a document. - * - *- * If the document contains an Egiz Dictionary, which means that it is already - * signed, the binary text is the Base64 coded string of the original document - * followed by the Ascii representation of the signature block. - *
- *- * If the document does not contain an Egiz Dictionary, which means that it is - * unsigned, only the binary Base64 coded original document is returned as - * binary text. - *
- *- * This function is intented for being used instead of the "text extraction" - * mechanism used in the plain text Egiz project. - *
- * - * @param doc - * The file. - * @return Returns the binary text of the document. - * @throws PDFDocumentException - * Forwarded exception. - */ - public static String extractTextBinary(File doc) throws PDFDocumentException - { - try - { - FileInputStream fis = new FileInputStream(doc); - return extractTextBinary(fis); - } - catch (FileNotFoundException e) - { - throw new PDFDocumentException(202, e); - } - } - - /** - * Extracts the text binary. - * - * @param is - * @return Returns the binary text. - * @throws PDFDocumentException - */ - public static String extractTextBinary(InputStream is) throws PDFDocumentException - { - try - { - // for some stupid reason this produces a read error if the is comes from - // a - // multipart servlet form..??? - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - int i = -1; - int acc = 0; - byte[] b = new byte[1000]; - while ((i = is.read(b)) > 0) - { - acc += i; - System.out.print(" " + i); - baos.write(b, 0, i); - } - System.out.println("acc = " + acc); - byte[] pdf = baos.toByteArray(); - - return extractTextBinary(pdf); - } - catch (IOException e) - { - throw new PDFDocumentException(202, e); - } - } - - /** - * Extracts the signable text from a binary pdf document. - * - *- * The signable text is the text that will be signed or verified afterwards. - *
- * - * @param pdf - * The pdf document. - * @return Returns the extracted text String. - * @throws PDFDocumentException - * Forwarded exception. - */ - public static String extractTextBinary(final byte[] pdf) throws PDFDocumentException - { - try - { - PdfReader reader = new PdfReader(new ByteArrayInputStream(pdf)); - PdfDictionary egiz_dict = getEgizDictFromReader(reader); - if (egiz_dict == null) - { - System.out.println("NO Egiz Dict found - whole doc = original doc"); - - int ods = pdf.length; - return retrieveSignableTextFromData(pdf, ods); - } - - String sig_text = extractSignatureTextOnly(egiz_dict); - - int ods = getOriginalDocumentSizeFromEgizDict(egiz_dict); - - String raw_text = retrieveSignableTextFromData(pdf, ods); - raw_text += "\n"; - raw_text += sig_text; - - return raw_text; - } - catch (IOException e) - { - throw new PDFDocumentException(202, e); - } - } - - /** - * Retrieves the List of SignatureHolders containing the information of all - * digital signatures of the given document. - * - *- * If the List of SignatureHolders is empty, the document is not signed - * anyways. - *
- * - * @param pdf - * The complete pdf document. - * @return Returns the List of SignatureHolders. - * @throws PDFDocumentException - * @throws SignatureTypesException - * @throws SignatureException - */ - public static List extractSignatureHoldersBinary(final byte[] pdf) throws PDFDocumentException, SignatureTypesException, SignatureException - { - try - { - PdfReader reader = new PdfReader(new ByteArrayInputStream(pdf)); - List chain = getEgizDictChainFromReader(reader); - - List signatures = new ArrayList(); - Iterator it = chain.iterator(); - while (it.hasNext()) - { - PdfDictionary dict = (PdfDictionary) it.next(); - - int ods = getOriginalDocumentSizeFromEgizDict(dict); - String signature_text = extractSignatureTextOnly(dict); - - SignatureTypes sig_types = SignatureTypes.getInstance(); - List types = sig_types.getSignatureTypeDefinitions(); - SignatureBlock sig_block = new SignatureBlock(types); - boolean could_separate = sig_block.separateBlockFromRawText(signature_text, false); - - if (could_separate) - { - SignatureObject sig_object = sig_block.getSignatureObject(); - - SignatureHolder holder = new BinarySignatureHolder(pdf, ods, sig_object); - signatures.add(holder); - } - } - - return signatures; - } - catch (IOException e) - { - throw new PDFDocumentException(201, e); - } - } + // TODO old code - remove + // /** + // * Extracts the binary 'text' of a document. + // * + // *+ // * If the document contains an Egiz Dictionary, which means that it is already + // * signed, the binary text is the Base64 coded string of the original document + // * followed by the Ascii representation of the signature block. + // *
+ // *+ // * If the document does not contain an Egiz Dictionary, which means that it is + // * unsigned, only the binary Base64 coded original document is returned as + // * binary text. + // *
+ // *+ // * This function is intented for being used instead of the "text extraction" + // * mechanism used in the plain text Egiz project. + // *
+ // * + // * @param doc + // * The file. + // * @return Returns the binary text of the document. + // * @throws PDFDocumentException + // * Forwarded exception. + // */ + // public static String extractTextBinary(File doc) throws PDFDocumentException + // { + // try + // { + // FileInputStream fis = new FileInputStream(doc); + // return extractTextBinary(fis); + // } + // catch (FileNotFoundException e) + // { + // throw new PDFDocumentException(202, e); + // } + // } + // + // /** + // * Extracts the text binary. + // * + // * @param is + // * @return Returns the binary text. + // * @throws PDFDocumentException + // */ + // public static String extractTextBinary(InputStream is) throws PDFDocumentException + // { + // try + // { + // // for some stupid reason this produces a read error if the is comes from + // // a + // // multipart servlet form..??? + // ByteArrayOutputStream baos = new ByteArrayOutputStream(); + // int i = -1; + // int acc = 0; + // byte[] b = new byte[1000]; + // while ((i = is.read(b)) > 0) + // { + // acc += i; + // System.out.print(" " + i); + // baos.write(b, 0, i); + // } + // System.out.println("acc = " + acc); + // byte[] pdf = baos.toByteArray(); + // + // return extractTextBinary(pdf); + // } + // catch (IOException e) + // { + // throw new PDFDocumentException(202, e); + // } + // } + // + // /** + // * Extracts the signable text from a binary pdf document. + // * + // *+ // * The signable text is the text that will be signed or verified afterwards. + // *
+ // * + // * @param pdf + // * The pdf document. + // * @return Returns the extracted text String. + // * @throws PDFDocumentException + // * Forwarded exception. + // */ + // public static String extractTextBinary(final byte[] pdf) throws PDFDocumentException + // { + // try + // { + // PdfReader reader = new PdfReader(new ByteArrayInputStream(pdf)); + // PdfDictionary egiz_dict = getEgizDictFromReader(reader); + // if (egiz_dict == null) + // { + // System.out.println("NO Egiz Dict found - whole doc = original doc"); + // + // int ods = pdf.length; + // return retrieveSignableTextFromData(pdf, ods); + // } + // + // String sig_text = extractSignatureTextOnly(egiz_dict); + // + // int ods = getOriginalDocumentSizeFromEgizDict(egiz_dict); + // + // String raw_text = retrieveSignableTextFromData(pdf, ods); + // raw_text += "\n"; + // raw_text += sig_text; + // + // return raw_text; + // } + // catch (IOException e) + // { + // throw new PDFDocumentException(202, e); + // } + // } + + // TODO obsolete code - remove + // /** + // * Retrieves the List of SignatureHolders containing the information of all + // * digital signatures of the given document. + // * + // *+ // * If the List of SignatureHolders is empty, the document is not signed + // * anyways. + // *
+ // * + // * @param pdf + // * The complete pdf document. + // * @return Returns the List of SignatureHolders. + // * @throws PDFDocumentException + // * @throws SignatureTypesException + // * @throws SignatureException + // */ + // public static List extractSignatureHoldersBinary(final byte[] pdf) throws PDFDocumentException, SignatureTypesException, SignatureException + // { + // try + // { + // PdfReader reader = new PdfReader(new ByteArrayInputStream(pdf)); + // List chain = getEgizDictChainFromReader(reader); + // + // List signatures = new ArrayList(); + // Iterator it = chain.iterator(); + // while (it.hasNext()) + // { + // PdfDictionary dict = (PdfDictionary) it.next(); + // + // int ods = getOriginalDocumentSizeFromEgizDict(dict); + // String signature_text = extractSignatureTextOnly(dict); + // + // SignatureTypes sig_types = SignatureTypes.getInstance(); + // List types = sig_types.getSignatureTypeDefinitions(); + // SignatureBlock sig_block = new SignatureBlock(types); + // boolean could_separate = sig_block.separateBlockFromRawText(signature_text, false); + // + // if (could_separate) + // { + // SignatureObject sig_object = sig_block.getSignatureObject(); + // + // SignatureHolder holder = new BinarySignatureHolder(pdf, ods, sig_object); + // signatures.add(holder); + // } + // } + // + // return signatures; + // } + // catch (IOException e) + // { + // throw new PDFDocumentException(201, e); + // } + // } // /** // * Signs a document with the given signature table using the Incremental @@ -677,22 +676,26 @@ public abstract class BinarySignature * @throws PresentableException * Forwarded exception. */ - public static IncrementalUpdateInformation writeIncrementalUpdate( - byte[] original_document, PdfPTable pdf_table, PositioningInstruction pi, + public static IncrementalUpdateInformation writeIncrementalUpdate(PdfDataSource original_document, DataSink written_pdf, PdfPTable pdf_table, PositioningInstruction pi, List variable_field_definitions, List all_field_definitions) throws PresentableException { try { IncrementalUpdateInformation iui = new IncrementalUpdateInformation(); iui.original_document = original_document; - iui.start_index = original_document.length; + iui.start_index = original_document.getLength(); Document.compress = false; // System.out.println("wprinz: STAMPING PDF"); - PdfReader reader = new PdfReader(original_document); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + InputStream is = original_document.createInputStream(); + PdfReader reader = new PdfReader(is); + is.close(); + + OutputStream baos = written_pdf.createOutputStream("application/pdf"); + // ByteArrayOutputStream baos = new ByteArrayOutputStream(); + // IMPORTANT: append the new content to the original document using // incremental updated // The stamper allows this by setting append = true @@ -786,19 +789,21 @@ public abstract class BinarySignature stamper.close(); // System.out.println("wprinz: STAMPING FINISHED"); - iui.signed_pdf = baos.toByteArray(); + // just to make sure the stream is really closed + baos.close(); + // iui.signed_pdf = baos.toByteArray(); return iui; } catch (IOException e) { e.printStackTrace(); - throw new PresentableException(e); + throw new PresentableException(ErrorCode.CANNOT_WRITE_PDF, e); } catch (DocumentException e) { e.printStackTrace(); - throw new PresentableException(e); + throw new PresentableException(ErrorCode.CANNOT_WRITE_PDF, e); } } @@ -816,9 +821,8 @@ public abstract class BinarySignature * @throws IOException * @throws SettingNotFoundException */ - protected static void createEgizDict(PdfStamper stamper, - PdfTemplate table_template, IncrementalUpdateInformation iui, - List variable_field_definitions, List all_field_definitions) throws IOException, SettingNotFoundException + protected static void createEgizDict(PdfStamper stamper, PdfTemplate table_template, IncrementalUpdateInformation iui, List variable_field_definitions, List all_field_definitions) + throws IOException, SettingNotFoundException { // iui.temp_ir = table_template.getIndirectReference(); iui.temp_ir_number = table_template.getIndirectReference().getNumber(); @@ -1302,8 +1306,7 @@ public abstract class BinarySignature * @return Returns the list of ReplaceInfo objects specifying the variable * areas. */ - protected static List determineReplacesInContentStream(final byte[] pdf, - int begin, int end, List field_definitions) + protected static List determineReplacesInContentStream(final byte[] pdf, int begin, int end, List field_definitions) { List replaces = new ArrayList(); try @@ -1343,8 +1346,7 @@ public abstract class BinarySignature } // sort replaces - Collections.sort(replaces, new Comparator() - { + Collections.sort(replaces, new Comparator() { public int compare(Object arg0, Object arg1) { ReplaceInfo ri0 = (ReplaceInfo) arg0; @@ -1373,8 +1375,7 @@ public abstract class BinarySignature * @throws SettingNotFoundException * F.e. */ - protected static List determineKZ(final byte[] pdf, int begin, int end, - List field_definitions) throws SettingNotFoundException + protected static List determineKZ(final byte[] pdf, int begin, int end, List field_definitions) throws SettingNotFoundException { try { @@ -1414,7 +1415,7 @@ public abstract class BinarySignature { e.printStackTrace(); } - throw new SettingNotFoundException(102, "Field " + SignatureTypes.SIG_KZ + " not found."); + throw new KZSettingNotFoundException("Field " + SignatureTypes.SIG_KZ + " not found."); } /** @@ -1508,8 +1509,7 @@ public abstract class BinarySignature return true; } - protected static boolean startsWithCaption(StringInfo si, - List field_definitions) + protected static boolean startsWithCaption(StringInfo si, List field_definitions) { try { @@ -1568,8 +1568,7 @@ public abstract class BinarySignature * @param placeholder * The placeholder the string should be filled with. */ - public static void restorePlaceholder(final byte[] pdf, StringInfo si, - final byte placeholder) + public static void restorePlaceholder(final byte[] pdf, StringInfo si, final byte placeholder) { byte[] ph = new byte[si.string_length]; for (int i = 0; i < ph.length; i++) @@ -1592,8 +1591,7 @@ public abstract class BinarySignature * values. * @throws PDFDocumentException */ - public static List reconstructReplaces(final byte[] pdf, byte[][] brevs, - StringInfo[] sis, byte[][] encodings) throws PDFDocumentException + public static List reconstructReplaces(final byte[] pdf, byte[][] brevs, StringInfo[] sis, byte[][] encodings) throws PDFDocumentException { try { @@ -1654,8 +1652,7 @@ public abstract class BinarySignature * The number of digits. * @return Returns the read number. */ - public static int readNumber(final byte[] pdf, final int start_index, - final int num_digits) + public static int readNumber(final byte[] pdf, final int start_index, final int num_digits) { try { @@ -1685,8 +1682,7 @@ public abstract class BinarySignature * @param num_digits * The number of digits. */ - public static void replaceNumber(final byte[] pdf, final int start_index, - final int number, final int num_digits) + public static void replaceNumber(final byte[] pdf, final int start_index, final int number, final int num_digits) { try { @@ -1717,30 +1713,31 @@ public abstract class BinarySignature } } - /** - * For debugging purposes. - * - * @param args - * @throws IOException - */ - public static void main(String[] args) throws IOException - { - File signed_doc = new File("C:/wprinz/temp.pdf"); - - PdfReader reader = new PdfReader(new FileInputStream(signed_doc)); - PdfDictionary egiz_dict = getEgizDictFromReader(reader); - if (egiz_dict == null) - { - System.out.println("NO Egiz Dict"); - return; - } - - String sig_text = extractSignatureTextOnly(egiz_dict); - System.out.println("Sig Text:"); - System.out.println(sig_text); - - int ods = getOriginalDocumentSizeFromEgizDict(egiz_dict); - System.out.println("Original Document Size = " + ods); - } + // TODO old code - remove + // /** + // * For debugging purposes. + // * + // * @param args + // * @throws IOException + // */ + // public static void main(String[] args) throws IOException + // { + // File signed_doc = new File("C:/wprinz/temp.pdf"); + // + // PdfReader reader = new PdfReader(new FileInputStream(signed_doc)); + // PdfDictionary egiz_dict = getEgizDictFromReader(reader); + // if (egiz_dict == null) + // { + // System.out.println("NO Egiz Dict"); + // return; + // } + // + // String sig_text = extractSignatureTextOnly(egiz_dict); + // System.out.println("Sig Text:"); + // System.out.println(sig_text); + // + // int ods = getOriginalDocumentSizeFromEgizDict(egiz_dict); + // System.out.println("Original Document Size = " + ods); + // } } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/BinarySignatureHolder.java b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/BinarySignatureHolder.java index 1f522ff..8d42370 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/BinarySignatureHolder.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/BinarySignatureHolder.java @@ -19,6 +19,10 @@ package at.knowcenter.wag.egov.egiz.pdf; import java.io.Serializable; +import at.gv.egiz.pdfas.impl.input.ByteArrayPdfDataSourceImpl; +import at.gv.egiz.pdfas.framework.input.DataSource; +import at.gv.egiz.pdfas.framework.input.PdfDataSource; + import at.knowcenter.wag.egov.egiz.sig.SignatureObject; /** @@ -44,48 +48,58 @@ public class BinarySignatureHolder implements Serializable, SignatureHolder */ private static final long serialVersionUID = -7208103904479272760L; - /** - * The whole pdf this holder was extracted from. - */ - private byte[] signed_pdf = null; - - /** - * The number of bytes that give the signed document. - */ - private int signed_pdf_length = -1; - - /** - * The signed text of this object. - * - *- * This is the value that will be signed by the Connector. - *
- */ - private String signed_text = null; +// /** +// * The whole pdf this holder was extracted from. +// */ +// private byte[] signed_pdf = null; + + private PdfDataSource pdfDataSource = null; + +// /** +// * The number of bytes that give the signed document. +// */ +// private int signed_pdf_length = -1; + +// /** +// * The signed text of this object. +// * +// *+// * This is the value that will be signed by the Connector. +// *
+// */ +// private String signed_text = null; /** * The signature object. */ private SignatureObject signature_object = null; - /** - * Constructor that takes the pdf and the SignatureObject as parameters. - * - * @param pdf - * The pdf data. - * @param length - * The length (number of bytes) of the pdf data to be used for being - * converted into "signed text". - * @param so - * The signed signature object. - */ - public BinarySignatureHolder(final byte[] pdf, final int length, SignatureObject so) +// /** +// * Constructor that takes the pdf and the SignatureObject as parameters. +// * +// * @param pdf +// * The pdf data. +// * @param length +// * The length (number of bytes) of the pdf data to be used for being +// * converted into "signed text". +// * @param so +// * The signed signature object. +// */ +// public BinarySignatureHolder(final byte[] pdf, final int length, SignatureObject so) +// { +//// this.signed_pdf = pdf; +// this.pdfDataSource = new ByteArrayPdfDataSourceImpl(pdf); +// // streaming byte array +// this.signed_pdf_length = length; +// this.signature_object = so; +// +//// this.signed_text = null; +// } + + public BinarySignatureHolder(PdfDataSource pdf, SignatureObject so) { - this.signed_pdf = pdf; - this.signed_pdf_length = length; + this.pdfDataSource = pdf; this.signature_object = so; - - this.signed_text = null; } /** @@ -93,11 +107,12 @@ public class BinarySignatureHolder implements Serializable, SignatureHolder */ public String getSignedText() { - if (this.signed_text == null) - { - computeSignedText(); - } - return this.signed_text; + throw new RuntimeException("BinarySignatureHolder must not return text."); +// if (this.signed_text == null) +// { +// computeSignedText(); +// } +// return this.signed_text; } /** @@ -107,40 +122,56 @@ public class BinarySignatureHolder implements Serializable, SignatureHolder { return this.signature_object; } - + /** - * Computes or recomputes the signed text from the underlying binary data. - * - *- * This usually encodes the binary data of given length in Base64. - *
- * - *- * This is usually called automatically when the signed text is first - * requested. - *
+ * @see at.knowcenter.wag.egov.egiz.pdf.SignatureHolder#getDataSource() */ - protected void computeSignedText() + public DataSource getDataSource() { - this.signed_text = BinarySignature.retrieveSignableTextFromData(this.signed_pdf, this.signed_pdf_length); + return getSignedPdf(); } - - /** - * Returns the signed_pdf. - * @return Returns the signed_pdf. - */ - public byte[] getSignedPdf() + + + + // TODO obsolete funtction - remove; +// /** +// * Computes or recomputes the signed text from the underlying binary data. +// * +// *+// * This usually encodes the binary data of given length in Base64. +// *
+// * +// *+// * This is usually called automatically when the signed text is first +// * requested. +// *
+// */ +// protected void computeSignedText() +// { +// this.signed_text = BinarySignature.retrieveSignableTextFromData(this.signed_pdf, this.signed_pdf_length); +// } + +// /** +// * Returns the signed_pdf. +// * @return Returns the signed_pdf. +// */ +// public byte[] getSignedPdf() +// { +// return this.signed_pdf; +// } + + public PdfDataSource getSignedPdf () { - return this.signed_pdf; + return this.pdfDataSource; } - /** - * Returns the signed_pdf_length. - * @return Returns the signed_pdf_length. - */ - public int getSignedPdfLength() - { - return this.signed_pdf_length; - } +// /** +// * Returns the signed_pdf_length. +// * @return Returns the signed_pdf_length. +// */ +// public int getSignedPdfLength() +// { +// return this.signed_pdf_length; +// } } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/IncrementalUpdateInformation.java b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/IncrementalUpdateInformation.java index 76c59c3..fc446f9 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/IncrementalUpdateInformation.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/IncrementalUpdateInformation.java @@ -20,6 +20,9 @@ package at.knowcenter.wag.egov.egiz.pdf; import java.io.Serializable; import java.util.List; +import at.gv.egiz.pdfas.framework.input.PdfDataSource; +import at.gv.egiz.pdfas.framework.output.DataSink; + import at.knowcenter.wag.egov.egiz.sig.SignatureData; import at.knowcenter.wag.egov.egiz.sig.SignatureObject; import at.knowcenter.wag.egov.egiz.sig.connectors.bku.SignSignatureObject; @@ -48,7 +51,8 @@ public class IncrementalUpdateInformation implements Serializable /** * The original PDF document. */ - public byte[] original_document = null; + //public byte[] original_document = null; + public PdfDataSource original_document = null; /** * The Singature type to be created. @@ -63,6 +67,10 @@ public class IncrementalUpdateInformation implements Serializable * */ public byte[] signed_pdf = null; + // this is only valid during prepare + + // holds the variable iui data for bin sigs. + public byte [] sign_iui_block = null; /** * The start index of this incremental update block. diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/PDFPage.java b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/PDFPage.java index 666ee52..0bae3d2 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/PDFPage.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/PDFPage.java @@ -355,7 +355,7 @@ public class PDFPage extends PDFTextStripper if (current_y > this.footer_line) { - logger_.debug("character is below footer_line. footer_line = " + this.footer_line + ", text.character=" + character + ", y=" + current_y); + //logger_.debug("character is below footer_line. footer_line = " + this.footer_line + ", text.character=" + character + ", y=" + current_y); return; } @@ -363,11 +363,11 @@ public class PDFPage extends PDFTextStripper if (!character.equals(" ") && current_y > this.max_character_ypos) { this.max_character_ypos = current_y; - logger_.debug("text.character=" + character + ", y=" + current_y); + //logger_.debug("text.character=" + character + ", y=" + current_y); // System.err.println(character + "|" + current_y); } - logger_.debug("text.character=" + character + ", y=" + current_y); + //logger_.debug("text.character=" + character + ", y=" + current_y); // System.err.println(character + "|" + current_y); } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/PDFSignatureCreation.java b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/PDFSignatureCreation.java index 453103b..fd885fc 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/PDFSignatureCreation.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/PDFSignatureCreation.java @@ -79,12 +79,12 @@ public class PDFSignatureCreation { * @throws PDFDocumentException ErrorCode:101 */ public PDFSignatureCreation(SignatureObject sigObject) throws PDFDocumentException { - try { +// try { loadSettings(); - } catch (PDFDocumentException e) { - e.setErrorCode(101); - throw e; - } +// } catch (PDFDocumentException e) { +// e.setErrorCode(101); +// throw e; +// } sigObject_ = sigObject; } @@ -157,12 +157,12 @@ public class PDFSignatureCreation { */ public PDFSignatureObject getPDFSignatureObject() throws PDFDocumentException { if (pdfSigObject_ == null) { - try { +// try { pdfSigObject_ = createPDFSignatureObject(); - } catch (PDFDocumentException e) { - e.setErrorCode(203); - throw e; - } +// } catch (PDFDocumentException e) { +// e.setErrorCode(203); +// throw e; +// } pdfSigObject_.setSignatorObject(sigObject_); } return pdfSigObject_; diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/PDFSignatureObjectIText.java b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/PDFSignatureObjectIText.java index 56b5f86..6c609ae 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/PDFSignatureObjectIText.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/PDFSignatureObjectIText.java @@ -28,7 +28,6 @@ import org.apache.log4j.Logger; import at.knowcenter.wag.egov.egiz.cfg.ConfigLogger; import at.knowcenter.wag.egov.egiz.cfg.SettingsReader; -import at.knowcenter.wag.egov.egiz.exceptions.ErrorCodeException; import at.knowcenter.wag.egov.egiz.exceptions.PDFDocumentException; import at.knowcenter.wag.egov.egiz.exceptions.SettingsException; import at.knowcenter.wag.egov.egiz.sig.SignatureObject; @@ -342,7 +341,7 @@ public class PDFSignatureObjectIText implements PDFSignatureObject } if (logger_.isEnabledFor(Level.ERROR)) { - logger_.error("Error Code:222 " + ErrorCodeException.getErrorCodeMessage(222) + ". IOException:" + e.getMessage()); + logger_.error("Error Code: 222, IOException:" + e.getMessage()); } PDFDocumentException pde = new PDFDocumentException(222, "PDF table can not created: Image can not loaded"); throw pde; diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/PDFUtilities.java b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/PDFUtilities.java index 8c15d21..e19c244 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/PDFUtilities.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/PDFUtilities.java @@ -22,6 +22,8 @@ import java.io.File; import java.io.IOException; import java.util.List; +import at.gv.egiz.pdfas.framework.input.PdfDataSource; + import org.pdfbox.pdfparser.PDFParser; import org.pdfbox.pdmodel.PDDocument; import org.pdfbox.pdmodel.PDPage; @@ -39,13 +41,15 @@ import com.lowagie.text.DocumentException; */ public abstract class PDFUtilities { - public static float calculatePageLength(final byte[] pdf,int page ,float footer_line, int pagerotation) throws PDFDocumentException + public static float calculatePageLength(final PdfDataSource pdfDataSource,int page ,float footer_line, int pagerotation) throws PDFDocumentException { try { - ByteArrayInputStream original_bais = new ByteArrayInputStream(pdf); - byte [] normalized_pdf = TextualSignature.normalizePDF(original_bais); + //ByteArrayInputStream original_bais = new ByteArrayInputStream(pdf); + //byte [] normalized_pdf = TextualSignature.normalizePDF(original_bais); + byte [] normalized_pdf = TextualSignature.normalizePDF(pdfDataSource.createInputStream()); + // PERF: The whole PDF normalization process is costy ByteArrayInputStream bais = new ByteArrayInputStream(normalized_pdf); PDFParser parser = new PDFParser(bais); diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/SignatureHolder.java b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/SignatureHolder.java index d7fcce9..aa8da2c 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/SignatureHolder.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/SignatureHolder.java @@ -17,6 +17,7 @@ */ package at.knowcenter.wag.egov.egiz.pdf; +import at.gv.egiz.pdfas.framework.input.DataSource; import at.knowcenter.wag.egov.egiz.sig.SignatureObject; /** @@ -36,21 +37,21 @@ import at.knowcenter.wag.egov.egiz.sig.SignatureObject; public interface SignatureHolder { - /** - * Returns the signed text (verification) or the to-be-signed signable text - * (signation). - * - *- * Note that this text must be the one that was actually signed. This text is - * directly passed to the connector for signation/verification. No - * normalization or modification will be / must be done to this text between - * reading out from the signature holder and passing the text to the - * connector. - *
- * - * @return Returns the signed text or the to-be-signed signable text. - */ - public String getSignedText(); +// /** +// * Returns the signed text (verification) or the to-be-signed signable text +// * (signation). +// * +// *+// * Note that this text must be the one that was actually signed. This text is +// * directly passed to the connector for signation/verification. No +// * normalization or modification will be / must be done to this text between +// * reading out from the signature holder and passing the text to the +// * connector. +// *
+// * +// * @return Returns the signed text or the to-be-signed signable text. +// */ +// public String getSignedText(); /** * @@ -59,4 +60,9 @@ public interface SignatureHolder */ public SignatureObject getSignatureObject(); + /** + * Returns the DataSource providing the data. + * @return + */ + public DataSource getDataSource(); } \ No newline at end of file diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/TextualSignature.java b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/TextualSignature.java index a52d6dd..668bbcb 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/TextualSignature.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/TextualSignature.java @@ -23,6 +23,9 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; +import at.gv.egiz.pdfas.performance.PerformanceCounters; +import at.gv.egiz.pdfas.exceptions.pdf.TextExtractionException; + import org.apache.log4j.Logger; import org.pdfbox.pdfparser.PDFParser; import org.pdfbox.pdmodel.PDDocument; @@ -31,7 +34,6 @@ import org.pdfbox.util.PDFTextStripper; import at.knowcenter.wag.egov.egiz.cfg.ConfigLogger; import at.knowcenter.wag.egov.egiz.cfg.SettingsReader; import at.knowcenter.wag.egov.egiz.exceptions.PresentableException; -import at.knowcenter.wag.egov.egiz.framework.signators.TextualSignator_1_0_0; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; @@ -52,6 +54,7 @@ public class TextualSignature * The logger definition. */ private static final Logger logger_ = ConfigLogger.getLogger(TextualSignature.class); + /** * Extracts the document text from a given pdf. * @@ -61,8 +64,10 @@ public class TextualSignature * @throws PresentableException * Forwarded exception. */ - public static String extractTextTextual(InputStream pdf_stream) throws PresentableException + public static String extractTextTextual(InputStream pdf_stream) throws TextExtractionException { + PerformanceCounters.textExtractions.increment(); + try { int first_page_rotation = 0; @@ -79,8 +84,10 @@ public class TextualSignature //iText PdfReader reader = new PdfReader(pdf_stream); + pdf_stream.close(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + // PERF: PDF normalization needs byte array - this is costy + ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); // For some reason the Reader -> ImportPage -> Writer mechanism produces // problems en mass. @@ -136,7 +143,7 @@ public class TextualSignature // } baos.close(); - byte[] normalizedPDF = baos.toByteArray(); + byte[] normalizedPDF = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(normalizedPDF); //PDFBox-parser @@ -164,9 +171,13 @@ public class TextualSignature return text; } - catch (Exception e) + catch (IOException e) + { + throw new TextExtractionException(e); + } + catch (DocumentException e) { - throw new PresentableException(e); + throw new TextExtractionException(e); } } @@ -195,6 +206,9 @@ public class TextualSignature { //iText PdfReader reader = new PdfReader(input_pdf); + input_pdf.close(); + + // PERF: PDF Normalization needs byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); // For some reason the Reader -> ImportPage -> Writer mechanism produces // problems en mass. diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/TextualSignatureHolder.java b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/TextualSignatureHolder.java index fd56125..0971f90 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/pdf/TextualSignatureHolder.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/pdf/TextualSignatureHolder.java @@ -19,6 +19,9 @@ package at.knowcenter.wag.egov.egiz.pdf; import java.io.Serializable; +import at.gv.egiz.pdfas.framework.input.DataSource; +import at.gv.egiz.pdfas.framework.input.TextDataSource; +import at.gv.egiz.pdfas.impl.input.TextDataSourceImpl; import at.knowcenter.wag.egov.egiz.sig.SignatureObject; /** @@ -35,34 +38,44 @@ public class TextualSignatureHolder implements Serializable, SignatureHolder */ private static final long serialVersionUID = -7208103904479272760L; - /** - * The signed text of this object. - * - *- * This is the value that will be signed by the Connector. - *
- */ - private String signed_text = null; +// /** +// * The signed text of this object. +// * +// *+// * This is the value that will be signed by the Connector. +// *
+// */ +// private String signed_text = null; /** * The signature object. */ private SignatureObject signature_object = null; + + private TextDataSource textDataSource = null; public TextualSignatureHolder(String text, SignatureObject so) { - this.signed_text = text; + //this.signed_text = text; this.signature_object = so; + this.textDataSource = new TextDataSourceImpl(text); } - /** - * @see at.knowcenter.wag.egov.egiz.pdf.SignatureHolder#getSignedText() - */ - public String getSignedText() + public TextualSignatureHolder(TextDataSource text, SignatureObject so) { - return this.signed_text; + //this.signed_text = text; + this.signature_object = so; + this.textDataSource = text; } +// /** +// * @see at.knowcenter.wag.egov.egiz.pdf.SignatureHolder#getSignedText() +// */ +// public String getSignedText() +// { +// return this.signed_text; +// } + /** * @see at.knowcenter.wag.egov.egiz.pdf.SignatureHolder#getSignatureObject() */ @@ -70,4 +83,37 @@ public class TextualSignatureHolder implements Serializable, SignatureHolder { return this.signature_object; } + + /** + * @see at.knowcenter.wag.egov.egiz.pdf.SignatureHolder#getDataSource() + */ + public DataSource getDataSource() + { + return this.textDataSource; + } + + /** + * This is used to replace the DataSource. + * + *+ * After processing the text, data sources containing large texts are usually replaced by a FileBased ones to save memory. + *
+ * + * @param tds + */ + public void exchangeDataSource(TextDataSource tds) + { + this.textDataSource = tds; + } + + /** + * This is just a shortcut to getDataSource().getText() + * @return Returns the text of this data source. + */ + public String getSignedText() + { + return this.textDataSource.getText(); + } + + } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/ConnectorFactory.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/ConnectorFactory.java index 690a913..9d744e1 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/sig/ConnectorFactory.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/ConnectorFactory.java @@ -34,6 +34,8 @@ import at.knowcenter.wag.egov.egiz.sig.connectors.MOAConnector; * This is a factory for creating the appropriate connector according to the * connector identifier. * + * @deprecated this code is far too complicated + * * @see at.knowcenter.wag.egov.egiz.sig.ConnectorInformation * @author wprinz */ diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/LocalConnector.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/LocalConnector.java index 65c79a9..3b647a0 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/sig/LocalConnector.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/LocalConnector.java @@ -39,6 +39,8 @@ import at.knowcenter.wag.egov.egiz.exceptions.SignatureException; * whereas the connection to the local service is made from the local client. * * + * @deprecated use the new connectory instead + * * @author wprinz */ public interface LocalConnector extends Connector @@ -82,7 +84,7 @@ public interface LocalConnector extends Connector * @throws SignatureException * F.e. */ - // TODO hotfix + // TODO hotfix - already deprecated public SignatureObject analyzeSignResponse(Properties response_properties, String signature_type) throws SignatureException; @@ -93,7 +95,7 @@ public interface LocalConnector extends Connector * @throws SignatureException * F.e. */ - // TODO hotfix + // TODO hotfix - already deprecated public SignatureResponse analyzeVerifyResponse(Properties response_properties) throws SignatureException; /** diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureData.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureData.java index 015831e..8c9ab12 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureData.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureData.java @@ -3,6 +3,8 @@ */ package at.knowcenter.wag.egov.egiz.sig; +import at.gv.egiz.pdfas.framework.input.DataSource; + /** * This encapsuilates the content data to be signed or verified. * @@ -20,14 +22,12 @@ package at.knowcenter.wag.egov.egiz.sig; */ public interface SignatureData { - - // TODO Performance: make this to an InputStream /** - * Returns the data to be signed or verified. + * Returns the DataSource that provides the data for this SignatureData. * - * @return Returns the data to be signed or verified. + * @return Returns the DataSource. */ - public byte[] getData(); + public DataSource getDataSource(); /** * Returns the mime type of the data. diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureDataImpl.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureDataImpl.java index 5b9304d..320c511 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureDataImpl.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureDataImpl.java @@ -5,6 +5,8 @@ package at.knowcenter.wag.egov.egiz.sig; import java.io.Serializable; +import at.gv.egiz.pdfas.framework.input.DataSource; + /** * Generic implementation of the SignatureData interface for being used by * signators and verificators. @@ -21,8 +23,8 @@ public class SignatureDataImpl implements SignatureData, Serializable /** * The signature data. */ - protected byte[] data = null; - + protected DataSource data = null; + /** * The mime type of the data. */ @@ -46,43 +48,50 @@ public class SignatureDataImpl implements SignatureData, Serializable * @param mime_type * The mime type of the data. */ - public SignatureDataImpl(byte[] data, String mime_type) + public SignatureDataImpl(DataSource data, String mime_type) { this.data = data; this.mimeType = mime_type; this.characterEncoding = null; } - /** - * Constructor that fills the SignatureData. - * - *- * Use this constructor for textual data as it allows to provide the character - * encoding. - *
- * - * @param data - * The signature data. - * @param mime_type - * The mime type of the data. - * @param character_encoding - * The character encoding of the data if appropriate, or null if not. - */ - public SignatureDataImpl(byte[] data, String mime_type, String character_encoding) +// /** +// * Constructor that fills the SignatureData. +// * +// *+// * Use this constructor for textual data as it allows to provide the character +// * encoding. +// *
+// * +// * @param data +// * The signature data. +// * @param mime_type +// * The mime type of the data. +// * @param character_encoding +// * The character encoding of the data if appropriate, or null if not. +// */ +// public SignatureDataImpl(byte[] data, String mime_type, String character_encoding) +// { +// this.data = data; +// this.mimeType = mime_type; +// this.characterEncoding = character_encoding; +// } + public SignatureDataImpl(DataSource data, String mime_type, String character_encoding) { this.data = data; this.mimeType = mime_type; this.characterEncoding = character_encoding; } - + /** - * @see at.knowcenter.wag.egov.egiz.sig.SignatureData#getData() + * @see at.knowcenter.wag.egov.egiz.sig.SignatureData#getDataSource() */ - public byte[] getData() + public DataSource getDataSource() { return this.data; } - + + /** * @see at.knowcenter.wag.egov.egiz.sig.SignatureData#getMimeType() */ diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureObject.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureObject.java index a48893c..52c986a 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureObject.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureObject.java @@ -252,9 +252,7 @@ public class SignatureObject implements Serializable { String log_message = "Can not load pdf signature settings. Cause:\n" + e.getMessage(); logger_.error(log_message); - SignatureException se = new SignatureException(101, log_message, e); - se.setErrorCode(101); - throw se; + throw new SignatureException(101, log_message, e); } } // pTree_ = settings_.getPTree(); @@ -829,7 +827,7 @@ public class SignatureObject implements Serializable public static boolean decideNewEtsiByBKUVersion(String productVersion) { boolean new_etsi = true; - // TODO make better + // TODO hotfix if (productVersion.startsWith("2.5") || productVersion.startsWith("2.4") || productVersion.startsWith("2.3") || productVersion.startsWith("2.2") || productVersion.startsWith("2.1") || productVersion.startsWith("1") || productVersion.startsWith("0")) { new_etsi = false; @@ -1540,7 +1538,7 @@ public class SignatureObject implements Serializable } catch (NormalizeException e) { - throw new SignatureTypesException("Can not set normalizer Version:" + value); + throw new SignatureTypesException(e); } } // value = new String(CodingHelper.encodeUTF8(value)); diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/BKUConnector.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/BKUConnector.java index d6301a9..75e4c31 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/BKUConnector.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/BKUConnector.java @@ -22,6 +22,8 @@ import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; +import at.gv.egiz.pdfas.exceptions.external.ExternalErrorException; + import org.apache.log4j.Level; import org.apache.log4j.Logger; @@ -41,6 +43,8 @@ import at.knowcenter.wag.egov.egiz.tools.FileHelper; /** * Connector for communicating with BKU. * + * @deprecated use the new connectors. + * * @author wlackner * @author wprinz */ @@ -270,7 +274,7 @@ public class BKUConnector implements LocalConnector ids[3] = extractId(xmlResponse, "etsi-data-reference-"); ids[4] = extractId(xmlResponse, "etsi-data-object-"); - //TODO hotfix + //TODO hotfix - already deprecated String final_ids =SignatureObject.formatSigIds(response_properties, ids); //sigObj.setSignationIDs(ids); sigObj.setSignationIDs(final_ids); @@ -291,11 +295,11 @@ public class BKUConnector implements LocalConnector int start_idx = text.indexOf(name) + name.length(); int end_idx = text.indexOf("\"", start_idx); - // TODO hotfix! + // TODO hotfix! - already deprecated final int quot_end_idx = end_idx; final int squot_end_idx = text.indexOf("'", start_idx); end_idx = Math.min(quot_end_idx, squot_end_idx); - // TODO hotfix end! + // TODO hotfix end! - already deprecated id = text.substring(start_idx, end_idx); if (logger_.isDebugEnabled()) @@ -342,7 +346,7 @@ public class BKUConnector implements LocalConnector logger_.debug("ids_string = " + ids_string); String[] ids = SignatureObject.parseSigIds(ids_string); - // TODO hotfix + // TODO hotfix - already deprecated final boolean neue_bku = ids[5] != null; logger_.debug("ids[5] = " + ids[5]); logger_.debug("neue_bku = " + neue_bku); @@ -391,7 +395,7 @@ public class BKUConnector implements LocalConnector ver_temp_str = ver_temp_str.replaceFirst("TemplateQualifyingPropertiesReplace", sig_prop_str); byte[] sig_prop_code = CodingHelper.buildDigest(sig_prop_str.getBytes("UTF-8")); - // TODO hotfix + // TODO hotfix - already deprecated if (neue_bku) { final String ETSI_SIGNED_PROPERTIES_START_TAG = "+ * This information is taken from the profile and if not defined from the + * defaults. + *
+ *+ * E.g. http://127.0.0.1:3495/http-security-layer-request + *
+ * + * @param profile + * The profile to take the data from. + * @param device + * The service device to be accessed. E.g. bku. + * @return Returns the URL for accessing the local service. + * @throws SettingsException F.e. + */ + public static String getLocalServiceAddress(String profile, String device) throws SettingsException + { + SettingsReader settings = SettingsReader.getInstance(); + + String url = getConnectorValueFromProfile(settings, profile, device + ".sign.url"); + + return url; //"http://127.0.0.1:3495/http-security-layer-request"; + } + + /** + * Reads the configuration entry given by the key, first from the given + * profile, if not found from the defaults. + * + * @param settings + * The settings. + * @param profile + * The profile. + * @param key + * The configuration key. + * @return Returns the configuration entry. + */ + public static String getConnectorValueFromProfile(SettingsReader settings, + String profile, String key) + { + String value = settings.getValueFromKey("sig_obj." + profile + "." + key); //$NON-NLS-1$//$NON-NLS-2$ + if (value == null) + { + value = settings.getValueFromKey(key); + } + return value; + } + } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/web/PdfASServletContextListener.java b/src/main/java/at/knowcenter/wag/egov/egiz/web/PdfASServletContextListener.java index 954bcce..0e0c625 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/web/PdfASServletContextListener.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/PdfASServletContextListener.java @@ -58,15 +58,15 @@ public class PdfASServletContextListener implements ServletContextListener String base_dir = sce.getServletContext().getRealPath("/"); //$NON-NLS-1$ logger.info("PDF-AS real path = " + base_dir); //$NON-NLS-1$ - try - { - logger.info("PDF-AS work directory = " + new File(work_dir).getCanonicalPath()); //$NON-NLS-1$ - logger.info("PDF-AS base directory = " + new File(base_dir).getCanonicalPath()); //$NON-NLS-1$ - } - catch (IOException e) - { - e.printStackTrace(); - } +// try +// { +// logger.info("PDF-AS work directory = " + new File(work_dir).getCanonicalPath()); //$NON-NLS-1$ +// logger.info("PDF-AS base directory = " + new File(base_dir).getCanonicalPath()); //$NON-NLS-1$ +// } +// catch (IOException e) +// { +// e.printStackTrace(); +// } if (work_dir != null && work_dir.length() > 0) { diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/web/SessionInformation.java b/src/main/java/at/knowcenter/wag/egov/egiz/web/SessionInformation.java index acf4416..3eb08f5 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/web/SessionInformation.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/SessionInformation.java @@ -21,6 +21,10 @@ import java.io.Serializable; import java.util.List; import java.util.Properties; +import at.gv.egiz.pdfas.impl.output.FileBasedDataSink; +import at.gv.egiz.pdfas.framework.input.PdfDataSource; +import at.gv.egiz.pdfas.framework.signator.SignatorInformation; + import at.knowcenter.wag.egov.egiz.framework.SignResult; import at.knowcenter.wag.egov.egiz.pdf.IncrementalUpdateInformation; import at.knowcenter.wag.egov.egiz.pdf.TablePos; @@ -63,7 +67,8 @@ public class SessionInformation implements Serializable /** * The original, uploaded pdf. */ - public byte[] pdf = null; + //public byte[] pdf = null; + public PdfDataSource pdfDataSource = null; /** * The type/profile of the signature. @@ -106,6 +111,10 @@ public class SessionInformation implements Serializable */ public IncrementalUpdateInformation iui; + public SignatorInformation si = null; + + public FileBasedDataSink output = null; + /** * The signature holders. */ @@ -127,10 +136,12 @@ public class SessionInformation implements Serializable */ public boolean download_inline; - /** - * The sign result to be passed back to the user. - */ - public SignResult sign_result; +// /** +// * The sign result to be passed back to the user. +// */ +// public SignResult sign_result; + + public boolean isSignFinished = false; diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/DataURLServlet.java b/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/DataURLServlet.java index 72f7c2d..2844c6d 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/DataURLServlet.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/DataURLServlet.java @@ -4,11 +4,11 @@ package at.knowcenter.wag.egov.egiz.web.servlets; import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; @@ -16,26 +16,31 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; + +import at.gv.egiz.pdfas.exceptions.framework.SignatorException; +import at.gv.egiz.pdfas.framework.SignatorFactory; +import at.gv.egiz.pdfas.framework.signator.Signator; +import at.gv.egiz.pdfas.web.SignSessionInformation; +import at.gv.egiz.pdfas.web.VerifySessionInformation; +import at.gv.egiz.pdfas.web.helper.SessionHelper; +import at.gv.egiz.pdfas.web.helper.SignServletHelper; +import at.gv.egiz.pdfas.web.helper.TempDirHelper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import at.knowcenter.wag.egov.egiz.PdfASID; +import at.knowcenter.wag.egov.egiz.exceptions.ConnectorException; +import at.knowcenter.wag.egov.egiz.exceptions.InvalidIDException; import at.knowcenter.wag.egov.egiz.exceptions.PresentableException; -import at.knowcenter.wag.egov.egiz.framework.Signator; -import at.knowcenter.wag.egov.egiz.framework.SignatorFactory; +import at.knowcenter.wag.egov.egiz.exceptions.SignatorFactoryException; import at.knowcenter.wag.egov.egiz.pdf.SignatureHolder; import at.knowcenter.wag.egov.egiz.sig.SignatureResponse; import at.knowcenter.wag.egov.egiz.sig.connectors.ConnectorChooser; import at.knowcenter.wag.egov.egiz.sig.connectors.LocalConnector; import at.knowcenter.wag.egov.egiz.sig.connectors.bku.BKUPostConnection; -import at.knowcenter.wag.egov.egiz.sig.connectors.bku.EnvelopedBase64BKUConnector; -import at.knowcenter.wag.egov.egiz.sig.connectors.bku.LocRefDetachedBKUConnector; import at.knowcenter.wag.egov.egiz.web.FormFields; import at.knowcenter.wag.egov.egiz.web.LocalRequest; -import at.knowcenter.wag.egov.egiz.web.SessionAttributes; -import at.knowcenter.wag.egov.egiz.web.SessionInformation; /** * @author wprinz @@ -71,9 +76,10 @@ public class DataURLServlet extends HttpServlet } protected void dispatchToResults(List results, HttpServletRequest request, - HttpServletResponse response) throws ServletException, IOException + HttpServletResponse response, String backToListURL) throws ServletException, IOException { request.setAttribute("results", results); + request.setAttribute("btlurl", backToListURL); dispatch(request, response, "/jsp/results.jsp"); } @@ -85,122 +91,171 @@ public class DataURLServlet extends HttpServlet { log.debug("Data URL is accessed."); //$NON-NLS-1$ - HttpSession session = request.getSession(false); - if (session == null) + try { - String msg = "There is no session associated with this request."; //$NON-NLS-1$ - log.error(msg); - throw new ServletException(msg); - } + Object sessionObject = SessionHelper.getSession(request); + + checkRequestCharacterEncoding(request); + + if (sessionObject instanceof SignSessionInformation) + { + SignSessionInformation si = (SignSessionInformation)sessionObject; + processSign(request, response, si); + } + else + { + VerifySessionInformation si = (VerifySessionInformation) sessionObject; + processVerify(request, response, si); + } - SessionInformation si = (SessionInformation) session.getAttribute(SessionAttributes.ATTRIBUTE_SESSION_INFORMATION); - if (si == null) + } + catch (PresentableException e) { - String msg = "The session is not found or no longer valid."; //$NON-NLS-1$ - log.error(msg); - throw new ServletException(msg); + log.error(e); + SignServlet.prepareDispatchToErrorPage(e, request); + dispatch(request, response, "/jsp/error.jsp"); } - try + log.debug("DataURL access finished."); //$NON-NLS-1$ + } + + protected void checkRequestCharacterEncoding(HttpServletRequest request) throws UnsupportedEncodingException + { + log.debug("Request character encoding = " + request.getCharacterEncoding()); //$NON-NLS-1$ +// if (request.getCharacterEncoding() == null || request.getCharacterEncoding().equals("UTF-8")) //$NON-NLS-1$ + if (request.getCharacterEncoding() == null || request.getCharacterEncoding().length() <= 0) //$NON-NLS-1$ + { + log.error("The BKU didn't set a character encoding for the request."); //$NON-NLS-1$ + + log.warn("Manually setting character encoding to UTF-8"); //$NON-NLS-1$ + request.setCharacterEncoding("UTF-8"); //$NON-NLS-1$ + } + } + + protected boolean isNullResponse(String xml_response) + { + return xml_response.indexOf("NullOperationResponse") >= 0; + } + + protected void processSign(HttpServletRequest request, HttpServletResponse response, SignSessionInformation si) throws ServletException, IOException, ConnectorException, SignatorException, SignatorFactoryException + { + log.trace("processSign"); + + String xml_response = request.getParameter("XMLResponse"); //$NON-NLS-1$ + log.debug("xml_response = " + xml_response); //$NON-NLS-1$ + + if (isNullResponse(xml_response)) { - log.debug("Request character encoding = " + request.getCharacterEncoding()); //$NON-NLS-1$ - if (request.getCharacterEncoding() == null || request.getCharacterEncoding().equals("UTF-8")) //$NON-NLS-1$ - { - log.error("The BKU didn't set a character encoding for the request."); //$NON-NLS-1$ + log.debug("Received a NullOperationResponse -> answering with the first request."); //$NON-NLS-1$ - log.warn("Manually setting character encoding to UTF-8"); //$NON-NLS-1$ - request.setCharacterEncoding("UTF-8"); //$NON-NLS-1$ - } + assert si.outputAvailable == false; + assert si.response_properties == null; + + log.debug("There are still requests to be performed -> answering with request."); //$NON-NLS-1$ - String xml_response = request.getParameter("XMLResponse"); //$NON-NLS-1$ - log.debug("xml_response = " + xml_response); //$NON-NLS-1$ + LocalRequest local_request = si.localRequest; - if (isNullResponse(xml_response)) - { - log.debug("Received a NullOperationResponse -> answering with the first request."); //$NON-NLS-1$ + String request_string = local_request.getRequestString(); - assert si.current_operation == 0; - } - else + response.setContentType("text/xml"); + response.setCharacterEncoding("UTF-8"); + response.getWriter().println(request_string); + } + else + { + log.debug("Recieved a normal response -> storing the response."); //$NON-NLS-1$ + + Properties response_properties = new Properties(); + response_properties.setProperty(BKUPostConnection.RESPONSE_STRING_KEY, xml_response); + si.response_properties = response_properties; + + log.debug("All requests have been processed -> processing the responses."); //$NON-NLS-1$ + + // Sign + + if (!si.outputAvailable) { - log.debug("Recieved a normal response -> storing the response."); //$NON-NLS-1$ + LocalConnector c = ConnectorChooser.chooseLocalConnectorForSign(si.connector, si.type, "loc ref content not needed here"); //$NON-NLS-1$ + + si.si.setSignSignatureObject(c.analyzeSignResponse(si.response_properties)); - Properties response_properties = new Properties(); - response_properties.setProperty(BKUPostConnection.RESPONSE_STRING_KEY, xml_response); - si.response_properties[si.current_operation] = response_properties; + PdfASID algorithm = FormFields.translateSignatureModeToPdfASID(si.mode); + Signator signator = SignatorFactory.createSignator(algorithm); - si.current_operation++; + si.output = TempDirHelper.createTempDataSink(si.filename + "_signed.pdf"); + + signator.finishSign(si.si, si.output); + + si.outputAvailable = true; } - if (si.current_operation < si.requests.length) - { - log.debug("There are still requests to be performed -> answering with request #" + si.current_operation); //$NON-NLS-1$ + SignServletHelper.returnSignResponse(si, response); - LocalRequest local_request = si.requests[si.current_operation]; + } + } + + protected void processVerify(HttpServletRequest request, HttpServletResponse response, VerifySessionInformation si) throws ServletException, IOException, ConnectorException, InvalidIDException + { + log.trace("processVerify"); + + String xml_response = request.getParameter("XMLResponse"); //$NON-NLS-1$ + log.debug("xml_response = " + xml_response); //$NON-NLS-1$ - String request_string = local_request.getRequestString(); + if (isNullResponse(xml_response)) + { + log.debug("Received a NullOperationResponse -> answering with the first request."); //$NON-NLS-1$ - response.setContentType("text/xml"); - response.setCharacterEncoding("UTF-8"); - response.getWriter().println(request_string); - } - else - { - log.debug("All requests have been processed -> processing the responses."); //$NON-NLS-1$ + assert si.currentLocalOperation.current_operation == 0; + } + else + { + log.debug("Recieved a normal response -> storing the response."); //$NON-NLS-1$ - if (si.application.equals("sign")) - { - // Sign - - if (si.sign_result == null) - { - LocalConnector c = ConnectorChooser.chooseLocalConnectorForSign(si.connector, si.type, "loc ref content not needed here"); //$NON-NLS-1$ + Properties response_properties = new Properties(); + response_properties.setProperty(BKUPostConnection.RESPONSE_STRING_KEY, xml_response); - si.iui.signed_signature_object = c.analyzeSignResponse(si.response_properties[0]); + si.currentLocalOperation.finishCurrentOperation(response_properties); + } - PdfASID algorithm = FormFields.translateSignatureModeToPdfASID(si.mode); - Signator signator = SignatorFactory.createSignator(algorithm); + if (!si.currentLocalOperation.isFinished()) + { + log.debug("There are still requests to be performed -> answering with request #" + si.currentLocalOperation.current_operation); //$NON-NLS-1$ - si.sign_result = signator.finishSign(si.iui); - } + LocalRequest local_request = si.currentLocalOperation.getCurrentLocalRequest(); - SignServlet.returnSignResponse(si, response); - } - else + String request_string = local_request.getRequestString(); + + response.setContentType("text/xml"); + response.setCharacterEncoding("UTF-8"); + response.getWriter().println(request_string); + } + else + { + log.debug("All requests have been processed -> processing the responses."); //$NON-NLS-1$ + + + List results = new ArrayList(); + + for (int i = 0; i < si.currentLocalOperation.response_properties.length; i++) { - // Verify + SignatureHolder sh = (SignatureHolder) si.currentLocalOperation.holders_to_be_verified.get(i); + + PdfASID sig_kz = sh.getSignatureObject().getKZ(); + String sig_id = sh.getSignatureObject().getSignationIds(); - List results = new ArrayList(); - - for (int i = 0; i < si.response_properties.length; i++) - { - SignatureHolder sh = (SignatureHolder) si.signature_holders.get(i); - - PdfASID sig_kz = sh.getSignatureObject().getKZ(); - String sig_id = sh.getSignatureObject().getSignationIds(); - - LocalConnector c = ConnectorChooser.chooseLocalConnectorForVerify(si.connector, sig_kz, sig_id, si.type, "loc ref content not needed here"); //$NON-NLS-1$ - - SignatureResponse sig_resp = c.analyzeVerifyResponse(si.response_properties[i]); - results.add(sig_resp); - } - - dispatchToResults(results, request, response); + LocalConnector c = ConnectorChooser.chooseLocalConnectorForVerify(si.connector, sig_kz, sig_id, si.type, "loc ref content not needed here"); //$NON-NLS-1$ + + SignatureResponse sig_resp = c.analyzeVerifyResponse(si.currentLocalOperation.response_properties[i]); + results.add(sig_resp); } - } - } - catch (PresentableException e) - { - log.error(e); - SignServlet.prepareDispatchToErrorPage(e, request); - dispatch(request, response, "/jsp/error.jsp"); - } + + si.currentLocalOperation = null; - log.debug("DataURL access finished."); //$NON-NLS-1$ - } + URL btlURL = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), request.getContextPath() + "/jsp/verifylist.jsp"); + String backToListURL = response.encodeURL(btlURL.toString()); + + dispatchToResults(results, request, response, backToListURL); + } - protected boolean isNullResponse(String xml_response) - { - return xml_response.indexOf("NullOperationResponse") >= 0; } } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/RetrieveSignatureDataServlet.java b/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/RetrieveSignatureDataServlet.java index 402170c..6653a60 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/RetrieveSignatureDataServlet.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/RetrieveSignatureDataServlet.java @@ -5,22 +5,29 @@ package at.knowcenter.wag.egov.egiz.web.servlets; import java.io.IOException; +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; + +import at.gv.egiz.pdfas.impl.input.TextDataSourceImpl; +import at.gv.egiz.pdfas.exceptions.web.SessionExpiredException; +import at.gv.egiz.pdfas.framework.input.DataSource; +import at.gv.egiz.pdfas.web.SignSessionInformation; +import at.gv.egiz.pdfas.web.VerifySessionInformation; +import at.gv.egiz.pdfas.web.helper.SessionHelper; +import at.gv.egiz.pdfas.utils.StreamUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import at.knowcenter.wag.egov.egiz.PdfAS; +import at.knowcenter.wag.egov.egiz.pdf.BinarySignatureHolder; import at.knowcenter.wag.egov.egiz.pdf.SignatureHolder; import at.knowcenter.wag.egov.egiz.sig.SignatureData; import at.knowcenter.wag.egov.egiz.sig.SignatureDataImpl; -import at.knowcenter.wag.egov.egiz.sig.SignatureObject; -import at.knowcenter.wag.egov.egiz.tools.CodingHelper; -import at.knowcenter.wag.egov.egiz.web.SessionAttributes; -import at.knowcenter.wag.egov.egiz.web.SessionInformation; /** * Retrieves the Signature Data from the session and returns it. @@ -40,61 +47,103 @@ public class RetrieveSignatureDataServlet extends HttpServlet */ private static Log log = LogFactory.getLog(RetrieveSignatureDataServlet.class); + protected void dispatch(HttpServletRequest request, + HttpServletResponse response, String resource) throws ServletException, IOException + { + dispatch(request, response, resource, getServletContext()); + } + + protected 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); + } + /** - * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Request for receiving signature data."); //$NON-NLS-1$ - - HttpSession session = request.getSession(false); - if (session == null) + + try { - String msg = "There is no session associated with this request."; //$NON-NLS-1$ - log.error(msg); - throw new ServletException(msg); + Object sessionObject = SessionHelper.getSession(request); + + if (sessionObject instanceof SignSessionInformation) + { + SignSessionInformation si = (SignSessionInformation) sessionObject; + processSign(request, response, si); } - - SessionInformation si = (SessionInformation) session.getAttribute(SessionAttributes.ATTRIBUTE_SESSION_INFORMATION); - if (si == null) + else { - String msg = "The session is not found or no longer valid."; //$NON-NLS-1$ - log.error(msg); - throw new ServletException(msg); + VerifySessionInformation si = (VerifySessionInformation) sessionObject; + processVerify(request, response, si); } - + } + catch (SessionExpiredException e) + { + log.error(e); + SignServlet.prepareDispatchToErrorPage(e, request); + dispatch(request, response, "/jsp/error.jsp"); + } + } + + protected void processSign(HttpServletRequest request, HttpServletResponse response, SignSessionInformation si) throws ServletException, IOException + { + writeSignatureData(si.si.getSignatureData(), response); + } + + protected void processVerify(HttpServletRequest request, HttpServletResponse response, VerifySessionInformation si) throws ServletException, IOException + { SignatureData sd = null; - if (si.application.equals("sign")) + + SignatureHolder holder = null; + + if (si.currentLocalOperation != null) { - sd = si.iui.signature_data; + holder = si.currentLocalOperation.getCurrentSignatureHolder(); } else { - SignatureHolder holder = (SignatureHolder) si.signature_holders.get(si.current_operation); - SignatureObject s = holder.getSignatureObject(); - - // TODO make better - String text_to_be_verified = holder.getSignedText(); - if (holder.getSignatureObject().isBinary()) - { - byte[] data = CodingHelper.decodeBase64(text_to_be_verified); - sd = new SignatureDataImpl(data, "application/pdf"); - } - else - { - sd = new SignatureDataImpl(text_to_be_verified.getBytes("UTF-8"), "text/plain", "UTF-8"); - } - + holder = si.moa_holder; } + + log.debug("holder = " + holder.toString()); - log.debug("Writing " + sd.getMimeType() + " data:"); //$NON-NLS-1$ //$NON-NLS-2$ + sd = PdfAS.convertSignatureHolderToSignatureData(holder); +// if (holder.getSignatureObject().isBinary()) +// { +// BinarySignatureHolder bsh = (BinarySignatureHolder) holder; +// // byte[] data = CodingHelper.decodeBase64(text_to_be_verified); +// sd = new SignatureDataImpl(bsh.getSignedPdf(), "application/pdf"); +// } +// else +// { +// String text_to_be_verified = holder.getSignedText(); +// DataSource ds = new TextDataSourceImpl(text_to_be_verified); +// sd = new SignatureDataImpl(ds, "text/plain", "UTF-8"); +// } + log.debug("sd = " + sd.toString() + ", " + sd.getDataSource().getClass().getName() + ", " + sd.getDataSource().getLength() + ", " + sd.getMimeType() + ", " + sd.getCharacterEncoding()); + + writeSignatureData(sd, response); + } + + protected void writeSignatureData(SignatureData sd, HttpServletResponse response) throws IOException + { + log.trace("Writing " + sd.getMimeType() + " data:"); //$NON-NLS-1$ //$NON-NLS-2$ + response.setContentType(sd.getMimeType()); response.setCharacterEncoding(sd.getCharacterEncoding()); - response.getOutputStream().write(sd.getData()); - - log.debug("Writing SignatureData finished."); //$NON-NLS-1$ - } + StreamUtils.writeInputStreamToOutputStream(sd.getDataSource().createInputStream(), response.getOutputStream()); + // response.getOutputStream().write(sd.getData()); - + log.trace("Writing SignatureData finished."); //$NON-NLS-1$ + } } diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/SignPreviewServlet.java b/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/SignPreviewServlet.java index 1d8ee0b..aec4f25 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/SignPreviewServlet.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/SignPreviewServlet.java @@ -24,13 +24,11 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import at.knowcenter.wag.egov.egiz.exceptions.ErrorCodeException; +import at.gv.egiz.pdfas.web.SignSessionInformation; +import at.gv.egiz.pdfas.web.helper.SessionHelper; +import at.gv.egiz.pdfas.web.helper.SignServletHelper; import at.knowcenter.wag.egov.egiz.exceptions.PresentableException; -import at.knowcenter.wag.egov.egiz.web.FormFields; -import at.knowcenter.wag.egov.egiz.web.SessionAttributes; -import at.knowcenter.wag.egov.egiz.web.SessionInformation; /** * @author wprinz @@ -55,34 +53,13 @@ public class SignPreviewServlet extends HttpServlet protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - SessionInformation si = null; try { - HttpSession session = request.getSession(false); - if (session == null) - { - throw new ErrorCodeException(600, "The session is missing."); - } - - si = (SessionInformation) session.getAttribute(SessionAttributes.ATTRIBUTE_SESSION_INFORMATION); - if (si == null) - { - throw new ErrorCodeException(600, "The session is not found or is no longer valid."); - } - - } - catch (PresentableException e) - { - e.printStackTrace(); - SignServlet.prepareDispatchToErrorPage(e, request); - dispatch(request, response, "/jsp/error.jsp"); - - return; - } - - try - { - SignServlet.finishSign(si, request, response, getServletContext()); + Object sessionObject = SessionHelper.getSession(request); + + SignSessionInformation si = (SignSessionInformation) sessionObject; + + SignServletHelper.finishSign(si, request, response, getServletContext()); } catch (PresentableException e) { diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/SignServlet.java b/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/SignServlet.java index 54be8df..3f1342d 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/SignServlet.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/SignServlet.java @@ -22,12 +22,10 @@ import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.Iterator; import java.util.List; -import java.util.Properties; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; @@ -35,7 +33,14 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; + +import at.gv.egiz.pdfas.exceptions.ErrorCode; +import at.gv.egiz.pdfas.exceptions.ErrorCodeHelper; +import at.gv.egiz.pdfas.exceptions.external.ExternalErrorException; +import at.gv.egiz.pdfas.impl.input.FileBasedPdfDataSourceImpl; +import at.gv.egiz.pdfas.web.SignSessionInformation; +import at.gv.egiz.pdfas.web.helper.SignServletHelper; +import at.gv.egiz.pdfas.web.helper.TempDirHelper; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; @@ -43,39 +48,16 @@ import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.log4j.Logger; import at.knowcenter.wag.egov.egiz.PdfAS; -import at.knowcenter.wag.egov.egiz.PdfASID; -import at.knowcenter.wag.egov.egiz.cfg.ConfigLogger; import at.knowcenter.wag.egov.egiz.cfg.SettingsReader; -import at.knowcenter.wag.egov.egiz.exceptions.ErrorCodeException; import at.knowcenter.wag.egov.egiz.exceptions.PDFDocumentException; import at.knowcenter.wag.egov.egiz.exceptions.PlaceholderException; import at.knowcenter.wag.egov.egiz.exceptions.PresentableException; -import at.knowcenter.wag.egov.egiz.framework.SignResult; -import at.knowcenter.wag.egov.egiz.framework.Signator; -import at.knowcenter.wag.egov.egiz.framework.SignatorFactory; -import at.knowcenter.wag.egov.egiz.framework.signators.DetachedSignator_1_0_0; import at.knowcenter.wag.egov.egiz.pdf.TablePos; -import at.knowcenter.wag.egov.egiz.sig.ConnectorFactory; -import at.knowcenter.wag.egov.egiz.sig.SignatureData; -import at.knowcenter.wag.egov.egiz.sig.SignatureDataImpl; -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.LocalConnector; -import at.knowcenter.wag.egov.egiz.sig.connectors.bku.DetachedBKUConnector; -import at.knowcenter.wag.egov.egiz.sig.connectors.bku.EnvelopedBase64BKUConnector; -import at.knowcenter.wag.egov.egiz.sig.connectors.bku.LocRefDetachedBKUConnector; -import at.knowcenter.wag.egov.egiz.sig.connectors.moa.DetachedLocRefMOAConnector; -import at.knowcenter.wag.egov.egiz.tools.CodingHelper; import at.knowcenter.wag.egov.egiz.web.ExternAppInformation; import at.knowcenter.wag.egov.egiz.web.FormFields; -import at.knowcenter.wag.egov.egiz.web.LocalRequest; -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.SessionInformation; /** * This method is the sign servlet for the pdf-as web application. It takes get @@ -97,15 +79,13 @@ public class SignServlet extends HttpServlet * The log. */ private static Log log = LogFactory.getLog(SignServlet.class); - - protected void dispatch(HttpServletRequest request, - HttpServletResponse response, String resource) throws ServletException, IOException + + protected void dispatch(HttpServletRequest request, HttpServletResponse response, String resource) throws ServletException, IOException { dispatch(request, response, resource, getServletContext()); } - protected static void dispatch(HttpServletRequest request, - HttpServletResponse response, String resource, ServletContext context) throws ServletException, IOException + protected static void dispatch(HttpServletRequest request, HttpServletResponse response, String resource, ServletContext context) throws ServletException, IOException { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); @@ -181,10 +161,11 @@ public class SignServlet extends HttpServlet UploadedData ud = null; ExternAppInformation exappinf = null; TablePos pos = null; - + // check if pdf-as has been called by external webapp - if(request.getParameter(FormFields.FIELD_PDF_URL) != null) { - + if (request.getParameter(FormFields.FIELD_PDF_URL) != null) + { + String preview = (String) request.getParameter(FormFields.FIELD_PREVIEW); String sig_type = (String) request.getParameter(FormFields.FIELD_SIGNATURE_TYPE); String sig_app = (String) request.getParameter(FormFields.FIELD_CONNECTOR); @@ -197,65 +178,74 @@ public class SignServlet extends HttpServlet String session_id = (String) request.getParameter(FormFields.FIELD_SESSION_ID); String sig_pos_y = (String) request.getParameter(FormFields.FIELD_SIGPOS_Y); String sig_pos_p = (String) request.getParameter(FormFields.FIELD_SIGPOS_P); - - try { - pos = new TablePos("y:" + sig_pos_y +";p:" + sig_pos_p); - } catch (PDFDocumentException e) { + + try + { + pos = new TablePos("y:" + sig_pos_y + ";p:" + sig_pos_p); + } + catch (PDFDocumentException e) + { log.warn("Uanable to create signature position object: " + e.getMessage()); } - - String query = pdf_url + "&" + FormFields.FIELD_PDF_ID + "=" + pdf_id; - - byte[] extern_pdf = new byte[Integer.parseInt(pdf_length)]; + + String query = pdf_url + "&" + FormFields.FIELD_PDF_ID + "=" + pdf_id; + + // wprinz: rem: this allocation is useless + // byte[] extern_pdf = new byte[Integer.parseInt(pdf_length)]; URL source_url = new URL(query); InputStream is = source_url.openStream(); - extern_pdf = toByteArray(is); - - // set UploadedData object... + // extern_pdf = toByteArray(is); + + // set UploadedData object... UploadedData ud_extern = new UploadedData(); ud_extern.file_name = filename; - ud_extern.pdf = extern_pdf; + ud_extern.pdfDataSource = TempDirHelper.placePdfIntoTempDir(is, filename); + // ud_extern.pdf = extern_pdf; ud_extern.preview = preview.equalsIgnoreCase("true") ? true : false; ud_extern.sig_app = sig_app; ud_extern.sig_mode = sig_mode; ud_extern.sig_type = sig_type; - + ud = ud_extern; - - exappinf = new ExternAppInformation(invoke_url,pdf_id, session_id); + + exappinf = new ExternAppInformation(invoke_url, pdf_id, session_id); } - else { - + else + { + try { // tzefferer: modified - //UploadedData ud = retrieveUploadedDataFromRequest(request); + // UploadedData ud = retrieveUploadedDataFromRequest(request); UploadedData ud_form = retrieveUploadedDataFromRequest(request); ud = ud_form; // end modify - - } catch(Exception e) { + + } + catch (Exception e) + { // Error retrieving data request.setAttribute("error", "Fehler beim Upload der Daten"); request.setAttribute("cause", "Beim Upload der Daten ist ein Fehler aufgetreten."); dispatch(request, response, "/jsp/error.jsp"); } } - try { + try + { - PdfAS.applyStrictMode(ud.pdf); + PdfAS.applyStrictMode(ud.pdfDataSource); - SessionInformation si = new SessionInformation(); // SessionTable.generateSessionInformationObject(); + SignSessionInformation si = new SignSessionInformation(); // SessionTable.generateSessionInformationObject(); si.connector = ud.sig_app; si.application = "sign"; si.mode = ud.sig_mode; - si.pdf = ud.pdf; + si.pdfDataSource = ud.pdfDataSource; si.type = ud.sig_type; si.filename = formatFileName(ud.file_name); si.download_inline = ud.download_inline; - + // added tzefferer: si.exappinf = exappinf; si.pos = pos; @@ -270,7 +260,7 @@ public class SignServlet extends HttpServlet // si.user_name = user_name; // si.user_password = user_password; - prepareSign(si); + SignServletHelper.prepareSign(si); if (ud.preview) { @@ -285,7 +275,7 @@ public class SignServlet extends HttpServlet return; } - finishSign(si, request, response, getServletContext()); + SignServletHelper.finishSign(si, request, response, getServletContext()); } catch (PresentableException e) { @@ -296,13 +286,13 @@ public class SignServlet extends HttpServlet } // tzefferer:added - public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { doPost(request, response); } // end add - - protected UploadedData retrieveUploadedDataFromRequest( - HttpServletRequest request) throws ServletException, UnsupportedEncodingException, FileUploadException, PDFDocumentException + + protected UploadedData retrieveUploadedDataFromRequest(HttpServletRequest request) throws ServletException, UnsupportedEncodingException, FileUploadException, PDFDocumentException { DiskFileItemFactory fif = new DiskFileItemFactory(); fif.setRepository(SettingsReader.getTemporaryDirectory()); @@ -413,12 +403,22 @@ public class SignServlet extends HttpServlet throw new PDFDocumentException(201, "The provided file '" + doc_file_name + "' doesn't have the PDF extension (.pdf)."); //$NON-NLS-1$//$NON-NLS-2$ } - byte[] pdf = file_upload_fi.get(); if (file_upload_fi.getSize() <= 0) { throw new PDFDocumentException(250, "The document is empty."); //$NON-NLS-1$ } + FileBasedPdfDataSourceImpl pdfDataSource = null; + try + { + pdfDataSource = TempDirHelper.placePdfIntoTempDir(file_upload_fi.getInputStream(), doc_file_name); + } + catch (IOException e) + { + throw new PDFDocumentException(201, "Couldn't store the file in the temp dir."); + } + // byte[] pdf = file_upload_fi.get(); + UploadedData ud = new UploadedData(); ud.preview = preview; @@ -427,129 +427,55 @@ public class SignServlet extends HttpServlet ud.sig_app = sig_app; ud.sig_mode = mode; ud.file_name = doc_file_name; - ud.pdf = pdf; + ud.pdfDataSource = pdfDataSource; return ud; } - /** - * 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(SessionInformation 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.iui = signator.prepareSign(si.pdf, si.type, si.pos, ConnectorFactory.needsSIG_ID(si.connector)); - // 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(SessionInformation si, - HttpServletRequest request, HttpServletResponse response, - ServletContext context) throws PresentableException, IOException, ServletException - { - log.debug("finishSign:"); //$NON-NLS-1$ - - 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(); - URL signature_data_URL = new URL(request.getScheme(), host, request.getServerPort(), request.getContextPath() + "/RetrieveSignatureData"); - String signature_data_url = response.encodeURL(signature_data_URL.toString()); - Connector c = ConnectorChooser.chooseWebConnectorForSign(si.connector, si.type, signature_data_url); - si.iui.signed_signature_object = c.doSign(si.iui.signature_data); - si.sign_result = signator.finishSign(si.iui); - returnSignResponse(si, response); - - log.debug("finishSign finished."); //$NON-NLS-1$ - } - - public static void prepareDispatchToErrorPage(PresentableException pe, - HttpServletRequest request) + public static void prepareDispatchToErrorPage(PresentableException pe, HttpServletRequest request) { - if (pe instanceof ErrorCodeException) - { - ErrorCodeException ece = (ErrorCodeException) pe; - request.setAttribute("error", "Fehler " + ece.getErrorCode()); + request.setAttribute("PresentableException", pe); +// if (pe instanceof ErrorCodeException) +// { + request.setAttribute("error", "Fehler " + pe.getErrorCode()); - String cause = ece.getErrorCodeMessage(); - if (ece.hasExternalErrorMessage()) + String cause = ErrorCodeHelper.getMessageForErrorCode(pe.getErrorCode()); + + if (pe instanceof ExternalErrorException) { - cause = ece.getExternalErrorCode() + ": " + ece.getExternalErrorMessage(); + ExternalErrorException eee = (ExternalErrorException) pe; + cause = eee.getExternalErrorCode() + ": " + eee.getExternalErrorMessage(); } request.setAttribute("cause", cause); - if (pe instanceof PlaceholderException) + if (pe.getErrorCode() == ErrorCode.PLACEHOLDER_EXCEPTION) { - PlaceholderException phe = (PlaceholderException) ece; + PlaceholderException phe = null; + if (pe instanceof PlaceholderException) + { + phe = (PlaceholderException) pe; + } + else + { + phe = (PlaceholderException) pe.getCause(); + } - request.setAttribute("cause", "Der Platzhalter des Feldes " + phe.getField() + " ist um " + phe.getMissing() + " Bytes zu kurz. " + ece.getErrorCodeMessage()); + request.setAttribute("cause", "Der Platzhalter des Feldes " + phe.getField() + " ist um " + phe.getMissing() + " Bytes zu kurz. " + cause); } - } - else - { - request.setAttribute("error", "PresentableException"); - request.setAttribute("cause", pe.toString()); - } +// } +// else +// { +// request.setAttribute("error", "PresentableException"); +// request.setAttribute("cause", pe.toString()); +// } } - public void dispatchToPreview(String document_text, String connector, - String mode, String signature_type, String submit_url, - HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + public void dispatchToPreview(String document_text, String connector, String mode, String signature_type, String submit_url, HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { request.setAttribute("document_text", document_text); request.setAttribute("connector", connector); @@ -576,112 +502,40 @@ public class SignServlet extends HttpServlet return file_name_only; } - /** - * 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, - SignResult sign_result) - { - String output = file_name + "_signed"; - if (sign_result.getMimeType().equals(DetachedSignator_1_0_0.MIME_TYPE)) - { - output += ".xml"; - } - else - { - output += ".pdf"; - } - return output; - } - /** - * Returns the data in the SignResult with proper content disposition. - * - * @param si - * SessionInformation. - * @param response - * The servlet response. - * @throws IOException - * The IO Exception. - */ - public static void returnSignResponse(SessionInformation si, - HttpServletResponse response) throws IOException - { - SignResult sign_result = si.sign_result; - - String file_name = formatFileNameForSignResult(si.filename, sign_result); - - // 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(sign_result.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 + "\""); - } - response.getOutputStream().write(sign_result.getData()); - // tzefferer: added else-block - } else { - SignResult sr = si.sign_result; - byte[] signed_pdf = sr.getData(); - 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; - - // build URL - int ind = invoke_url.indexOf("?"); - String query = invoke_url.substring(0, ind) + ";jsessionid=" + session_id + invoke_url.substring(ind) + "&" + FormFields.FIELD_PDF_URL + "=" + providePDFServlet + "&" + FormFields.FIELD_PDF_ID + "=" + pdf_id + "&" + FormFields.FIELD_FILE_LENGTH + "=" + signed_pdf.length; - response.sendRedirect(query); - - } - } - - // tzefferer: added - public static byte[] toByteArray(InputStream inputStream) throws IOException { - - if(inputStream == null) { + public static byte[] toByteArray(InputStream inputStream) throws IOException + { + + if (inputStream == null) + { return null; } - + ByteArrayOutputStream out = new ByteArrayOutputStream(8192); int n; byte[] buffer = new byte[2048]; BufferedInputStream bufIn = new BufferedInputStream(inputStream); - try { - while ((n = bufIn.read(buffer)) != -1) { + try + { + while ((n = bufIn.read(buffer)) != -1) + { out.write(buffer, 0, n); } - } finally { - if(bufIn != null) { + } + finally + { + if (bufIn != null) + { bufIn.close(); } } return out.toByteArray(); } + // end add protected static class UploadedData @@ -698,6 +552,7 @@ public class SignServlet extends HttpServlet protected String file_name = null; - protected byte[] pdf = null; + protected FileBasedPdfDataSourceImpl pdfDataSource = null; + // protected byte[] pdf = null; } } \ No newline at end of file diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/VerifyPreviewServlet.java b/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/VerifyPreviewServlet.java index 150b592..732e6cc 100644 --- a/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/VerifyPreviewServlet.java +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/servlets/VerifyPreviewServlet.java @@ -20,6 +20,7 @@ package at.knowcenter.wag.egov.egiz.web.servlets; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; +import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; @@ -30,19 +31,22 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.apache.log4j.Logger; - +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import at.gv.egiz.pdfas.framework.input.TextDataSource; +import at.gv.egiz.pdfas.utils.StreamUtils; +import at.gv.egiz.pdfas.web.VerifySessionInformation; +import at.gv.egiz.pdfas.web.helper.SessionHelper; +import at.gv.egiz.pdfas.web.helper.TempDirHelper; import at.knowcenter.wag.egov.egiz.PdfAS; import at.knowcenter.wag.egov.egiz.PdfASID; -import at.knowcenter.wag.egov.egiz.cfg.ConfigLogger; import at.knowcenter.wag.egov.egiz.cfg.SettingsReader; -import at.knowcenter.wag.egov.egiz.exceptions.ErrorCodeException; import at.knowcenter.wag.egov.egiz.exceptions.InvalidIDException; import at.knowcenter.wag.egov.egiz.exceptions.PresentableException; import at.knowcenter.wag.egov.egiz.exceptions.SignatureException; @@ -55,8 +59,6 @@ import at.knowcenter.wag.egov.egiz.sig.SignatureObject; import at.knowcenter.wag.egov.egiz.sig.SignatureTypes; import at.knowcenter.wag.egov.egiz.web.FormFields; import at.knowcenter.wag.egov.egiz.web.LocalRequestHelper; -import at.knowcenter.wag.egov.egiz.web.SessionAttributes; -import at.knowcenter.wag.egov.egiz.web.SessionInformation; /** * @author wprinz @@ -71,7 +73,7 @@ public class VerifyPreviewServlet extends HttpServlet /** * The logger. */ - private static final Logger logger_ = ConfigLogger.getLogger(VerifyPreviewServlet.class); + private static final Log logger_ = LogFactory.getLog(VerifyPreviewServlet.class); protected void dispatch(HttpServletRequest request, HttpServletResponse response, String resource) throws ServletException, IOException @@ -82,7 +84,29 @@ public class VerifyPreviewServlet extends HttpServlet RequestDispatcher disp = getServletContext().getRequestDispatcher(resource); disp.forward(request, response); } + + protected void dispatchToPreview(HttpServletRequest request, HttpServletResponse response, int verify_which)throws ServletException, IOException + { + request.setAttribute(FormFields.FIELD_VERIFY_WHICH, new Integer(verify_which)); + request.setAttribute("btlurl", formBackToListURL(request, response)); + dispatch(request, response, "/jsp/verifypreview.jsp"); + + } + protected void dispatchToDataOk(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException + { + request.setAttribute("btlurl", formBackToListURL(request, response)); + dispatch(request, response, "/jsp/dataok.jsp"); + } + + protected String formBackToListURL(HttpServletRequest request, HttpServletResponse response) throws MalformedURLException + { + URL btlURL = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), request.getContextPath() + "/jsp/verifylist.jsp"); + String backToListURL = response.encodeURL(btlURL.toString()); + + return backToListURL; + } + protected static String generateNamePrefix(int num) { return SIG_INPUT_PREFIX + num + "_"; @@ -249,6 +273,10 @@ public class VerifyPreviewServlet extends HttpServlet { continue; } + if (SignatureTypes.SIG_KZ.equals(key) && value == null) + { + continue; + } value = value.replaceAll("\\s", " "); value = value.replaceAll("\\\"", "\\\""); @@ -281,6 +309,10 @@ public class VerifyPreviewServlet extends HttpServlet { continue; } + if (SignatureTypes.SIG_KZ.equals(key) && value == null) + { + continue; + } writer.println("