<%@page contentType="text/html;charset=UTF-8" pageEncoding="ISO-8859-1" session="true"
%><%@page errorPage="Exception.jsp"
%><%@page import="com.fujitsu.iflow.common.ErrorMessage"
%><%@page import="com.fujitsu.iflow.common.exceptions.IflowException"
%><%@page import="com.fujitsu.iflow.model.bpm.BPMSession"
%><%@page import="com.fujitsu.iflow.model.bpmcore.BPMSessionImpl"
%><%@page import="com.fujitsu.iflow.model.util.ModelException"
%><%@page import="com.fujitsu.iflow.model.util.ModelInternalException"
%><%@page import="com.fujitsu.iflow.model.wfadapter.DocRepository"
%><%@page import="com.fujitsu.iflow.model.workflow.AttachmentRef"
%><%@page import="com.fujitsu.iflow.model.workflow.DMS"
%><%@page import="com.fujitsu.iflow.model.workflow.Plan"
%><%@page import="com.fujitsu.iflow.model.workflow.ProcessInstance"
%><%@page import="com.fujitsu.iflow.model.workflow.ProcessInstantiator"
%><%@page import="com.fujitsu.iflow.model.workflow.WFObjectFactory"
%><%@page import="com.fujitsu.iflow.model.workflow.WorkItem"
%><%@page import="com.fujitsu.iflow.model.workflow.WFSession"
%><%@page import="java.io.File"
%><%@page import="java.util.Enumeration"
%><%@page import="java.util.Hashtable"
%><%@page import="java.util.Properties"
%><%@page import="java.util.StringTokenizer"
%><%
    request.setCharacterEncoding("UTF-8");request.getParameterNames(); //Need dummy call for WL9.1
    BPMSession bps = (BPMSession) session.getAttribute("BPMSession");
    if (bps == null) {
        %><jsp:include page="PasswordPanel.jsp" flush="true"/><%
        return;
    }

