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

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

import com.ptc.core.HTMLtemplateutil.server.processors.EntityTaskDelegate;
import com.ptc.windchill.enterprise.nativeapp.server.ApplicationIntegrationFactory;
import com.ptc.windchill.enterprise.templateutil.ActionValidator;
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.identity.IdentityFactory;
import wt.pom.Transaction;
import wt.templateutil.processor.*;
import wt.util.*;
import wt.vc.wip.*;

public class CheckInDocumentFormTaskDelegate extends FormTaskDelegate
    implements Serializable
{

    public CheckInDocumentFormTaskDelegate()
    {
        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)
        {
            if(VERBOSE)
                System.out.println("!!!!!!!!!!!!!!!!!!!!checkin didn't have formname!!!!!!!!!!");
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        }
        EntityTaskDelegate.saveEntityFormDataInSession(getState().getCookieManager(), formName, fData);
        boolean validForm = validateForm(pageName, fData);
        EntityTaskDelegate.saveEntityFormDataInSession(getState().getCookieManager(), formName, fData);
        if(validForm)
        {
            if(getContextAction().equals("DoCheckInDocument_plm"))
                doCheckIn(formName);
            else
            if(qData.get("nextAction").equals("CheckInDocumentUpload_plm"))
                doContent(formName);
            else
                switchPages((String)qData.get("nextAction"), null, (wt.doc.WTDocument.class).getName());
        } else
        {
            switchPages(getContextAction(), null, (wt.doc.WTDocument.class).getName());
        }
        RedirectObject redirectObj = new RedirectObject();
        redirectObj.setRedirection(getState());
    }

    private void doContent(String formName)
        throws WTException, PropertyVetoException, WTPropertyVetoException
    {
        WTDocument doc = (WTDocument)getContextObj();
        Properties formData = getFormData();
        if(!WorkInProgressHelper.isWorkingCopy(doc))
            doc = (WTDocument)WorkInProgressHelper.service.workingCopyOf(doc);
        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", "");
        String filename = (String)formData.get("File");
        if(filename == null || filename.equals(""))
            filename = getFormValueFromSession((String)formData.get("formName"), "File", "");
        String scmname = (String)formData.get("SCMHidden");
        if(scmname == null || scmname.equals(""))
            scmname = getFormValueFromSession((String)formData.get("formName"), "SCMHidden", "");
        String upload = (String)formData.get("upload");
        if(upload == null || upload.equals(""))
            upload = getFormValueFromSession((String)formData.get("formName"), "upload", "");
        if(!PRIMARY_REQUIRED && (filename == null || filename.length() == 0))
        {
            if(VERBOSE)
                System.out.println("doContent() - there is no primary, and primary is not required");
            upload = "false";
        }
        if(VERBOSE)
            System.out.println("CheckInFormTaskDelegate.doContent() has: targetType= " + targetType + " scmname = " + scmname + " File = " + filename + " upload = " + upload);
        if(upload.equalsIgnoreCase("false"))
        {
            if(VERBOSE)
                System.out.println("***doContent() -- no primary");
            formData.put("File", "");
            formData.put("targetType", "NONE");
            doCheckIn(formName);
        } else
        if(targetType != null && targetType.equalsIgnoreCase("URL"))
        {
            if(VERBOSE)
                System.out.println("***doContent() -- URL primary");
            persistPrimaryURL(doc, filename);
            formData.put("File", "");
            formData.put("targetType", "NONE");
            doCheckIn(formName);
        } else
        if(targetType != null && targetType.equalsIgnoreCase("SCM"))
        {
            if(VERBOSE)
                System.out.println("***doContent() -- SCM primary");
            persistPrimarySCM(doc, scmname);
            formData.put("File", "");
            formData.put("targetType", "NONE");
            doCheckIn(formName);
        } else
        if(filename != null && filename.length() > 0)
        {
            if(VERBOSE)
                System.out.println("***doContent() -- file primary");
            removePrimaryURL(doc);
            removePrimarySCM(doc);
            setContextObj(doc);
            setContextAction("CheckInDocumentUpload_plm");
        } else
        if(VERBOSE)
            System.out.println("***doContent() -- no other primary case applied");
        EntityTaskDelegate.saveEntityFormDataInSession(getState().getCookieManager(), (String)formData.get("formName"), formData);
    }

    private void doCheckIn(String formName)
        throws WTException
    {
        WTDocument doc = (WTDocument)getContextObj();
        WTDocument old_doc = null;
        if(WorkInProgressHelper.isWorkingCopy(doc))
            old_doc = (WTDocument)WorkInProgressHelper.service.originalCopyOf(doc);
        else
            old_doc = doc;
        boolean isTemplate = false;
        Properties formData = getFormData();
        if(doc != null && formData != null)
        {
            if(VERBOSE)
                System.out.println("Checking in document ...");
            String comment = formData.getProperty("Comment");
            if(comment == null)
                comment = getFormValueFromSession(formName, "Comment", "");
            if(comment != null)
            {
                comment = comment.trim();
                if(VERBOSE)
                    System.out.println("comment = " + comment);
            }
            if(comment == null && VERBOSE)
                System.out.println("*****Comment field is null for input to Check In.");
            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);
            }
            if(!ActionValidator.isCheckInValid(doc))
            {
                Object param[] = {
                    doc.getName()
                };
                addToResponseHeaders(new WTMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "19", null));
                setContextAction("CloseWindow");
                return;
            }
            if(VERBOSE)
                System.out.println("DEBUG: CheckInDocumentFormTaskDelegate -> getting working copy");
            if(!WorkInProgressHelper.isWorkingCopy(doc))
                doc = (WTDocument)WorkInProgressHelper.service.workingCopyOf(doc);
            if(doc instanceof Workable)
            {
                Workable w = doc;
                HashMap nameValueData = new HashMap();
                nameValueData.put("template.enabled", enabled);
                w = ApplicationIntegrationFactory.checkin(doc, nameValueData, comment, false, locale, "html");
                if(w instanceof WTDocument)
                    doc = (WTDocument)w;
            } else
            {
                System.err.println("object not Workable, can't be checked in");
            }
            if(VERBOSE)
                System.out.println("Document updated successfully.  " + doc.getDisplayIdentifier().getLocalizedMessage(locale));
            Object params[] = {
                IdentityFactory.getDisplayIdentifier(doc).getLocalizedMessage(locale)
            };
            setContextObj(doc);
        }
        deleteFormDataFromSession(formName);
        setContextAction("CheckInDocCloseWindow");
        Properties context_properties = getContextProperties();
        if(context_properties == null)
            context_properties = new Properties();
        ReferenceFactory factory = new ReferenceFactory();
        context_properties.put("newOid", factory.getReferenceString(ObjectReference.newObjectReference(doc.getPersistInfo().getObjectIdentifier())));
        context_properties.put("oldOid", factory.getReferenceString(ObjectReference.newObjectReference(old_doc.getPersistInfo().getObjectIdentifier())));
        setContextProperties(context_properties);
    }

    private boolean validateForm(String pageName, Properties fData)
        throws Exception
    {
        Properties qData = getQueryData();
        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("CheckInDocFTD.validateForm() - filename = " + filename + ", upload = " + upload + ", doUpload = " + doUpload);
        if(filename == null || filename.equals(""))
            filename = getFormValueFromSession((String)fData.get("formName"), "File", "");
        if(filename != null && filename.trim().length() == 0)
        {
            filename = "";
            fData.put("File", "");
        }
        if(getContextAction().equals("DoCheckInDocument_plm"))
        {
            String uploaded = (String)qData.get("uploaded");
            if(uploaded != null && uploaded.equalsIgnoreCase("true"))
            {
                long checksum = 0L;
                try
                {
                    checksum = Long.parseLong((String)qData.get("checksum"));
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
                FormatContentHolder holder = (FormatContentHolder)getContextObj();
                holder = (FormatContentHolder)ContentHelper.service.getContents(holder);
                wt.content.ContentItem item = ContentHelper.getPrimary(holder);
                if(item instanceof ApplicationData)
                {
                    ApplicationData app = (ApplicationData)item;
                    app.setChecksum(checksum);
                    try
                    {
                        ContentHelper.service.updateAppData(holder, app);
                    }
                    catch(Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        }
        if(getContextAction().equals("CheckInDocumentUploadFailure"))
        {
            if(VERBOSE)
                System.out.println("CheckInDocFTD.validateForm() - in upload failure case");
            Object messageParams[] = {
                switchSlashes(getFormValueFromSession((String)fData.get("formName"), "File", ""))
            };
            if((String)qData.get("changed") == null)
            {
                if(VERBOSE)
                    System.out.println("CheckInDocFTD.validateForm() - couldn't read file");
                addToResponseHeaders(new WTMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "21", messageParams));
            } else
            {
                if(VERBOSE)
                    System.out.println("CheckInDocFTD.validateForm() - upload cancelled");
                addToResponseHeaders(new WTMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "22", messageParams));
            }
            return true;
        }
        if(!doUpload)
        {
            if(VERBOSE)
                System.out.println("CheckInDocFTD.validateForm() - doUpload set to false");
            fData.put("File", "");
            return true;
        }
        if(PRIMARY_REQUIRED)
        {
            if(VERBOSE)
                System.out.println("CheckInDocFTD.validateForm() - PRIMARY_REQUIRED=true");
            if(filename == null || filename.trim().length() == 0)
            {
                setContextAction("CheckInDocument_plm");
                fData.put("File", "");
                addToResponseHeaders(new WTMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "12", null));
                return false;
            }
        } else
        {
            if(VERBOSE)
                System.out.println("CheckInDocFTD.validateForm() - PRIMARY_REQUIRED=false");
            return true;
        }
        if(VERBOSE)
            System.out.println("CheckInDocFTD.validateForm() - didn't return from any of the conditional cases");
        return true;
    }

    public String getFormValueFromSession(String formName, String inputFieldName, String defaultValue)
        throws WTException
    {
        if(VERBOSE)
            System.out.println("^^^^^^^^^CheckInDocumentFormTaskDelegate.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 persistPrimaryURL(FormatContentHolder document, String url)
        throws WTException, WTPropertyVetoException, PropertyVetoException
    {
        wt.content.ContentHolder holder;
        wt.content.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(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 removePrimaryURL(FormatContentHolder document)
        throws WTException, WTPropertyVetoException, PropertyVetoException
    {
        if(VERBOSE)
            System.out.println("\nremovePrimaryURL");
        wt.content.ContentHolder holder = document;
        holder = (FormatContentHolder)ContentHelper.service.getContents(holder);
        wt.content.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);
        wt.content.ContentItem item = ContentHelper.getPrimary((FormatContentHolder)holder);
        if(item instanceof ApplicationData)
            ContentServerHelper.service.deleteContent(holder, item);
    }

    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;
        boolean success;
        if(InstalledProperties.isInstalled("Windchill.SoftwareConfigMgmtIntegration"))
            success = ScmFacade.getInstance().createScmData(document, scm);
        else
            return;
    }

    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);
        wt.content.ContentItem item = ContentHelper.getPrimary((FormatContentHolder)holder);
        if((item instanceof ApplicationData) && InstalledProperties.isInstalled("Windchill.SoftwareConfigMgmtIntegration") && ScmFacade.getInstance().isScmData((ApplicationData)item))
            ContentServerHelper.service.deleteContent(holder, item);
    }

    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.CheckInDocumentFormTaskDelegate : Error reading wt.doc.* properties");
        }
    }
}
