/**
* Copyright 2006 by Know-Center, Graz, Austria
* PDF-AS has been contracted by the E-Government Innovation Center EGIZ, a
* joint initiative of the Federal Chancellery Austria and Graz University of
* Technology.
*
* Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
* the European Commission - subsequent versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
* http://www.osor.eu/eupl/
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*
* This product combines work with different licenses. See the "NOTICE" text
* file for details on the various modules and licenses.
* The "NOTICE" text file is part of the distribution. Any derivative works
* that you distribute must include a readable copy of the "NOTICE" text file.
*
* $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 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("
");
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;
}
writer.println(" ");
writer.println(" " + caption + ": | ");
writer.println(" ");
value = value.replaceAll("\\s", " ");
value = value.replaceAll("\\\"", "\\\"");
writer.println(" " + value);
writer.println(" | ");
writer.println("
");
}
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");
}
/**
* 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.");
}
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)
{
response.setContentType("application/pdf");
IOUtils.copy(sigInfo.getSignedData().createInputStream(), response.getOutputStream());
}
else
{
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");
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");
sigValues.put(key, value);
logger_.debug("sig_obj_number" + key + " = " + value);
}
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");
}
}
}