%><jsp:useBean id="myUpload" scope="page" class="com.fujitsu.iflow.model.util.Upload" /><%

    myUpload.initialize(pageContext);
    myUpload.upload();
    boolean overwrite = false;
    String fileName = "";
    String dmsPath = "";
    String title = "";
    boolean isNewAttachment = false;

    try {
        fileName = myUpload.getFiles().getFile(0).getFileName();
    } catch (Exception e) {
        // dont throw exception here.
        // this code has to be revisted.
    }

    Hashtable params = new Hashtable();

    Enumeration sElements = myUpload.getRequest().getParameterNames();
    while ( sElements.hasMoreElements() )
    {
        String key = "";
        String value = "";

        key = (String)sElements.nextElement();
        if (key.equalsIgnoreCase("documentTitle"))
        {
            String[] values = myUpload.getRequest().getParameterValues(key);
            value = values[0];
        }
        value = myUpload.getRequest().getParameter(key);
        params.put(key, value);
    }

    // below see code is repeated twice becoz for some reason the request object
    // does not return the paramater list in the order as it was posted.
    sElements = params.keys();
    while (sElements.hasMoreElements())
    {
        String key = (String)sElements.nextElement();
        if ( key.equalsIgnoreCase("documentTitle") )
        {
            title = (String) params.get("documentTitle");

        }
        else if (key.equals("overwrite")) {
            overwrite = new Boolean( (String)params.get("overwrite")).booleanValue();
        }
        else if (key.equals("dmsPath")) {

            String attType = (String) params.get("isNewAttachment");
            if (attType != null) {
                isNewAttachment = new Boolean(attType.trim()).booleanValue();
            }
            dmsPath = (String) params.get("dmsPath");

            if(!isNewAttachment)
            {
                if(!dmsPath.startsWith("http:"))
                {
                    File lcFile = new File(dmsPath);
                    if(!lcFile.exists())
                        throw new Exception("System cannot find the file specified: "+dmsPath);
                }
            }
            dmsPath = dmsPath.replace('\\','/');

            if(isNewAttachment) {
                if (dmsPath.endsWith("/")) {
                    dmsPath = dmsPath + fileName;
                }
                else {
                    dmsPath = dmsPath + "/" + fileName;
                }
            }

        }
    }

    if ( (isNewAttachment) && ( title == null || title.trim().equals("") || fileName == null || fileName.trim().equals("")) )
    {
        String message = "<br/><table border=\"0\" cellpadding=\"4\" cellspacing=\"1\" class=\"tableClass\" width=\"450\" align=\"center\" bgcolor=\"#CCCCCC\" align=\"center\"><tr><td class=\"headrow\"><b>Warning</b></td></tr><tr><td bgcolor=\"#FFFFFF\"><font class=\"arialfonts\"><br/><blockquote/>You need to provide a title for the document and press" +
                    " the browse button to locate the document to be attached.</blockquote/></td></tr></table>";
         request.setAttribute("message", message);
         request.setAttribute("nextPage", "");
         request.setAttribute("nextLink", "");
%>
        <jsp:forward page="Error.jsp"/>
<%
    }
    else
    {

        String attFile = "";

        if (isNewAttachment) {
            String root = application.getRealPath("/").trim();
            if (root.endsWith(File.separator))
                root = root + "attachments";
            else
                root = root + File.separator + "attachments";

            attFile = root + File.separator + fileName;
            myUpload.save(root);
        }

        boolean isWorkitem = new Boolean(request.getParameter("isWorkitem")).booleanValue();
        String returnPage = null;
        String pwd = (String)session.getAttribute("password");
        if (isWorkitem) {
            long taskId = Long.parseLong(request.getParameter("taskId"));
            WorkItem task = bps.getWorkItem(taskId);
            ProcessInstance pi = task.getProcessInstance();
            try {
                addAttachment(pi, dmsPath, attFile, overwrite, title, bps, pwd, isNewAttachment);
            }
            catch (Exception mie) {

                if (pi.isInEditMode()) {
                    pi.cancelEdit();
                }

                if ((mie instanceof IflowException &&
                    ((IflowException)mie).getErrorCode() == ErrorMessage.DUPLICATE_FILE)
                    ||
                    (mie instanceof ModelException &&
                    ((ModelException)mie).getErrorCode() == ErrorMessage.DUPLICATE_FILE))
                {
                    String message = "<br/><table border=\"0\" cellpadding=\"4\" cellspacing=\"1\" class=\"tableClass\" width=\"450\" align=\"center\" bgcolor=\"#CCCCCC\" align=\"center\"><tr><td class=\"headrow\"><b>Warning</b></td></tr><tr><td bgcolor=\"#FFFFFF\"><font class=\"arialfonts\"><br/><blockquote/>The file to be attached already exists on the server. " +
                                      "To overwrite the existing file, go back to the previous page, "+
                                      "reselect the file to be attached, check the 'Overwrite file, if exists' option "+
                                      "and resubmit.</blockquote/></td></tr></table>";
                    request.setAttribute("message", message);
                    request.setAttribute("nextPage", "");
                    request.setAttribute("nextLink", "");
%>
                    <jsp:forward page="Error.jsp"/>
<%
                }
                else if ((mie instanceof IflowException &&
                    ((IflowException)mie).getErrorCode() == ErrorMessage.NAME_VALUE_SET_ALREADY_EXISTS)
                    ||
                    (mie instanceof ModelException &&
                    ((ModelException)mie).getErrorCode() == ErrorMessage.NAME_VALUE_SET_ALREADY_EXISTS))
                {
                    String message = "<br/><table border=\"0\" cellpadding=\"4\" cellspacing=\"1\" class=\"tableClass\" width=\"450\" align=\"center\" bgcolor=\"#CCCCCC\" align=\"center\"><tr><td class=\"headrow\"><b>Warning</b></td></tr><tr><td bgcolor=\"#FFFFFF\"><font class=\"arialfonts\"><br/><blockquote/>Another attachment with the same title already exists. " +
                                "Change the name of the attachment and try again.</blockquote/></td></tr></table>";
                    request.setAttribute("message", message);
                    request.setAttribute("nextPage", "");
                    request.setAttribute("nextLink", "");
%>
                    <jsp:forward page="Error.jsp"/>
<%
                }
                else
                    throw mie;
            }
            String formName = request.getParameter("Forms");
            if (formName != null && formName.trim().length() > 0) {
                response.sendRedirect(response.encodeRedirectURL("WorkItem.jsp?taskId=" + taskId + "&Forms="+formName));
            }
            else {
                response.sendRedirect(response.encodeRedirectURL("WorkItem.jsp?taskId=" + taskId));
            }
        }
        else {
            String splanId = (String) session.getAttribute("planID");
            ProcessInstantiator processInstantiator =
                (ProcessInstantiator)session.getAttribute("processInstantiator");

            DocRepository docRepos = getDocRepository(bps, pwd);
            boolean bAdded = false;
            try {
                if (!overwrite) {
                    AttachmentRef[] attaches = processInstantiator.getAttachments();
                    if (attaches != null && attaches.length > 0) {
                        for (int i=0; i<attaches.length; i++) {
                            if (attaches[i].getPath().equalsIgnoreCase(attFile)) {
                                //ErrorMessage The file requested as new already exists. = 14611 = DUPLICATE_FILE
                                ModelInternalException sof = new ModelInternalException(ErrorMessage.DUPLICATE_FILE, attFile);
                                throw sof;
                            }
                        }
                    }
                }

                processInstantiator.addAttachment(title, dmsPath);
                bAdded = true;

                if (isNewAttachment) {
                    docRepos.checkInNew(replaceWithBackSlash(dmsPath), attFile, overwrite);
                }
            }
            catch (Exception mie) {
                if (bAdded) {
                    processInstantiator.removeAttachment(title);
                }
                if ((mie instanceof IflowException &&
                    ((IflowException)mie).getErrorCode() == ErrorMessage.DUPLICATE_FILE)
                    ||
                    (mie instanceof ModelException &&
                    ((ModelException)mie).getErrorCode() == ErrorMessage.DUPLICATE_FILE))
                {
                    String message = "<br/><table border=\"0\" cellpadding=\"4\" cellspacing=\"1\" class=\"tableClass\" width=\"450\" align=\"center\" bgcolor=\"#CCCCCC\" align=\"center\"><tr><td class=\"headrow\"><b>Warning</b></td></tr><tr><td bgcolor=\"#FFFFFF\"><font class=\"arialfonts\"><br/><blockquote/>The file to be attached already exists on the server. " +
                                      "To overwrite the existing file, go back to the previous page, "+
                                      "reselect the file to be attached, check the 'Overwrite file, if exists' option "+
                                      "and resubmit.</blockquote/></td></tr></table>";
                    request.setAttribute("message", message);
                    request.setAttribute("nextPage", "");
                    request.setAttribute("nextLink", "");
%>
                    <jsp:forward page="Error.jsp"/>
<%
                }
                else if ((mie instanceof IflowException &&
                    ((IflowException)mie).getErrorCode() == ErrorMessage.NAME_VALUE_SET_ALREADY_EXISTS)
                    ||
                    (mie instanceof ModelException &&
                    ((ModelException)mie).getErrorCode() == ErrorMessage.NAME_VALUE_SET_ALREADY_EXISTS))
                {
                    String message = "<br/><table border=\"0\" cellpadding=\"4\" cellspacing=\"1\" class=\"tableClass\" width=\"450\" align=\"center\" bgcolor=\"#CCCCCC\" align=\"center\"><tr><td class=\"headrow\"><b>Warning</b></td></tr><tr><td bgcolor=\"#FFFFFF\"><font class=\"arialfonts\"><br/><blockquote/>Another attachment with the same title already exists. " +
                                "Change the name of the attachment and try again.</blockquote/></td></tr></table>";
                    StringBuffer qString = new StringBuffer("AddAttachment.jsp");
                    request.setAttribute("message", message);
                    request.setAttribute("nextPage", "");
                    request.setAttribute("nextLink", "");
%>
                    <jsp:forward page="Error.jsp"/>
<%
                }
                else
                    throw mie;
            }
            session.setAttribute("reuseProcInstantiator", new Boolean(true));
            returnPage = "ProcessInstantiator.jsp";
            response.sendRedirect(response.encodeRedirectURL("ProcessInstantiator.jsp?planToProcess=" + splanId));
        }
    }
