<%@page contentType="text/html;charset=UTF-8" pageEncoding="ISO-8859-1" session="true"
%><%@page errorPage="Exception.jsp"
%><%@page import="com.fujitsu.iflow.model.workflow.DMS"
%><%@page import="com.fujitsu.iflow.model.workflow.WFObjectFactory"
%><%@page import="com.fujitsu.iflow.model.workflow.WFSession"
%><%@page import="com.fujitsu.iflow.model.workflow.WorkItem"
%><%@page import="com.fujitsu.iflow.model.workflow.AttachmentRef"
%><%@page import="com.fujitsu.iflow.model.workflow.ProcessInstance"
%><%@page import="com.fujitsu.iflow.model.wfadapter.DocRepository"
%><%@page import="java.io.*"
%><%@page import="java.util.*"
%><%
    request.setCharacterEncoding("UTF-8");request.getParameterNames(); //Need dummy call for WL9.1
    WFSession wfSession = (WFSession)session.getAttribute("ModelsessionID");
    if (wfSession == null) {
        %><jsp:include page="PasswordPanel.jsp" flush="true"/><%
        return;
    }

    String docRoot = application.getRealPath("/").trim();
    if (docRoot.endsWith(File.separator))
        docRoot = docRoot + "attachments";
    else
        docRoot = docRoot + File.separator + "attachments";
    long taskId = Long.parseLong(request.getParameter("taskId"));
    WorkItem task = WFObjectFactory.getWorkItem(taskId, wfSession);
    String documentName = request.getParameter("documentName");
    String strFilename = getAttachmentFileName(task, documentName);
    String attach = request.getContextPath() + "/attachments/" + strFilename;
    String serverName = request.getServerName();
    int serverPort = request.getServerPort();
    String formName = request.getParameter("Forms");
    String formsUrlParam = "";
    if (formName == null) {
        formName = "";
    }
    else {
        formsUrlParam = "&Forms="+formName;
    }
    String url = "WorkItem.jsp?taskId=" + taskId + formsUrlParam;

    String option = request.getParameter("AttachOption");   //"ReadOnly", "Edit", "CheckIn"
    if ( option.equalsIgnoreCase("CheckIn") )
    {
        String chkURL = "CheckIn.jsp?taskId=" + taskId + "&documentName=" + documentName;
        if (formName != null && formName.trim().length() > 0) {
            response.sendRedirect(response.encodeRedirectURL(chkURL + "&Forms="+formName));
        }
        else {
            response.sendRedirect(response.encodeRedirectURL(chkURL));
        }
    }
    else {
        boolean bEdit = false;
        if ( option.equalsIgnoreCase("Edit") )
        {
            bEdit = true;
        }

        String clientPath = docRoot + File.separator + strFilename;
        String attachFolder = getAttachmentFolder(wfSession);
        String documentPathOnServer = attachFolder + strFilename;
        File clientFile = new File(clientPath);

        String pwd = (String)session.getAttribute("password");

        DocRepository docRepository = getDocRepository(docRoot, wfSession, pwd);
        try {
            docRepository.checkOut(documentPathOnServer, clientFile, bEdit);
        }
        catch (Exception e) {
                request.setAttribute("message", "The attachment '" + documentName + "' could not be checked out <br>" + e.getMessage());
                request.setAttribute("nextPage", url);
                request.setAttribute("nextLink", "Back to WorkList");
%>
                <jsp:forward page="Error.jsp" />
<%
        }

        OutputStream os = response.getOutputStream();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition",
                           "attachment; filename=\"" + strFilename + "\"");
        FileInputStream fileInputStream =
                new FileInputStream(docRoot + File.separator + strFilename);
        int i;
        byte[] bytes = new byte[8192];
        while ( (i = fileInputStream.read(bytes)) != -1 ) os.write(bytes, 0, i);
        fileInputStream.close();
        os.close();
    }
%>

<%!
    /**
    *   @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(
        WFSession wfSession)
        throws Exception
    {
        String dmsRoot = null;
        String folder = null;
        dmsRoot = wfSession.getServerOption("DMSRoot");
        if (dmsRoot != null)
        {
            StringTokenizer st = new StringTokenizer(dmsRoot, ",");
            folder = st.nextToken();
        }
        return folder;
    }

    public
    DocRepository
    getDocRepository(
        String documentRoot,
        WFSession wfSession,
        String password)
        throws Exception
    {
        DocRepository docRepository = null;
        String docRoot = null;
        if (documentRoot != null && documentRoot.length() > 0) {
            docRoot = documentRoot;
        }
        else {
            Properties sysProp = System.getProperties();
            docRoot = sysProp.getProperty("user.home");
        }
        DMS dms =  WFObjectFactory.getDMS(wfSession, wfSession.getUserName(), password);
        docRepository = WFObjectFactory.getDocRepository(dms, docRoot);

        return docRepository;
    }

    public
    String
    getAttachmentFileName(
        WorkItem wi,
        String strTitle)
        throws Exception
    {
        String strFilename = "";
        ProcessInstance pi = wi.getProcessInstance();
        AttachmentRef[] arAttach = pi.getAttachments();
        int nSize = arAttach.length;

        for (int i = 0; i < nSize; i++)
        {
            AttachmentRef ar = arAttach[i];
            if (strTitle.equals(ar.getName()))
            {
                String strPath = ar.getPath();
                int nIndex = strPath.lastIndexOf(File.separator);
                if (nIndex == -1) {
                    nIndex = strPath.lastIndexOf("\\");
                }
                strFilename = strPath.substring(nIndex+1, strPath.length());
            }
        }
        return strFilename;
   }
%>

