From 6025b6016517c6d898d8957d1d7e03ba71431912 Mon Sep 17 00:00:00 2001 From: tknall Date: Fri, 1 Dec 2006 12:20:24 +0000 Subject: Initial import of release 2.2. git-svn-id: https://joinup.ec.europa.eu/svn/pdf-as/trunk@4 7b5415b0-85f9-ee4d-85bd-d5d0c3b42d1c --- .../egov/egiz/web/AsynchronousDataResponder.java | 155 +++++ .../egiz/web/AsynchronousRedirectResponder.java | 196 ++++++ .../knowcenter/wag/egov/egiz/web/FormFields.java | 210 ++++++ .../knowcenter/wag/egov/egiz/web/LocalRequest.java | 80 +++ .../wag/egov/egiz/web/LocalRequestHelper.java | 226 +++++++ .../egov/egiz/web/PdfASServletContextListener.java | 76 +++ .../wag/egov/egiz/web/SessionAttributes.java | 46 ++ .../wag/egov/egiz/web/SessionInformation.java | 126 ++++ .../knowcenter/wag/egov/egiz/web/SessionTable.java | 94 +++ .../java/at/knowcenter/wag/egov/egiz/web/Sign.java | 525 +++++++++++++++ .../knowcenter/wag/egov/egiz/web/SignPreview.java | 105 +++ .../at/knowcenter/wag/egov/egiz/web/Verify.java | 285 +++++++++ .../wag/egov/egiz/web/VerifyPreview.java | 704 +++++++++++++++++++++ 13 files changed, 2828 insertions(+) create mode 100644 src/main/java/at/knowcenter/wag/egov/egiz/web/AsynchronousDataResponder.java create mode 100644 src/main/java/at/knowcenter/wag/egov/egiz/web/AsynchronousRedirectResponder.java create mode 100644 src/main/java/at/knowcenter/wag/egov/egiz/web/FormFields.java create mode 100644 src/main/java/at/knowcenter/wag/egov/egiz/web/LocalRequest.java create mode 100644 src/main/java/at/knowcenter/wag/egov/egiz/web/LocalRequestHelper.java create mode 100644 src/main/java/at/knowcenter/wag/egov/egiz/web/PdfASServletContextListener.java create mode 100644 src/main/java/at/knowcenter/wag/egov/egiz/web/SessionAttributes.java create mode 100644 src/main/java/at/knowcenter/wag/egov/egiz/web/SessionInformation.java create mode 100644 src/main/java/at/knowcenter/wag/egov/egiz/web/SessionTable.java create mode 100644 src/main/java/at/knowcenter/wag/egov/egiz/web/Sign.java create mode 100644 src/main/java/at/knowcenter/wag/egov/egiz/web/SignPreview.java create mode 100644 src/main/java/at/knowcenter/wag/egov/egiz/web/Verify.java create mode 100644 src/main/java/at/knowcenter/wag/egov/egiz/web/VerifyPreview.java (limited to 'src/main/java/at/knowcenter/wag/egov/egiz/web') diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/web/AsynchronousDataResponder.java b/src/main/java/at/knowcenter/wag/egov/egiz/web/AsynchronousDataResponder.java new file mode 100644 index 0000000..847bbcf --- /dev/null +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/AsynchronousDataResponder.java @@ -0,0 +1,155 @@ +/** + * Copyright (c) 2006 by Know-Center, Graz, Austria + * + * This software is the confidential and proprietary information of Know-Center, + * Graz, Austria. You shall not disclose such Confidential Information and shall + * use it only in accordance with the terms of the license agreement you entered + * into with Know-Center. + * + * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF + * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR + * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY + * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. + * + * $Id: AsynchronousDataResponder.java,v 1.3 2006/08/30 14:02:35 wprinz Exp $ + */ +package at.knowcenter.wag.egov.egiz.web; + +import java.io.IOException; +import java.util.List; + +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 at.knowcenter.wag.egov.egiz.cfg.ConfigLogger; +import at.knowcenter.wag.egov.egiz.cfg.SettingsReader; + +/** + * Servlet that responds to the data post requests of the local service (e.g. + * BKU). + * + * @author wprinz + */ +public class AsynchronousDataResponder extends HttpServlet +{ + + /** + * SVUID. + */ + private static final long serialVersionUID = -4992297156381763174L; + + /** + * The logger definition. + */ + private static final Logger logger_ = ConfigLogger.getLogger(AsynchronousDataResponder.class); + + protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException + { + logger_.debug("AsyncDataResp GET REQUEST."); + super.doGet(arg0, arg1); + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + logger_.debug("AsyncDataResp !!!!!!!!!!!!!!!!!!!!!!"); + + HttpSession session = request.getSession(false); + if (session == null) + { + throw new ServletException("There is no session associated with this request."); + } + + // String session_id_string = request.getParameter("session"); + // if (session_id_string == null) + // { + // throw new ServletException("The session parameter is missing."); + // } + + SessionInformation si = (SessionInformation) session.getAttribute(SessionAttributes.ATTRIBUTE_SESSION_INFORMATION); + // long session_id = Long.parseLong(session_id_string); + // SessionInformation si = SessionTable.get(session_id); + if (si == null) + { + throw new ServletException("The session is not found or no longer valid."); + } + + // InputStream is = request.getInputStream(); + // byte [] data = new byte[request.getContentLength()]; + // is.read(data); + // is.close(); + // String enc = request.getCharacterEncoding(); + // String ct = request.getContentType(); + // Enumeration enum = request.getHeaderNames(); + // + // String dat = new String(data, "US-ASCII"); + // // dat looks like: XMLResponse=blablabla ... + // // so the actual XMLResponse begins after the = + // String resp = URLDecoder.decode(dat, "UTF-8"); + + logger_.debug("Answer from local service: content-type = '" + request.getContentType() + "', character encoding = '" + request.getCharacterEncoding() + "'"); + + // .getParameter will use the character encoding specified by the + // content-type header. + // Unfortunately BKU forgets to specify a chatacter encoding. + // Therefor, .getParameter will assume US-ASCII or something. + // ==> we explicitely set UTF-8 + if (request.getCharacterEncoding() == null) + { + request.setCharacterEncoding("UTF-8"); + logger_.debug(" no character encoding specified - set to UTF-8"); + } + + logger_.debug("AsyncDataResponder: si.current_operation = " + si.current_operation); + + String resp_string = request.getParameter("XMLResponse"); + if (resp_string == null) + { + logger_.debug("response String is null => trying multipart form"); + + DiskFileItemFactory fif = new DiskFileItemFactory(); + fif.setRepository(SettingsReader.getTemporaryDirectory()); + ServletFileUpload sfu = new ServletFileUpload(fif); + + try + { + List items = sfu.parseRequest(request); + + for (int i = 0; i < items.size(); i++) + { + FileItem item = (FileItem) items.get(i); + logger_.debug("item = " + item.getFieldName()); + + if (item.getFieldName().equals("XMLResponse")) + { + resp_string = item.getString("UTF-8"); + } + } + } + catch (FileUploadException e) + { + throw new ServletException("File Upload exception. cannot parse POST data"); + } + + } + + si.response_string[si.current_operation] = resp_string; //request.getParameter("XMLResponse"); + //logger_.debug("AsyncDataResponder: si.response_string[si.current_operation] = " + si.response_string[si.current_operation]); + + si.current_operation++; + + si.finished = true; + + LocalRequestHelper.formatBKUOkResponse(response); + } +} diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/web/AsynchronousRedirectResponder.java b/src/main/java/at/knowcenter/wag/egov/egiz/web/AsynchronousRedirectResponder.java new file mode 100644 index 0000000..fb5d2e3 --- /dev/null +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/AsynchronousRedirectResponder.java @@ -0,0 +1,196 @@ +/** + * Copyright (c) 2006 by Know-Center, Graz, Austria + * + * This software is the confidential and proprietary information of Know-Center, + * Graz, Austria. You shall not disclose such Confidential Information and shall + * use it only in accordance with the terms of the license agreement you entered + * into with Know-Center. + * + * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF + * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR + * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY + * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. + * + * $Id: AsynchronousRedirectResponder.java,v 1.4 2006/10/11 07:39:13 wprinz Exp $ + */ +package at.knowcenter.wag.egov.egiz.web; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.RequestDispatcher; +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.log4j.Logger; + +import at.knowcenter.wag.egov.egiz.PdfASID; +import at.knowcenter.wag.egov.egiz.cfg.ConfigLogger; +import at.knowcenter.wag.egov.egiz.exceptions.ErrorCodeException; +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.sig.ConnectorFactory; +import at.knowcenter.wag.egov.egiz.sig.SignatureResponse; +import at.knowcenter.wag.egov.egiz.sig.connectors.BKUConnector; + +/** + * Servlet that responds to the redirect requests of the local service (e.g. + * BKU). + * + * @author wprinz + */ +public class AsynchronousRedirectResponder extends HttpServlet +{ + + /** + * SVUID. + */ + private static final long serialVersionUID = -682360466333727236L; + + /** + * The logger definition. + */ + private static final Logger logger_ = ConfigLogger.getLogger(AsynchronousRedirectResponder.class); + + protected void dispatch(HttpServletRequest request, + HttpServletResponse response, String resource) throws ServletException, IOException + { + response.setContentType("text/html"); + response.setCharacterEncoding("UTF-8"); + + RequestDispatcher disp = getServletContext().getRequestDispatcher(resource); + disp.forward(request, response); + } + + protected void dispatchToResults(List results, HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException + { + request.setAttribute("results", results); + dispatch(request, response, "/jsp/results.jsp"); + } + + protected void dispatchToRedirectRefreshPage (HttpServletRequest request, + HttpServletResponse response, String refresh_url) throws ServletException, IOException + { + request.setAttribute("refresh_url", refresh_url); + dispatch(request, response, LocalRequestHelper.REDIRECT_REFRESH_PAGE_JSP); + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + logger_.debug("AsyncRedirResp"); + + SessionInformation si = null; + + HttpSession session = null; + try + { + session = request.getSession(false); + //String session_id_string = request.getParameter("session"); + if (session == null) + { + throw new ErrorCodeException(600, "The session is missing."); + } + + si = (SessionInformation) session.getAttribute(SessionAttributes.ATTRIBUTE_SESSION_INFORMATION); +// long session_id = Long.parseLong(session_id_string); +// si = SessionTable.get(session_id); + if (si == null) + { + throw new ErrorCodeException(600, "The session is not found or is no longer valid."); + } + + } + catch (PresentableException e) + { + e.printStackTrace(); + Sign.prepareDispatchToErrorPage(e, request); + dispatch(request, response, "/jsp/error.jsp"); + + return; + } + + try + { + if (si.finished == false) + { + String url = request.getRequestURL().toString(); + logger_.debug("RequestURL = " + url); + String refresh_url = response.encodeURL(url); + logger_.debug("RefreshURL = " + refresh_url); + dispatchToRedirectRefreshPage(request, response, refresh_url); + return; + } + + si.finished = false; + + if (si.current_operation < si.requests.length) + { + LocalRequestHelper.prepareDispatchToLocalConnectionPage(si.requests[si.current_operation], request, response); + dispatch(request, response, LocalRequestHelper.LOCAL_CONNECTION_PAGE_JSP); + return; + } + + // all requests have been carried out. + //session.removeAttribute(SessionAttributes.ATTRIBUTE_SESSION_INFORMATION); + //SessionTable.remove(si.session_id); + + BKUConnector local_conn = (BKUConnector) ConnectorFactory.createConnector(si.connector); + + if (si.application.equals("verify")) + { + List results = new ArrayList(); + + for (int i = 0; i < si.response_string.length; i++) + { + SignatureResponse sig_resp = local_conn.analyzeVerifyResponse(si.response_string[i]); + results.add(sig_resp); + } + + dispatchToResults(results, request, response); + } + else + { + //logger_.debug("AsyncRedirResponder: si.response_string[0] = " + si.response_string[0]); + logger_.debug("AsyncRedirResponder: si.current_op = " + si.current_operation); + + if (si.response_string[0] == null) + { + String url = request.getRequestURL().toString(); + logger_.debug("RequestURL = " + url); + String refresh_url = response.encodeURL(url); + logger_.debug("RefreshURL = " + refresh_url); + dispatchToRedirectRefreshPage(request, response, refresh_url); + return ; + } + + si.iui.signed_signature_object = local_conn.analyzeSignResponse(si.response_string[0], si.type); + + PdfASID algorithm = FormFields.translateSignatureModeToPdfASID(si.mode); + Signator signator = SignatorFactory.createSignator(algorithm); + + si.sign_result = signator.finishSign(si.iui); + + Sign.returnSignResponse(si, response); + } + + } + catch (PresentableException e) + { + session.removeAttribute(SessionAttributes.ATTRIBUTE_SESSION_INFORMATION); + //SessionTable.remove(si.session_id); + + e.printStackTrace(); + Sign.prepareDispatchToErrorPage(e, request); + dispatch(request, response, "/jsp/error.jsp"); + } + + } +} diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/web/FormFields.java b/src/main/java/at/knowcenter/wag/egov/egiz/web/FormFields.java new file mode 100644 index 0000000..6331a54 --- /dev/null +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/FormFields.java @@ -0,0 +1,210 @@ +/** + * Copyright (c) 2006 by Know-Center, Graz, Austria + * + * This software is the confidential and proprietary information of Know-Center, + * Graz, Austria. You shall not disclose such Confidential Information and shall + * use it only in accordance with the terms of the license agreement you entered + * into with Know-Center. + * + * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF + * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR + * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY + * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. + * + * $Id: FormFields.java,v 1.4 2006/10/11 07:39:13 wprinz Exp $ + */ +package at.knowcenter.wag.egov.egiz.web; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Iterator; + +import javax.servlet.ServletException; + +import at.knowcenter.wag.egov.egiz.PdfASID; +import at.knowcenter.wag.egov.egiz.cfg.SettingsReader; +import at.knowcenter.wag.egov.egiz.exceptions.ConnectorFactoryException; +import at.knowcenter.wag.egov.egiz.exceptions.SettingsException; +import at.knowcenter.wag.egov.egiz.framework.SignatorFactory; +import at.knowcenter.wag.egov.egiz.sig.ConnectorFactory; +import at.knowcenter.wag.egov.egiz.sig.ConnectorInformation; +import at.knowcenter.wag.egov.egiz.sig.SignatureTypes; + +/** + * Helper class that provides methods and constants for creating and dealing + * with the various form fields. + * + * @author wprinz + */ +public abstract class FormFields +{ + public static final String PARAMETER_FREE_TEXT_ENTRY = "freetext"; + + public static final String FIELD_UPLOAD = "upload"; + + public static final String FIELD_CONNECTOR = "connector"; + + public static final String FIELD_MODE = "mode"; + + public static final String FIELD_PREVIEW = "preview"; + + public static final String FIELD_RAW_DOCUMENT_TEXT = "raw_document_text"; + + public static final String FIELD_SIGNATURE_TYPE = "sig_type"; + + public static final String FIELD_VERIFY_WHICH = "verify_which"; + + public static final String FIELD_DOWNLOAD = "download"; + + public static final String VALUE_TRUE = "true"; + + public static final String VALUE_FALSE = "false"; + + public static final String VALUE_MODE_BINARY = "binary"; + + public static final String VALUE_MODE_TEXTUAL = "textual"; + + public static final String VALUE_MODE_DETACHED = "detached"; + + public static final String VALUE_VERIFY_WHICH_ALL = "all"; + + public static final String VALUE_DOWNLOAD_INLINE = "inline"; + + public static final String VALUE_DOWNLOAD_ATTACHMENT = "attachment"; + + protected static final String STYLE_CLASS_FIELD = "field"; + + /** + * Translates the form field to a PDF-AS-ID. + * + * @param signature_mode + * The signator mode form field. + * @return Returns the corresponding PDFASID. + */ + protected static PdfASID translateSignatureModeToPdfASID(String signature_mode) + { + if (signature_mode.equals(VALUE_MODE_BINARY)) + { + return SignatorFactory.MOST_RECENT_BINARY_SIGNATOR_ID; + } + if (signature_mode.equals(VALUE_MODE_TEXTUAL)) + { + return SignatorFactory.MOST_RECENT_TEXTUAL_SIGNATOR_ID; + } + if (signature_mode.equals(VALUE_MODE_DETACHED)) + { + return SignatorFactory.MOST_RECENT_DETACHED_SIGNATOR_ID; + } + return null; + } + + /** + * Generates the HTML snippet of a FIELD_CONNECTOR select box that allows to + * choose a connector. + * + * @return Returns the HTML snippet. + * @throws SettingsException + * Forwarded exception. + * @throws ConnectorFactoryException + * Forwarded exception. + */ + public static String generateConnectorSelectBox() throws SettingsException, ConnectorFactoryException + { + StringWriter sw = new StringWriter(); + PrintWriter writer = new PrintWriter(sw); + + writer.println(""); + + return sw.toString(); + } + + /** + * Generates a HTML snippet of a FIELD_SIGNATURE_TYPE select box that allows + * to choose the signature type. + * + * @return Returns the HTML snippet. + * @throws ServletException + * Forwarded exception. + */ + public static String generateTypeSelectBox() throws ServletException + { + try + { + StringWriter sw = new StringWriter(); + PrintWriter writer = new PrintWriter(sw); + + SettingsReader settings = SettingsReader.getInstance(); + SignatureTypes sig_types = SignatureTypes.getInstance(); + + // SettingsReader settings = null; + // SignatureTypes sig_types = null; + // try + // { + // settings = SettingsReader.getInstance(); + // sig_types = SignatureTypes.getInstance(); + // } + // catch (IOException e) + // { + // String log_message = "Can not load signature settings. Cause:\n" + + // e.getMessage(); + // logger_.error(log_message); + // req.setAttribute("error", "Das System konnte nicht gestartet werden."); + // req.setAttribute("cause", "Die Konfiguration ist fehlerhaft oder konnte + // nicht geladen werden."); + // dispatch(req, res, "/jsp/error.jsp"); + // } + + ArrayList types_array = sig_types.getSignatureTypes(); + Iterator type_it = types_array.iterator(); + + String default_type = settings.getValueFromKey(SignatureTypes.DEFAULT_TYPE); + + writer.println(""); + + return sw.toString(); + } + catch (Exception e) + { + throw new ServletException(e); + } + } + +} diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/web/LocalRequest.java b/src/main/java/at/knowcenter/wag/egov/egiz/web/LocalRequest.java new file mode 100644 index 0000000..d3c24a7 --- /dev/null +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/LocalRequest.java @@ -0,0 +1,80 @@ +/** + * Copyright (c) 2006 by Know-Center, Graz, Austria + * + * This software is the confidential and proprietary information of Know-Center, + * Graz, Austria. You shall not disclose such Confidential Information and shall + * use it only in accordance with the terms of the license agreement you entered + * into with Know-Center. + * + * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF + * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR + * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY + * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. + * + * $Id: LocalRequest.java,v 1.2 2006/08/25 17:06:11 wprinz Exp $ + */ +package at.knowcenter.wag.egov.egiz.web; + +import java.io.Serializable; + +/** + * Encapsulates a local request, basicall an URL where the local request is sent + * to and a request string. + * + * @author wprinz + */ +public class LocalRequest implements Serializable +{ + + /** + * SVUID. + */ + private static final long serialVersionUID = -3734904043231861998L; + + /** + * The URL the local request sould be directed at. + */ + protected String url_; + + /** + * The request string to be sent to that URL. + */ + protected String request_string_; + + /** + * Constructor that initializes the URL and request string. + * + * @param url + * The URL the local request sould be directed at. + * @param request_string + * The request string to be sent to that URL. + */ + public LocalRequest(String url, String request_string) + { + this.url_ = url; + this.request_string_ = request_string; + } + + /** + * Returns the URL. + * + * @return Returns the URL. + */ + public String getUrl() + { + return url_; + } + + /** + * Returns the request string. + * + * @return Returns the request string. + */ + public String getRequestString() + { + return request_string_; + } + +} diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/web/LocalRequestHelper.java b/src/main/java/at/knowcenter/wag/egov/egiz/web/LocalRequestHelper.java new file mode 100644 index 0000000..50bea41 --- /dev/null +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/LocalRequestHelper.java @@ -0,0 +1,226 @@ +/** + * Copyright (c) 2006 by Know-Center, Graz, Austria + * + * This software is the confidential and proprietary information of Know-Center, + * Graz, Austria. You shall not disclose such Confidential Information and shall + * use it only in accordance with the terms of the license agreement you entered + * into with Know-Center. + * + * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF + * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR + * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY + * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. + * + * $Id: LocalRequestHelper.java,v 1.6 2006/10/31 08:22:04 wprinz Exp $ + */ +package at.knowcenter.wag.egov.egiz.web; + +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import at.knowcenter.wag.egov.egiz.exceptions.ConnectorFactoryException; +import at.knowcenter.wag.egov.egiz.exceptions.NormalizeException; +import at.knowcenter.wag.egov.egiz.exceptions.PresentableException; +import at.knowcenter.wag.egov.egiz.exceptions.SignatureException; +import at.knowcenter.wag.egov.egiz.pdf.SignatureHolder; +import at.knowcenter.wag.egov.egiz.sig.ConnectorFactory; +import at.knowcenter.wag.egov.egiz.sig.LocalConnector; + +/** + * Contains commonly used helper functions for the local request procedure. + * + * @author wprinz + */ +public abstract class LocalRequestHelper +{ + /** + * The resource of the local connection page jsp. + */ + public static final String LOCAL_CONNECTION_PAGE_JSP = "/jsp/local_connection_page.jsp"; + + /** + * The resource of the redirect refresh page jsp. + */ + public static final String REDIRECT_REFRESH_PAGE_JSP = "/jsp/redirect_refresh_page.jsp"; + + /** + * Sets up the local sign procedure. + * + * @param response + * The HttpServletResponse the local request page is written to. + * @throws IOException + * Forwarded exception. + * @throws PresentableException + * Forwarded exception. + */ + public static void processLocalSign(SessionInformation si, + HttpServletRequest request, HttpServletResponse response) throws IOException, PresentableException + { + LocalConnector local_conn = (LocalConnector) ConnectorFactory.createConnector(si.connector); + + String document_text = si.iui.document_text; + String request_string = local_conn.prepareSignRequest(si.user_name, document_text, si.type); + String request_url = local_conn.getSignURL(si.type); + + LocalRequest local_request = new LocalRequest(request_url, request_string); + List local_requests = new ArrayList(); + local_requests.add(local_request); + + // ByteArrayOutputStream baos = new ByteArrayOutputStream(); + // ObjectOutputStream oos = new ObjectOutputStream(baos); + // oos.writeObject(local_requests); + // oos.close(); + // baos.close(); + + si.requests = new LocalRequest[1]; + si.requests[0] = new LocalRequest(local_conn.getSignURL(si.type), request_string); + si.current_operation = 0; + si.response_string = new String[1]; + si.response_string[0] = null; + + // SessionTable.put(si); + request.getSession().setAttribute(SessionAttributes.ATTRIBUTE_SESSION_INFORMATION, si); + + // byte [] requests_bytes = baos.toByteArray(); + // String base64 = CodingHelper.encodeBase64(requests_bytes); + + LocalRequestHelper.prepareDispatchToLocalConnectionPage(si.requests[0], request, response); + } + + /** + * Sets up the local verify procedure. + * + * @param response + * The HttpServletResponse the local request page is written to. + * @throws SignatureException + * Forwarded exception. + * @throws NormalizeException + * Forwarded exception. + * @throws IOException + * Forwarded exception. + * @throws ConnectorFactoryException + * Forwarded exception. + */ + public static void processLocalVerify(SessionInformation si, + List holders_to_verify, HttpServletRequest request, + HttpServletResponse response) throws SignatureException, NormalizeException, IOException, ConnectorFactoryException + { + si.requests = new LocalRequest[holders_to_verify.size()]; + si.response_string = new String[si.requests.length]; + si.current_operation = 0; + si.finished = false; + + request.getSession().setAttribute(SessionAttributes.ATTRIBUTE_SESSION_INFORMATION, si); + // SessionTable.put(si); + + LocalConnector local_conn = (LocalConnector) ConnectorFactory.createConnector(si.connector); + + for (int i = 0; i < si.requests.length; i++) + { + SignatureHolder holder = (SignatureHolder) holders_to_verify.get(i); + + String text_to_be_verified = holder.getSignedText(); + // Normalizer normalizer = new Normalizer(); + // String normalized = normalizer.normalize(holder.signed_text); + + String request_string = local_conn.prepareVerifyRequest(text_to_be_verified, holder.getSignatureObject()); + + LocalRequest local_request = new LocalRequest(local_conn.getVerifyURL(holder.getSignatureObject().getSignationType()), request_string); + si.requests[i] = local_request; + si.response_string[i] = null; + } + + // ByteArrayOutputStream baos = new ByteArrayOutputStream(); + // ObjectOutputStream oos = new ObjectOutputStream(baos); + // oos.writeObject(local_requests); + // oos.close(); + // baos.close(); + + // byte [] requests_bytes = baos.toByteArray(); + // String base64 = CodingHelper.encodeBase64(requests_bytes); + + prepareDispatchToLocalConnectionPage(si.requests[0], request, response); + } + + /** + * Formats the OK response from the web application back to the local BKU. + * + *

