From 29ad090c29567ff1a4d3a2ec9b8ad0b5d80ee24d Mon Sep 17 00:00:00 2001 From: pdanner Date: Mon, 6 Dec 2010 16:34:52 +0000 Subject: git-svn-id: https://joinup.ec.europa.eu/svn/pdf-as/trunk@671 7b5415b0-85f9-ee4d-85bd-d5d0c3b42d1c --- .../web/servlets/AsynchronousDataResponder.java | 157 +++++ .../servlets/AsynchronousRedirectResponder.java | 184 ++++++ .../gv/egiz/pdfas/web/servlets/DataURLServlet.java | 390 +++++++++++ .../egiz/pdfas/web/servlets/ProvidePDFServlet.java | 119 ++++ .../web/servlets/RetrieveSignatureDataServlet.java | 129 ++++ .../pdfas/web/servlets/SignPreviewServlet.java | 76 +++ .../at/gv/egiz/pdfas/web/servlets/SignServlet.java | 656 +++++++++++++++++++ .../egiz/pdfas/web/servlets/UpdateFormServlet.java | 56 ++ .../pdfas/web/servlets/VerifyPreviewServlet.java | 717 +++++++++++++++++++++ .../gv/egiz/pdfas/web/servlets/VerifyServlet.java | 479 ++++++++++++++ 10 files changed, 2963 insertions(+) create mode 100644 pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/AsynchronousDataResponder.java create mode 100644 pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/AsynchronousRedirectResponder.java create mode 100644 pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/DataURLServlet.java create mode 100644 pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/ProvidePDFServlet.java create mode 100644 pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/RetrieveSignatureDataServlet.java create mode 100644 pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/SignPreviewServlet.java create mode 100644 pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/SignServlet.java create mode 100644 pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/UpdateFormServlet.java create mode 100644 pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/VerifyPreviewServlet.java create mode 100644 pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/VerifyServlet.java (limited to 'pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets') diff --git a/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/AsynchronousDataResponder.java b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/AsynchronousDataResponder.java new file mode 100644 index 0000000..26f1670 --- /dev/null +++ b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/AsynchronousDataResponder.java @@ -0,0 +1,157 @@ +/** + * 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.gv.egiz.pdfas.web.servlets; + +import javax.servlet.http.HttpServlet; + +/** + * Servlet that responds to the data post requests of the local service (e.g. + * BKU). + * + * @deprecated + * + * @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"); +// } +// +// } +// +// // TODO hotfix - already deprecated +// if (logger_.isDebugEnabled()) +// { +// Enumeration header_names = request.getHeaderNames(); +// while (header_names.hasMoreElements()) +// { +// String header_name = (String)header_names.nextElement(); +// String header_value = request.getHeader(header_name); +// logger_.debug("header: name = " + header_name + ", value = " +header_value); +// } +// } +// String user_agent = request.getHeader("User-Agent"); +// logger_.debug("User-Agent header = " + user_agent); +// Properties response_properties = new Properties(); +// BKUPostConnection.parseBKUVersion(user_agent, response_properties); +// response_properties.setProperty("response_string", resp_string); +// si.response_properties[si.current_operation] = response_properties; //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/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/AsynchronousRedirectResponder.java b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/AsynchronousRedirectResponder.java new file mode 100644 index 0000000..80078ed --- /dev/null +++ b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/AsynchronousRedirectResponder.java @@ -0,0 +1,184 @@ +/** + * 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.gv.egiz.pdfas.web.servlets; + +import javax.servlet.http.HttpServlet; + +/** + * Servlet that responds to the redirect requests of the local service (e.g. + * BKU). + * + * @deprecated remove this + * + * @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(); +// SignServlet.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 is true, but maybe there are more requests to process. +// if (si.current_operation < si.requests.length) +// { +// si.finished = false; +// +// LocalRequestHelper.prepareDispatchToLocalConnectionPage(si.requests[si.current_operation], request, response); +// dispatch(request, response, LocalRequestHelper.LOCAL_CONNECTION_PAGE_JSP); +// return; +// } +// +// // all requests have been carried out. +// +// BKUConnector local_conn = (BKUConnector) ConnectorFactory.createConnector(si.connector); +// +// if (si.application.equals("verify")) +// { +// List results = new ArrayList(); +// +// for (int i = 0; i < si.response_properties.length; i++) +// { +// SignatureResponse sig_resp = local_conn.analyzeVerifyResponse(si.response_properties[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); +// +// // The response string must not be null here - otherwise finished mustn't have been set! +//// 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 ; +//// } +// +// // A download blocker may have blocked the first download. +// // So, if the user asks for the document a second time and the sign_result +// // has already been computed - don't recompute it. +// if (si.sign_result == null) +// { +// // refactor WEB +// si.iui.signed_signature_object = null; //local_conn.analyzeSignResponse(si.response_properties[0], si.type); +// +// PdfASID algorithm = FormFields.translateSignatureModeToPdfASID(si.mode); +// Signator signator = SignatorFactory.createSignator(algorithm); +// +// si.sign_result = signator.finishSign(si.iui); +// } +// +// SignServlet.returnSignResponse(si, response); +// } +// +// } +// catch (PresentableException e) +// { +// session.removeAttribute(SessionAttributes.ATTRIBUTE_SESSION_INFORMATION); +// //SessionTable.remove(si.session_id); +// +// e.printStackTrace(); +// SignServlet.prepareDispatchToErrorPage(e, request); +// dispatch(request, response, "/jsp/error.jsp"); +// } +// +// } +} diff --git a/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/DataURLServlet.java b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/DataURLServlet.java new file mode 100644 index 0000000..2f6a76c --- /dev/null +++ b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/DataURLServlet.java @@ -0,0 +1,390 @@ +/** + * + */ +package at.gv.egiz.pdfas.web.servlets; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.net.URL; +import java.util.ArrayList; +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.FileItemFactory; +import org.apache.commons.fileupload.FileUploadException; +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 at.gv.egiz.pdfas.api.PdfAs; +import at.gv.egiz.pdfas.api.commons.Constants; +import at.gv.egiz.pdfas.api.commons.SignatureInformation; +import at.gv.egiz.pdfas.api.exceptions.PdfAsException; +import at.gv.egiz.pdfas.api.internal.LocalBKUParams; +import at.gv.egiz.pdfas.api.internal.PdfAsInternal; +import at.gv.egiz.pdfas.api.verify.VerifyResult; +import at.gv.egiz.pdfas.api.verify.VerifyResults; +import at.gv.egiz.pdfas.web.LocalRequest; +import at.gv.egiz.pdfas.web.helper.ApiHelper; +import at.gv.egiz.pdfas.web.helper.LocalRequestHelper; +import at.gv.egiz.pdfas.web.helper.SessionHelper; +import at.gv.egiz.pdfas.web.helper.SignServletHelper; +import at.gv.egiz.pdfas.web.helper.SigningTimeHelper; +import at.gv.egiz.pdfas.web.session.SessionAttributes; +import at.gv.egiz.pdfas.web.session.SignSessionInformation; +import at.gv.egiz.pdfas.web.session.VerifySessionInformation; +import at.knowcenter.wag.egov.egiz.exceptions.ConnectorException; +import at.knowcenter.wag.egov.egiz.exceptions.SignatureException; + +/** + * @author wprinz + * + */ +public class DataURLServlet extends HttpServlet +{ + + /** + * SVUID. + */ + private static final long serialVersionUID = -5846618335843762752L; + + /** + * The log. + */ + private static Log log = LogFactory.getLog(DataURLServlet.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); + } + + protected void dispatchToResults(VerifyResults results, HttpServletRequest request, + HttpServletResponse response, String backToListURL) throws ServletException, IOException + { + request.setAttribute("results", results); + request.setAttribute("btlurl", backToListURL); + dispatch(request, response, "/jsp/results.jsp"); + } + + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + this.doPost(req, resp); + } + + private static void temporaryRedirect(String redirectURL, HttpServletResponse response) throws IOException { + String encodedRedirect = response.encodeRedirectURL(redirectURL); + response.addHeader("Location", encodedRedirect); + response.setContentType("text/xml"); + response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); + String nop = ""; + PrintWriter pw = response.getWriter(); + response.setCharacterEncoding("UTF-8"); + response.setContentLength(nop.getBytes("UTF-8").length); + log.debug("Redirecting via NullOperationRequest to " + encodedRedirect + "."); + pw.println(nop); + pw.flush(); + pw.close(); + } + +/** + * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse) + */ + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + log.debug("Data URL is accessed."); //$NON-NLS-1$ + + try + { + Object sessionObject = SessionHelper.getSession(request); + + // obsolete since EncodingFilter is set in web.xml + checkRequestCharacterEncoding(request); + + if (sessionObject instanceof SignSessionInformation) + { + SignSessionInformation si = (SignSessionInformation)sessionObject; + processSign(request, response, si); + } + else + { + VerifySessionInformation si = (VerifySessionInformation) sessionObject; + processVerify(request, response, si); + } + + } + catch (PdfAsException e) + { + log.error(e.getMessage(), e); + SignServlet.prepareDispatchToErrorPage(e, request); + dispatch(request, response, "/jsp/error.jsp"); + } + + log.debug("DataURL access finished."); //$NON-NLS-1$ + } + + protected void checkRequestCharacterEncoding(HttpServletRequest request) throws UnsupportedEncodingException + { + if (request.getCharacterEncoding() == null || request.getCharacterEncoding().length() <= 0) //$NON-NLS-1$ + { + log.info("The BKU didn't set a character encoding for the request."); //$NON-NLS-1$ + + log.info("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 != null && xml_response.indexOf("NullOperationResponse") != -1; + } + + private static String retrieveXMLResponse(HttpServletRequest request) throws ServletException { + log.debug("Trying to fetch XMLResponse..."); + String xml_response = null; + if (ServletFileUpload.isMultipartContent(request)) { + log.debug("Response is multipart."); + FileItemFactory factory = new DiskFileItemFactory(); + ServletFileUpload upload = new ServletFileUpload(factory); + try { + List items = upload.parseRequest(request); + Iterator iter = items.iterator(); + while (iter.hasNext()) { + FileItem item = (FileItem) iter.next(); + if (item.isFormField() && "XMLResponse".equals(item.getFieldName())) { + log.debug("XMLResponse part found."); + xml_response = item.getString(); + break; + } + } + } catch (FileUploadException e) { + throw new ServletException(e); + } + } else { + xml_response = request.getParameter("XMLResponse"); + } + log.debug("XMLResponse = " + xml_response); + return xml_response; + } + + protected void processSign(HttpServletRequest request, HttpServletResponse response, SignSessionInformation si) throws ServletException, IOException, PdfAsException + { + log.trace("processSign"); + + String xml_response = retrieveXMLResponse(request); + + PdfAsInternal pdfAsInternal = ApiHelper.getPdfAsInternalFromContext(getServletContext()); + + String server = request.getHeader("server"); + String userAgent = request.getHeader("user-agent"); + String signatureLayout = request.getHeader(Constants.BKU_HEADER_SIGNATURE_LAYOUT); + LocalBKUParams bkuParams = new LocalBKUParams(server, userAgent, signatureLayout); + si.localBKUParams = bkuParams; + + pdfAsInternal.verifyBKUSupport(bkuParams); + +// Properties response_properties = BKUHelper.getBKUProperties(request); +// +// String bkuIdentifier = BKUHelper.getBKUIdentifier(response_properties); +// log.debug("BKU identifier: \"" + bkuIdentifier + "\""); +// +// try { +// SignatureLayoutHandlerFactory.verifyBKUSupport(bkuIdentifier); +// } catch (SettingsException e) { +// throw new ConnectorException(e.getErrorCode(), e.getMessage()); +// } + + if (isNullResponse(xml_response)) + { + log.debug("Received a NullOperationResponse -> answering with the first request."); //$NON-NLS-1$ + + assert si.outputAvailable == false; + assert si.xmlResponse == null; + + log.debug("There are still requests to be performed -> answering with request."); //$NON-NLS-1$ + + LocalRequest local_request = si.localRequest; + + String request_string = local_request.getRequestString(); + + log.debug("request = " + request_string); + response.setContentType("text/xml"); + response.setCharacterEncoding("UTF-8"); + response.getWriter().println(request_string); + } + else if (xml_response != null) + { + log.debug("Received a normal response -> storing the response."); //$NON-NLS-1$ + +// response_properties.setProperty(BKUPostConnection.RESPONSE_STRING_KEY, xml_response); +// +// si.response_properties = response_properties; + si.xmlResponse = xml_response; + + log.debug("All requests have been processed -> processing the responses."); //$NON-NLS-1$ + + // Sign + + if (!si.outputAvailable) + { + PdfAs pdfAs = ApiHelper.getPdfAsFromContext(getServletContext()); + SignServletHelper.finishLocalSign(pdfAs, pdfAsInternal, si); + SigningTimeHelper.checkSigningTimeAgainstHostTime(si.sdi.getSignDate()); +// 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)); +// +// // workaround for invalid signing time +// SigningTimeHelper.checkSigningTimeAgainstHostTime(si.sdi.getSignDate()); +// +// PdfASID algorithm = FormFields.translateSignatureModeToPdfASID(si.mode); +// Signator signator = SignatorFactory.createSignator(algorithm); +// +// si.output = TempDirHelper.createTempDataSink(si.filename + "_signed.pdf"); +// +// signator.finishSign(si.si, si.output); + + si.outputAvailable = true; + } + + if (si.output.getMimeType().equals("text/xml") && si.outputAvailable) + { + // For "detached" signatures, the return value (data sink) is the response xml, + // but when passed through the BKU it is interpreted as another request + // which will generate a return code 1501 + // Then PDF-AS would answer with the response as well generating + // another 1501 and so forth. + // Therefor return it as TXT. + response.setContentType("text/plain"); + response.setCharacterEncoding("UTF-8"); + response.getWriter().println("Das detached XML kann nicht direkt durch die BKU geschliffen werden, weil diese es als Request interpretieren würde. Daher das XML als Text:"); + //response.getWriter().println(si.sdi.getSignSignatureObject().response_properties.getProperty(BKUPostConnection.RESPONSE_STRING_KEY)); + response.getWriter().println(new String(si.signedPdf, "UTF-8")); + } + else + { + // tzefferer: If PDF-AS has been called by an external web-application, we do not + // redirect to download.jsp but return the sign-response immediately + if (si.exappinf != null) { + log.debug("Entering external application interface mode. Skipping redirection to download page."); + SignServletHelper.returnSignResponse(si, request, response); + + // Not needed due to redirection of returnSignResponse. + // Just to clarify that there must not be any code after returnSignResponse. + return; + } else { + log.debug("Preparing download page."); + HttpSession session = request.getSession(true); + log.debug("Putting signed document into session (" + session.getId() + ")."); + session.setAttribute(SessionAttributes.SIGNED_PDF_DOCUMENT, si); + String downloadURL = response.encodeRedirectURL(LocalRequestHelper.getLocalContextAddress(request, response) + "/ProvidePDF"); + log.debug("Creating download URL \"" + downloadURL + "\"."); + session.setAttribute(SessionAttributes.DOWNLOAD_URL_FOR_SIGNED_PDF_DOCUMENT, downloadURL); + temporaryRedirect(response.encodeRedirectURL(LocalRequestHelper.getLocalContextAddress(request, response) + "/jsp/download.jsp") , response); + + // Not needed due to temporaryRedirect. + // Just to clarify that there must not be any code after temporaryRedirect. + return; + } + + // do not insert any code within this else block ! + } + } else { + log.debug("No XMLResponse found. Do nothing."); + } + } + + protected void processVerify(HttpServletRequest request, HttpServletResponse response, VerifySessionInformation si) throws ServletException, IOException, ConnectorException, SignatureException + { + log.trace("processVerify"); + + String xml_response = request.getParameter("XMLResponse"); //$NON-NLS-1$ + log.debug("xml_response = " + xml_response); //$NON-NLS-1$ + + if (isNullResponse(xml_response)) + { + log.debug("Received a NullOperationResponse -> answering with the first request."); //$NON-NLS-1$ + + assert si.currentLocalOperation.current_operation == 0; + } + 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.currentLocalOperation.finishCurrentOperation(xml_response); + } + + if (!si.currentLocalOperation.isFinished()) + { + log.debug("There are still requests to be performed -> answering with request #" + si.currentLocalOperation.current_operation); //$NON-NLS-1$ + + LocalRequest local_request = si.currentLocalOperation.getCurrentLocalRequest(); + + 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$ + + + PdfAsInternal pdfAsInternal = ApiHelper.getPdfAsInternalFromContext(getServletContext()); + final ArrayList resList = new ArrayList(); + for (int i = 0; i < si.currentLocalOperation.response_xmls.length; i++) + { + SignatureInformation sigInfo = (SignatureInformation) si.currentLocalOperation.signaturesToBeverified.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$ + + VerifyResult result = pdfAsInternal.finishLocalVerify(sigInfo, si.connector, si.type, "loc ref content not needed here", si.currentLocalOperation.response_xmls[i]); + resList.add(result); +// SignatureResponse sig_resp = c.analyzeVerifyResponse(si.currentLocalOperation.response_xmls[i]); +// results.add(sig_resp); + } + + si.currentLocalOperation = null; + + URL btlURL = new URL(LocalRequestHelper.getLocalContextAddress(request, response) + "/jsp/verifylist.jsp"); + String backToListURL = response.encodeURL(btlURL.toString()); + + VerifyResults results = new VerifyResults() { + + public List getResults() { + return resList; + } + }; + dispatchToResults(results, request, response, backToListURL); + } + + } +} diff --git a/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/ProvidePDFServlet.java b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/ProvidePDFServlet.java new file mode 100644 index 0000000..fa3072d --- /dev/null +++ b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/ProvidePDFServlet.java @@ -0,0 +1,119 @@ +package at.gv.egiz.pdfas.web.servlets; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +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.logging.Log; +import org.apache.commons.logging.LogFactory; + +import at.gv.egiz.pdfas.web.FormFields; +import at.gv.egiz.pdfas.web.PDFContainer; +import at.gv.egiz.pdfas.web.helper.SignServletHelper; +import at.gv.egiz.pdfas.web.session.SessionAttributes; +import at.gv.egiz.pdfas.web.session.SignSessionInformation; +import at.knowcenter.wag.egov.egiz.exceptions.PresentableException; + +public class ProvidePDFServlet extends HttpServlet { + + /** + * SVUID. + */ + private static final long serialVersionUID = 1L; + + /** + * The log. + */ + private static Log log = LogFactory.getLog(ProvidePDFServlet.class); + + public static Set signedDocuments = Collections.synchronizedSet(new HashSet()); + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + String pdfIdString = request.getParameter(FormFields.FIELD_PDF_ID); + HttpSession session = request.getSession(); + + if (pdfIdString == null) { + log.debug("No " + FormFields.FIELD_PDF_ID + " provided. Trying to retrieve PDF from session (" + session.getId() + ")."); + SignSessionInformation si = (SignSessionInformation) session.getAttribute(SessionAttributes.SIGNED_PDF_DOCUMENT); + if (si == null) { + log.warn("Unable to find signed pdf in session (" + session.getId() + ")."); + SignServlet.prepareDispatchToErrorPage(new PresentableException(600, "Das signierte Dokument konnte nicht gefunden werden."), request); + response.setContentType("text/html"); + response.setCharacterEncoding("UTF-8"); + RequestDispatcher disp = super.getServletContext().getRequestDispatcher("/jsp/error.jsp"); + disp.forward(request, response); + return; + } else { + log.debug("Signed pdf found."); + // do NOT remove signed pdf document from session since IE9 loads this page/servlet twice...) + // Popup-Blocker, Link-Prefetching, IE 9 SmartScreen-Filter...??? + // session.removeAttribute(SessionAttributes.SIGNED_PDF_DOCUMENT); + log.debug("Returning signed pdf to browser."); + SignServletHelper.returnSignResponse(si, request, response); + log.debug("Removing free text (if any) from session."); + session.removeAttribute(UpdateFormServlet.UPLOADFORM_FREETEXT_KEY); + return; + } + } else { + long pdfId = Long.parseLong(pdfIdString); + + byte[] pdf = null; + + synchronized (signedDocuments) { + Iterator it = signedDocuments.iterator(); + + while (it.hasNext() && pdf == null) { + PDFContainer current = (PDFContainer) it.next(); + if (current.id == pdfId) { + pdf = current.pdf; + signedDocuments.remove(current); + } + } + } + + if (pdf != null) { + try { + + SignServletHelper.disableBrowserCacheForResponse(response); + response.setContentType("application/pdf"); + response.setContentLength(pdf.length); + + InputStream is = new ByteArrayInputStream(pdf); + final int bufferSize = 1024; + byte[] buffer = new byte[bufferSize]; + int len = -1; + while ((len = is.read(buffer)) != -1) { + response.getOutputStream().write(buffer, 0, len); + } + response.getOutputStream().flush(); + log.debug("File sent. Invalidating session."); + session.invalidate(); + } catch (IOException e) { + log.error("IO excepton while providing pdf document: " + e.getMessage(), e); + } + } else { + log.error("Unable to find signed pdf (id=" + pdfId + ") in session (" + session.getId() + ")."); + return; + } + + } + + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + +} diff --git a/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/RetrieveSignatureDataServlet.java b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/RetrieveSignatureDataServlet.java new file mode 100644 index 0000000..c7fe841 --- /dev/null +++ b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/RetrieveSignatureDataServlet.java @@ -0,0 +1,129 @@ +/** + * + */ +package at.gv.egiz.pdfas.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 org.apache.commons.io.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import at.gv.egiz.pdfas.api.commons.SignatureInformation; +import at.gv.egiz.pdfas.api.io.DataSource; +import at.gv.egiz.pdfas.api.verify.VerifyResult; +import at.gv.egiz.pdfas.exceptions.web.SessionExpiredException; +import at.gv.egiz.pdfas.web.helper.SessionHelper; +import at.gv.egiz.pdfas.web.session.SignSessionInformation; +import at.gv.egiz.pdfas.web.session.VerifySessionInformation; + +/** + * Retrieves the Signature Data from the session and returns it. + * + * @author wprinz + */ +public class RetrieveSignatureDataServlet extends HttpServlet +{ + + /** + * SVUID. + */ + private static final long serialVersionUID = -5387006236836240538L; + + /** + * The log. + */ + 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) + */ + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + if (log.isDebugEnabled()) { + log.debug("Request for receiving signature data."); //$NON-NLS-1$ + log.debug("Requested session id is = " + request.getRequestedSessionId()); + } + + try + { + Object sessionObject = SessionHelper.getSession(request); + + if (sessionObject instanceof SignSessionInformation) + { + SignSessionInformation si = (SignSessionInformation) sessionObject; + processSign(request, response, si); + } + else + { + VerifySessionInformation si = (VerifySessionInformation) sessionObject; + processVerify(request, response, si); + } + } + catch (SessionExpiredException e) + { + log.error(e.getMessage(), 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.sdi.getSignatureData(), response); + } + + protected void processVerify(HttpServletRequest request, HttpServletResponse response, VerifySessionInformation si) throws ServletException, IOException + { + + DataSource data = null; + if (si.currentLocalOperation != null) + { + data = ((SignatureInformation) si.currentLocalOperation.signaturesToBeverified.get(si.currentLocalOperation.current_operation)).getSignedData(); + } + else + { + data = ((VerifyResult)si.verifyResults.getResults().get(0)).getSignedData(); + } + + writeSignatureData(data, response); + } + + protected void writeSignatureData(DataSource ds, HttpServletResponse response) throws IOException + { + log.trace("Writing " + ds.getMimeType() + " data:"); //$NON-NLS-1$ //$NON-NLS-2$ + + response.setContentType(ds.getMimeType()); + response.setCharacterEncoding(ds.getCharacterEncoding()); + // [tknall] content length must be set, otherwise ITS BKU for Mac rejects the request. + response.setContentLength(ds.getLength()); + IOUtils.copy(ds.createInputStream(), response.getOutputStream()); + // response.getOutputStream().write(sd.getData()); + + log.trace("Writing SignatureData finished."); //$NON-NLS-1$ + } +} diff --git a/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/SignPreviewServlet.java b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/SignPreviewServlet.java new file mode 100644 index 0000000..8d6a436 --- /dev/null +++ b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/SignPreviewServlet.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: SignPreview.java,v 1.2 2006/10/11 07:39:13 wprinz Exp $ + */ +package at.gv.egiz.pdfas.web.servlets; + +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 org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import at.gv.egiz.pdfas.api.exceptions.PdfAsException; +import at.gv.egiz.pdfas.web.helper.SessionHelper; +import at.gv.egiz.pdfas.web.helper.SignServletHelper; +import at.gv.egiz.pdfas.web.session.SignSessionInformation; + +/** + * @author wprinz + */ +public class SignPreviewServlet extends HttpServlet +{ + + protected static Log logger = LogFactory.getLog(SignPreviewServlet.class); + + /** + * 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 + { + try + { + Object sessionObject = SessionHelper.getSession(request); + + SignSessionInformation si = (SignSessionInformation) sessionObject; + + SignServletHelper.finishSign(si, request, response, getServletContext()); + } + catch (PdfAsException e) { + logger.error(e.getMessage(), e); + + SignServlet.prepareDispatchToErrorPage(e, request); + dispatch(request, response, "/jsp/error.jsp"); + } + } +} diff --git a/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/SignServlet.java b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/SignServlet.java new file mode 100644 index 0000000..acd71b0 --- /dev/null +++ b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/SignServlet.java @@ -0,0 +1,656 @@ +/** + * 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.gv.egiz.pdfas.web.servlets; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.URL; +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.commons.io.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import at.gv.egiz.pdfas.api.exceptions.PdfAsException; +import at.gv.egiz.pdfas.api.io.DataSource; +import at.gv.egiz.pdfas.api.io.TextBased; +import at.gv.egiz.pdfas.api.sign.pos.SignaturePositioning; +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.web.ExternAppInformation; +import at.gv.egiz.pdfas.web.FormFields; +import at.gv.egiz.pdfas.web.helper.ApiHelper; +import at.gv.egiz.pdfas.web.helper.SignServletHelper; +import at.gv.egiz.pdfas.web.helper.WebSettingsReader; +import at.gv.egiz.pdfas.web.helper.WebUtils; +import at.gv.egiz.pdfas.web.io.ByteArrayPdfDataSource; +import at.gv.egiz.pdfas.web.itext.IText; +import at.gv.egiz.pdfas.web.session.SessionAttributes; +import at.gv.egiz.pdfas.web.session.SignSessionInformation; +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 com.lowagie.text.DocumentException; + +/** + * 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 SignServlet extends HttpServlet +{ + + /** + * SVUID. + */ + private static final long serialVersionUID = -4156938216903740438L; + + /** + * The log. + */ + private static Log log = LogFactory.getLog(SignServlet.class); + private static Log statLog = LogFactory.getLog("statistic"); + + 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); + } + + // The sign servlet is used for processing the upload only. + // Authentication is deactivated. if required - make an own servlet. + // /** + // * @author modified by tknall + // */ + // 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); + // // start modification tknall + // // logger_.info("password:" + user_password); + // logger_.info("password:XXXXXXXXXXXX"); + // // stop modification tknall + // + // 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; + // } + // // start modification tknall + // } else { + // String user_name = ""; + // String user_password = ""; + // logger_.info("authenticate:User has not been authenticated!"); + // logger_.info("username: UNKNOWN"); + // logger_.info("password: XXXXXXXXXXXX"); + // HttpSession session = request.getSession(); + // session.setAttribute("uname", user_name); + // session.setAttribute("upass", user_password); + // dispatch(request, response, "/jsp/signupload.jsp"); + // } + + // request.setAttribute("error", "Falsche Authentifikation"); + // request.setAttribute("cause", "Passwort oder Benutzername ist falsch"); + // dispatch(request, response, "/jsp/error.jsp"); + // // stop modification tknall + // } + + /** + * Processes the sign upload. + * + * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse) + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + UploadedData ud = null; + ExternAppInformation exappinf = null; +// TablePos pos = null; + SignaturePositioning sigpos = null; + + // for performance measurement + long startTime = 0; + if (statLog.isInfoEnabled()) { + startTime = System.currentTimeMillis(); + } + + + + // check if pdf-as has been called by external webapp + 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); + String sig_mode = (String) request.getParameter(FormFields.FIELD_MODE); + String filename = (String) request.getParameter(FormFields.FIELD_FILENAME); + String pdf_url = (String) request.getParameter(FormFields.FIELD_PDF_URL); + String pdf_id = (String) request.getParameter(FormFields.FIELD_PDF_ID); + String pdf_length = (String) request.getParameter(FormFields.FIELD_FILE_LENGTH); + String invoke_url = (String) request.getParameter(FormFields.FIELD_INVOKE_APP_URL); + String invoke_error_url = (String) request.getParameter(FormFields.FIELD_INVOKE_APP_ERROR_URL); + 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); + + // added by tknall + if (sig_pos_y != null && sig_pos_p != null) { + try + { +// pos = new TablePos("y:" + sig_pos_y + ";p:" + sig_pos_p); + sigpos = new SignaturePositioning("y:" + sig_pos_y + ";p:" + sig_pos_p); + } + catch (PDFDocumentException e) + { + log.warn("Unable to create signature position object: " + e.getMessage(), e); + } + } else { + log.debug("No signature position provided."); + } + + // fixed by tknall: if we already have parameters "&" must be used instead of "?" + String paramSeparator = (pdf_url.indexOf("?") != -1) ? "&" : "?"; + String query = pdf_url + paramSeparator + 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... + UploadedData ud_extern = new UploadedData(); + + ud_extern.file_name = filename; + ud_extern.pdfDataSource = new ByteArrayPdfDataSource(IOUtils.toByteArray(is)); + + // ud_extern.pdf = extern_pdf; +// ud_extern.preview = preview.equalsIgnoreCase("true") ? true : false; + ud_extern.preview = "true".equalsIgnoreCase(preview); + 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, invoke_error_url); + } + else + { + + try + { + + // tzefferer: modified + // UploadedData ud = retrieveUploadedDataFromRequest(request); + UploadedData ud_form = retrieveUploadedDataFromRequest(request); + ud = ud_form; + // end modify + + } + catch (Exception e) + { + log.error(e); + request.setAttribute("error", "signservlet.error"); + request.setAttribute("cause", "signservlet.cause"); + request.setAttribute("resourcebundle", Boolean.TRUE); + dispatch(request, response, "/jsp/error.jsp"); + return; + } + } + try + { + +// not needed, that is done in sign() +// ud.pdfDataSource = PdfAS.applyStrictMode(ud.pdfDataSource); + + SignSessionInformation si = new SignSessionInformation(); // SessionTable.generateSessionInformationObject(); + si.connector = ud.sig_app; + si.application = "sign"; + si.mode = ud.sig_mode; + 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 = sigpos; + // end add + + HttpSession session = request.getSession(); + log.info("Putting signature data into session " + session.getId()); + session.setAttribute(SessionAttributes.ATTRIBUTE_SESSION_INFORMATION, si); + + // String user_name = (String) + // request.getSession().getAttribute(SessionAttributes.ATTRIBUTE_USER_NAME); + // String user_password = (String) + // request.getSession().getAttribute(SessionAttributes.ATTRIBUTE_USER_PASSWORD); + // si.user_name = user_name; + // si.user_password = user_password; + + SignServletHelper.prepareSign(ApiHelper.getPdfAsFromContext(getServletContext()), si); + + if (ud.preview) + { + String submit_url = response.encodeURL(request.getContextPath() + "/SignPreview"); +// String signature_data_url = response.encodeURL(WebUtils.addJSessionID(request.getContextPath() + "/RetrieveSignatureData", request)); + String signature_data_url = response.encodeURL(WebUtils.buildRetrieveSignatureDataURL(request, response)); + + request.setAttribute("submit_url", submit_url); + request.setAttribute("signature_data_url", signature_data_url); + if (si.mode.equals(FormFields.VALUE_MODE_TEXTUAL)){ + request.setAttribute("document_text", ((TextBased)si.sdi.getSignatureData()).getText()); + } + + dispatch(request, response, "/jsp/signpreview.jsp"); + + return; + } + + SignServletHelper.finishSign(si, request, response, getServletContext()); + + // for performance measurement + if (statLog.isInfoEnabled()) { + long endTime = System.currentTimeMillis(); +// String toReport = "SIGN;" + si.mode + ";" + si.filename + ";"+ fileSize + ";" + + String toReport = "SIGN;" + si.mode + ";" + si.connector + ";" + si.pdfDataSource.getLength() + ";" + (endTime - startTime); + + statLog.info(toReport); + } + } + catch (PresentableException e) + { + log.error(e.getMessage(), e); + prepareDispatchToErrorPage(e, request); + dispatch(request, response, "/jsp/error.jsp"); + } catch (Exception e) { + log.error(e.getMessage(), e); + PresentableException pe = new PresentableException(ErrorCode.UNKNOWN_ERROR, e); + prepareDispatchToErrorPage(pe, request); + dispatch(request, response, "/jsp/error.jsp"); + } + } + + // tzefferer:added + 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 + { + DiskFileItemFactory fif = new DiskFileItemFactory(); + fif.setRepository(WebSettingsReader.getTemporaryDirectory()); + ServletFileUpload sfu = new ServletFileUpload(fif); + + 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; + FileItem freeText = null; + FileItem pdfa = null; + + Iterator it = items.iterator(); + HttpSession session = request.getSession(); + while (it.hasNext()) + { + FileItem item = (FileItem) it.next(); + log.debug("item = " + item.getFieldName()); //$NON-NLS-1$ + + if (log.isDebugEnabled()) + { + if (item.isFormField()) + { + String item_string = item.getString("UTF-8"); //$NON-NLS-1$ + log.debug(" form field string = " + item_string); //$NON-NLS-1$ + } + else + { + log.debug(" filename = " + item.getName()); //$NON-NLS-1$ + log.debug(" filesize = " + item.getSize()); //$NON-NLS-1$ + } + } + + if (item.getFieldName().equals(FormFields.FIELD_PREVIEW)) + { + preview_fi = item; + continue; + } + + if (item.getFieldName().equals(FormFields.FIELD_SIGNATURE_TYPE)) + { + sig_type_fi = item; + session.setAttribute(UpdateFormServlet.UPLOADFORM_SIGNATURE_TYPE_KEY, sig_type_fi.getString("UTF-8")); + continue; + } + + if (item.getFieldName().equals(FormFields.FIELD_CONNECTOR)) + { + sig_app_fi = item; + session.setAttribute(UpdateFormServlet.UPLOADFORM_SIGNATURE_DEVICE_KEY, sig_app_fi.getString("UTF-8")); + continue; + } + + if (item.getFieldName().equals(FormFields.FIELD_MODE)) + { + mode_fi = item; + session.setAttribute(UpdateFormServlet.UPLOADFORM_SIGNATURE_MODE_KEY, mode_fi.getString("UTF-8")); + continue; + } + + if (item.getFieldName().equals(FormFields.FIELD_UPLOAD)) + { + file_upload_fi = item; + continue; + } + + if (item.getFieldName().equals(FormFields.FIELD_DOWNLOAD)) + { + download_fi = item; + continue; + } + + if (FormFields.FIELD_PDFA_ENABLED.equals(item.getFieldName())) { + pdfa = item; + session.setAttribute(UpdateFormServlet.UPLOADFORM_PDFA_KEY, pdfa.getString("UTF-8")); + continue; + } + + if (FormFields.FIELD_FREETEXT.equals(item.getFieldName())) { + freeText = item; + String value = freeText.getString("UTF-8"); + if (value != null) { + session.setAttribute(UpdateFormServlet.UPLOADFORM_FREETEXT_KEY, value); + } + continue; + } + + if (FormFields.FIELD_SOURCE.equals(item.getFieldName())) { + session.setAttribute(UpdateFormServlet.UPLOADFORM_SOURCE_KEY, item.getString("UTF-8")); + continue; + } + + throw new ServletException("Unrecognized POST data."); //$NON-NLS-1$ + + } + + if (preview_fi == null || sig_type_fi == null || sig_app_fi == null || (file_upload_fi == null && freeText== null) || download_fi == null) + { + throw new ServletException("Insufficient data provided in request"); //$NON-NLS-1$ + } + + String mode = mode_fi.getString("UTF-8"); //$NON-NLS-1$ + 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."); //$NON-NLS-1$ //$NON-NLS-2$ + } + + String preview_str = preview_fi.getString("UTF-8"); //$NON-NLS-1$ + boolean preview = false; + if (preview_str.equals("true")) //$NON-NLS-1$ + { + preview = true; + } + + boolean download_inline = true; + if (download_fi.getString("UTF-8").equals(FormFields.VALUE_DOWNLOAD_ATTACHMENT)) //$NON-NLS-1$ + { + download_inline = false; + } + + String sig_type = sig_type_fi.getString("UTF-8"); //$NON-NLS-1$ + String sig_app = sig_app_fi.getString("UTF-8"); //$NON-NLS-1$ + + DataSource pdfDataSource; + String doc_file_name = "nofilename"; + // distinguish between file and freetext + if (file_upload_fi != null) { + log.debug("Processing file."); + File f = new File(file_upload_fi.getName()); + doc_file_name = f.getName(); + log.debug("file content type =" + file_upload_fi.getContentType()); //$NON-NLS-1$ + + String extension = VerifyServlet.extractExtension(doc_file_name); + if (extension != null && !extension.equals("pdf")) //$NON-NLS-1$ + { + throw new PDFDocumentException(201, "The provided file '" + doc_file_name + "' doesn't have the PDF extension (.pdf)."); //$NON-NLS-1$//$NON-NLS-2$ + } + + if (file_upload_fi.getSize() <= 0) + { + throw new PDFDocumentException(250, "The document is empty."); //$NON-NLS-1$ + } + + try + { + pdfDataSource = new ByteArrayPdfDataSource(IOUtils.toByteArray(file_upload_fi.getInputStream())); + } + catch (IOException e) + { + throw new PDFDocumentException(201, "Couldn't store the file in the temp dir.", e); + } + } else { + log.debug("Processing free text."); + try { + boolean pdfaEnabled = pdfa != null && "true".equalsIgnoreCase(pdfa.getString()); + byte[] freeTextPDF = IText.createPDF(freeText.getString("UTF-8"), pdfaEnabled); + + pdfDataSource = new ByteArrayPdfDataSource(freeTextPDF); + doc_file_name = IText.DEFAULT_FILENAME; + } catch (DocumentException e) { + throw new PDFDocumentException(201, "Unable to create PDF document.", e); + } catch (IOException e) { + throw new PDFDocumentException(201, "Unable to create PDF document.", e); + } + + } + // byte[] pdf = file_upload_fi.get(); + + UploadedData ud = new UploadedData(); + + ud.preview = preview; + ud.download_inline = download_inline; + ud.sig_type = sig_type; + ud.sig_app = sig_app; + ud.sig_mode = mode; + ud.file_name = doc_file_name; + ud.pdfDataSource = pdfDataSource; + + return ud; + } + + + + + + public static void prepareDispatchToErrorPage(PdfAsException pe, HttpServletRequest request) + { + request.setAttribute("PresentableException", pe); +// if (pe instanceof ErrorCodeException) +// { + request.setAttribute("error", "Fehler " + pe.getErrorCode()); + + String cause = ErrorCodeHelper.getMessageForErrorCode(pe.getErrorCode()); + + if (pe instanceof ExternalErrorException) + { + ExternalErrorException eee = (ExternalErrorException) pe; + cause = eee.getExternalErrorCode() + ": " + eee.getExternalErrorMessage(); + } + request.setAttribute("cause", cause); + + if (pe.getErrorCode() == ErrorCode.PLACEHOLDER_EXCEPTION) + { + 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. " + cause); + } +// } +// 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"); + } + + /** + * 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; + } + + + + + + // tzefferer: added + 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) + { + out.write(buffer, 0, n); + } + } + finally + { + if (bufIn != null) + { + bufIn.close(); + } + } + return out.toByteArray(); + } + + // end add + + protected static class UploadedData + { + protected boolean preview = false; + + protected boolean download_inline = false; + + protected String sig_type = null; + + protected String sig_app = null; + + protected String sig_mode = null; + + protected String file_name = null; + + protected DataSource pdfDataSource = null; + // protected byte[] pdf = null; + } +} \ No newline at end of file diff --git a/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/UpdateFormServlet.java b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/UpdateFormServlet.java new file mode 100644 index 0000000..24aa941 --- /dev/null +++ b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/UpdateFormServlet.java @@ -0,0 +1,56 @@ +package at.gv.egiz.pdfas.web.servlets; + +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.gv.egiz.pdfas.web.FormFields; + +public class UpdateFormServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + public static final String UPLOADFORM_SIGNATURE_TYPE_KEY = "signupload.jsp:signatureType"; + public static final String UPLOADFORM_SIGNATURE_MODE_KEY = "signupload.jsp:signatureMode"; + public static final String UPLOADFORM_SIGNATURE_DEVICE_KEY = "signupload.jsp:signatureKey"; + public static final String UPLOADFORM_PDFA_KEY = "signupload.jsp:pdfaKey"; + public static final String UPLOADFORM_SOURCE_KEY = "signupload.jsp:sourceKey"; + public static final String UPLOADFORM_FREETEXT_KEY = "signupload.jsp:freeTextKey"; + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + this.doPost(request, response); + } + + public static void updateSession(HttpServletRequest request) { + String mode = request.getParameter(FormFields.FIELD_MODE); + String device = request.getParameter(FormFields.FIELD_CONNECTOR); + String type = request.getParameter(FormFields.FIELD_SIGNATURE_TYPE); + String pdfa = request.getParameter(FormFields.FIELD_PDFA_ENABLED); + String source = request.getParameter(FormFields.FIELD_SOURCE); + String freeText = request.getParameter(FormFields.FIELD_FREETEXT); + + HttpSession session = request.getSession(); + session.setAttribute(UPLOADFORM_SIGNATURE_DEVICE_KEY, device); + session.setAttribute(UPLOADFORM_SIGNATURE_MODE_KEY, mode); + session.setAttribute(UPLOADFORM_SIGNATURE_TYPE_KEY, type); + session.setAttribute(UPLOADFORM_PDFA_KEY, pdfa); + session.setAttribute(UPLOADFORM_SOURCE_KEY, source); + if (freeText != null) { + session.setAttribute(UPLOADFORM_FREETEXT_KEY, freeText); + } + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + updateSession(request); + + RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/signupload.jsp"); + dispatcher.forward(request, response); +// response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/jsp/signupload.jsp")); + } + +} diff --git a/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/VerifyPreviewServlet.java b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/VerifyPreviewServlet.java new file mode 100644 index 0000000..243e762 --- /dev/null +++ b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/VerifyPreviewServlet.java @@ -0,0 +1,717 @@ +/** + * 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.gv.egiz.pdfas.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.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +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 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.commons.io.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import at.gv.egiz.pdfas.api.PdfAs; +import at.gv.egiz.pdfas.api.commons.Constants; +import at.gv.egiz.pdfas.api.commons.SignatureInformation; +import at.gv.egiz.pdfas.api.exceptions.PdfAsException; +import at.gv.egiz.pdfas.api.internal.PdfAsInternal; +import at.gv.egiz.pdfas.api.internal.SignatureEntry; +import at.gv.egiz.pdfas.api.verify.VerifyAfterAnalysisParameters; +import at.gv.egiz.pdfas.api.verify.VerifyResults; +import at.gv.egiz.pdfas.web.FormFields; +import at.gv.egiz.pdfas.web.helper.ApiHelper; +import at.gv.egiz.pdfas.web.helper.LocalRequestHelper; +import at.gv.egiz.pdfas.web.helper.SessionHelper; +import at.gv.egiz.pdfas.web.helper.WebSettingsReader; +import at.gv.egiz.pdfas.web.session.VerifySessionInformation; +import at.knowcenter.wag.egov.egiz.exceptions.SignatureException; + +/** + * @author wprinz + */ +public class VerifyPreviewServlet extends HttpServlet +{ + /** + * SVUID. + */ + private static final long serialVersionUID = 6954343542890239109L; + + public static String[] REQUIRED_SIG_KEYS = new String[] { "SIG_DATE", + "SIG_ISSUER", "SIG_VALUE", "SIG_NUMBER", "SIG_ID", "SIG_KZ" }; + + /** + * The logger. + */ + private static final Log logger_ = LogFactory.getLog(VerifyPreviewServlet.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 dispatchToPreview(HttpServletRequest request, HttpServletResponse response, String signedText, int verify_which)throws ServletException, IOException + { + request.setAttribute(FormFields.FIELD_VERIFY_WHICH, new Integer(verify_which)); + request.setAttribute(FormFields.FIELD_SIGNED_TEXT, signedText); + 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(LocalRequestHelper.getLocalContextAddress(request, response) + "/jsp/verifylist.jsp"); + String backToListURL = response.encodeURL(btlURL.toString()); + + return backToListURL; + } + + 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(ServletContext sc, + SignatureInformation signatureInfo, String name_prefix) + { + StringWriter sw = new StringWriter(); + PrintWriter writer = new PrintWriter(sw); + + String[] rkeys = REQUIRED_SIG_KEYS; + + PdfAsInternal pdfAsInternal = ApiHelper.getPdfAsInternalFromContext(sc); + for (int key_idx = 0; key_idx < rkeys.length; key_idx++) + { + String key = rkeys[key_idx]; + SignatureEntry entry = pdfAsInternal.getSignatureEntryFromSignatureInformation(key, signatureInfo); + String value = entry.getValue(); + if ("SIG_ID".equals(key) && value == null) + { + continue; + } + if ("SIG_KZ".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(ServletContext sc, SignatureInformation signatureInfo, + String name_prefix, boolean write_value) + { + StringWriter sw = new StringWriter(); + PrintWriter writer = new PrintWriter(sw); + + writer.println(""); + + String[] rkeys = REQUIRED_SIG_KEYS; + + PdfAsInternal pdfAsInternal = ApiHelper.getPdfAsInternalFromContext(sc); + for (int key_idx = 0; key_idx < rkeys.length; key_idx++) + { + String key = rkeys[key_idx]; + SignatureEntry entry = pdfAsInternal.getSignatureEntryFromSignatureInformation(key, signatureInfo); + String caption = entry.getCaption(); + String value = entry.getValue(); + if ("SIG_ID".equals(key) && value == null) + { + continue; + } + if ("SIG_KZ".equals(key) && value == null) + { + continue; + } + + writer.println(" "); + writer.println(" "); + writer.println(" "); + writer.println(" "); + } + writer.println("
" + caption + ":"); + + value = value.replaceAll("\\s", " "); + // wuhu! replacing all \" with \" + value = value.replaceAll("\\\"", "\\\""); + + String input_key = name_prefix + key; + writer.println(" "); + + writer.println("
"); + + return sw.toString(); + } + + public static String renderRequiredKeysText(ServletContext sc, SignatureInformation signatureInformation) + { + StringWriter sw = new StringWriter(); + PrintWriter writer = new PrintWriter(sw); + + writer.println(""); + + // just render useful information + // FIXME: NPE in case SignatureTypes.SIG_NAME is not used (in case of friendly signer name) + // Problem: SignatureTypes.SIG_NAME is defined as Signer-RFC2253Name, but there is not certain + // key for friendly name (e.g. SIG_SUBJECT or SIG_FOO), therefore we do not know which key contains + // the friendly signer name + + // workaround: include "SIG_SUBJECT" since it is usually used + String[] rkeys = { "SIG_NAME", "SIG_SUBJECT", "SIG_DATE", "SIG_ISSUER", "SIG_NUMBER"}; // SignatureTypes.REQUIRED_SIG_KEYS; + + PdfAsInternal pdfAsInternal = ApiHelper.getPdfAsInternalFromContext(sc); + for (int key_idx = 0; key_idx < rkeys.length; key_idx++) + { + String key = rkeys[key_idx]; + SignatureEntry entry = pdfAsInternal.getSignatureEntryFromSignatureInformation(key, signatureInformation); + if (entry == null) { + continue; + } + String caption = entry.getCaption(); + String value = entry.getValue(); + if (caption == null || value == null) { + continue; + } + +// if (SignatureTypes.SIG_KZ.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(VerifyResults verifyResults, HttpServletRequest request, + HttpServletResponse response, boolean backbutton, String backToListURL) throws ServletException, IOException + { + request.setAttribute("results", verifyResults); + request.setAttribute("backbutton", backbutton ? "true" : "false"); + request.setAttribute("btlurl", backToListURL); + 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 + { + try + { + Object sessionObject = SessionHelper.getSession(request); + + VerifySessionInformation si = (VerifySessionInformation)sessionObject; + + + 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.analyzeResult.getSignatures(); + + if (verify_which >= 0) + { + if (verify_which >= si.analyzeResult.getSignatures().size()) + { + throw new SignatureException(312, "The selected signature to be verified doesn't exist."); + } + +// SignatureHolder holder = (SignatureHolder) si.signature_holders.get(verify_which); +// si.current_operation = verify_which; + + SignatureInformation sigInfo = (SignatureInformation) si.analyzeResult.getSignatures().get(verify_which); + holders_to_verify = new ArrayList(); + holders_to_verify.add(sigInfo); + + if (preview == true) + { + if (sigInfo.getSignatureType() == Constants.SIGNATURE_TYPE_BINARY) + { +// BinarySignatureHolder binary_holder = (BinarySignatureHolder) holder; + response.setContentType("application/pdf"); + IOUtils.copy(sigInfo.getSignedData().createInputStream(), response.getOutputStream()); +// StreamUtils.writeInputStreamToOutputStream(binary_holder.getSignedPdf().createInputStream(), response.getOutputStream()); +// 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)); + PdfAsInternal pdfAsInternal = ApiHelper.getPdfAsInternalFromContext(getServletContext()); + String signedText = pdfAsInternal.getSignedText(sigInfo); + dispatchToPreview(request, response, signedText, verify_which); + } + + return; + } + + } + + verifyAndDispatch(ApiHelper.getPdfAsInternalFromContext(getServletContext()), request, response, si, holders_to_verify, verify_which); + + } + catch (PdfAsException e) + { + logger_.error(e.getMessage(), e); + SignServlet.prepareDispatchToErrorPage(e, request); + dispatch(request, response, "/jsp/error.jsp"); + } + } + + private void verifyAndDispatch(PdfAsInternal pdfAsInternal, HttpServletRequest request, HttpServletResponse response, VerifySessionInformation si, List holders_to_verify, int verify_which) throws IOException, ServletException, PdfAsException { + if (LocalRequestHelper.isConnectorLocal(si.connector)) + { + String dispatch_to = LocalRequestHelper.processLocalVerify(pdfAsInternal, si, holders_to_verify, request, response); + dispatch(request, response, dispatch_to); + + return; + } + + PdfAs pdfAs = ApiHelper.getPdfAsFromContext(getServletContext()); + VerifyAfterAnalysisParameters verifyAfterAnalysisParameters = new VerifyAfterAnalysisParameters(); + verifyAfterAnalysisParameters.setAnalyzeResult(si.analyzeResult); + verifyAfterAnalysisParameters.setSignatureDevice(si.connector); + verifyAfterAnalysisParameters.setVerifySignatureIndex(verify_which); + VerifyResults verifyResults = pdfAs.verify(verifyAfterAnalysisParameters); + + boolean backbutton = true; + if (verify_which >= 0) + { + backbutton = false; + } + URL btlURL = new URL(LocalRequestHelper.getLocalContextAddress(request, response) + "/jsp/verifylist.jsp"); + String backToListURL = response.encodeURL(btlURL.toString()); + dispatchToResults(verifyResults, request, response, backbutton, backToListURL); + } + +protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + DiskFileItemFactory fif = new DiskFileItemFactory(); + fif.setRepository(WebSettingsReader.getTemporaryDirectory()); + ServletFileUpload sfu = new ServletFileUpload(fif); + + try + { + Object sessionObject = SessionHelper.getSession(request); + + PdfAsInternal pdfAsInternal = ApiHelper.getPdfAsInternalFromContext(getServletContext()); + + VerifySessionInformation si = (VerifySessionInformation)sessionObject; + + + String text_to_be_verified = null; + + int verify_which = -1; + boolean verify = false; + + List items = sfu.parseRequest(request); + + Map sigValues = new HashMap(); + 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)) + { + text_to_be_verified = item.getString("UTF-8"); +// String raw_document_text = item.getString("UTF-8"); +// text_to_be_verified = pdfAsInternal.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); + sigValues.put(key, value); + logger_.debug("sig_obj_number" + key + " = " + value); + } + +// SignatureHolder old_holder = (SignatureHolder) si.signature_holders.get(verify_which); +// TempDirHelper.deleteDataSourceIfFileBased(old_holder.getDataSource()); + +// TextDataSource tds = TempDirHelper.placeTextIntoTempDir(text_to_be_verified, "_previewholder.utf8.txt"); +// SignatureHolder new_holder = new TextualSignatureHolder(tds, signature_object); + +// si.signature_holders.set(verify_which, new_holder); + + si.analyzeResult = pdfAsInternal.analyzeFromRawText(text_to_be_verified, sigValues); + + if (verify == false) + { + dispatchToDataOk(request, response); + return; + } + + List holders_to_verify = si.analyzeResult.getSignatures(); + + if (verify_which >= 0) + { + if (verify_which >= si.analyzeResult.getSignatures().size()) + { + throw new SignatureException(312, "The selected signature to be verified doesn't exist."); + } + + SignatureInformation sigInfo = (SignatureInformation) si.analyzeResult.getSignatures().get(verify_which); + holders_to_verify = new ArrayList(); + holders_to_verify.add(sigInfo); + } + + verifyAndDispatch(pdfAsInternal, request, response, si, holders_to_verify, verify_which); + } + catch (FileUploadException e) + { + request.setAttribute("error", "verifypreviewservlet.error"); + request.setAttribute("cause", "verifypreviewservlet.cause"); + request.setAttribute("resourcebundle", Boolean.TRUE); + dispatch(request, response, "/jsp/error.jsp"); + } + catch (PdfAsException e) + { + logger_.error(e.getMessage(), e); + SignServlet.prepareDispatchToErrorPage(e, request); + dispatch(request, response, "/jsp/error.jsp"); + } + } +} diff --git a/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/VerifyServlet.java b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/VerifyServlet.java new file mode 100644 index 0000000..938f7bf --- /dev/null +++ b/pdf-as-web/src/main/java/at/gv/egiz/pdfas/web/servlets/VerifyServlet.java @@ -0,0 +1,479 @@ +/* + * 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.gv.egiz.pdfas.web.servlets; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URL; +import java.util.Arrays; +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.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import at.gv.egiz.pdfas.api.PdfAs; +import at.gv.egiz.pdfas.api.analyze.AnalyzeParameters; +import at.gv.egiz.pdfas.api.analyze.AnalyzeResult; +import at.gv.egiz.pdfas.api.commons.Constants; +import at.gv.egiz.pdfas.api.exceptions.PdfAsException; +import at.gv.egiz.pdfas.api.internal.PdfAsInternal; +import at.gv.egiz.pdfas.api.io.DataSource; +import at.gv.egiz.pdfas.api.verify.VerifyAfterAnalysisParameters; +import at.gv.egiz.pdfas.api.verify.VerifyResult; +import at.gv.egiz.pdfas.api.verify.VerifyResults; +import at.gv.egiz.pdfas.web.FormFields; +import at.gv.egiz.pdfas.web.helper.ApiHelper; +import at.gv.egiz.pdfas.web.helper.LocalRequestHelper; +import at.gv.egiz.pdfas.web.helper.WebSettingsReader; +import at.gv.egiz.pdfas.web.helper.WebUtils; +import at.gv.egiz.pdfas.web.io.ByteArrayPdfDataSource; +import at.gv.egiz.pdfas.web.io.TextDataSource; +import at.gv.egiz.pdfas.web.session.SessionAttributes; +import at.gv.egiz.pdfas.web.session.VerifySessionInformation; +import at.knowcenter.wag.egov.egiz.exceptions.PDFDocumentException; +import at.knowcenter.wag.egov.egiz.exceptions.SettingNotFoundException; + +/** + * 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 VerifyServlet extends HttpServlet +{ + + /** + * SVUID. + */ + private static final long serialVersionUID = 309198792358636766L; + + /** + * The log. + */ + private static Log log = LogFactory.getLog(SignServlet.class); + + protected void dispatch(HttpServletRequest request, HttpServletResponse response, String resource) throws ServletException, IOException + { + response.setContentType("text/html"); //$NON-NLS-1$ + response.setCharacterEncoding("UTF-8"); //$NON-NLS-1$ + + RequestDispatcher disp = getServletContext().getRequestDispatcher(resource); + disp.forward(request, response); + } + + protected void dispatchToResults(VerifyResults verifyResults, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + request.setAttribute("results", verifyResults); //$NON-NLS-1$ + dispatch(request, response, "/jsp/results.jsp"); //$NON-NLS-1$ + } + + /** + * Processes the verify upload. + * + * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse) + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + // for performance measurement + long startTime = 0; + long fileSize = 0; + if (log.isInfoEnabled()) { + startTime = System.currentTimeMillis(); + } + try + { + UploadedData ud = retrieveUploadedDataFromRequest(request); + + VerifySessionInformation si = new VerifySessionInformation(); + si.connector = ud.sig_app; + si.application = "verify"; + si.mode = null; + si.inputDataSource = ud.dataSource; + si.type = null; +// si.user_name = null; +// si.user_password = null; + + PdfAs pdfAs = ApiHelper.getPdfAsFromContext(getServletContext()); + PdfAsInternal pdfAsInternal = ApiHelper.getPdfAsInternalFromContext(getServletContext()); + AnalyzeParameters analyzeParameters = new AnalyzeParameters(); + analyzeParameters.setDocument(ud.dataSource); + analyzeParameters.setVerifyMode(Constants.VERIFY_MODE_FULL_CONSERVATIVE); + AnalyzeResult analyzeResult = pdfAs.analyze(analyzeParameters); + si.analyzeResult = analyzeResult; + + // List signature_holders = extractSignatureHoldersFromFile(ud.file_name, + // ud.file_data); +// List signature_holders = extractSignatureHolders(ud.dataSource); +// +// TempDirHelper.storeTextSignatureHoldersIfApplicable(signature_holders, "_textholder.utf8.txt"); +// +// si.signature_holders = signature_holders; + + request.getSession().setAttribute(SessionAttributes.ATTRIBUTE_SESSION_INFORMATION, si); + + if (ud.preview) + { + dispatch(request, response, "/jsp/verifylist.jsp"); + // VerifyPreview.formatPreview(signature_holders, connector, request, + // response); + } + else + { + if (LocalRequestHelper.isConnectorLocal(si.connector)) + { + String dispatch_to = LocalRequestHelper.processLocalVerify(pdfAsInternal, si, analyzeResult.getSignatures(), request, response); + + dispatch(request, response, dispatch_to); + return; + } + +// String host = request.getServerName(); + // TODO still required for old communication with MOA-SS/SP +// URL loc_ref_URL = new URL(WebUtils.addJSessionID(LocalRequestHelper.getLocalContextAddress(request, response) + "/RetrieveSignatureData", request)); +// URL loc_ref_URL = new URL(WebUtils.buildRetrieveSignatureDataURL(request, response)); +// String loc_ref_url = response.encodeURL(loc_ref_URL.toString()); + + VerifyAfterAnalysisParameters verifyAfterAnalysisParameters = new VerifyAfterAnalysisParameters(); + verifyAfterAnalysisParameters.setAnalyzeResult(si.analyzeResult); + verifyAfterAnalysisParameters.setSignatureDevice(si.connector); + verifyAfterAnalysisParameters.setVerifySignatureIndex(-1); + VerifyResults verifyResults = pdfAs.verify(verifyAfterAnalysisParameters); + si.verifyResults = verifyResults; + + dispatchToResults(verifyResults, request, response); + + // for performance measurement + if (log.isInfoEnabled()) { + long endTime = System.currentTimeMillis(); + String toReport = "VERIFY;"+ ud.file_name + ";"+ 0 + ";" + (endTime - startTime) + ";" + debugVerifyResults(verifyResults); + log.info(toReport); + } + + } + + } + 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_verify.jsp"); + } + catch (PdfAsException e) + { + log.error(e.getMessage(), e); + SignServlet.prepareDispatchToErrorPage(e, request); + dispatch(request, response, "/jsp/error_verify.jsp"); + } + + } + + protected UploadedData retrieveUploadedDataFromRequest(HttpServletRequest request) throws ServletException, UnsupportedEncodingException, FileUploadException, PDFDocumentException + { + DiskFileItemFactory fif = new DiskFileItemFactory(); + fif.setRepository(WebSettingsReader.getTemporaryDirectory()); + + ServletFileUpload sfu = new ServletFileUpload(fif); + + List items = sfu.parseRequest(request); + + FileItem upload_fi = null; + FileItem connector_fi = null; + // FileItem mode_fi = null; + FileItem preview_fi = null; + + String characterEncoding = request.getCharacterEncoding(); + log.debug("request character encoding = " + characterEncoding); + + { + Iterator it = items.iterator(); + while (it.hasNext()) + { + FileItem item = (FileItem) it.next(); + log.debug("item = " + item.getFieldName()); //$NON-NLS-1$ + + if (item.isFormField()) + { + String item_string = item.getString("UTF-8"); //$NON-NLS-1$ + log.debug(" form field string = " + item_string); //$NON-NLS-1$ + } + else + { + log.debug(" filename = " + item.getName()); //$NON-NLS-1$ + log.debug(" filesize = " + item.getSize()); //$NON-NLS-1$ + } + + 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."); //$NON-NLS-1$ + } + } + + if (upload_fi == null || connector_fi == null || /* mode_fi == null || */preview_fi == null) + { + throw new ServletException("Unsufficient data provided in request."); //$NON-NLS-1$ + } + + String connector = connector_fi.getString("UTF-8"); //$NON-NLS-1$ + + // 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"); //$NON-NLS-1$ + if (!preview_str.equals(FormFields.VALUE_TRUE) && !preview_str.equals(FormFields.VALUE_FALSE)) + { + throw new ServletException("The preview '" + preview_str + "' is unrecognized."); //$NON-NLS-1$//$NON-NLS-2$ + } + boolean preview = false; + if (preview_str.equals(FormFields.VALUE_TRUE)) + { + preview = true; + } + + // process the request + DataSource dataSource = convertUploadToDataSource(upload_fi); + + UploadedData ud = new UploadedData(); + ud.preview = preview; + ud.sig_app = connector; + ud.file_name = upload_fi.getName(); + ud.dataSource = dataSource; + // ud.file_data = document_bytes; + + return ud; + } + + protected DataSource convertUploadToDataSource(FileItem upload_fi) throws PDFDocumentException + { + log.debug("file content type =" + upload_fi.getContentType()); //$NON-NLS-1$ + log.debug("file size = " + upload_fi.getSize()); //$NON-NLS-1$ + if (upload_fi.getSize() <= 0) + { + throw new PDFDocumentException(250, "The document is empty."); //$NON-NLS-1$ + } + + + // TR: do not check MIME-type of incoming file - might vary depending on the browser used + if ((upload_fi.getContentType() != null ) && ((upload_fi.getContentType().startsWith("application/pdf") || upload_fi.getContentType().startsWith("application/x-download") ))) + { + return new ByteArrayPdfDataSource(upload_fi.get()); +// try +// { +// String fileNameSuffix = TempDirHelper.extractFileNameSuffix(upload_fi.getName()); +// PdfDataSource pdfDataSource = TempDirHelper.placePdfIntoTempDir(upload_fi.getInputStream(), fileNameSuffix); +// return pdfDataSource; +// } +// catch (IOException e) +// { +// throw new PDFDocumentException(201, "The document could not be placed in the temp dir.", e); //$NON-NLS-1$ +// } + // byte[] document_bytes = upload_fi.get(); + } + + try + { +// String fileNameSuffix = TempDirHelper.extractFileNameSuffix(upload_fi.getName()); + String text = new String(upload_fi.get(), "UTF-8"); //$NON-NLS-1$ + TextDataSource textDataSource = new TextDataSource(text); + return textDataSource; + } + catch (IOException e) + { + throw new PDFDocumentException(201, e); + } + } +// +// protected List extractSignatureHolders(DataSource dataSource) throws PresentableException +// { +// VerificationFilterParameters parameters = SettingsHelper.readVerificationFilterParametersFromSettings(); +// +// ExtractionStage es = new ExtractionStage(); +// List signature_holders = es.extractSignatureHolders(dataSource, parameters); +// +// // filter out NoSignatureHolders that are possibly present due to the direct call method extractSignatureHolders() +// List filtered_signature_holders = new ArrayList(); +// Iterator it = signature_holders.iterator(); +// while(it.hasNext()) { +// SignatureHolder current = (SignatureHolder) it.next(); +// if(!(current instanceof NoSignatureHolder)) { +// filtered_signature_holders.add(current); +// } +// } +// +// if (filtered_signature_holders.size() == 0) +// { +// throw new PDFDocumentException(ErrorCode.DOCUMENT_NOT_SIGNED, "PDF document not signed."); //$NON-NLS-1$ +// } +// +// return filtered_signature_holders; +// } + + // TODO obsolete method - remove + // protected List extractSignatureHoldersFromFile(String file_name, byte[] + // data) throws UnsupportedEncodingException, PresentableException + // { + // VerificationFilterParameters parameters = new + // VerificationFilterParametersImpl(false, false, true); + // ExtractionStage es = new ExtractionStage(); + // // VerificationFilter vf = new VerificationFilter(); + // List signature_holders = null; + // + // String extension = extractExtension(file_name); + // + // String raw_text = null; + // if (file_name == null || (extension != null && extension.equals("txt"))) + // //$NON-NLS-1$ + // { + // raw_text = new String(data, "UTF-8"); //$NON-NLS-1$ + // + // signature_holders = es.extractSignatureHolders(new + // TextDataSourceImpl(raw_text), parameters); + // // signature_holders = vf.extractSignaturesFromPlainText(raw_text); + // } + // else + // { + // signature_holders = es.extractSignatureHolders(new + // ByteArrayPdfDataSourceImpl(data), parameters); + // + // // signature_holders = vf.extractSignaturesFromPdf(data); + // } + // + // if (signature_holders.size() == 0) + // { + // throw new PDFDocumentException(206, "PDF document not signed."); + // //$NON-NLS-1$ + // } + // + // return signature_holders; + // } + + /** + * 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); + } + + protected static class UploadedData + { + protected boolean preview = false; + + protected String sig_app = null; + + protected String file_name = null; + + protected DataSource dataSource = null; + // protected byte[] file_data = null; + } + + /** + * Formats the verification results for debugging. Returns 0 if no error occurs or the sum of all error-codes. + * + * @param verifyResults + * + * @param writer + * The output sink to write the formatted text to. + * @throws SettingNotFoundException + * Forwarded exception. + */ + protected static int debugVerifyResults(VerifyResults verifyResults) throws SettingNotFoundException + { + int toreturn = 0; + Iterator it = verifyResults.getResults().iterator(); + while (it.hasNext()) + { + VerifyResult result = (VerifyResult) it.next(); + + toreturn += result.getValueCheckCode().getCode(); + } + return toreturn; + } + + public boolean isPDF(byte[] data) { + final byte[] PDF_MAGIC_NUMBER = { (byte) 0x25, (byte) 0x50, (byte) + 0x44, (byte) 0x46 }; // %PDF + if (data == null || data.length < PDF_MAGIC_NUMBER.length) { + return false; + } + byte[] documentHeader = new byte[PDF_MAGIC_NUMBER.length]; + System.arraycopy(data, 0, documentHeader, 0, documentHeader.length); + return Arrays.equals(documentHeader, PDF_MAGIC_NUMBER); + } + + +} \ No newline at end of file -- cgit v1.2.3