/**
* Copyright (c) 2006 by Know-Center, Graz, Austria
*
* This software is the confidential and proprietary information of Know-Center,
* Graz, Austria. You shall not disclose such Confidential Information and shall
* use it only in accordance with the terms of the license agreement you entered
* into with Know-Center.
*
* KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
* THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
* NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
* LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES.
*
* $Id: Sign.java,v 1.7 2006/10/11 07:39:13 wprinz Exp $
*/
package at.knowcenter.wag.egov.egiz.web;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import at.knowcenter.wag.egov.egiz.PdfAS;
import at.knowcenter.wag.egov.egiz.PdfASID;
import at.knowcenter.wag.egov.egiz.cfg.ConfigLogger;
import at.knowcenter.wag.egov.egiz.cfg.SettingsReader;
import at.knowcenter.wag.egov.egiz.exceptions.ErrorCodeException;
import at.knowcenter.wag.egov.egiz.exceptions.PDFDocumentException;
import at.knowcenter.wag.egov.egiz.exceptions.PlaceholderException;
import at.knowcenter.wag.egov.egiz.exceptions.PresentableException;
import at.knowcenter.wag.egov.egiz.framework.SignResult;
import at.knowcenter.wag.egov.egiz.framework.Signator;
import at.knowcenter.wag.egov.egiz.framework.SignatorFactory;
import at.knowcenter.wag.egov.egiz.framework.signators.DetachedSignator_1_0_0;
import at.knowcenter.wag.egov.egiz.sig.ConnectorFactory;
import at.knowcenter.wag.egov.egiz.tools.CodingHelper;
/**
* This method is the sign servlet for the pdf-as web application. It takes get
* and post requests fill out jsp templates and give the user feedback about the
* results of the sign process
*
* @author wlackner
* @author wprinz
*/
public class Sign extends HttpServlet
{
/**
* SVUID.
*/
private static final long serialVersionUID = -4156938216903740438L;
/**
* Authorisation marker for the http header string.
*/
protected static final String AUTH = "authorization";
/**
* Authorisation marker for the http header string.
*/
protected static final String AUTH_BASIC = "Basic";
/**
* The logger.
*/
private static final Logger logger_ = ConfigLogger.getLogger(Sign.class);
protected void dispatch(HttpServletRequest request,
HttpServletResponse response, String resource) throws ServletException, IOException
{
dispatch(request, response, resource, getServletContext());
}
protected static void dispatch(HttpServletRequest request,
HttpServletResponse response, String resource, ServletContext context) throws ServletException, IOException
{
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
RequestDispatcher disp = context.getRequestDispatcher(resource);
disp.forward(request, response);
}
/**
* @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
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
DiskFileItemFactory fif = new DiskFileItemFactory();
fif.setRepository(SettingsReader.getTemporaryDirectory());
ServletFileUpload sfu = new ServletFileUpload(fif);
try
{
List items = sfu.parseRequest(request);
FileItem preview_fi = null;
FileItem sig_type_fi = null;
FileItem sig_app_fi = null;
FileItem mode_fi = null;
FileItem file_upload_fi = null;
FileItem download_fi = null;
Iterator it = items.iterator();
while (it.hasNext())
{
FileItem item = (FileItem) it.next();
logger_.debug("item = " + item.getFieldName());
if (item.isFormField())
{
byte[] item_data = item.get();
String item_string = new String(item_data, "UTF-8");
logger_.debug(" form field string = " + item_string);
}
else
{
logger_.debug(" filename = " + item.getName());
logger_.debug(" filesize = " + item.getSize());
}
if (item.getFieldName().equals(FormFields.FIELD_PREVIEW))
{
preview_fi = item;
continue;
}
if (item.getFieldName().equals(FormFields.FIELD_SIGNATURE_TYPE))
{
sig_type_fi = item;
continue;
}
if (item.getFieldName().equals(FormFields.FIELD_CONNECTOR))
{
sig_app_fi = item;
continue;
}
if (item.getFieldName().equals(FormFields.FIELD_MODE))
{
mode_fi = item;
continue;
}
if (item.getFieldName().equals(FormFields.FIELD_UPLOAD))
{
file_upload_fi = item;
continue;
}
if (item.getFieldName().equals(FormFields.FIELD_DOWNLOAD))
{
download_fi = item;
continue;
}
throw new ServletException("unrecognized POST data.");
}
if (preview_fi == null || sig_type_fi == null || sig_app_fi == null || file_upload_fi == null || download_fi == null)
{
throw new ServletException("Unsufficient data provided in request");
}
String mode = mode_fi.getString("UTF-8");
if (!mode.equals(FormFields.VALUE_MODE_BINARY) && !mode.equals(FormFields.VALUE_MODE_TEXTUAL) && !mode.equals(FormFields.VALUE_MODE_DETACHED))
{
throw new ServletException("The mode '" + mode + "' is unrecognized.");
}
String preview_str = preview_fi.getString("UTF-8");
boolean preview = false;
if (preview_str.equals("true"))
{
preview = true;
}
boolean download_inline = true;
if (download_fi.getString("UTF-8").equals(FormFields.VALUE_DOWNLOAD_ATTACHMENT))
{
download_inline = false;
}
String sig_type = sig_type_fi.getString("UTF-8");
String connector = sig_app_fi.getString("UTF-8");
String doc_file_name = file_upload_fi.getName();
logger_.debug(" file content type =" + file_upload_fi.getContentType());
String extension = Verify.extractExtension(doc_file_name);
if (extension != null && !extension.equals("pdf"))
{
throw new PDFDocumentException(201, "The provided file '" + doc_file_name + "' doesn't have the PDF extension (.pdf).");
}
byte[] pdf = file_upload_fi.get();
if (file_upload_fi.getSize() <= 0)
{
throw new PDFDocumentException(250, "The document is empty.");
}
PdfAS.applyStrictMode(pdf);
String user_name = (String) request.getSession().getAttribute(SessionAttributes.ATTRIBUTE_USER_NAME);
String user_password = (String) request.getSession().getAttribute(SessionAttributes.ATTRIBUTE_USER_PASSWORD);
SessionInformation si = new SessionInformation(); // SessionTable.generateSessionInformationObject();
si.connector = connector;
si.application = "sign";
si.mode = mode;
si.pdf = pdf;
si.type = sig_type;
si.user_name = user_name;
si.user_password = user_password;
si.filename = formatFileName(file_upload_fi.getName());
si.download_inline = download_inline;
prepareSign(si);
if (preview)
{
request.getSession().setAttribute(SessionAttributes.ATTRIBUTE_SESSION_INFORMATION, si);
String submit_url = response.encodeURL(request.getContextPath() + "/SignPreview");
request.setAttribute("submit_url", submit_url);
dispatch(request, response, "/jsp/signpreview.jsp");
return;
}
finishSign(si, request, response, getServletContext());
}
catch (FileUploadException e)
{
request.setAttribute("error", "Fehler beim Upload der Daten");
request.setAttribute("cause", "Beim Upload der Daten ist ein Fehler aufgetreten.");
dispatch(request, response, "/jsp/error.jsp");
}
catch (PresentableException e)
{
e.printStackTrace();
prepareDispatchToErrorPage(e, request);
dispatch(request, response, "/jsp/error.jsp");
}
}
public static void prepareSign(SessionInformation si) throws PresentableException
{
PdfASID algorithm = FormFields.translateSignatureModeToPdfASID(si.mode);
Signator signator = SignatorFactory.createSignator(algorithm);
si.iui = signator.prepareSign(si.pdf, si.type, null, ConnectorFactory.needsSIG_ID(si.connector));
}
public static void finishSign(SessionInformation si,
HttpServletRequest request, HttpServletResponse response, ServletContext context) throws PresentableException, IOException, ServletException
{
if (ConnectorFactory.isConnectorLocal(si.connector))
{
LocalRequestHelper.processLocalSign(si, request, response);
dispatch(request, response, LocalRequestHelper.LOCAL_CONNECTION_PAGE_JSP, context);
return;
}
PdfASID algorithm = FormFields.translateSignatureModeToPdfASID(si.mode);
Signator signator = SignatorFactory.createSignator(algorithm);
// FIXME refactor WEB
si.iui.signed_signature_object = null; //PdfAS.sign(si.iui.document_text, si.type, si.connector, si.user_name, si.user_password);
si.sign_result = signator.finishSign(si.iui);
returnSignResponse(si, response);
}
public static void prepareDispatchToErrorPage(PresentableException pe,
HttpServletRequest request)
{
if (pe instanceof ErrorCodeException)
{
ErrorCodeException ece = (ErrorCodeException) pe;
request.setAttribute("error", "Fehler " + ece.getErrorCode());
String cause = ece.getErrorCodeMessage();
if (ece.hasExternalErrorMessage())
{
cause = ece.getExternalErrorCode() + ": " + ece.getExternalErrorMessage();
}
request.setAttribute("cause", cause);
if (pe instanceof PlaceholderException)
{
PlaceholderException phe = (PlaceholderException) ece;
request.setAttribute("cause", "Der Platzhalter des Feldes " + phe.getField() + " ist um " + phe.getMissing() + " Bytes zu kurz. " + ece.getErrorCodeMessage());
}
}
else
{
request.setAttribute("error", "PresentableException");
request.setAttribute("cause", pe.toString());
}
}
public void dispatchToPreview(String document_text, String connector,
String mode, String signature_type, String submit_url,
HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
request.setAttribute("document_text", document_text);
request.setAttribute("connector", connector);
request.setAttribute("mode", mode);
request.setAttribute("signature_type", signature_type);
request.setAttribute("submit_url", submit_url);
dispatch(request, response, "/jsp/signpreview.jsp");
}
// public static void formatPreview(String document_text, String connector,
// String mode, String signature_type, String submit_url,
// HttpServletResponse response) throws ServletException, IOException
// {
// response.setContentType("text/html");
// response.setCharacterEncoding("UTF-8");
//
// PrintWriter writer = response.getWriter();
//
// writer.println("");
// writer.println("");
// writer.println("");
// writer.println("
");
// writer.println(" ");
// writer.println("PDF-AS Amtssignaturen Vorschau ");
// writer.println(" ");
// writer.println("");
//
// writer.println("");
// writer.println("");
//
// writer.println("
PDF-AS Amtssignaturen ");
//
// writer.println("
");
// writer.println("
Vorschau: Dokument Prüfen
");
// writer.println("
");
// writer.println("
");
//
// writer.println("
zurück ");
//
// writer.println("
");
// writer.println("");
//
// writer.println("");
// }
/**
* This class is just used to put the pdf byte array into the session.
*
* @author wprinz
*/
protected class SignPreviewInfo implements Serializable
{
/**
* SVUID.
*/
private static final long serialVersionUID = 3102824040163616332L;
public byte[] pdf = null;
public String mode = null;
}
/**
* Formats the file name so that it is suitable for content disposition.
*
* @param file_name
* The file name.
* @return Returns the formatted file name.
*/
public static String formatFileName(String file_name)
{
File file = new File(file_name);
String file_name_only = file.getName();
// the file_name contains \\ ==> remove them so Internet Explorer works
// correctly.
return file_name_only;
}
/**
* Formats the file name according to the SignResult.
*
* @param file_name
* The file name.
* @param sign_result
* The sign result.
* @return Returns the formatted file name.
*/
public static String formatFileNameForSignResult(String file_name,
SignResult sign_result)
{
String output = file_name + "_signed";
if (sign_result.getMimeType().equals(DetachedSignator_1_0_0.MIME_TYPE))
{
output += ".xml";
}
else
{
output += ".pdf";
}
return output;
}
/**
* Returns the data in the SignResult with proper content disposition.
*
* @param si
* SessionInformation.
* @param response
* The servlet response.
* @throws IOException
* The IO Exception.
*/
public static void returnSignResponse(SessionInformation si,
HttpServletResponse response) throws IOException
{
SignResult sign_result = si.sign_result;
String file_name = formatFileNameForSignResult(si.filename, sign_result);
// The name parameter is actually deprecated in favour of Content-Disposition filename
// Unfortunately Acrobat reader does recognize neither of these parameters
// with its inline save-as. It always takes the page name.
response.setContentType(sign_result.getMimeType() + "; name=\"" + file_name + "\"");
if (si.download_inline)
{
response.addHeader("Content-Disposition", "inline; filename=\"" + file_name + "\"");
}
else
{
response.addHeader("Content-Disposition", "attachment; filename=\"" + file_name + "\"");
}
response.getOutputStream().write(sign_result.getData());
}
}