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

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

import com.ptc.core.HTMLtemplateutil.server.processors.EntityTaskDelegate;
import com.ptc.windchill.enterprise.doc.server.DocumentUtility;
import com.ptc.windchill.enterprise.nativeapp.server.ApplicationIntegrationFactory;
import com.ptc.windchill.enterprise.nativeapp.server.WindchillAttributeUtility;
import java.beans.PropertyVetoException;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.*;
import wt.content.*;
import wt.doc.WTDocument;
import wt.facade.scm.ScmFacade;
import wt.fc.*;
import wt.httpgw.HTTPRequest;
import wt.httpgw.LanguagePreference;
import wt.pom.Transaction;
import wt.templateutil.processor.*;
import wt.util.*;

public class UpdateDocumentFormTaskDelegate extends FormTaskDelegate
    implements Serializable
{

    public UpdateDocumentFormTaskDelegate()
    {
        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);
        EntityTaskDelegate.saveCustomFormDataInSession(getState().getCookieManager(), formName, fData);
        boolean validForm = validateForm(pageName, fData);
        EntityTaskDelegate.saveCustomFormDataInSession(getState().getCookieManager(), formName, fData);
        if(validForm)
            if(getContextAction().equals("DoUpdateDocument"))
                doUpdate(formName);
            else
                switchPages((String)qData.get("nextAction"), null, (wt.doc.WTDocument.class).getName());
    }

    private void doUpdate(String formName)
        throws WTException, WTPropertyVetoException, PropertyVetoException
    {
        WTDocument doc = (WTDocument)getContextObj();
        Properties formData = getFormData();
        if(VERBOSE)
            System.out.println("\n***formData = " + formData);
        if(doc != null && formData != null)
        {
            HashMap input_data = new HashMap(5);
            if(VERBOSE)
                System.out.println("Updating document ...");
            String title = formData.getProperty("Title");
            if(title == null)
                title = getFormValueFromSession(formName, "Title", "");
            if(title != null)
            {
                title = title.trim();
                if(VERBOSE)
                    System.out.println("title = " + title);
                input_data.put("title", title);
            }
            String description = formData.getProperty("Description");
            if(description == null)
                description = getFormValueFromSession(formName, "Description", "");
            if(description != null)
            {
                description = description.trim();
                if(VERBOSE)
                    System.out.println("description = " + description);
                input_data.put("description", description);
            }
            String enabled = formData.getProperty("Enabled");
            if(enabled == null)
                enabled = getFormValueFromSession(formName, "Enabled", "");
            if(enabled != null)
            {
                enabled = enabled.trim();
                if(VERBOSE)
                    System.out.println("enabled = " + enabled);
                input_data.put("enabled", enabled);
            }
            try
            {
                ServletSessionCookie cookie = getState().getCookieManager().getCookie(formName);
                Properties soft_attribs = cookie.toProperties();
                input_data = WindchillAttributeUtility.propertiesToHashMap(soft_attribs, input_data, WTContext.getContext().getTimeZone(), locale);
                if(VERBOSE)
                    System.out.println("\n*** THIS IS WHAT GETS PERSISTED ***\ninput_data = " + input_data);
                doc = ApplicationIntegrationFactory.updateDocument(doc, input_data, locale, "html");
                if(VERBOSE)
                    System.out.println("Document updated successfully.  " + doc.getDisplayIdentifier().getLocalizedMessage(locale));
                String targetType = (String)formData.get("targetType");
                if(targetType == null || targetType.equals(""))
                    targetType = getFormValueFromSession((String)formData.get("formName"), "targetType", "");
                if(targetType == null || targetType.equals(""))
                    targetType = getFormValueFromSession((String)formData.get("formName"), "persistedTargetType", "");
                if(VERBOSE)
                    System.out.println("\n*** GOT TARGET TYPE  = " + targetType);
                String filename = (String)formData.get("File");
                if(filename == null || filename.equals(""))
                    filename = getFormValueFromSession((String)formData.get("formName"), "File", "");
                if(VERBOSE)
                    System.out.println("\n*** GOT FILE NAME  = " + filename);
                String scmname = (String)formData.get("SCMHidden");
                if(scmname == null || scmname.equals(""))
                    scmname = getFormValueFromSession((String)formData.get("formName"), "SCMHidden", "");
                if(VERBOSE)
                    System.out.println("\n*** GOT SCMNAME NAME  = " + scmname);
                if(targetType != null && targetType.equalsIgnoreCase("URL"))
                {
                    persistPrimaryURL(doc, filename);
                    formData.put("File", "");
                    formData.put("targetType", "NONE");
                } else
                if(targetType != null && targetType.equalsIgnoreCase("SCM"))
                    try
                    {
                        persistPrimarySCM(doc, scmname);
                        formData.put("File", "");
                        formData.put("targetType", "NONE");
                    }
                    catch(Throwable t)
                    {
                        t.printStackTrace();
                    }
                else
                if(filename != null && filename.length() > 0)
                {
                    removePrimaryURL(doc);
                    removePrimarySCM(doc);
                }
                processURLAttachments(doc, formData);
                processSCMAttachments(doc, formData);
                setContextObj(doc);
                setContextAction("UpdateDocumentProcessing");
            }
            catch(WTException e)
            {
                addToResponseHeaders(e);
                e.printStackTrace();
                setContextAction("UpdateDocument1");
            }
        }
    }

    private boolean validateForm(String pageName, Properties fData)
        throws WTException
    {
        String formName = (String)fData.get("formName");
        if(getContextAction().equals("UpdateDocumentUploadFailure"))
        {
            Object messageParams[] = {
                switchSlashes(getFormValueFromSession((String)fData.get("formName"), "File", ""))
            };
            Properties qData = getQueryData();
            if((String)qData.get("changed") == null)
                addToResponseHeaders(new WTMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "21", messageParams));
            else
                addToResponseHeaders(new WTMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "22", messageParams));
            return true;
        }
        if(getContextAction().equals("DoUpdateDocument"))
        {
            String targetType = (String)fData.get("targetType");
            if(targetType == null || targetType.equals(""))
                targetType = getFormValueFromSession((String)fData.get("formName"), "targetType", "");
            String filename = (String)fData.get("File");
            String upload = (String)fData.get("upload");
            if(upload == null)
                upload = getFormValueFromSession((String)fData.get("formName"), "upload", null);
            boolean doUpload = upload == null || upload != null && !upload.equalsIgnoreCase("false");
            if(VERBOSE)
                System.out.println("UpdateDocFTD.validateForm() - filename = " + filename + ", upload = " + upload + ", doUpload = " + doUpload);
            if(filename == null || filename.equals(""))
                filename = getFormValueFromSession((String)fData.get("formName"), "File", "");
            if(!doUpload)
            {
                if(VERBOSE)
                    System.out.println("UpdateDocFTD.validateForm() - doUpload set to false");
                fData.put("File", "");
                return true;
            }
            if(PRIMARY_REQUIRED && (filename == null || filename.trim().length() == 0))
            {
                setContextAction("UpdateDocument");
                addToResponseHeaders(new WTMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "12", null));
                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("UpdateDocument");
                Object args[] = {
                    new Integer(DocumentUtility.getTitleUpperLimit())
                };
                addToResponseHeaders(new WTMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "73", args));
                return false;
            } else
            {
                return true;
            }
        } else
        {
            return true;
        }
    }

    public String getFormValueFromSession(String formName, String inputFieldName, String defaultValue)
        throws WTException
    {
        if(VERBOSE)
            System.out.println("^^^^^^^^^UpdateDocumentFormTaskDelegate.getFormValueFromSession()");
        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 String switchSlashes(String path)
    {
        return path.replace('\\', '/');
    }

    protected void persistPrimarySCM(FormatContentHolder document, String scm)
        throws WTException, WTPropertyVetoException, PropertyVetoException
    {
        if(VERBOSE)
            System.out.println("\npersistPrimarySCM:  " + scm);
        if(scm == null || scm.length() == 0)
            return;
        if(InstalledProperties.isInstalled("Windchill.SoftwareConfigMgmtIntegration"))
        {
            if(VERBOSE)
                System.out.println("DWP.persistPrimarySCM() invoking createScmData with..." + scm);
            boolean success = ScmFacade.getInstance().createScmData(document, scm);
        } else
        {
            return;
        }
    }

    protected void persistPrimaryURL(FormatContentHolder document, String url)
        throws WTException, WTPropertyVetoException, PropertyVetoException
    {
        wt.content.ContentHolder holder;
        ContentItem item;
        URLData urlData;
        Transaction trx;
        if(VERBOSE)
            System.out.println("\npersistPrimaryURL:  " + url);
        if(url == null || url.length() == 0)
            return;
        holder = document;
        holder = (FormatContentHolder)ContentHelper.service.getContents(holder);
        item = ContentHelper.getPrimary((FormatContentHolder)holder);
        urlData = null;
        trx = new Transaction();
        String urlLocation;
        trx.start();
        if(item == null)
        {
            urlData = URLData.newURLData(holder);
            break MISSING_BLOCK_LABEL_168;
        }
        if(!(item instanceof URLData))
            break MISSING_BLOCK_LABEL_143;
        urlData = (URLData)item;
        urlLocation = urlData.getUrlLocation();
        if(url.equals(urlLocation))
        {
            if(trx != null)
                trx.rollback();
            return;
        }
        break MISSING_BLOCK_LABEL_168;
        if(item instanceof ApplicationData)
        {
            ContentServerHelper.service.deleteContent(holder, item);
            urlData = URLData.newURLData(holder);
        }
        urlData.setUrlLocation(fixQuotesForURL(url));
        urlData.setRole(ContentRoleType.toContentRoleType("PRIMARY"));
        urlData = ContentServerHelper.service.updateContent(holder, urlData);
        holder = ContentServerHelper.service.updateHolderFormat((FormatContentHolder)holder);
        trx.commit();
        trx = null;
        if(trx != null)
            trx.rollback();
        return;
        Exception exception;
        exception;
        if(trx != null)
            trx.rollback();
        throw exception;
    }

    protected void removePrimarySCM(FormatContentHolder document)
        throws WTException, WTPropertyVetoException, PropertyVetoException
    {
        if(VERBOSE)
            System.out.println("\nremovePrimarySCM");
        wt.content.ContentHolder holder = document;
        holder = (FormatContentHolder)ContentHelper.service.getContents(holder);
        ContentItem item = ContentHelper.getPrimary((FormatContentHolder)holder);
        if((item instanceof ApplicationData) && InstalledProperties.isInstalled("Windchill.SoftwareConfigMgmtIntegration") && ScmFacade.getInstance().isScmData((ApplicationData)item))
            ContentServerHelper.service.deleteContent(holder, item);
    }

    protected void removePrimaryURL(FormatContentHolder document)
        throws WTException, WTPropertyVetoException, PropertyVetoException
    {
        if(VERBOSE)
            System.out.println("\nremovePrimaryURL");
        wt.content.ContentHolder holder = document;
        holder = (FormatContentHolder)ContentHelper.service.getContents(holder);
        ContentItem item = ContentHelper.getPrimary((FormatContentHolder)holder);
        if(item instanceof URLData)
            ContentServerHelper.service.deleteContent(holder, item);
    }

    protected void removePrimaryFile(FormatContentHolder document)
        throws WTException, WTPropertyVetoException, PropertyVetoException
    {
        if(VERBOSE)
            System.out.println("\nremovePrimaryURL");
        wt.content.ContentHolder holder = document;
        holder = (FormatContentHolder)ContentHelper.service.getContents(holder);
        ContentItem item = ContentHelper.getPrimary((FormatContentHolder)holder);
        if(item instanceof ApplicationData)
            if(InstalledProperties.isInstalled("Windchill.SoftwareConfigMgmtIntegration"))
            {
                if(!ScmFacade.getInstance().isScmData((ApplicationData)item))
                    ContentServerHelper.service.deleteContent(holder, item);
            } else
            {
                ContentServerHelper.service.deleteContent(holder, item);
            }
    }

    protected void processSCMAttachments(FormatContentHolder document, Properties form_data)
        throws WTException, WTPropertyVetoException, PropertyVetoException
    {
        if(VERBOSE)
            System.out.println("processSCMAttachments  form_data = " + form_data + "\n\n");
        String secondaryContent = (String)form_data.get("displayAttachments");
        if(secondaryContent == null || secondaryContent.length() == 0)
            secondaryContent = getFormValueFromSession((String)form_data.get("formName"), "displayAttachments", "");
        if(secondaryContent != null && secondaryContent.length() > 0)
        {
            String RECORD_DELIM = ";;;zzz";
            String secondaries[] = secondaryContent.split(RECORD_DELIM);
            for(int i = 0; i < secondaries.length; i++)
                if(secondaries[i].indexOf("SCM") == 0)
                    persistSCMAttachment(document, secondaries[i]);

        }
    }

    protected void processURLAttachments(FormatContentHolder document, Properties form_data)
        throws WTException
    {
        if(VERBOSE)
            System.out.println("processURLAttachments  form_data = " + form_data + "\n\n");
        String secondaryContent = (String)form_data.get("displayAttachments");
        if(secondaryContent == null || secondaryContent.length() == 0)
            secondaryContent = getFormValueFromSession((String)form_data.get("formName"), "displayAttachments", "");
        if(secondaryContent != null && secondaryContent.length() > 0)
        {
            String RECORD_DELIM = ";;;zzz";
            String secondaries[] = secondaryContent.split(RECORD_DELIM);
            for(int i = 0; i < secondaries.length; i++)
            {
                if(secondaries[i].indexOf("URL") != 0)
                    continue;
                try
                {
                    persistURLAttachment(document, secondaries[i]);
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            }

        }
    }

    protected void persistSCMAttachment(FormatContentHolder holder, String scmAttachment)
        throws WTException, WTPropertyVetoException, PropertyVetoException
    {
        if(VERBOSE)
            System.out.println("\npersistSCMAttachment:  " + scmAttachment);
        String DELIM = ";;;qqq";
        String attachData[] = scmAttachment.split(DELIM);
        String action = null;
        if(attachData.length >= 10)
            action = attachData[9];
        if(VERBOSE)
        {
            System.out.println("action = " + action);
            System.out.println("scmLocation = " + attachData[7]);
            System.out.println("scmId = " + attachData[1]);
        }
        if(action != null);
        boolean success;
        if(action.equals("ADD"))
        {
            if(InstalledProperties.isInstalled("Windchill.SoftwareConfigMgmtIntegration"))
                success = ScmFacade.getInstance().createScmData(holder, attachData[7]);
        } else
        if(action.equals("REMOVE"))
            removeSCMAttachment(holder, attachData[1]);
    }

    protected void persistURLAttachment(FormatContentHolder holder, String urlAttachment)
        throws WTException, WTPropertyVetoException, PropertyVetoException
    {
        if(VERBOSE)
            System.out.println("\npersistURLAttachment:  " + urlAttachment);
        String DELIM = ";;;qqq";
        String attachData[] = urlAttachment.split(DELIM);
        String action = null;
        if(attachData.length >= 10)
            action = attachData[9];
        if(VERBOSE)
        {
            System.out.println("action = " + action);
            System.out.println("urlLocation = " + attachData[7]);
            System.out.println("description = " + attachData[3]);
            System.out.println("urlId = " + attachData[1]);
        }
        if(action == null)
            return;
        URLData urlData = null;
        ObjectIdentifier urlId = null;
        if(action.equals("ADD"))
            persistURLAttachment(holder, attachData[7], attachData[3]);
        else
        if(action.equals("REMOVE"))
            removeURLAttachment(holder, attachData[1]);
    }

    protected void persistURLAttachment(FormatContentHolder document, String url, String description)
        throws WTException, WTPropertyVetoException, PropertyVetoException
    {
        wt.content.ContentHolder holder = document;
        URLData urlData = null;
        urlData = URLData.newURLData(holder);
        urlData.setUrlLocation(fixQuotesForURL(url));
        if(description != null && description.length() > 0)
            urlData.setDescription(fixQuotesForDescription(description));
        urlData.setRole(ContentRoleType.toContentRoleType("SECONDARY"));
        urlData = ContentServerHelper.service.updateContent(holder, urlData);
    }

    protected void removeURLAttachment(FormatContentHolder document, String urlIdString)
        throws WTException, WTPropertyVetoException, PropertyVetoException
    {
        wt.content.ContentHolder holder = document;
        ObjectIdentifier urlId = null;
        if(urlIdString.length() > 0)
            urlId = new ObjectIdentifier(urlIdString);
        if(urlId != null)
        {
            ContentItem item = (ContentItem)PersistenceHelper.manager.refresh(urlId);
            ContentServerHelper.service.deleteContent(holder, item);
        }
    }

    protected void removeSCMAttachment(FormatContentHolder document, String scmIdString)
        throws WTException, WTPropertyVetoException, PropertyVetoException
    {
        wt.content.ContentHolder holder = document;
        ObjectIdentifier scmId = null;
        if(scmIdString.length() > 0)
            scmId = new ObjectIdentifier(scmIdString);
        if(scmId != null)
        {
            ContentItem item = (ContentItem)PersistenceHelper.manager.refresh(scmId);
            ContentServerHelper.service.deleteContent(holder, item);
        }
    }

    public static String fixQuotesForURL(String input)
    {
        String jscharacter[] = {
            "\"", "'"
        };
        String jsreplacement[] = {
            "%22", "%27"
        };
        return replace(jscharacter, jsreplacement, input);
    }

    public static String fixQuotesForDescription(String input)
    {
        String jscharacter[] = {
            "\"", "'"
        };
        String jsreplacement[] = {
            "&#34;", "&#39;"
        };
        return replace(jscharacter, jsreplacement, input);
    }

    private static String replace(String chars[], String reps[], String input)
    {
        if(input == null)
            return "";
        int length = input.length();
        for(int i = 0; i < chars.length; i++)
        {
            int replen;
            for(int idx = input.indexOf(chars[i]); idx >= 0; idx = input.indexOf(chars[i], idx + replen))
            {
                replen = reps[i].length();
                int chrlen = chars[i].length();
                input = input.substring(0, idx) + reps[i] + input.substring(idx + chrlen, length);
                length = input.length();
            }

        }

        return input;
    }

    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 boolean PRIMARY_REQUIRED = false;

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