%>


<%!
    /**
    *   @return the absolute path of the folder that contains attachments.
    *   This folder is on the machine on which iFlow Server is running, and not
    *   the machine from which the model (this class) is running. This folder
    *   is the same folder listed in as the DMSRoot inside iFlow.properties.
    */
    public
    String
    getAttachmentFolder(
        BPMSession bps)
        throws Exception
    {
        String dmsRoot = null;
        String folder = null;
        dmsRoot = bps.getServerOption("DMSRoot");
        if (dmsRoot != null)
        {
            StringTokenizer st = new StringTokenizer(dmsRoot, ",");
            folder = st.nextToken();
        }
        return folder;
    }

    public
    DocRepository
    getDocRepository(
        BPMSession bps,
        String password)
        throws Exception
    {
        DocRepository docRepository = null;
        Properties sysProp = System.getProperties();
        String docRoot = sysProp.getProperty("user.home");
        WFSession wfSession = ((BPMSessionImpl)bps)._wfs;
        DMS dms =  WFObjectFactory.getDMS(wfSession, wfSession.getUserName(), password);
        docRepository = WFObjectFactory.getDocRepository(dms, docRoot);

        return docRepository;
    }


    /**
    *  Attaches the document specified by its full path <i>clientAbsolutePath</i>
    *  to the process instance.
    *  @param clientAbsolutePath is the full path of the document to be
    *  attached (this path is on the machine on which the model is running).
    *
    */
    public
    void
    addAttachment(
        ProcessInstance processInstance,
        String dmsPath,
        String clientAbsolutePath,
        boolean overwritePreviousAttachment,
        String title,
        BPMSession bps,
        String password,
        boolean isNewAttachment)
        throws Exception
    {
        if  ( (isNewAttachment) && (processInstance == null ||
            clientAbsolutePath == null ||
            clientAbsolutePath.trim().equals("")) )
        {
            return;
        }

        if (isNewAttachment) {
            DocRepository docRepos = getDocRepository(bps, password);
            docRepos.checkInNew(replaceWithBackSlash(dmsPath), clientAbsolutePath, overwritePreviousAttachment);
        }

        processInstance.startEdit();
        processInstance.addAttachment(title, dmsPath);
        processInstance.commitEdit();
    }

    private String replaceWithBackSlash(String str)
    {
        return replace(str, "/", "\\");
    }

    private String replace(String str, String original, String replacement)
    {
        StringBuffer sb = new StringBuffer(str);
        for (int i=0; i<sb.length(); i++)
        {
            if (sb.substring(i,i+1).equals(original))
                sb.replace(i,i+1,replacement);
        }
        return sb.toString();
    }


%>