// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: packimports(3) deadcode 
// Source File Name:   WTDocumentTemplateFormTaskDelegate.java

package com.ptc.windchill.enterprise.templates.doc.server.processors;

import com.ptc.windchill.enterprise.doc.server.DocumentUtility;
import com.ptc.windchill.enterprise.templates.TemplatesFactory;
import com.ptc.windchill.enterprise.templates.TemplatesUtility;
import java.beans.PropertyVetoException;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.*;
import wt.content.*;
import wt.doc.*;
import wt.enterprise.EnterpriseHelper;
import wt.fc.*;
import wt.httpgw.HTTPRequest;
import wt.httpgw.LanguagePreference;
import wt.identity.IdentityFactory;
import wt.org.WTOrganization;
import wt.pom.UniquenessException;
import wt.prefs.*;
import wt.templateutil.processor.*;
import wt.util.*;
import wt.vc.VersionReference;
import wt.vc.wip.Workable;

public class WTDocumentTemplateFormTaskDelegate extends FormTaskDelegate
    implements Serializable
{

    public WTDocumentTemplateFormTaskDelegate()
    {
        locale = null;
    }

    /**
     * @deprecated Method processAction is deprecated
     */

    public void processAction(ContentHTTPStream contentStream)
        throws Exception
    {
        locale = LanguagePreference.getLocale(getState().getRequestObj().getProperty("cgi.http_accept_language", ""));
        Properties fData = getFormData();
        String pageName = (String)fData.get("thisPage");
        boolean validForm = false;
        validForm = validateForm(pageName, fData);
        if(validForm)
            if(getContextAction().equals("DoCreateTemplateDocument"))
                doTemplateCreation();
            else
            if(getContextAction().equals("DoCreateDocumentFromTemplate"))
                doDocFromTemplateCreation();
            else
            if(getContextAction().equals("DoUpdateTemplateDocument"))
                doTemplateUpdate();
    }

    private void doTemplateCreation()
        throws WTException
    {
        Properties formData = getFormData();
        if(formData != null)
        {
            if(VERBOSE)
                System.out.println("Create new template document ...");
            String number = formData.getProperty("Number");
            if(number != null)
            {
                number = number.trim();
                if(VERBOSE)
                    System.out.println("number = " + number);
            }
            String name = formData.getProperty("Name");
            if(name != null)
            {
                name = name.trim();
                if(VERBOSE)
                    System.out.println("name = " + name);
            }
            String title = formData.getProperty("Title");
            if(title != null)
            {
                title = title.trim();
                if(VERBOSE)
                    System.out.println("title = " + title);
            }
            String description = formData.getProperty("Description");
            if(description != null)
            {
                description = description.trim();
                if(VERBOSE)
                    System.out.println("description = " + description);
            }
            String dept = formData.getProperty("department");
            if(dept != null)
            {
                dept = dept.trim();
                if(VERBOSE)
                    System.out.println("dept = " + dept);
            }
            String docType = formData.getProperty("docType");
            if(docType != null)
            {
                docType = docType.trim();
                if(VERBOSE)
                    System.out.println("docType = " + docType);
            }
            String location = formData.getProperty("Location");
            if(location != null)
            {
                location = location.trim();
                if(VERBOSE)
                    System.out.println("location = " + location);
            }
            String lifeCycle = formData.getProperty("lifeCycleTemplate");
            if(lifeCycle != null)
            {
                lifeCycle = lifeCycle.trim();
                if(VERBOSE)
                    System.out.println("lifeCycle = " + lifeCycle);
            }
            String teamTemplate = formData.getProperty("teamTemplateName");
            if(teamTemplate != null)
            {
                teamTemplate = teamTemplate.trim();
                if(VERBOSE)
                    System.out.println("teamTemplate = " + teamTemplate);
            }
            String enabled = formData.getProperty("Enabled");
            if(enabled != null)
                enabled = "true";
            else
                enabled = "false";
            if(VERBOSE)
                System.out.println("enabled = " + enabled);
            String orgID = formData.getProperty("Organization");
            if(orgID != null)
            {
                orgID = orgID.trim();
                if(VERBOSE)
                    System.out.println("orgID = " + orgID);
            }
            String obj_type = "wt.doc.WTDocument";
            String context = "Classic";
            WTDocument wtdoc = null;
            try
            {
                wtdoc = (WTDocument)TemplatesFactory.newTemplate(obj_type, context);
                wtdoc = DocumentUtility.setName(wtdoc, name);
                wtdoc = DocumentUtility.setTitle(wtdoc, title);
                wtdoc = DocumentUtility.setDescription(wtdoc, description);
                wtdoc = DocumentUtility.setNumber(wtdoc, number);
                wtdoc = DocumentUtility.setEnabled(wtdoc, Boolean.valueOf(enabled).booleanValue());
                wtdoc = DocumentUtility.setLifeCycleTemplate(wtdoc, lifeCycle);
                wtdoc = DocumentUtility.setTeamTemplate(wtdoc, teamTemplate);
                wtdoc = DocumentUtility.setDept(wtdoc, dept);
                wtdoc = DocumentUtility.setDocType(wtdoc, docType);
                HashMap mapCreate = new HashMap();
                mapCreate.put("context", context);
                mapCreate.put("orgRef", orgID);
                mapCreate.put("folderRef", location);
                wtdoc = (WTDocument)TemplatesFactory.doCreateTemplateContextTasks("Enterprise", wtdoc, wtdoc, mapCreate);
                if(wtdoc != null)
                    wtdoc = (WTDocument)PersistenceHelper.manager.save(wtdoc);
                HashMap mapPCreate = new HashMap();
                wtdoc = (WTDocument)TemplatesFactory.doPostCreateTemplateContextTasks("Enterprise", wtdoc, wtdoc, mapPCreate);
                if(VERBOSE)
                    System.out.println("Document Template created successfully.  " + wtdoc.getDisplayIdentifier().getLocalizedMessage(locale));
                setContextObj(wtdoc);
                addToResponseHeaders(new WTMessage("com.ptc.windchill.enterprise.templates.doc.server.processors.processorsResource", "2", null));
                String filePath = formData.getProperty("File");
                if(filePath != null && filePath.length() > 0)
                {
                    if(VERBOSE)
                        System.out.println("in doTemplateCreation - must be successful and have content:  \n\tFile = " + filePath);
                    setContextAction("CreateDocTemplateProcessing");
                } else
                {
                    setContextAction("ObjProps");
                    RedirectObject redirectObject = new RedirectObject();
                    redirectObject.setRedirection(getState());
                }
            }
            catch(WTException e)
            {
                boolean caughtException = false;
                Throwable nested = e.getNestedThrowable();
                do
                {
                    if(nested == null || !(nested instanceof WTException))
                        break;
                    if(nested instanceof UniquenessException)
                    {
                        Object param[] = {
                            IdentityFactory.getDisplayIdentity(wtdoc)
                        };
                        addToResponseHeaders(new WTMessage("com.ptc.windchill.enterprise.templates.doc.server.processors.processorsResource", "9", param));
                        caughtException = true;
                        break;
                    }
                    nested = ((WTException)nested).getNestedThrowable();
                } while(true);
                if(!caughtException)
                {
                    e.printStackTrace();
                    addToResponseHeaders(e);
                }
                setContextObj(null);
                setContextAction("CreateDocTemplateGeneral");
            }
            catch(Throwable t)
            {
                t.printStackTrace();
                addToResponseHeaders((LocalizableMessage)t);
                setContextObj(null);
                setContextAction("CreateDocTemplateGeneral");
            }
        }
    }

    private void doDocFromTemplateCreation()
        throws WTException
    {
        Properties formData = getFormData();
        if(formData != null)
        {
            if(VERBOSE)
                System.out.println("Create new document from template ...");
            String number = formData.getProperty("Number");
            if(number != null)
            {
                number = number.trim();
                if(VERBOSE)
                    System.out.println("number = " + number);
            }
            String name = formData.getProperty("Name");
            if(name != null)
            {
                name = name.trim();
                if(VERBOSE)
                    System.out.println("name = " + name);
            }
            String title = formData.getProperty("Title");
            if(title != null)
            {
                title = title.trim();
                if(VERBOSE)
                    System.out.println("title = " + title);
            }
            String description = formData.getProperty("Description");
            if(description != null)
            {
                description = description.trim();
                if(VERBOSE)
                    System.out.println("description = " + description);
            }
            String dept = formData.getProperty("department");
            if(dept != null)
            {
                dept = dept.trim();
                if(VERBOSE)
                    System.out.println("dept = " + dept);
            }
            String docType = formData.getProperty("docType");
            if(docType != null)
            {
                docType = docType.trim();
                if(VERBOSE)
                    System.out.println("docType = " + docType);
            }
            String location = formData.getProperty("Location");
            if(location != null)
            {
                location = location.trim();
                if(VERBOSE)
                    System.out.println("location = " + location);
            }
            String lifeCycle = formData.getProperty("lifeCycleTemplate");
            if(lifeCycle != null)
            {
                lifeCycle = lifeCycle.trim();
                if(VERBOSE)
                    System.out.println("lifeCycle = " + lifeCycle);
            }
            String teamTemplate = formData.getProperty("teamTemplateName");
            if(teamTemplate != null)
            {
                teamTemplate = teamTemplate.trim();
                if(VERBOSE)
                    System.out.println("teamTemplate = " + teamTemplate);
            }
            String keepCheckedOut = formData.getProperty("KeepCheckedOut");
            if(keepCheckedOut != null)
                keepCheckedOut = "true";
            else
                keepCheckedOut = "false";
            if(VERBOSE)
                System.out.println("keepCheckedOut = " + keepCheckedOut);
            String submit = formData.getProperty("Submit");
            if(submit != null)
                submit = "true";
            else
                submit = "false";
            if(VERBOSE)
                System.out.println("submit = " + submit);
            String orgID = formData.getProperty("Organization");
            if(orgID != null)
            {
                orgID = orgID.trim();
                if(VERBOSE)
                    System.out.println("orgID = " + orgID);
            }
            String obj_id = formData.getProperty("Template");
            if(obj_id == null || obj_id.equals(""))
                throw new WTException("com.ptc.windchill.enterprise.templates.doc.server.processors.processorsResource", "4", null);
            WTDocument template = null;
            try
            {
                template = (WTDocument)(new ReferenceFactory()).getReference(obj_id).getObject();
            }
            catch(Exception e)
            {
                throw new WTException(e, "com.ptc.windchill.enterprise.templates.doc.server.processors.processorsResource", "5", null);
            }
            String context = "Classic";
            WTDocument wtdoc = null;
            try
            {
                wtdoc = (WTDocument)TemplatesFactory.newObjFromTemplate(template, context);
                HashMap mapCreate = new HashMap();
                mapCreate.put("context", context);
                mapCreate.put("orgRef", orgID);
                mapCreate.put("folderRef", location);
                wtdoc = (WTDocument)TemplatesFactory.doCreateFromTemplateContextTasks("Enterprise", wtdoc, wtdoc, template, mapCreate);
                wtdoc = DocumentUtility.setName(wtdoc, name);
                wtdoc = DocumentUtility.setTitle(wtdoc, title);
                wtdoc = DocumentUtility.setDescription(wtdoc, description);
                wtdoc = DocumentUtility.setNumber(wtdoc, number);
                wtdoc = DocumentUtility.setLifeCycleTemplate(wtdoc, lifeCycle);
                wtdoc = DocumentUtility.setTeamTemplate(wtdoc, teamTemplate);
                wtdoc = DocumentUtility.setDept(wtdoc, dept);
                wtdoc = DocumentUtility.setDocType(wtdoc, docType);
                wtdoc = (WTDocument)TemplatesUtility.saveObjFromTemplate(wtdoc, template);
                HashMap mapPCreate = new HashMap();
                mapPCreate.put("submit", submit);
                mapPCreate.put("keepCheckedOut", keepCheckedOut);
                wtdoc = (WTDocument)TemplatesFactory.doPostCreateFromTemplateContextTasks("Enterprise", wtdoc, wtdoc, template, mapPCreate);
                if(VERBOSE)
                    System.out.println("Document from Template created successfully.  " + wtdoc.getDisplayIdentifier().getLocalizedMessage(locale));
                setContextObj(wtdoc);
                addToResponseHeaders(new WTMessage("com.ptc.windchill.enterprise.templates.doc.server.processors.processorsResource", "6", null));
                if(VERBOSE)
                    System.out.println("*** keepCheckedOut = " + keepCheckedOut);
                if(VERBOSE)
                    System.out.println("*** checkIfDownloadNeeded() = " + checkIfDownloadNeeded());
                if(keepCheckedOut.equalsIgnoreCase("true") && checkIfDownloadNeeded())
                {
                    setContextAction("CreateDocFromTemplateProcessing");
                } else
                {
                    setContextAction("ObjProps");
                    RedirectObject redirectObject = new RedirectObject();
                    redirectObject.setRedirection(getState());
                }
            }
            catch(WTException e)
            {
                boolean caughtException = false;
                Throwable nested = e.getNestedThrowable();
                do
                {
                    if(nested == null || !(nested instanceof WTException))
                        break;
                    if(nested instanceof UniquenessException)
                    {
                        Object param[] = {
                            IdentityFactory.getDisplayIdentity(wtdoc)
                        };
                        addToResponseHeaders(new WTMessage("com.ptc.windchill.enterprise.templates.doc.server.processors.processorsResource", "9", param));
                        caughtException = true;
                        break;
                    }
                    nested = ((WTException)nested).getNestedThrowable();
                } while(true);
                if(!caughtException)
                {
                    e.printStackTrace();
                    addToResponseHeaders(e);
                }
                setContextObj(null);
                setContextAction("CreateDocFromTemplateGeneral");
            }
            catch(Throwable t)
            {
                t.printStackTrace();
                addToResponseHeaders((LocalizableMessage)t);
                setContextObj(null);
                setContextAction("CreateDocFromTemplateGeneral");
            }
        }
    }

    private void doTemplateUpdate()
        throws WTException, WTPropertyVetoException, PropertyVetoException
    {
        FormatContentHolder doc = (FormatContentHolder)getContextObj();
        try
        {
            Properties formData = getFormData();
            DocumentFormData docFormData = new DocumentFormData(formData);
            doc = DocumentFactory.updateDocument(doc, docFormData);
            setContextObj(doc);
            addToResponseHeaders(new WTMessage("com.ptc.windchill.enterprise.templates.doc.server.processors.processorsResource", "3", null));
            String filePath = formData.getProperty("File");
            boolean needUpload = false;
            if(filePath != null && filePath.length() > 0)
                needUpload = true;
            else
            if(filePath != null && filePath.length() == 0)
            {
                doc = (FormatContentHolder)ContentHelper.service.getContents(doc);
                wt.content.ContentItem item = ContentHelper.getPrimary(doc);
                String primary = null;
                if(item instanceof ApplicationData)
                {
                    ApplicationData app = (ApplicationData)item;
                    primary = app.getUploadedFromPath();
                    if(VERBOSE)
                        System.out.println("primary from ApplicationData = " + primary);
                } else
                if(item instanceof URLData)
                {
                    URLData url = (URLData)item;
                    primary = url.getUrlLocation();
                    if(VERBOSE)
                        System.out.println("primary from URLData = " + primary);
                }
                if(primary != null && primary.length() > 0)
                    needUpload = true;
            }
            if(needUpload)
            {
                setContextAction("UpdateDocTemplateProcessing");
            } else
            {
                setContextAction("ObjProps");
                RedirectObject redirectObject = new RedirectObject();
                redirectObject.setRedirection(getState());
            }
        }
        catch(WTException e)
        {
            addToResponseHeaders(e);
            setContextAction("UpdateDocTemplateGeneral");
        }
    }

    private boolean validateForm(String pageName, Properties fData)
        throws WTException
    {
        String contextAction = null;
        fData.remove("OperationError");
        if(getContextAction().equals("DoCreateTemplateDocument") || getContextAction().equals("DoCreateDocumentFromTemplate"))
        {
            String name = (String)fData.get("Name");
            String number = null;
            Object numberTarget = getContextObj();
            if(numberTarget == null)
                if(getContextClassName() != null)
                    try
                    {
                        numberTarget = Class.forName(getContextClassName());
                    }
                    catch(ClassNotFoundException cnfe)
                    {
                        throw new WTException(cnfe);
                    }
                else
                    numberTarget = wt.doc.WTDocument.class;
            String orgRef = fData.getProperty("Organization", "");
            WTOrganization organization = orgRef.length() <= 0 ? null : (WTOrganization)RF.getReference(orgRef).getObject();
            boolean user_enter_number = !EnterpriseHelper.isAutoNumber(numberTarget, organization);
            boolean number_null = false;
            if(user_enter_number)
            {
                number = (String)fData.get("Number");
                if(VERBOSE)
                    System.out.println("validateForm:  number = " + number);
                if(number == null || number.equals(""))
                    number_null = true;
            }
            if(VERBOSE)
                System.out.println("validateForm:  user_enter_number = " + user_enter_number);
            if(VERBOSE)
                System.out.println("validateForm:  number_null = " + number_null);
            if(VERBOSE)
                System.out.println("validateForm:  name = " + name);
            String location = (String)fData.get("Location");
            contextAction = getContextAction().equals("DoCreateTemplateDocument") ? "CreateDocTemplateGeneral" : "CreateDocFromTemplateGeneral";
            if(name == null || name.equals("") || number_null || location == null || location.equals(""))
            {
                fData.put("OperationError", "true");
                setContextAction(contextAction);
                addToResponseHeaders(new WTMessage("com.ptc.windchill.enterprise.templates.doc.server.processors.processorsResource", "0", null));
                return false;
            }
            if(!DocumentUtility.checkNameLength(name))
            {
                fData.put("OperationError", "true");
                setContextAction(contextAction);
                Object args[] = {
                    new Integer(DocumentUtility.getNameUpperLimit())
                };
                addToResponseHeaders(new WTMessage("com.ptc.windchill.enterprise.templates.doc.server.processors.processorsResource", "7", args));
                return false;
            }
            if(!DocumentUtility.checkNumberLength(number))
            {
                fData.put("OperationError", "true");
                setContextAction(contextAction);
                Object args[] = {
                    new Integer(DocumentUtility.getNumberUpperLimit())
                };
                addToResponseHeaders(new WTMessage("com.ptc.windchill.enterprise.templates.doc.server.processors.processorsResource", "8", args));
                return false;
            }
        }
        if(getContextAction().equals("DoCreateTemplateDocument"))
            contextAction = "CreateDocTemplateGeneral";
        else
        if(getContextAction().equals("DoCreateDocumentFromTemplate"))
            contextAction = "CreateDocFromTemplateGeneral";
        else
        if(getContextAction().equals("DoUpdateTemplateDocument"))
        {
            Workable doc = null;
            doc = (Workable)getContextObj();
            ReferenceFactory rf = new ReferenceFactory();
            VersionReference ref = VersionReference.newVersionReference(doc);
            String oid = rf.getReferenceString(ref);
            Properties qData = getQueryData();
            qData.put("oid", oid);
            contextAction = "UpdateDocTemplateGeneral";
        }
        String title = (String)fData.get("Title");
        if(!DocumentUtility.checkTitleLength(title))
        {
            fData.put("OperationError", "true");
            setContextAction(contextAction);
            Object args[] = {
                new Integer(DocumentUtility.getTitleUpperLimit())
            };
            addToResponseHeaders(new WTMessage("com.ptc.windchill.enterprise.templates.doc.server.processors.processorsResource", "1", args));
            return false;
        } else
        {
            return true;
        }
    }

    private boolean checkIfDownloadNeeded()
        throws WTException, PropertyVetoException
    {
        boolean needDownload = false;
        String skipDownloadValue = getPreferenceValue("/wt/content", "noDownloadOnCheckout", "false");
        if(VERBOSE)
            System.out.println("skipDownloadValue = " + skipDownloadValue);
        if(skipDownloadValue != null)
            needDownload = !skipDownloadValue.equalsIgnoreCase("true");
        if(needDownload)
        {
            if(VERBOSE)
                System.out.println("user does want download on checkout - is there anything to download?");
            FormatContentHolder doc = (FormatContentHolder)getContextObj();
            doc = (FormatContentHolder)ContentHelper.service.getContents(doc);
            wt.content.ContentItem item = ContentHelper.getPrimary(doc);
            String primary = null;
            if(item instanceof ApplicationData)
            {
                ApplicationData app = (ApplicationData)item;
                primary = app.getFileName();
                if(VERBOSE)
                    System.out.println("primary from ApplicationData = " + primary);
            } else
            if(item instanceof URLData)
            {
                URLData url = (URLData)item;
                primary = url.getUrlLocation();
                if(VERBOSE)
                    System.out.println("primary from URLData = " + primary);
            }
            if(VERBOSE)
                System.out.println("primary = \"" + primary + "\"");
            if(primary != null && primary.length() > 0)
                needDownload = true;
            else
                needDownload = false;
        }
        return needDownload;
    }

    protected static String getPreferenceValue(String node, String key, String defaultValue)
    {
        Preferences root = WTPreferences.root();
        WTPreferences myPrefs = (WTPreferences)root.node(node);
        myPrefs.setContextMask(PreferenceHelper.createContextMask());
        String returnValue = myPrefs.get(key, defaultValue);
        if(returnValue == null)
        {
            if(VERBOSE)
                System.out.println("DEBUG:  getPreferenceValue() returned value was null - using default value");
            returnValue = defaultValue;
        }
        return returnValue;
    }

    private static final String RESOURCE = "com.ptc.windchill.enterprise.templates.doc.server.processors.processorsResource";
    private static final String CLASSNAME;
    private static final String DOCUMENT = "wt.doc.WTDocument";
    private Locale locale;
    private static final ReferenceFactory RF = new ReferenceFactory();
    private static boolean VERBOSE = false;

    static 
    {
        CLASSNAME = (com.ptc.windchill.enterprise.templates.doc.server.processors.WTDocumentTemplateFormTaskDelegate.class).getName();
        try
        {
            WTProperties properties = WTProperties.getLocalProperties();
            VERBOSE = properties.getProperty("com.ptc.windchill.enterprise.verbose", false);
        }
        catch(Throwable t)
        {
            System.err.println("com.ptc.windchill.enterprise.templates.doc.server.processors.WTDocumentTemplateFormTaskDelegate : Error reading com.ptc.windchill.enterprise.* properties");
            t.printStackTrace(System.err);
            throw new ExceptionInInitializerError(t);
        }
    }
}
