// 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:   CreateDocumentFromTemplateFormTaskDelegate.java

package com.ptc.windchill.pdmlink.doc.server.processors;

import com.ptc.core.HTMLtemplateutil.server.processors.EntityTaskDelegate;
import com.ptc.core.foundation.type.common.impl.AttributeValueException;
import com.ptc.core.foundation.type.server.impl.TypeHelper;
import com.ptc.core.meta.common.TypeIdentifier;
import com.ptc.core.meta.server.TypeIdentifierUtility;
import com.ptc.windchill.enterprise.doc.server.DocumentUtility;
import com.ptc.windchill.enterprise.nativeapp.server.WindchillAttributeUtility;
import com.ptc.windchill.enterprise.templates.TemplatesFactory;
import com.ptc.windchill.enterprise.templates.TemplatesUtility;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.*;
import wt.content.ContentHTTPStream;
import wt.doc.WTDocument;
import wt.fc.ReferenceFactory;
import wt.fc.WTReference;
import wt.httpgw.HTTPRequest;
import wt.httpgw.LanguagePreference;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.pom.UniquenessException;
import wt.rule.util.InitRuleHelper;
import wt.templateutil.processor.*;
import wt.util.*;

public class CreateDocumentFromTemplateFormTaskDelegate extends FormTaskDelegate
    implements Serializable
{

    public CreateDocumentFromTemplateFormTaskDelegate()
    {
        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();
        Properties qData = getQueryData();
        String formName = (String)fData.get("formName");
        String pageName = (String)fData.get("pageName");
        if(formName == null)
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        clearValues(pageName, fData);
        EntityTaskDelegate.saveCustomFormDataInSession(getState().getCookieManager(), formName, fData);
        boolean validForm = validateForm(pageName, fData);
        if(validForm)
        {
            if(getContextAction().equals("DoCreateDocumentFromTemplate"))
                doCreation(formName);
            else
                switchPages((String)qData.get("nextAction"), null, (wt.doc.WTDocument.class).getName());
        } else
        {
            switchPages(getContextAction(), null, (wt.doc.WTDocument.class).getName());
        }
    }

    private void doCreation(String formName)
        throws WTException
    {
        Properties formData = getFormData();
        String contextObj = null;
        if(formData != null)
        {
            if(VERBOSE)
                System.out.println("Form Name = " + formName);
            HashMap input_data = new HashMap(5);
            if(VERBOSE)
                System.out.println("Create new document from template ...");
            String number = formData.getProperty("Number");
            if(number == null)
                number = getFormValueFromSession((String)formData.get("formName"), "Number", "");
            if(number != null)
            {
                number = number.trim();
                if(VERBOSE)
                    System.out.println("number = " + number);
            }
            String name = formData.getProperty("Name");
            if(name == null)
                name = getFormValueFromSession((String)formData.get("formName"), "Name", "");
            if(name != null)
            {
                name = name.trim();
                if(VERBOSE)
                    System.out.println("name = " + name);
            }
            String title = formData.getProperty("Title");
            if(title == null)
                title = getFormValueFromSession((String)formData.get("formName"), "Title", "");
            if(title != null)
            {
                title = title.trim();
                if(VERBOSE)
                    System.out.println("title = " + title);
            }
            String description = formData.getProperty("Description");
            if(description == null)
                description = getFormValueFromSession((String)formData.get("formName"), "Description", "");
            if(description != null)
            {
                description = description.trim();
                if(VERBOSE)
                    System.out.println("description = " + description);
            }
            String keepCheckedOut = formData.getProperty("KeepCheckedOut");
            if(keepCheckedOut == null)
            {
                keepCheckedOut = getFormValueFromSession((String)formData.get("formName"), "KeepCheckedOut", "false");
            } else
            {
                keepCheckedOut = keepCheckedOut.trim();
                if(VERBOSE)
                    System.out.println("keepCheckedOut = " + keepCheckedOut);
            }
            String context = getRepository(formName);
            if(context == null || context.equals(""))
                throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "9", null);
            if(VERBOSE)
                System.out.println("Repository from the session = " + context);
            String obj_id = getFormValueFromSession(formName, "Template", "");
            if(obj_id == null || obj_id.equals(""))
                throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "7", null);
            WTDocument template = null;
            try
            {
                template = (WTDocument)(new ReferenceFactory()).getReference(obj_id).getObject();
            }
            catch(Exception e)
            {
                throw new WTException(e, "com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "8", null);
            }
            String org = formData.getProperty("OrganizationDN");
            if(org == null)
                org = getFormValueFromSession((String)formData.get("formName"), "OrganizationDN", "");
            if(org == null || org.equals(""))
                throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "109", null);
            org = org.trim();
            if(VERBOSE)
                System.out.println("OrganizationDN = " + org);
            String folderRef = formData.getProperty("FolderLocation");
            if(folderRef == null)
                folderRef = getFormValueFromSession((String)formData.get("formName"), "FolderLocation", "");
            if(folderRef.equals("SelectFolder"))
            {
                folderRef = formData.getProperty("FolderPicker");
                if(folderRef == null)
                    folderRef = getFormValueFromSession((String)formData.get("formName"), "FolderPicker", "");
            } else
            {
                folderRef = null;
            }
            if(folderRef != null && !folderRef.trim().equals(""))
            {
                folderRef = folderRef.trim();
                input_data.put("folderRef", folderRef);
            }
            try
            {
                ServletSessionCookie cookie = getState().getCookieManager().getCookie(formName);
                Properties soft_attribs = cookie.toProperties();
                input_data = WindchillAttributeUtility.propertiesToHashMap(soft_attribs, input_data, WTContext.getContext().getTimeZone(), locale);
                WTDocument wtdoc = (WTDocument)TemplatesFactory.newObjFromTemplate(template, context);
                HashMap mapCreate = new HashMap();
                mapCreate.put("context", context);
                mapCreate.put("OrganizationDN", org);
                if(folderRef != null && folderRef.length() > 0)
                    mapCreate.put("folderRef", folderRef);
                wtdoc = (WTDocument)TemplatesFactory.doCreateFromTemplateContextTasks("PDMLink", wtdoc, wtdoc, template, mapCreate);
                wtdoc = DocumentUtility.setName(wtdoc, name);
                wtdoc = DocumentUtility.setTitle(wtdoc, title);
                wtdoc = DocumentUtility.setDescription(wtdoc, description);
                wtdoc = DocumentUtility.setNumber(wtdoc, number);
                template = DocumentUtility.setCustomAttributes(template, input_data, locale);
                String baseType = TypeHelper.getBaseType(TypeHelper.getTypeIdentifier(wtdoc.getClass().getName()));
                try
                {
                    TypeHelper.copyCustomModeledAttributes(template, wtdoc, baseType, locale);
                }
                catch(ClassNotFoundException cnfe)
                {
                    cnfe.printStackTrace(System.err);
                }
                wtdoc = (WTDocument)TemplatesUtility.saveObjFromTemplate(wtdoc, template);
                HashMap mapPCreate = new HashMap();
                mapPCreate.put("keepCheckedOut", keepCheckedOut);
                wtdoc = (WTDocument)TemplatesFactory.doPostCreateFromTemplateContextTasks("PDMLink", wtdoc, wtdoc, template, mapPCreate);
                if(VERBOSE)
                    System.out.println("Document from Template created successfully.  " + wtdoc.getDisplayIdentifier().getLocalizedMessage(locale));
                setContextObj(wtdoc);
                if(keepCheckedOut.equalsIgnoreCase("true"))
                {
                    setContextAction("CreateDocumentFromTemplateProcessing");
                } else
                {
                    DefaultTemplateProcessor.addToFeedbackCookie(new WTMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "76", null), getState());
                    deleteFormDataFromSession(formName);
                    setContextAction("ComplexCloseWizardWindow");
                    getContextProperties().put("refreshOnly", "true");
                }
            }
            catch(WTException e)
            {
                boolean caughtException = false;
                Throwable nested = e.getNestedThrowable();
                do
                {
                    if(nested == null || !(nested instanceof WTException))
                        break;
                    if(nested instanceof UniquenessException)
                    {
                        Object param[] = {
                            number, name
                        };
                        addToResponseHeaders(new WTMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "117", param));
                        caughtException = true;
                        contextObj = "CreateDocumentFromTemplate2";
                        break;
                    }
                    nested = ((WTException)nested).getNestedThrowable();
                } while(true);
                if(e instanceof AttributeValueException)
                {
                    caughtException = true;
                    contextObj = "CreateDocumentFromTemplate3";
                    addToResponseHeaders(e);
                }
                if(!caughtException)
                {
                    e.printStackTrace();
                    contextObj = "CreateDocumentFromTemplate2";
                    addToResponseHeaders(e);
                }
                setContextObj(null);
                setContextAction(contextObj);
            }
        }
    }

    private boolean validateForm(String pageName, Properties fData)
        throws WTException
    {
        String formName = (String)fData.get("formName");
        if(getContextAction().equals("DoCreateDocumentFromTemplate"))
        {
            String number = null;
            String name = (String)fData.get("Name");
            if(name == null || name.equals(""))
                name = getFormValueFromSession((String)fData.get("formName"), "Name", "");
            WTContainer container = (WTContainer)rf.getReference(getRepository(formName)).getObject();
            TypeIdentifier typeIdentifier = null;
            String obj_id = getFormValueFromSession(formName, "Template", "");
            if(obj_id == null || obj_id.equals(""))
                throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "7", null);
            try
            {
                WTDocument template = (WTDocument)(new ReferenceFactory()).getReference(obj_id).getObject();
                typeIdentifier = TypeIdentifierUtility.getTypeIdentifier(template);
            }
            catch(Exception e)
            {
                throw new WTException(e, "com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "8", null);
            }
            boolean user_enter_number = !InitRuleHelper.isAutoNumber(typeIdentifier.getTypename(), WTContainerRef.newWTContainerRef(container));
            boolean number_null = false;
            if(user_enter_number)
            {
                number = (String)fData.get("Number");
                if(number == null || number.equals(""))
                {
                    number = getFormValueFromSession((String)fData.get("formName"), "Number", "");
                    if(number == null || number.equals(""))
                        number_null = true;
                }
            }
            if(name == null || name.equals("") || number_null)
            {
                setContextObj(null);
                setContextAction("CreateDocumentFromTemplate2");
                addToResponseHeaders(new WTMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "12", null));
                return false;
            }
            if(!DocumentUtility.checkNameLength(name))
            {
                setContextAction("CreateDocumentFromTemplate2");
                Object args[] = {
                    new Integer(DocumentUtility.getNameUpperLimit())
                };
                addToResponseHeaders(new WTMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "115", args));
                return false;
            }
            if(!DocumentUtility.checkNumberLength(number))
            {
                setContextAction("CreateDocumentFromTemplate2");
                Object args[] = {
                    new Integer(DocumentUtility.getNumberUpperLimit())
                };
                addToResponseHeaders(new WTMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "116", args));
                return false;
            }
            String title = (String)fData.get("Title");
            if(title == null || title.equals(""))
                title = getFormValueFromSession((String)fData.get("formName"), "Title", "");
            if(!DocumentUtility.checkTitleLength(title))
            {
                setContextAction("CreateDocumentFromTemplate2");
                Object args[] = {
                    new Integer(DocumentUtility.getTitleUpperLimit())
                };
                addToResponseHeaders(new WTMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "73", args));
                return false;
            }
            String orgID = (String)fData.get("OrganizationDN");
            boolean orgID_null = false;
            if(orgID == null || orgID.equals(""))
            {
                orgID = getFormValueFromSession(formName, "OrganizationDN", "");
                if(orgID == null || orgID.equals(""))
                    orgID_null = true;
            }
            if(orgID_null)
            {
                setContextAction("CreateDocumentFromTemplate2");
                addToResponseHeaders(new WTMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "12", null));
                return false;
            } else
            {
                return true;
            }
        } else
        {
            return true;
        }
    }

    private String getRepository(String formName)
        throws WTException
    {
        return getFormValueFromSession(formName, "Repository", "");
    }

    public String getFormValueFromSession(String formName, String inputFieldName, String defaultValue)
        throws WTException
    {
        if(formName == null || formName.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        if(inputFieldName == null || inputFieldName.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "14", null);
        ServletSessionCookie cookie = getState().getCookieManager().getCookie(formName);
        String value = (String)cookie.get(inputFieldName);
        if(value == null && defaultValue != null)
            value = defaultValue;
        return value;
    }

    public void clearValues(String pageName, Properties fData)
        throws WTException
    {
        String formName = (String)fData.get("formName");
        if(pageName.equals("CreateDocumentFromTemplateForm1"))
        {
            String sessionTemplate = getFormValueFromSession(formName, "Template", "");
            if(sessionTemplate.length() > 0 && !sessionTemplate.equals((String)fData.get("Template")))
            {
                String fileName = getFormValueFromSession(formName, "File", "");
                String docName = getFormValueFromSession(formName, "Name", "");
                String repository = getFormValueFromSession(formName, "Repository", "");
                String folderlocation = getFormValueFromSession(formName, "FolderLocation", "");
                String folderpicker = getFormValueFromSession(formName, "FolderPicker", "");
                if(fileName.length() > 0)
                    fData.put("File", fileName);
                if(docName.length() > 0)
                    fData.put("Name", docName);
                if(repository.length() > 0)
                    fData.put("Repository", repository);
                if(fData.getProperty("Title") != null)
                    fData.remove("Title");
                if(fData.getProperty("Description") != null)
                    fData.remove("Description");
                if(folderlocation.length() > 0)
                    fData.put("FolderLocation", folderlocation);
                if(folderpicker.length() > 0)
                    fData.put("FolderPicker", folderpicker);
                deleteFormDataFromSession(formName);
            }
        }
    }

    private static final String RESOURCE = "com.ptc.windchill.pdmlink.doc.server.processors.processorsResource";
    private static final String CLASSNAME;
    private Locale locale;
    protected static boolean VERBOSE = false;
    protected static final ReferenceFactory rf = new ReferenceFactory();

    static 
    {
        CLASSNAME = (com.ptc.windchill.pdmlink.doc.server.processors.CreateDocumentFromTemplateFormTaskDelegate.class).getName();
        try
        {
            WTProperties properties = WTProperties.getLocalProperties();
            VERBOSE = properties.getProperty("wt.doc.verbose", false);
        }
        catch(Throwable t)
        {
            System.err.println("com.ptc.windchill.pdmlink.doc.server.processors.CreateDocumentFromTemplateFormTaskDelegate : Error reading wt.doc.* properties");
        }
    }
}