+ * As stated in the BKU tutorial, this response must be plain text "". + * Otherwise BKU will assume a failure. + *

+ * + * @param response + * The HttpServletResponse to answer to. + * @throws IOException + * Forwarded exception. + */ + protected static void formatBKUOkResponse(HttpServletResponse response) throws IOException + { + response.setContentType("text/plain"); + response.setCharacterEncoding("ISO-8859-1"); + + response.getWriter().println(""); + } + + /** + * Prepares the dispatch to the local data connection page. + * + *

+ * The calling servlet just has to dispatch to the jsp after calling this + * method. + *

+ * + * @param local_request + * The local request. Basically this contains the local service's + * target URL and the XML request string. + * @param response + * The HttpServletResponse to write this page to. + * @throws IOException + * Forwarded exception. + * @throws SignatureException + * Forwarded exception. + * @throws NormalizeException + * Forwarded exception. + */ + public static void prepareDispatchToLocalConnectionPage( + LocalRequest local_request, HttpServletRequest request, + HttpServletResponse response) throws IOException, SignatureException, NormalizeException + { + response.setContentType("text/html"); + response.setCharacterEncoding("UTF-8"); + + String local_request_url = local_request.getUrl(); + + String quoted_request = makeStringHTMLReady(local_request.getRequestString()); + + String host = request.getServerName(); // "129.27.153.77" + URL data_URL = new URL(request.getScheme(), host, request.getServerPort(), request.getContextPath() + "/AsynchronousDataResponder"); + String data_url = response.encodeURL(data_URL.toString()); + URL redirect_URL = new URL(request.getScheme(), host, request.getServerPort(), request.getContextPath() + "/AsynchronousRedirectResponder"); + String redirect_url = response.encodeURL(redirect_URL.toString()); + + request.setAttribute("local_request_url", local_request_url); + request.setAttribute("quoted_request", quoted_request); + request.setAttribute("data_url", data_url); + request.setAttribute("redirect_url", redirect_url); + } + + public static String makeStringHTMLReady(String input) + { + String output = input; + + output = output.replaceAll("&", "&"); + output = output.replaceAll("\"", """); + output = output.replaceAll("<", "<"); + output = output.replaceAll(">", ">"); + return output; + } +} 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 new file mode 100644 index 0000000..fab3e04 --- /dev/null +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/PdfASServletContextListener.java @@ -0,0 +1,76 @@ +/** + * Copyright (c) 2006 by Know-Center, Graz, Austria + * + * This software is the confidential and proprietary information of Know-Center, + * Graz, Austria. You shall not disclose such Confidential Information and shall + * use it only in accordance with the terms of the license agreement you entered + * into with Know-Center. + * + * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF + * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR + * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY + * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. + * + * $Id: PdfASServletContextListener.java,v 1.3 2006/10/31 08:22:04 wprinz Exp $ + */ +package at.knowcenter.wag.egov.egiz.web; + +import java.io.File; +import java.io.IOException; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +import org.apache.log4j.Logger; + +import at.knowcenter.wag.egov.egiz.cfg.ConfigLogger; +import at.knowcenter.wag.egov.egiz.cfg.SettingsReader; + +/** + * The ServletContextListener is notified when the webapplication starts up and shuts down. + * + *

+ * Maintainance work is performed. + *

+ * + * @author wprinz + */ +public class PdfASServletContextListener implements ServletContextListener +{ + /** + * The logger. + */ + private static final Logger logger = ConfigLogger.getLogger(PdfASServletContextListener.class); + + /** + * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) + */ + public void contextInitialized(ServletContextEvent arg0) + { + logger.info("PDF-AS Context init"); + String base_dir = arg0.getServletContext().getRealPath("/"); + try + { + logger.info("PDF-AS base directory = " + new File(base_dir).getCanonicalPath()); + } + catch (IOException e) + { + e.printStackTrace(); + } + + SettingsReader.initializeForWeb(base_dir); + + SettingsReader.clearTemporaryDirectory(); + } + + /** + * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent) + */ + public void contextDestroyed(ServletContextEvent arg0) + { + SettingsReader.clearTemporaryDirectory(); + logger.info("PDF-AS Context exit"); + } +} diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/web/SessionAttributes.java b/src/main/java/at/knowcenter/wag/egov/egiz/web/SessionAttributes.java new file mode 100644 index 0000000..02b6855 --- /dev/null +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/SessionAttributes.java @@ -0,0 +1,46 @@ +/** + * Copyright (c) 2006 by Know-Center, Graz, Austria + * + * This software is the confidential and proprietary information of Know-Center, + * Graz, Austria. You shall not disclose such Confidential Information and shall + * use it only in accordance with the terms of the license agreement you entered + * into with Know-Center. + * + * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF + * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR + * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY + * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. + * + * $Id: SessionAttributes.java,v 1.2 2006/08/25 17:06:11 wprinz Exp $ + */ +package at.knowcenter.wag.egov.egiz.web; + +/** + * Helper class that provides constants for the session attributes. + * + * @author wprinz + */ +public abstract class SessionAttributes +{ + + /** + * The user name. + */ + public static final String ATTRIBUTE_USER_NAME = "uname"; + + /** + * The user password. + */ + public static final String ATTRIBUTE_USER_PASSWORD = "upass"; + + /** + * The attribute name under which the SessionInformation object is stored. + * + *

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

+ */ + public static final String ATTRIBUTE_SESSION_INFORMATION = "session_information"; +} 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 new file mode 100644 index 0000000..f3c34d3 --- /dev/null +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/SessionInformation.java @@ -0,0 +1,126 @@ +/** + * Copyright (c) 2006 by Know-Center, Graz, Austria + * + * This software is the confidential and proprietary information of Know-Center, + * Graz, Austria. You shall not disclose such Confidential Information and shall + * use it only in accordance with the terms of the license agreement you entered + * into with Know-Center. + * + * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF + * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR + * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY + * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. + * + * $Id: SessionInformation.java,v 1.2 2006/08/25 17:06:11 wprinz Exp $ + */ +package at.knowcenter.wag.egov.egiz.web; + +import java.io.Serializable; +import java.util.List; + +import at.knowcenter.wag.egov.egiz.framework.SignResult; +import at.knowcenter.wag.egov.egiz.pdf.IncrementalUpdateInformation; + +/** + * This class is a collection of various session parameters that are passed + * between the servlets and jsps. + * + *

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

+ * + * @author wprinz + */ +public class SessionInformation implements Serializable +{ + + /** + * SVUID. + */ + private static final long serialVersionUID = -7413884936584659150L; + + // public long session_id = -1; + + /** + * The connector. + */ + public String connector = null; + + /** + * For local requests, tells the application (sign, verify). + */ + public String application = null; + + /** + * Tells the operation mode (binary, textual). + */ + public String mode = null; + + /** + * The original, uploaded pdf. + */ + public byte[] pdf = null; + + /** + * The type/profile of the signature. + */ + public String type = null; + + /** + * The user name. + */ + public String user_name = null; + + /** + * The password. + */ + public String user_password = null; + + /** + * An array of local requests to be processed. + */ + public LocalRequest[] requests = null; + + /** + * The index of the local request to be processed next. + */ + public int current_operation = 0; + + /** + * An array of response strings of the local requests. + */ + public String[] response_string = null; + + /** + * Tells, if the current local request has been finished. + */ + public boolean finished = false; + + /** + * The incremental update information that has been extracted from the given + * PDF document. + */ + public IncrementalUpdateInformation iui; + + /** + * The signature holders. + */ + public List signature_holders; + + /** + * The suggested filename. + */ + public String filename; + + /** + * Tells, if the file download should be done inline or as attachment. + */ + public boolean download_inline; + + /** + * The sign result to be passed back to the user. + */ + public SignResult sign_result; +} diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/web/SessionTable.java b/src/main/java/at/knowcenter/wag/egov/egiz/web/SessionTable.java new file mode 100644 index 0000000..4d0ba21 --- /dev/null +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/SessionTable.java @@ -0,0 +1,94 @@ +/** + * + */ +package at.knowcenter.wag.egov.egiz.web; + + +/** + * This class contains the session table that is used for local requests. + * + * @author wprinz + */ +public abstract class SessionTable +{ + // Session table no longer needed - because J2EE Servlet sessions are used. + +// /** +// * The HashMap for mapping the session id to the SessionInformation object on +// * the server. +// */ +// protected static Map session_table = new HashMap(); +// +// /** +// * The random number generator used to generate session_ids. +// */ +// protected static Random random = new Random(); +// +// /** +// * Generates a new SessionInformation object with a unique session_id. +// * +// *

+// * The object has to be added to the session table by using put(). +// *

+// * +// * @return Returns the generated SessionInformation object. +// * +// * @see #put(SessionInformation) +// */ +// public static SessionInformation generateSessionInformationObject() +// { +// SessionInformation si = new SessionInformation(); +// si.session_id = random.nextLong(); +// +// return si; +// } +// +// /** +// * Puts the SessionInformation object into the session table. +// * +// * @param si +// * The SessionInformation object. The session_id field must be filled +// * out properly. +// */ +// public static void put(SessionInformation si) +// { +// session_table.put(new Long(si.session_id), si); +// } +// +// /** +// * Gets the SessionInformation object associated with the given session_id. +// * +// * @param session_id +// * The session_id. +// * @return Returns the corresponding SessionInformation object or null, if no +// * object is associated with that id. +// */ +// public static SessionInformation get(final long session_id) +// { +// return (SessionInformation) session_table.get(new Long(session_id)); +// } +// +// /** +// * Removes the SessionInformation object with the provided session_id from the +// * session table. +// * +// * @param session_id +// * The session_id to be removed. +// */ +// public static void remove(long session_id) +// { +// session_table.remove(new Long(session_id)); +// } +// +// /** +// * Simply clear the session table. +// * +// *

+// * This should be used once in a while to tie up some loose ends. +// *

+// */ +// public static void clear() +// { +// session_table.clear(); +// } +} diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/web/Sign.java b/src/main/java/at/knowcenter/wag/egov/egiz/web/Sign.java new file mode 100644 index 0000000..a3ded84 --- /dev/null +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/Sign.java @@ -0,0 +1,525 @@ +/** + * Copyright (c) 2006 by Know-Center, Graz, Austria + * + * This software is the confidential and proprietary information of Know-Center, + * Graz, Austria. You shall not disclose such Confidential Information and shall + * use it only in accordance with the terms of the license agreement you entered + * into with Know-Center. + * + * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF + * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR + * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY + * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. + * + * $Id: Sign.java,v 1.7 2006/10/11 07:39:13 wprinz Exp $ + */ +package at.knowcenter.wag.egov.egiz.web; + +import java.io.File; +import java.io.IOException; +import java.io.Serializable; +import java.util.Iterator; +import java.util.List; + +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 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 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.sig.ConnectorFactory; +import at.knowcenter.wag.egov.egiz.tools.CodingHelper; + +/** + * This method is the sign servlet for the pdf-as web application. It takes get + * and post requests fill out jsp templates and give the user feedback about the + * results of the sign process + * + * @author wlackner + * @author wprinz + */ +public class Sign extends HttpServlet +{ + + /** + * SVUID. + */ + private static final long serialVersionUID = -4156938216903740438L; + + /** + * Authorisation marker for the http header string. + */ + protected static final String AUTH = "authorization"; + + /** + * Authorisation marker for the http header string. + */ + protected static final String AUTH_BASIC = "Basic"; + + /** + * The logger. + */ + private static final Logger logger_ = ConfigLogger.getLogger(Sign.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); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + String authenticate = request.getHeader(AUTH); + if (authenticate != null) + { + logger_.info("authenticate:" + authenticate); + if (authenticate.indexOf(AUTH_BASIC) == 0) + { + authenticate = authenticate.substring(AUTH_BASIC.length() + 1); + logger_.info("authenticate:" + authenticate); + authenticate = new String(CodingHelper.decodeBase64(authenticate), "UTF-8"); + logger_.info("authenticate:" + authenticate); + + String[] auth_value = authenticate.split(":"); + String user_name = auth_value[0]; + String user_password = auth_value[1]; + logger_.info("username:" + user_name); + logger_.info("password:" + user_password); + + HttpSession session = request.getSession(); + session.setAttribute(SessionAttributes.ATTRIBUTE_USER_NAME, user_name); + session.setAttribute(SessionAttributes.ATTRIBUTE_USER_PASSWORD, user_password); + + dispatch(request, response, "/jsp/signupload.jsp"); + return; + } + } + + request.setAttribute("error", "Falsche Authentifikation"); + request.setAttribute("cause", "Passwort oder Benutzername ist falsch"); + dispatch(request, response, "/jsp/error.jsp"); + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + DiskFileItemFactory fif = new DiskFileItemFactory(); + fif.setRepository(SettingsReader.getTemporaryDirectory()); + ServletFileUpload sfu = new ServletFileUpload(fif); + + try + { + List items = sfu.parseRequest(request); + + FileItem preview_fi = null; + FileItem sig_type_fi = null; + FileItem sig_app_fi = null; + FileItem mode_fi = null; + FileItem file_upload_fi = null; + FileItem download_fi = null; + + Iterator it = items.iterator(); + while (it.hasNext()) + { + FileItem item = (FileItem) it.next(); + logger_.debug("item = " + item.getFieldName()); + + if (item.isFormField()) + { + byte[] item_data = item.get(); + String item_string = new String(item_data, "UTF-8"); + logger_.debug(" form field string = " + item_string); + } + else + { + logger_.debug(" filename = " + item.getName()); + logger_.debug(" filesize = " + item.getSize()); + } + + if (item.getFieldName().equals(FormFields.FIELD_PREVIEW)) + { + preview_fi = item; + continue; + } + + if (item.getFieldName().equals(FormFields.FIELD_SIGNATURE_TYPE)) + { + sig_type_fi = item; + continue; + } + + if (item.getFieldName().equals(FormFields.FIELD_CONNECTOR)) + { + sig_app_fi = item; + continue; + } + + if (item.getFieldName().equals(FormFields.FIELD_MODE)) + { + mode_fi = item; + continue; + } + + if (item.getFieldName().equals(FormFields.FIELD_UPLOAD)) + { + file_upload_fi = item; + continue; + } + + if (item.getFieldName().equals(FormFields.FIELD_DOWNLOAD)) + { + download_fi = item; + continue; + } + + throw new ServletException("unrecognized POST data."); + + } + + if (preview_fi == null || sig_type_fi == null || sig_app_fi == null || file_upload_fi == null || download_fi == null) + { + throw new ServletException("Unsufficient data provided in request"); + } + + String mode = mode_fi.getString("UTF-8"); + if (!mode.equals(FormFields.VALUE_MODE_BINARY) && !mode.equals(FormFields.VALUE_MODE_TEXTUAL) && !mode.equals(FormFields.VALUE_MODE_DETACHED)) + { + throw new ServletException("The mode '" + mode + "' is unrecognized."); + } + + String preview_str = preview_fi.getString("UTF-8"); + boolean preview = false; + if (preview_str.equals("true")) + { + preview = true; + } + + boolean download_inline = true; + if (download_fi.getString("UTF-8").equals(FormFields.VALUE_DOWNLOAD_ATTACHMENT)) + { + download_inline = false; + } + + String sig_type = sig_type_fi.getString("UTF-8"); + String connector = sig_app_fi.getString("UTF-8"); + + String doc_file_name = file_upload_fi.getName(); + logger_.debug(" file content type =" + file_upload_fi.getContentType()); + + String extension = Verify.extractExtension(doc_file_name); + if (extension != null && !extension.equals("pdf")) + { + throw new PDFDocumentException(201, "The provided file '" + doc_file_name + "' doesn't have the PDF extension (.pdf)."); + } + + byte[] pdf = file_upload_fi.get(); + if (file_upload_fi.getSize() <= 0) + { + throw new PDFDocumentException(250, "The document is empty."); + } + PdfAS.applyStrictMode(pdf); + + String user_name = (String) request.getSession().getAttribute(SessionAttributes.ATTRIBUTE_USER_NAME); + String user_password = (String) request.getSession().getAttribute(SessionAttributes.ATTRIBUTE_USER_PASSWORD); + + SessionInformation si = new SessionInformation(); // SessionTable.generateSessionInformationObject(); + si.connector = connector; + si.application = "sign"; + si.mode = mode; + si.pdf = pdf; + si.type = sig_type; + si.user_name = user_name; + si.user_password = user_password; + si.filename = formatFileName(file_upload_fi.getName()); + si.download_inline = download_inline; + + prepareSign(si); + + if (preview) + { + request.getSession().setAttribute(SessionAttributes.ATTRIBUTE_SESSION_INFORMATION, si); + + String submit_url = response.encodeURL(request.getContextPath() + "/SignPreview"); + + request.setAttribute("submit_url", submit_url); + + dispatch(request, response, "/jsp/signpreview.jsp"); + + return; + } + + finishSign(si, request, response, getServletContext()); + } + catch (FileUploadException e) + { + 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"); + } + catch (PresentableException e) + { + e.printStackTrace(); + prepareDispatchToErrorPage(e, request); + dispatch(request, response, "/jsp/error.jsp"); + } + } + + public static void prepareSign(SessionInformation si) throws PresentableException + { + PdfASID algorithm = FormFields.translateSignatureModeToPdfASID(si.mode); + Signator signator = SignatorFactory.createSignator(algorithm); + si.iui = signator.prepareSign(si.pdf, si.type, null, ConnectorFactory.needsSIG_ID(si.connector)); + } + + public static void finishSign(SessionInformation si, + HttpServletRequest request, HttpServletResponse response, ServletContext context) throws PresentableException, IOException, ServletException + { + if (ConnectorFactory.isConnectorLocal(si.connector)) + { + LocalRequestHelper.processLocalSign(si, request, response); + dispatch(request, response, LocalRequestHelper.LOCAL_CONNECTION_PAGE_JSP, context); + return; + } + + PdfASID algorithm = FormFields.translateSignatureModeToPdfASID(si.mode); + Signator signator = SignatorFactory.createSignator(algorithm); + + si.iui.signed_signature_object = PdfAS.sign(si.iui.document_text, si.type, si.connector, si.user_name, si.user_password); + + si.sign_result = signator.finishSign(si.iui); + + returnSignResponse(si, response); + } + + public static void prepareDispatchToErrorPage(PresentableException pe, + HttpServletRequest request) + { + if (pe instanceof ErrorCodeException) + { + ErrorCodeException ece = (ErrorCodeException) pe; + request.setAttribute("error", "Fehler " + ece.getErrorCode()); + + String cause = ece.getErrorCodeMessage(); + if (ece.hasExternalErrorMessage()) + { + cause = ece.getExternalErrorCode() + ": " + ece.getExternalErrorMessage(); + } + request.setAttribute("cause", cause); + + if (pe instanceof PlaceholderException) + { + PlaceholderException phe = (PlaceholderException) ece; + + request.setAttribute("cause", "Der Platzhalter des Feldes " + phe.getField() + " ist um " + phe.getMissing() + " Bytes zu kurz. " + ece.getErrorCodeMessage()); + } + } + 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 + { + request.setAttribute("document_text", document_text); + request.setAttribute("connector", connector); + request.setAttribute("mode", mode); + request.setAttribute("signature_type", signature_type); + request.setAttribute("submit_url", submit_url); + + dispatch(request, response, "/jsp/signpreview.jsp"); + } + + // public static void formatPreview(String document_text, String connector, + // String mode, String signature_type, String submit_url, + // HttpServletResponse response) throws ServletException, IOException + // { + // response.setContentType("text/html"); + // response.setCharacterEncoding("UTF-8"); + // + // PrintWriter writer = response.getWriter(); + // + // writer.println(""); + // writer.println(""); + // writer.println(""); + // writer.println(""); + // writer.println(""); + // writer.println("PDF-AS Amtssignaturen Vorschau"); + // writer.println(""); + // writer.println(""); + // + // writer.println(""); + // writer.println("
"); + // + // writer.println("

PDF-AS Amtssignaturen

"); + // + // writer.println("
"); + // writer.println("
Vorschau: Dokument Prüfen
"); + // writer.println("
"); + // writer.println("
"); + // + // writer.println(""); + // writer.println(""); + // writer.println(""); + // writer.println(""); + // writer.println(""); + // + // writer.println(""); + // writer.println("
"); + // + // writer.println(""); + // + // writer.println("
"); + // writer.println("
"); + // writer.println("
"); + // + // writer.println("zurück"); + // + // writer.println("
"); + // writer.println(""); + // + // writer.println(""); + // } + + /** + * This class is just used to put the pdf byte array into the session. + * + * @author wprinz + */ + protected class SignPreviewInfo implements Serializable + { + /** + * SVUID. + */ + private static final long serialVersionUID = 3102824040163616332L; + + public byte[] pdf = null; + + public String mode = null; + } + + /** + * Formats the file name so that it is suitable for content disposition. + * + * @param file_name + * The file name. + * @return Returns the formatted file name. + */ + public static String formatFileName(String file_name) + { + File file = new File(file_name); + String file_name_only = file.getName(); + // the file_name contains \\ ==> remove them so Internet Explorer works + // correctly. + 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); + + // 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()); + + } +} \ No newline at end of file diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/web/SignPreview.java b/src/main/java/at/knowcenter/wag/egov/egiz/web/SignPreview.java new file mode 100644 index 0000000..1b32bdf --- /dev/null +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/SignPreview.java @@ -0,0 +1,105 @@ +/** + * Copyright (c) 2006 by Know-Center, Graz, Austria + * + * This software is the confidential and proprietary information of Know-Center, + * Graz, Austria. You shall not disclose such Confidential Information and shall + * use it only in accordance with the terms of the license agreement you entered + * into with Know-Center. + * + * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF + * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR + * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY + * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. + * + * $Id: SignPreview.java,v 1.2 2006/10/11 07:39:13 wprinz Exp $ + */ +package at.knowcenter.wag.egov.egiz.web; + +import java.io.IOException; + +import javax.servlet.RequestDispatcher; +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.knowcenter.wag.egov.egiz.exceptions.PresentableException; + +/** + * @author wprinz + */ +public class SignPreview extends HttpServlet +{ + + /** + * SVUID. + */ + private static final long serialVersionUID = -8818532511322299998L; + + protected void dispatch(HttpServletRequest request, + HttpServletResponse response, String resource) throws ServletException, IOException + { + response.setContentType("text/html"); + response.setCharacterEncoding("UTF-8"); + + RequestDispatcher disp = getServletContext().getRequestDispatcher(resource); + disp.forward(request, response); + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + SessionInformation si = null; + HttpSession session = null; + try + { + session = request.getSession(false); + // String session_id_string = request.getParameter("session"); + if (session == null) + { + throw new ErrorCodeException(600, "The session is missing."); + } + + si = (SessionInformation) session.getAttribute(SessionAttributes.ATTRIBUTE_SESSION_INFORMATION); + // long session_id = Long.parseLong(session_id_string); + // si = SessionTable.get(session_id); + if (si == null) + { + throw new ErrorCodeException(600, "The session is not found or is no longer valid."); + } + + } + catch (PresentableException e) + { + e.printStackTrace(); + Sign.prepareDispatchToErrorPage(e, request); + dispatch(request, response, "/jsp/error.jsp"); + + return; + } + + try + { + String preview = request.getParameter(FormFields.FIELD_PREVIEW); + if (preview != null && preview.equals(FormFields.VALUE_TRUE)) + { + response.setContentType("application/pdf"); + response.getOutputStream().write(si.iui.signed_pdf); + return; + } + else + { + Sign.finishSign(si, request, response, getServletContext()); + } + } + catch (PresentableException e) + { + e.printStackTrace(); + Sign.prepareDispatchToErrorPage(e, request); + dispatch(request, response, "/jsp/error.jsp"); + } + } +} diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/web/Verify.java b/src/main/java/at/knowcenter/wag/egov/egiz/web/Verify.java new file mode 100644 index 0000000..a8a5a5b --- /dev/null +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/Verify.java @@ -0,0 +1,285 @@ +/* + * Copyright (c) 2006 by Know-Center, Graz, Austria + * + * This software is the confidential and proprietary information of Know-Center, + * Graz, Austria. You shall not disclose such Confidential Information and shall + * use it only in accordance with the terms of the license agreement you entered + * into with Know-Center. + * + * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF + * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR + * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY + * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. + * + * $Id: Verify.java,v 1.7 2006/10/11 07:39:13 wprinz Exp $ + */ +package at.knowcenter.wag.egov.egiz.web; + +import java.io.IOException; +import java.util.Iterator; +import java.util.List; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +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 at.knowcenter.wag.egov.egiz.PdfAS; +import at.knowcenter.wag.egov.egiz.cfg.ConfigLogger; +import at.knowcenter.wag.egov.egiz.cfg.SettingsReader; +import at.knowcenter.wag.egov.egiz.exceptions.PDFDocumentException; +import at.knowcenter.wag.egov.egiz.exceptions.PresentableException; +import at.knowcenter.wag.egov.egiz.framework.VerificationFilter; +import at.knowcenter.wag.egov.egiz.sig.ConnectorFactory; + +/** + * This method is the verify servlet for the pdf-as web application. It takes + * get and post requests fill out jsp templates and give the user feedback about + * the results of the verify process. + * + * @author wlackner + * @author wprinz + */ +public class Verify extends HttpServlet +{ + + /** + * SVUID. + */ + private static final long serialVersionUID = 309198792358636766L; + + /** + * The logger. + */ + private static final Logger logger_ = ConfigLogger.getLogger(Verify.class); + + protected void dispatch(HttpServletRequest request, + HttpServletResponse response, String resource) throws ServletException, IOException + { + response.setContentType("text/html"); + response.setCharacterEncoding("UTF-8"); + + RequestDispatcher disp = getServletContext().getRequestDispatcher(resource); + disp.forward(request, response); + } + + protected void dispatchToResults(List results, HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException + { + request.setAttribute("results", results); + dispatch(request, response, "/jsp/results.jsp"); + } + + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + dispatch(request, response, "/jsp/verifyupload.jsp"); + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + + DiskFileItemFactory fif = new DiskFileItemFactory(); + fif.setRepository(SettingsReader.getTemporaryDirectory()); + ServletFileUpload sfu = new ServletFileUpload(fif); + + try + { + + List items = sfu.parseRequest(request); + + FileItem upload_fi = null; + FileItem connector_fi = null; +// FileItem mode_fi = null; + FileItem preview_fi = null; + + { + Iterator it = items.iterator(); + while (it.hasNext()) + { + FileItem item = (FileItem) it.next(); + logger_.debug("item = " + item.getFieldName()); + + if (item.isFormField()) + { + byte[] item_data = item.get(); + String item_string = new String(item_data, "UTF-8"); + logger_.debug(" form field string = " + item_string); + } + else + { + logger_.debug(" filename = " + item.getName()); + logger_.debug(" filesize = " + item.getSize()); + } + + if (item.getFieldName().equals(FormFields.FIELD_UPLOAD)) + { + upload_fi = item; + continue; + } + + if (item.getFieldName().equals(FormFields.FIELD_CONNECTOR)) + { + connector_fi = item; + continue; + } + +// if (item.getFieldName().equals(FormFields.FIELD_MODE)) +// { +// mode_fi = item; +// continue; +// } + + if (item.getFieldName().equals(FormFields.FIELD_PREVIEW)) + { + preview_fi = item; + continue; + } + + throw new ServletException("unrecognized POST data."); + } + } + + if (upload_fi == null || connector_fi == null || /*mode_fi == null ||*/ preview_fi == null) + { + throw new ServletException("Unsufficient data provided in request."); + } + + String connector = connector_fi.getString("UTF-8"); + +// String mode = mode_fi.getString("UTF-8"); +// if (!mode.equals(FormFields.VALUE_MODE_BINARY) && !mode.equals(FormFields.VALUE_MODE_TEXTUAL)) +// { +// throw new ServletException("The mode '" + mode + "' is unrecognized."); +// } + + String preview_str = preview_fi.getString("UTF-8"); + if (!preview_str.equals(FormFields.VALUE_TRUE) && !preview_str.equals(FormFields.VALUE_FALSE)) + { + throw new ServletException("The preview '" + preview_str + "' is unrecognized."); + } + boolean preview = false; + if (preview_str.equals(FormFields.VALUE_TRUE)) + { + preview = true; + } + + // process the request + logger_.debug("file content type =" + upload_fi.getContentType()); + logger_.debug("file size = " + upload_fi.getSize()); + if (upload_fi.getSize() <= 0) + { + throw new PDFDocumentException(250, "The document is empty."); + } + byte[] document_bytes = upload_fi.get(); + + VerificationFilter vf = new VerificationFilter(); + List signature_holders = null; + + String doc_file_name = upload_fi.getName(); + String extension = extractExtension(doc_file_name); + + String raw_text = null; + if (doc_file_name == null || (extension != null && extension.equals("txt"))) + { + raw_text = new String(document_bytes, "UTF-8"); + signature_holders = vf.extractSignaturesFromPlainText(raw_text); + } + else + { + signature_holders = vf.extractSignaturesFromPdf(document_bytes); + } + + if (signature_holders.size() == 0) + { + throw new PDFDocumentException(206, "PDF document not signed."); + } + + if (preview) + { + SessionInformation si = new SessionInformation(); + si.application = "verify"; + si.connector = connector; + si.signature_holders = signature_holders; + request.getSession().setAttribute(SessionAttributes.ATTRIBUTE_SESSION_INFORMATION, si); + + dispatch(request, response, "/jsp/verifylist.jsp"); + //VerifyPreview.formatPreview(signature_holders, connector, request, response); + } + else + { + if (ConnectorFactory.isConnectorLocal(connector)) + { + SessionInformation si = new SessionInformation(); //SessionTable.generateSessionInformationObject(); + si.connector = connector; + si.application = "verify"; + si.mode = null; + si.pdf = null; + si.type = null; + si.user_name = null; + si.user_password = null; + + si.signature_holders = signature_holders; + + LocalRequestHelper.processLocalVerify(si, si.signature_holders, request, response); + dispatch(request, response, LocalRequestHelper.LOCAL_CONNECTION_PAGE_JSP); + return; + } + + List results = PdfAS.verifySignatureHolders(signature_holders, connector); + dispatchToResults(results, request, response); + } + + } + catch (FileUploadException e) + { + 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"); + } + catch (PresentableException e) + { + e.printStackTrace(); + Sign.prepareDispatchToErrorPage(e, request); + dispatch(request, response, "/jsp/error.jsp"); + } + + } + + /** + * Extracts the extension from a file name string. + * + *

+ * The extension of a file name is whatever text follows the last '.'. + *

+ * + * @param file_name + * The file name. + * @return Returns the extension. If the file name ends with the '.', then an + * empty string is returned. If the file name doesn't contain any '.' + * or file_name is null, null is returned. + */ + public static String extractExtension(String file_name) + { + if (file_name == null) + { + return null; + } + + int dot_index = file_name.lastIndexOf('.'); + if (dot_index < 0) + { + return null; + } + return file_name.substring(dot_index + 1); + } +} \ No newline at end of file diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/web/VerifyPreview.java b/src/main/java/at/knowcenter/wag/egov/egiz/web/VerifyPreview.java new file mode 100644 index 0000000..c39fd91 --- /dev/null +++ b/src/main/java/at/knowcenter/wag/egov/egiz/web/VerifyPreview.java @@ -0,0 +1,704 @@ +/** + * Copyright (c) 2006 by Know-Center, Graz, Austria + * + * This software is the confidential and proprietary information of Know-Center, + * Graz, Austria. You shall not disclose such Confidential Information and shall + * use it only in accordance with the terms of the license agreement you entered + * into with Know-Center. + * + * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF + * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR + * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY + * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. + * + * $Id: VerifyPreview.java,v 1.4 2006/10/11 07:39:13 wprinz Exp $ + */ +package at.knowcenter.wag.egov.egiz.web; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import javax.servlet.RequestDispatcher; +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 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; +import at.knowcenter.wag.egov.egiz.pdf.BinarySignatureHolder; +import at.knowcenter.wag.egov.egiz.pdf.SignatureHolder; +import at.knowcenter.wag.egov.egiz.pdf.TextualSignatureHolder; +import at.knowcenter.wag.egov.egiz.sig.ConnectorFactory; +import at.knowcenter.wag.egov.egiz.sig.SignatureEntry; +import at.knowcenter.wag.egov.egiz.sig.SignatureObject; +import at.knowcenter.wag.egov.egiz.sig.SignatureTypes; + +/** + * @author wprinz + */ +public class VerifyPreview extends HttpServlet +{ + /** + * SVUID. + */ + private static final long serialVersionUID = 6954343542890239109L; + + /** + * The logger. + */ + private static final Logger logger_ = ConfigLogger.getLogger(VerifyPreview.class); + + protected void dispatch(HttpServletRequest request, + HttpServletResponse response, String resource) throws ServletException, IOException + { + response.setContentType("text/html"); + response.setCharacterEncoding("UTF-8"); + + RequestDispatcher disp = getServletContext().getRequestDispatcher(resource); + disp.forward(request, response); + } + + protected static String generateNamePrefix(int num) + { + return SIG_INPUT_PREFIX + num + "_"; + } + + // public static void formatPreview(List signature_holders, String connector, + // HttpServletRequest request, HttpServletResponse response) throws + // ServletException, IOException + // { + // response.setContentType("text/html"); + // response.setCharacterEncoding("UTF-8"); + // + // PrintWriter writer = response.getWriter(); + // + // writer.println(""); + // writer.println(""); + // writer.println(""); + // writer.println(""); + // writer.println("PDF-AS Amtssignaturen Vorschau"); + // writer.println(""); + // + // writer.println(""); + // + // writer.println(""); + // + // writer.println(""); + // writer.println("
"); + // + // writer.println("

PDF-AS Amtssignaturen

"); + // + // writer.println("
"); + // writer.println("
Vorschau: Dokument Prüfen
"); + // writer.println("
"); + // writer.println("
"); + // + // // writer.println(""); + // writer.println(""); + // + // // if (mode.equals(FormFields.VALUE_MODE_TEXTUAL)) + // // { + // // String raw_document_text = ((SignatureHolder) + // // signature_holders.get(0)).signed_text; + // // writer.println(""); + // // writer.println("
"); + // // } + // + // if (signature_holders.size() == 1) + // { + // writer.println("
Rekonstruktion der Signaturmarke:
"); + // } + // else + // { + // writer.println("
Rekonstruktion der Signaturmarken:
"); + // } + // + // // this special
is only needed because internet explorer doesn't + // // format the width of the + // // tables right when the div is not given. + // // probably this is because the table then tries to calculate the relative + // // width from the surrounding form object. + // writer.println("
"); + // int num = 0; + // Iterator it = signature_holders.iterator(); + // while (it.hasNext()) + // { + // SignatureHolder signature_holder = (SignatureHolder) it.next(); + // + // String name_prefix = generateNamePrefix(num); + // + // String input_key = name_prefix + FormFields.FIELD_RAW_DOCUMENT_TEXT; + // if (signature_holder.signature_object.isBinary()) + // { + // writer.println(""); + // } + // else + // { + // writer.println("
"); + // writer.println(""); + // writer.println("
"); + // } + // + // String html = renderRequiredKeys(signature_holder.signature_object, + // name_prefix, false); + // writer.println(html); + // + // writer.println(""); + // + // num++; + // } + // writer.println("
"); + // + // writer.println("");// + + // // FormFields.VALUE_VERIFY_WHICH_ALL + // // + + // // "\" + // // />"); + // writer.println(""); + // + // writer.println("
"); + // writer.println(""); + // writer.println("
"); + // + // writer.println("zurück"); + // + // writer.println("
"); + // writer.println(""); + // + // writer.println(""); + // + // } + + public static String renderRequiredKeysJavaScript( + SignatureObject signature_object, String name_prefix) + { + StringWriter sw = new StringWriter(); + PrintWriter writer = new PrintWriter(sw); + + String[] rkeys = SignatureTypes.REQUIRED_SIG_KEYS; + + for (int key_idx = 0; key_idx < rkeys.length; key_idx++) + { + String key = rkeys[key_idx]; + SignatureEntry entry = signature_object.getSigEntry(key); + String value = entry.getValue(); + if (SignatureTypes.SIG_ID.equals(key) && value == null) + { + continue; + } + + value = value.replaceAll("\\s", " "); + value = value.replaceAll("\\\"", "\\\""); + + String input_key = name_prefix + key; + + writer.println(" document.submitform." + input_key + ".value = \"" + value + "\";"); + } + + return sw.toString(); + } + + public static String renderRequiredKeys(SignatureObject signature_object, + String name_prefix, boolean write_value) + { + StringWriter sw = new StringWriter(); + PrintWriter writer = new PrintWriter(sw); + + writer.println(""); + + String[] rkeys = SignatureTypes.REQUIRED_SIG_KEYS; + + for (int key_idx = 0; key_idx < rkeys.length; key_idx++) + { + String key = rkeys[key_idx]; + SignatureEntry entry = signature_object.getSigEntry(key); + String caption = entry.getCaption(); + String value = entry.getValue(); + if (SignatureTypes.SIG_ID.equals(key) && value == null) + { + continue; + } + + writer.println(" "); + writer.println(" "); + writer.println(" "); + writer.println(" "); + } + writer.println("
" + caption + ":"); + + value = value.replaceAll("\\s", " "); + value = value.replaceAll("\\\"", "\\\""); + + String input_key = name_prefix + key; + writer.println(" "); + + writer.println("
"); + + return sw.toString(); + } + + public static String renderRequiredKeysText(SignatureObject signature_object) + { + StringWriter sw = new StringWriter(); + PrintWriter writer = new PrintWriter(sw); + + String title = "alte PDF-AS Signatur"; + try + { + PdfASID kz = signature_object.getKZ(); + if (kz != null) + { + title = kz.toString(); + } + } + catch (InvalidIDException e) + { + e.printStackTrace(); + } + writer.println("
Signatur: " + title + "
"); + writer.println(""); + + // just render useful information + String[] rkeys = { SignatureTypes.SIG_DATE, SignatureTypes.SIG_ISSUER, + SignatureTypes.SIG_NUMBER }; // SignatureTypes.REQUIRED_SIG_KEYS; + + for (int key_idx = 0; key_idx < rkeys.length; key_idx++) + { + String key = rkeys[key_idx]; + SignatureEntry entry = signature_object.getSigEntry(key); + String caption = entry.getCaption(); + String value = entry.getValue(); + if (SignatureTypes.SIG_ID.equals(key) && value == null) + { + continue; + } + + writer.println(" "); + writer.println(" "); + writer.println(" "); + writer.println(" "); + } + writer.println("
" + caption + ":"); + + value = value.replaceAll("\\s", " "); + value = value.replaceAll("\\\"", "\\\""); + + writer.println(" " + value); + + writer.println("
"); + + return sw.toString(); + } + + protected void dispatchToResults(List results, HttpServletRequest request, + HttpServletResponse response, boolean backbutton) throws ServletException, IOException + { + request.setAttribute("results", results); + request.setAttribute("backbutton", backbutton ? "true" : "false"); + dispatch(request, response, "/jsp/results.jsp"); + } + + // public static void formatVerifyResults(List results, + // HttpServletResponse response) throws IOException, SettingNotFoundException + // { + // response.setContentType("text/html"); + // response.setCharacterEncoding("UTF-8"); + // + // PrintWriter writer = response.getWriter(); + // + // writer.println(""); + // writer.println(""); + // writer.println(""); + // writer.println(""); + // writer.println("PDF-AS Amtssignaturen Resultat"); + // writer.println(""); + // writer.println(""); + // + // writer.println(""); + // writer.println("
"); + // + // writer.println("

PDF-AS Amtssignaturen

"); + // + // writer.println("
"); + // writer.println("
Resultat
"); + // writer.println("
"); + // + // Iterator it = results.iterator(); + // while (it.hasNext()) + // { + // SignatureResponse result = (SignatureResponse) it.next(); + // formatSignatureResponse(result, writer); + // + // if (it.hasNext()) + // { + // writer.println("
"); + // } + // } + // + // writer.println("
"); + // writer.println("
"); + // + // writer.println("zurück"); + // + // writer.println("
"); + // writer.println(""); + // + // writer.println(""); + // + // } + // + // public static void formatSignatureResponse(SignatureResponse result, + // PrintWriter writer) throws SettingNotFoundException + // { + // writer.println("
Zertifikat"); + // writer.println(""); + // writer.println(" "); + // writer.println(" "); + // writer.println(" "); + // List public_properties = result.getPublicProperties(); + // Iterator it = public_properties.iterator(); + // while (it.hasNext()) + // { + // String public_property = (String) it.next(); + // writer.println(" "); + // } + // + // writer.println(" "); + // + // writer.println("
Signator:" + + // result.getX509SubjectName() + "
Aussteller:" + + // result.getX509IssuerName() + "
Seriennummer:" + + // result.getX509SerialNumber() + "
Eigenschaft:" + + // public_property + "
Zertifikat:" + result.getCertificateCheckInfo() + // + "
"); + // writer.println("
"); + // writer.println("
Signatur-Check"); + // writer.println("
" + result.getSignatureCheckInfo() + "
"); + // writer.println("
"); + // writer.println("
Manifest-Check"); + // writer.println("
" + + // result.getSignatureManifestCheckInfo() + "
"); + // writer.println("
"); + // } + + /** + * Form field name prefix for signature table names + */ + public static final String SIG_INPUT_PREFIX = "sig_inp_"; + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + SessionInformation si = null; + HttpSession session = null; + try + { + session = request.getSession(false); + // String session_id_string = request.getParameter("session"); + if (session == null) + { + throw new ErrorCodeException(600, "The session is missing."); + } + + si = (SessionInformation) session.getAttribute(SessionAttributes.ATTRIBUTE_SESSION_INFORMATION); + // long session_id = Long.parseLong(session_id_string); + // si = SessionTable.get(session_id); + if (si == null) + { + throw new ErrorCodeException(600, "The session is not found or is no longer valid."); + } + + } + catch (PresentableException e) + { + e.printStackTrace(); + Sign.prepareDispatchToErrorPage(e, request); + dispatch(request, response, "/jsp/error.jsp"); + + return; + } + + try + { + + int verify_which = -1; + boolean preview = false; + + { + String str_verify_which = request.getParameter(FormFields.FIELD_VERIFY_WHICH); + logger_.debug("verify_which = " + str_verify_which); + if (str_verify_which.equals(FormFields.VALUE_VERIFY_WHICH_ALL)) + { + verify_which = -1; + } + else + { + verify_which = Integer.parseInt(str_verify_which); + } + logger_.debug("verify_which = " + verify_which); + } + + { + String preview_string = request.getParameter(FormFields.FIELD_PREVIEW); + if (preview_string.equals("true")) + { + preview = true; + } + } + + List holders_to_verify = si.signature_holders; + + if (verify_which >= 0) + { + if (verify_which >= si.signature_holders.size()) + { + throw new SignatureException(312, "The selected signature to be verified doesn't exist."); + } + + SignatureHolder holder = (SignatureHolder) si.signature_holders.get(verify_which); + holders_to_verify = new ArrayList(); + holders_to_verify.add(holder); + + if (preview == true) + { + if (holder instanceof BinarySignatureHolder) + { + BinarySignatureHolder binary_holder = (BinarySignatureHolder) holder; + response.setContentType("application/pdf"); + response.getOutputStream().write(binary_holder.getSignedPdf(), 0, binary_holder.getSignedPdfLength()); + } + else + // if (holder.getSignatureObject().isTextual()) + { + // formatPreview(holders_to_verify, si.connector, request, + // response); + request.setAttribute(FormFields.FIELD_VERIFY_WHICH, new Integer(verify_which)); + dispatch(request, response, "/jsp/verifypreview.jsp"); + } + + return; + } + + } + + if (ConnectorFactory.isConnectorLocal(si.connector)) + { + LocalRequestHelper.processLocalVerify(si, holders_to_verify, request, response); + dispatch(request, response, LocalRequestHelper.LOCAL_CONNECTION_PAGE_JSP); + return; + } + + List results = PdfAS.verifySignatureHolders(holders_to_verify, si.connector); + boolean backbutton = true; + if (verify_which >= 0) + { + backbutton = false; + } + dispatchToResults(results, request, response, backbutton); + + } + catch (PresentableException e) + { + e.printStackTrace(); + Sign.prepareDispatchToErrorPage(e, request); + dispatch(request, response, "/jsp/error.jsp"); + } + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + SessionInformation si = null; + HttpSession session = null; + try + { + session = request.getSession(false); + // String session_id_string = request.getParameter("session"); + if (session == null) + { + throw new ErrorCodeException(600, "The session is missing."); + } + + si = (SessionInformation) session.getAttribute(SessionAttributes.ATTRIBUTE_SESSION_INFORMATION); + // long session_id = Long.parseLong(session_id_string); + // si = SessionTable.get(session_id); + if (si == null) + { + throw new ErrorCodeException(600, "The session is not found or is no longer valid."); + } + + } + catch (PresentableException e) + { + e.printStackTrace(); + Sign.prepareDispatchToErrorPage(e, request); + dispatch(request, response, "/jsp/error.jsp"); + + return; + } + + DiskFileItemFactory fif = new DiskFileItemFactory(); + fif.setRepository(SettingsReader.getTemporaryDirectory()); + ServletFileUpload sfu = new ServletFileUpload(fif); + + try + { + String text_to_be_verified = null; + SignatureObject signature_object = new SignatureObject(); + + String default_type = SettingsReader.getInstance().getValueFromKey(SignatureTypes.DEFAULT_TYPE); + signature_object.setSigType(default_type); + signature_object.initByType(); + + int verify_which = -1; + boolean verify = false; + + List items = sfu.parseRequest(request); + + Iterator it = items.iterator(); + while (it.hasNext()) + { + FileItem item = (FileItem) it.next(); + logger_.debug("item = " + item.getFieldName()); + + if (item.getFieldName().equals(FormFields.FIELD_RAW_DOCUMENT_TEXT)) + { + String raw_document_text = item.getString("UTF-8"); + text_to_be_verified = PdfAS.normalizeText(raw_document_text); + continue; + } + + if (item.getFieldName().equals(FormFields.FIELD_VERIFY_WHICH)) + { + String which_str = item.getString("UTF-8"); + verify_which = Integer.parseInt(which_str); + continue; + } + + if (item.getFieldName().equals("verify")) + { + if (item.getString("UTF-8").equals("true")) + { + verify = true; + } + continue; + } + + String key = item.getFieldName(); + String value = item.getString("UTF-8"); + + signature_object.setSigValue(key, value); + logger_.debug("sig_obj_number" + key + " = " + value); + } + + SignatureHolder new_holder = new TextualSignatureHolder(text_to_be_verified, signature_object); + si.signature_holders.set(verify_which, new_holder); + + if (verify == false) + { + dispatch(request, response, "/dataok.html"); + return; + } + + List holders_to_verify = si.signature_holders; + + if (verify_which >= 0) + { + if (verify_which >= si.signature_holders.size()) + { + throw new SignatureException(312, "The selected signature to be verified doesn't exist."); + } + + SignatureHolder holder = (SignatureHolder) si.signature_holders.get(verify_which); + holders_to_verify = new ArrayList(); + holders_to_verify.add(holder); + } + + if (ConnectorFactory.isConnectorLocal(si.connector)) + { + LocalRequestHelper.processLocalVerify(si, holders_to_verify, request, response); + dispatch(request, response, LocalRequestHelper.LOCAL_CONNECTION_PAGE_JSP); + return; + } + + List results = PdfAS.verifySignatureHolders(holders_to_verify, si.connector); + dispatchToResults(results, request, response, true); + } + catch (FileUploadException e) + { + 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"); + } + catch (PresentableException e) + { + e.printStackTrace(); + Sign.prepareDispatchToErrorPage(e, request); + dispatch(request, response, "/jsp/error.jsp"); + } + + } +} -- cgit v1.2.3