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

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

import com.ptc.core.HTMLtemplateutil.server.processors.*;
import com.ptc.core.command.common.CommandException;
import com.ptc.core.command.common.bean.entity.PrepareEntityCommand;
import com.ptc.core.foundation.container.common.FdnWTContainerHelper;
import com.ptc.core.foundation.container.common.FdnWTContainerService;
import com.ptc.core.foundation.type.common.TypeIdentifierSelectionHelper;
import com.ptc.core.foundation.type.server.impl.TypeHelper;
import com.ptc.core.meta.common.*;
import com.ptc.core.meta.common.impl.WCTypeIdentifier;
import com.ptc.core.meta.container.common.*;
import com.ptc.core.meta.server.TypeIdentifierUtility;
import com.ptc.core.meta.type.common.TypeInstance;
import com.ptc.core.meta.type.runtime.server.PopulatedAttributeContainerFactory;
import com.ptc.core.util.feedback.common.impl.DefaultFeedbackSpec;
import com.ptc.windchill.enterprise.copy.server.CoreMetaUtility;
import com.ptc.windchill.enterprise.doc.server.DocumentUtility;
import com.ptc.windchill.enterprise.templates.TemplatesUtility;
import java.beans.PropertyVetoException;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.*;
import wt.admin.AdminDomainRef;
import wt.admin.DomainAdministered;
import wt.content.*;
import wt.doc.WTDocument;
import wt.enterprise.*;
import wt.facade.scm.ScmFacade;
import wt.fc.*;
import wt.folder.SubFolder;
import wt.htmlutil.HtmlUtil;
import wt.httpgw.URLFactory;
import wt.identity.IdentityFactory;
import wt.inf.container.*;
import wt.method.MethodContext;
import wt.org.*;
import wt.part.WTPart;
import wt.pdmlink.PDMLinkProduct;
import wt.pds.PDSObjectInput;
import wt.query.*;
import wt.rule.util.InitRuleHelper;
import wt.services.applicationcontext.UnableToCreateServiceException;
import wt.services.applicationcontext.implementation.DefaultServiceProvider;
import wt.session.SessionHelper;
import wt.session.SessionManager;
import wt.templateutil.processor.*;
import wt.type.*;
import wt.util.*;
import wt.vc.*;
import wt.vc.wip.*;

public class DocumentWizardProcessor extends WizardProcessor
    implements Externalizable
{

    public DocumentWizardProcessor()
    {
        templatesExist = false;
    }

    public void writeExternal(ObjectOutput output)
        throws IOException
    {
        output.writeLong(0xa6700984c6548630L);
        super.writeExternal(output);
    }

    public void readExternal(ObjectInput input)
        throws IOException, ClassNotFoundException
    {
        long readSerialVersionUID = input.readLong();
        readVersion(this, input, readSerialVersionUID, false, false);
    }

    protected boolean readVersion(DocumentWizardProcessor thisObject, ObjectInput input, long readSerialVersionUID, boolean passThrough, boolean superDone)
        throws IOException, ClassNotFoundException
    {
        boolean success = true;
        if(readSerialVersionUID == 0xa6700984c6548630L)
        {
            if(!superDone)
                super.readExternal(input);
        } else
        {
            success = readOldVersion(input, readSerialVersionUID, passThrough, superDone);
            if(input instanceof PDSObjectInput)
                EvolvableHelper.requestRewriteOfEvolvedBlobbedObject();
        }
        return success;
    }

    private boolean readOldVersion(ObjectInput input, long readSerialVersionUID, boolean passThrough, boolean superDone)
        throws IOException, ClassNotFoundException
    {
        boolean success = true;
        if(readSerialVersionUID != 0xa423c93b516d760cL)
            if(!superDone)
            {
                success = super.readVersion(this, input, readSerialVersionUID, false, false);
                if(success && !passThrough && readSerialVersionUID != 0x5c9ab67f442bc0d1L)
                    readVersion(this, input, input.readLong(), false, true);
            } else
            {
                throw new InvalidClassException(CLASSNAME, "Local class not compatible: stream classdesc externalizationVersionUID=" + readSerialVersionUID + " local class externalizationVersionUID=" + 0xa6700984c6548630L);
            }
        return success;
    }

    public void getRepositoryDisplay(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        PrintWriter out = getPrintWriter(os, locale);
        String form_name = parameters.getProperty("formName");
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        WTContainer container = getRepositoryFromForm(form_name);
        String label = null;
        if(container instanceof PDMLinkProduct)
            label = WTMessage.getLocalizedMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "11", null, locale);
        else
            label = WTMessage.getLocalizedMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "10", null, locale);
        out.println("      <TD align=right valign=top class=wizFormLabel>");
        out.println("         " + label + " &nbsp");
        out.println("      </TD>");
        out.println("      <TD>");
        out.println("         " + container.getName());
        out.println("      </TD>");
        out.flush();
    }

    public void getRepositoryInput(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        PrintWriter out = getPrintWriter(os, locale);
        TypeIdentifier type = FdnWTContainerHelper.toTypeIdentifier(wt.doc.WTDocument.class);
        if(VERBOSE)
            System.out.println("Type = " + type.toString());
        ContainerSpec cSpec = new ContainerSpec(new Class[] {
            wt.inf.library.WTLibrary.class, wt.pdmlink.PDMLinkProduct.class
        });
        try
        {
            cSpec.setFilterByMembership(true);
        }
        catch(WTPropertyVetoException wtpve)
        {
            throw new WTException(wtpve);
        }
        WTContainer containers[] = FdnWTContainerHelper.service.getWTContainersForCreatableType(cSpec, type);
        String form_name = parameters.getProperty("formName");
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        String field_name = "RepositoryPick";
        if(containers != null && containers.length > 0)
        {
            int size = containers.length;
            Vector product_localized = new Vector(size);
            Vector libs_localized = new Vector(size);
            Vector product_names = new Vector(size);
            Vector libs_names = new Vector(size);
            boolean product = false;
            for(int i = 0; i < size; i++)
            {
                WTContainer container = containers[i];
                String name = container.getName();
                if(container instanceof PDMLinkProduct)
                {
                    product_localized.addElement(name);
                    product_names.addElement(name);
                    product = true;
                } else
                {
                    libs_localized.addElement(name);
                    libs_names.addElement(name);
                }
            }

            String radio_selection = getFormValueFromSession(form_name, "repos", "");
            String product_select = getFormValueFromSession(form_name, "product_drop", "");
            String lib_select = getFormValueFromSession(form_name, "repos_drop", "");
            int product_selection_index = 0;
            int lib_selection_index = 0;
            String repos_checked = " CHECKED";
            String product_checked = "";
            if(radio_selection.equals("prodrepos"))
            {
                repos_checked = "";
                product_checked = " CHECKED";
            }
            String default_lib = (String)libs_localized.elementAt(0);
            if(!default_lib.equals(lib_select))
            {
                for(int i = 0; i < libs_localized.size(); i++)
                    if(libs_localized.elementAt(i).equals(lib_select))
                        lib_selection_index = i;

            }
            String reposFeatureName = "RepositorySelection";
            String prodFeatureName = "ProductSelection";
            String reposIdStr = " ID=\"" + HtmlUtil.createTrailId("PDML", reposFeatureName, "Radio", "") + "\" ";
            String prodIdStr = " ID=\"" + HtmlUtil.createTrailId("PDML", prodFeatureName, "Radio", "") + "\" ";
            if(VERBOSE)
                System.out.println("Trail ID = " + reposIdStr);
            if(VERBOSE)
                System.out.println("Trail ID = " + prodIdStr);
            out.println("<TR>");
            out.println("   <TD valign=top class=wizFormLabel>");
            out.println("      <INPUT TYPE=\"radio\" NAME=repos VALUE=docrepos" + repos_checked + reposIdStr + ">");
            out.println("      &nbsp");
            out.println("      " + WTMessage.getLocalizedMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "10", null, locale));
            out.println("      &nbsp");
            out.print(HtmlUtil.createSelectHTML("repos_drop", "", libs_names, libs_localized, false, lib_selection_index));
            out.println("   </TD>");
            out.println("</TR>");
            if(product)
            {
                String default_prod = (String)product_localized.elementAt(0);
                if(!default_prod.equals(product_select))
                {
                    for(int i = 0; i < product_localized.size(); i++)
                        if(product_localized.elementAt(i).equals(product_select))
                            product_selection_index = i;

                }
                out.println("<TR>");
                out.println("   <TD valign=top class=wizFormLabel>");
                out.println("      <INPUT TYPE=\"radio\" NAME=repos VALUE=prodrepos" + product_checked + prodIdStr + ">");
                out.println("      &nbsp");
                out.println("      " + WTMessage.getLocalizedMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "11", null, locale));
                out.println("      &nbsp");
                out.print(HtmlUtil.createSelectHTML("product_drop", "", product_names, product_localized, false, product_selection_index));
                out.println("   </TD>");
                out.println("</TR>");
            }
        } else
        {
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "5", null);
        }
        out.flush();
    }

    public void getTypeDisplay(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        PrintWriter out = getPrintWriter(os, locale);
        String obj_context = parameters.getProperty("contextObj");
        if(obj_context != null && !obj_context.equals("") && obj_context.equalsIgnoreCase("true"))
        {
            Object obj = getContextObj();
            String localized_string = CoreMetaUtility.getLocalizedTypeString((WTObject)obj, locale);
            out.print(localized_string);
        } else
        {
            String form_name = parameters.getProperty("formName");
            if(form_name == null || form_name.equals(""))
                throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
            String object_type = getFormValueFromSession(form_name, "ObjectType", "");
            if(object_type == null || object_type.equals(""))
            {
                out.print(WTMessage.getLocalizedMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "20", null, locale));
            } else
            {
                String localized_string = CoreMetaUtility.getLocalizedTypeString(CoreMetaUtility.getTypeIdentifier(object_type), locale);
                out.print(localized_string);
            }
        }
        out.flush();
    }

    public void getTypeInput(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        PrintWriter out = getPrintWriter(os, locale);
        String form_name = parameters.getProperty("formName");
        if(form_name == null || form_name.equals(""))
        {
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        } else
        {
            WTContainer container = getRepositoryFromForm(form_name);
            String idStr = HtmlUtil.createTrailId("PDML", "DocumentTypes", "DropDown", "");
            String selection = getFormValueFromSession(form_name, "ObjectType", "");
            out.print(TypeIdentifierSelectionHelper.getTypeHTMLSelector("ObjectType", (wt.doc.WTDocument.class).getName(), container, TypeIdentifierSelectionHelper.getAdminDomainRef(getContextObj()), idStr, selection, locale));
            out.flush();
            return;
        }
    }

    public void getTemplateDisplay(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        String form_name = parameters.getProperty("formName");
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        String template = getFormValueFromSession(form_name, "Template", "");
        Persistable obj = (new ReferenceFactory()).getReference(template).getObject();
        Object params[] = {
            CoreMetaUtility.getLocalizedTypeString((WTObject)obj, locale), ((WTDocument)obj).getName()
        };
        MethodContext ctx = MethodContext.getContext();
        boolean encodeForHTMLDisplay = false;
        if(ctx.get("preserveFormatting") != null && ctx.get("preserveFormatting").toString().equalsIgnoreCase("true"))
            encodeForHTMLDisplay = true;
        String l_identity = WTMessage.getLocalizedMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "6", params);
        if(encodeForHTMLDisplay)
            l_identity = HtmlUtil.encodeEscapeCharacters(l_identity);
        PrintWriter out = getPrintWriter(os, locale);
        out.print(l_identity);
        out.flush();
    }

    public void getTemplateInput(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        PrintWriter out = getPrintWriter(os, locale);
        String form_name = parameters.getProperty("formName");
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        WTContainer container = getRepositoryFromForm(form_name);
        try
        {
            templatesExist = EnterpriseHelper.service.templatesExist(container, Class.forName("wt.doc.WTDocument"), true, true);
        }
        catch(Exception e)
        {
            throw new WTException(WTMessage.getLocalizedMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "128", null, locale));
        }
        if(!templatesExist)
        {
            out.println(WTMessage.getLocalizedMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "128", null, locale));
        } else
        {
            QuerySpec qs = new QuerySpec(wt.doc.WTDocument.class);
            ClassAttribute classAttrName = new ClassAttribute(wt.doc.WTDocument.class, "master>name");
            OrderBy orderByName = new OrderBy(SQLFunction.newSQLFunction("UPPER", classAttrName), false, locale);
            QueryResult templates = EnterpriseHelper.service.getTemplates(container, qs, new OrderBy[] {
                orderByName
            }, true, true, true);
            if(templates.size() > 0)
            {
                int size = templates.size();
                Vector localized = new Vector(size);
                Vector names = new Vector(size);
                ReferenceFactory referenceFactory = new ReferenceFactory();
                for(int i = 0; i < size; i++)
                {
                    Persistable template = (Persistable)templates.nextElement();
                    Object params[] = {
                        CoreMetaUtility.getLocalizedTypeString((WTObject)template, locale), ((WTDocument)template).getName()
                    };
                    String l_identity = WTMessage.getLocalizedMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "6", params);
                    WTReference ref = referenceFactory.getReference(template);
                    String iden = referenceFactory.getReferenceString(ref);
                    localized.addElement(l_identity);
                    names.addElement(iden);
                }

                String default_value = (String)localized.elementAt(0);
                String selection = getFormValueFromSession(form_name, "Template", default_value);
                int selection_index = 0;
                if(!default_value.equals(selection))
                {
                    for(int i = 0; i < size; i++)
                        if(names.elementAt(i).equals(selection))
                            selection_index = i;

                }
                String featureName = "DocTemplatesList";
                String idStr = " ID=\"" + HtmlUtil.createTrailId("PDML", featureName, "DropDown", "") + "\" ";
                out.print(HtmlUtil.createSelectHTML("Template", idStr, names, localized, false, selection_index));
            } else
            {
                throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "3", null);
            }
        }
        out.flush();
    }

    public void getTemplateTypeInput(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        PrintWriter out = getPrintWriter(os, locale);
        String form_name = parameters.getProperty("formName");
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        WTContainer container = getRepositoryFromForm(form_name);
        TypeIdentifier base_type = FdnWTContainerHelper.toTypeIdentifier(wt.doc.WTDocument.class);
        if(VERBOSE)
            System.out.println("Base type = " + base_type.toString());
        TypeIdentifier types[] = FdnWTContainerHelper.service.getCreatableDocTemplateTypesForWTContainer(container, base_type);
        out.print(getTypeInput(types, form_name, locale));
        out.flush();
    }

    public void getOrgIDDisplay(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        PrintWriter out = getPrintWriter(os, locale);
        String form_name = parameters.getProperty("formName");
        String page_name = parameters.getProperty("pageName");
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        if(page_name == null || page_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "108", null);
        WTContainer container = getRepositoryFromForm(form_name);
        Object context_obj = getContextObj();
        String orgID = getFormValueFromSession(form_name, "OrganizationDN", "");
        if(orgID.length() == 0 && container != null)
            orgID = getCurrentOrganizationDN(container);
        if(VERBOSE)
            System.out.println("DocumentWizardProcessor.getOrgIDDisplay:orgID=" + orgID);
        if(ProjectlinkUtilProcessorService.displayOrganization(WTContainerRef.newWTContainerRef(container), wt.doc.WTDocument.class))
        {
            String label = WTMessage.getLocalizedMessage("com.ptc.windchill.pdmlink.doc.client.clientRB", "63", null, locale);
            String searchLabel = WTMessage.getLocalizedMessage("wt.query.queryResource", "126", null, locale);
            String orgValue = "";
            String featureName = "OrgIDDisplay";
            String textIdStr = " ID=\"" + HtmlUtil.createTrailId("PDML", featureName, "InputText", "") + "\" ";
            String buttonIdStr = " ID=\"" + HtmlUtil.createTrailId("PDML", featureName, "Button", "") + "\" ";
            if(VERBOSE)
                System.out.println("Trail ID = " + textIdStr);
            if(VERBOSE)
                System.out.println("Trail ID = " + buttonIdStr);
            if(orgID.length() > 0)
            {
                WTPrincipal p = OrganizationServicesHelper.manager.getPrincipalByDN(orgID);
                if(p != null)
                    orgValue = p.getName();
            }
            out.println("<TD align=right valign=top class=wizFormLabel>");
            out.println(label + " &nbsp");
            out.println("</TD>");
            out.println("<TD>");
            out.println("  <INPUT type=text disabled name='DocOrganization' size=30 value='" + orgValue + "'" + textIdStr + ">");
            out.println("  <INPUT type='button' value=\"" + searchLabel + "\" onClick='javascript:openSearch();'" + buttonIdStr + " />");
            out.println("</TD>");
        }
        out.println("<script language='Javascript'>document." + page_name + ".OrganizationDN.value='" + escapeForJavascriptUse(orgID) + "';</script>");
        out.flush();
    }

    public void getDocumentDisplayIdentity(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        String identity = IdentityFactory.getDisplayIdentifier(getContextObj()).getLocalizedMessage(locale);
        if(VERBOSE)
            System.out.println("Identity in display identity = " + identity);
        String key = parameters.getProperty("resourceKey");
        if(VERBOSE)
            System.out.println("resourceKey = " + key);
        String bundle = parameters.getProperty("resourceClass");
        if(VERBOSE)
            System.out.println("resourceClass = " + bundle);
        MethodContext ctx = MethodContext.getContext();
        boolean encodeForHTMLDisplay = false;
        if(ctx.get("preserveFormatting") != null && ctx.get("preserveFormatting").toString().equalsIgnoreCase("true"))
            encodeForHTMLDisplay = true;
        if(encodeForHTMLDisplay)
            identity = HtmlUtil.encodeEscapeCharacters(identity);
        Object param[] = {
            identity
        };
        String docIdentity = getLocalizedResourceParameterString(key, bundle, param, locale);
        if(VERBOSE)
            System.out.println("Localized version of the identity and string = " + docIdentity);
        PrintWriter out = getPrintWriter(os, locale);
        out.print(docIdentity);
        out.flush();
    }

    private static String getLocalizedResourceParameterString(String resource_key, String resource_class, Object params[], Locale locale)
        throws WTException
    {
        if(VERBOSE)
            System.out.println("Entering getLocalizedResourceParameterString()...");
        Class resourceKeyClass = null;
        try
        {
            if(VERBOSE)
                System.out.println("Resource class = " + resource_class);
            resourceKeyClass = Class.forName(resource_class);
        }
        catch(ClassNotFoundException e)
        {
            throw new WTException(e, WTMessage.getLocalizedMessage("wt.enterprise.enterpriseResource", "74", null, locale));
        }
        Field attributeField = null;
        try
        {
            if(VERBOSE)
                System.out.println("Resource key = " + resource_key);
            attributeField = resourceKeyClass.getField(resource_key);
        }
        catch(NoSuchFieldException e)
        {
            throw new WTException(e, WTMessage.getLocalizedMessage("wt.enterprise.enterpriseResource", "75", null, locale));
        }
        if(VERBOSE)
            System.out.println("  attributeField -> " + attributeField);
        String attrName = null;
        try
        {
            attrName = (String)attributeField.get(null);
        }
        catch(IllegalAccessException e)
        {
            throw new WTException(e);
        }
        if(VERBOSE)
            System.out.println("  attrName -> " + attrName);
        return WTMessage.getLocalizedMessage(resource_class, attrName, params, locale);
    }

    private String validateTypePreference(TypeIdentifier types[], String localizedString, Locale locale)
        throws WTException
    {
        Vector type_string;
        String prefValue;
        String resName;
        int index;
        type_string = null;
        if(types != null && types.length > 0)
        {
            int size = types.length;
            type_string = new Vector(size);
            for(int i = 0; i < size; i++)
            {
                TypeIdentifier type_id = types[i];
                type_string.insertElementAt(((WCTypeIdentifier)type_id).getTypename(), i);
            }

        }
        prefValue = getPreferenceValue("/com/ptc/windchill/doc", "DefaultType");
        if(VERBOSE)
            System.out.println("preference value: " + prefValue);
        if(prefValue == null || prefValue.length() <= 0)
            break MISSING_BLOCK_LABEL_433;
        resName = null;
        index = prefValue.indexOf(":");
        if(index == -1)
            break MISSING_BLOCK_LABEL_342;
        resName = prefValue.substring(0, index);
        if(VERBOSE)
            System.out.println("resource bundle name for default type selection" + resName);
        Class resource_class = Class.forName(resName);
        Field a_field = null;
        a_field = resource_class.getField(prefValue.substring(index + 1, prefValue.length()));
        localizedString = WTMessage.getLocalizedMessage(resName, (String)a_field.get(resource_class), null, locale);
        if(VERBOSE)
            System.out.println("resource string for default type selection: " + localizedString);
        return "SelectAType," + localizedString;
        ClassNotFoundException cnfe;
        cnfe;
        Object params[] = {
            prefValue
        };
        throw new WTException("com.ptc.windchill.pdmlink.doc.client.clientRB", "66", params);
        NoSuchFieldException nsfe;
        nsfe;
        Object params[] = {
            prefValue
        };
        throw new WTException("com.ptc.windchill.pdmlink.doc.client.clientRB", "66", params);
        Exception e;
        e;
        e.printStackTrace();
        break MISSING_BLOCK_LABEL_433;
        int indexC = prefValue.indexOf(".");
        if(indexC != -1)
            if(type_string.contains(prefValue))
            {
                return prefValue;
            } else
            {
                Object params[] = {
                    prefValue
                };
                throw new WTException("com.ptc.windchill.pdmlink.doc.client.clientRB", "66", params);
            }
        if(prefValue.equals("blank"))
        {
            return "blank";
        } else
        {
            Object params[] = {
                prefValue
            };
            throw new WTException("com.ptc.windchill.pdmlink.doc.client.clientRB", "66", params);
        }
        return "SelectAType";
    }

    private String getTypeInput(TypeIdentifier types[], String form_name, Locale locale)
        throws WTException
    {
        if(types != null && types.length > 0)
        {
            int size = types.length;
            Vector type_localized = new Vector(size + 1);
            Vector type_string = new Vector(size + 1);
            for(int i = 0; i < size; i++)
            {
                TypeIdentifier type_id = types[i];
                String localizedString = CoreMetaUtility.getLocalizedTypeString(type_id, locale);
                int pos = DocumentUtility.getInsertLocation(type_localized, localizedString, locale);
                type_localized.insertElementAt(localizedString, pos);
                type_string.insertElementAt(((WCTypeIdentifier)type_id).getTypename(), pos);
            }

            String localizedStr = "";
            String default_value = null;
            try
            {
                default_value = validateTypePreference(types, localizedStr, locale);
                int ind = default_value.indexOf(",");
                if(ind > 0)
                {
                    localizedStr = default_value.substring(ind + 1, default_value.length());
                    default_value = default_value.substring(0, ind);
                }
            }
            catch(Exception e)
            {
                default_value = "SelectAType";
                e.printStackTrace(System.err);
            }
            if(default_value.equals("SelectAType"))
            {
                if(VERBOSE)
                    System.out.println("localizedString: " + localizedStr);
                if(localizedStr.equals(""))
                    localizedStr = WTMessage.getLocalizedMessage("wt.doc.docResource", "118", null, locale);
                size++;
                type_localized.insertElementAt(localizedStr, 0);
                type_string.insertElementAt("SelectAType", 0);
            } else
            if(default_value.equals("blank"))
            {
                size++;
                type_localized.insertElementAt("", 0);
                type_string.insertElementAt("blank", 0);
            }
            if(VERBOSE)
                System.out.println("default_value: " + default_value);
            String selection = getFormValueFromSession(form_name, "ObjectType", default_value);
            int selection_index = 0;
            for(int i = 0; i < size; i++)
                if(type_string.get(i).equals(selection))
                    selection_index = i;

            String featureName = "DocumentTypes";
            String idStr = "ID=\"" + HtmlUtil.createTrailId("PDML", featureName, "DropDown", "") + "\"";
            return HtmlUtil.createSelectHTML("ObjectType", idStr, type_string, type_localized, false, selection_index);
        } else
        {
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "3", null);
        }
    }

    private WTContainer getRepositoryFromForm(String form_name)
        throws WTException
    {
        Object context_obj = getContextObj();
        WTContainer container = null;
        if(VERBOSE)
            System.out.println("In DocumentWizardProcessor.getRepositoryFromForm form_name = " + form_name);
        if(VERBOSE)
            System.out.println("DocumentWizardProcessor.getRepositoryFromForm: context_obj=" + context_obj);
        if(context_obj instanceof WTContainer)
        {
            container = (WTContainer)getContextObj();
            ServletSessionCookie cookie = getState().getCookieManager().getCookie(form_name);
            cookie.put("Repository", (new ReferenceFactory()).getReferenceString(container));
            if(VERBOSE)
                System.out.println("DocumentWizardProcessor.getRepositoryFromForm:WTContainer container=" + container);
        } else
        if(context_obj instanceof WTContained)
        {
            container = ((WTContained)context_obj).getContainer();
            ServletSessionCookie cookie = getState().getCookieManager().getCookie(form_name);
            cookie.put("Repository", (new ReferenceFactory()).getReferenceString(container));
            if(VERBOSE)
                System.out.println("DocumentWizardProcessor.getRepositoryFromForm:WTContained container=" + container);
        }
        if(container == null)
        {
            String container_strg = getFormValueFromSession(form_name, "Repository", "");
            if(container_strg == null || container_strg.equals(""))
                throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "9", null);
            container = (WTContainer)(new ReferenceFactory()).getReference(container_strg).getObject();
        }
        return container;
    }

    private String getRepositorySelection(String form_name)
        throws WTException
    {
        if(form_name.equals("CreateTemplateDocumentWizard"))
        {
            if(VERBOSE)
                System.out.println("Creating a template in the administrator page, get the value from the form.");
            String radio_selection = getFormValueFromSession(form_name, "repos", "");
            String repos_select = "";
            if(radio_selection.equals("docrepos"))
            {
                repos_select = getFormValueFromSession(form_name, "repos_drop", "");
                if(VERBOSE)
                    System.out.println("Radio repository selected = " + repos_select);
            } else
            if(radio_selection.equals("prodrepos"))
            {
                repos_select = getFormValueFromSession(form_name, "product_drop", "");
                if(VERBOSE)
                    System.out.println("Radio product repository selected = " + repos_select);
            } else
            {
                throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "9", null);
            }
            if(repos_select == null || repos_select.equals(""))
            {
                throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "9", null);
            } else
            {
                ServletSessionCookie cookie = getState().getCookieManager().getCookie(form_name);
                cookie.put("Repository", repos_select);
                return repos_select;
            }
        } else
        {
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "9", null);
        }
    }

    public void getNumberPrompt(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        String form_name = parameters.getProperty("formName");
        TypeIdentifier typeIdentifier = getTypeIdentifierFromSession(form_name);
        String number_prompt = "";
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        boolean auto_number = InitRuleHelper.isAutoNumber(typeIdentifier.getTypename(), WTContainerRef.newWTContainerRef(getRepositoryFromForm(form_name)));
        if(!auto_number)
            number_prompt = WTMessage.getLocalizedMessage("com.ptc.windchill.pdmlink.doc.client.clientRB", "2", null, locale);
        else
            number_prompt = WTMessage.getLocalizedMessage("com.ptc.windchill.pdmlink.doc.client.clientRB", "33", null, locale);
        PrintWriter out = getPrintWriter(os, locale);
        out.print(number_prompt);
        out.flush();
    }

    public void getNumberValue(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        String form_name = parameters.getProperty("formName");
        TypeIdentifier typeIdentifier = getTypeIdentifierFromSession(form_name);
        String number_value = "";
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        boolean auto_number = InitRuleHelper.isAutoNumber(typeIdentifier.getTypename(), WTContainerRef.newWTContainerRef(getRepositoryFromForm(form_name)));
        if(!auto_number)
        {
            String value = getFormValueFromSession(form_name, "Number", "");
            String featureName = "NumberField";
            String idStr = " ID=\"" + HtmlUtil.createTrailId("PDML", featureName, "InputText", "") + "\" ";
            if(VERBOSE)
                System.out.println("Trail ID = " + idStr);
            number_value = "<INPUT name = \"Number\" type=\"text\" value=\"" + value + "\"" + idStr + ">";
        } else
        {
            number_value = WTMessage.getLocalizedMessage("com.ptc.windchill.pdmlink.doc.client.clientRB", "34", null, locale);
        }
        PrintWriter out = getPrintWriter(os, locale);
        out.print(number_value);
        out.flush();
    }

    private TypeIdentifier getTypeIdentifierFromSession(String form_name)
        throws WTException
    {
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        TypeIdentifier typeIdentifier = null;
        String obj_id = getFormValueFromSession(form_name, "Template", "");
        if(obj_id != null && !obj_id.equals(""))
        {
            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);
            }
        } else
        {
            String obj_type = getFormValueFromSession(form_name, "ObjectType", "");
            if(obj_type == null || obj_type.equals(""))
                throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "13 7", null);
            typeIdentifier = CoreMetaUtility.getTypeIdentifier(obj_type);
        }
        return typeIdentifier;
    }

    public void displayNumberField(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        String form_name = parameters.getProperty("formName");
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        if(!InitRuleHelper.isAutoNumber(WTDocument.newWTDocument(), WTContainerRef.newWTContainerRef(getRepositoryFromForm(form_name))))
        {
            PrintWriter out = getPrintWriter(os, locale);
            out.print("<TR><TD align=right valign=top class=wizFormLabel>");
            out.flush();
            getNumberPrompt(parameters, locale, os);
            out.print("&nbsp;</TD><TD>");
            out.flush();
            getNumberValue(parameters, locale, os);
            out.print("</TD></TR>");
            out.flush();
        }
    }

    /**
     * @deprecated Method hasSoftTypes is deprecated
     */

    public boolean hasSoftTypes(Properties parameters, Locale locale)
        throws WTException
    {
        boolean tempValue = false;
        Object obj = getContextObj();
        String form_name = getFormName(parameters);
        if(obj == null)
        {
            String obj_id = getFormValueFromSession(form_name, "Template", "");
            if(obj_id != null && !obj_id.equals(""))
                try
                {
                    obj = (WTDocument)(new ReferenceFactory()).getReference(obj_id).getObject();
                }
                catch(Exception e)
                {
                    throw new WTException(e, "com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "8", null);
                }
        }
        TypeInstanceIdentifier type_instance_identifier = null;
        if(obj != null && (obj instanceof WTDocument))
        {
            type_instance_identifier = TypeIdentifierUtility.getTypeInstanceIdentifier(obj);
        } else
        {
            IdentifierFactory identifierFactory = null;
            try
            {
                identifierFactory = (IdentifierFactory)DefaultServiceProvider.getService(com.ptc.core.meta.common.IdentifierFactory.class, "default");
            }
            catch(UnableToCreateServiceException utcse)
            {
                throw new WTException(utcse);
            }
            String type = getFormValueFromSession(form_name, "ObjectType", "");
            if(VERBOSE)
                System.out.println("********" + type);
            String object_type = "WCTYPE|" + type;
            TypeIdentifier ti = (TypeIdentifier)identifierFactory.get(object_type);
            type_instance_identifier = ti.newTypeInstanceIdentifier();
        }
        TypeInstance result = null;
        AttributeContainer ac = null;
        result = EntityTaskDelegate.getTypeInstance(type_instance_identifier, null, locale);
        AttributeIdentifier attributes[] = result.getAttributeIdentifiers();
        if(attributes.length > 0)
        {
            if(VERBOSE)
                System.out.println("Total no. of soft attributes" + attributes.length);
            tempValue = true;
        }
        return tempValue;
    }

    /**
     * @deprecated Method hasSoftSchAttributes is deprecated
     */

    public boolean[] hasSoftSchAttributes(Properties parameters, Locale locale)
        throws WTException
    {
        Object obj = getContextObj();
        String form_name = getFormName(parameters);
        TypeIdentifier type = null;
        if(obj != null && (obj instanceof WTDocument))
            type = TypeIdentifierUtility.getTypeIdentifier(obj);
        if(type == null)
        {
            String obj_id = getFormValueFromSession(form_name, "Template", "");
            if(obj_id != null && obj_id.length() > 0)
            {
                WTDocument template = (WTDocument)(new ReferenceFactory()).getReference(obj_id).getObject();
                type = TypeIdentifierUtility.getTypeIdentifier(template);
                obj = template;
            }
        }
        if(type == null)
        {
            String object_type = getFormValueFromSession(form_name, "ObjectType", "");
            if(object_type != null && object_type.length() > 0)
                type = FdnWTContainerHelper.toTypeIdentifier(object_type);
            else
            if(getContextObj() != null)
            {
                String obj_type = TypedUtility.getExternalTypeIdentifier(getContextObj());
                type = FdnWTContainerHelper.toTypeIdentifier(obj_type);
            }
        }
        boolean values[] = null;
        try
        {
            values = EntityTaskDelegate.hasSoftSchemaAttributes(type.toString());
        }
        catch(WTPropertyVetoException wtpve)
        {
            throw new WTException(wtpve);
        }
        boolean req_default = false;
        if(obj != null && (obj instanceof WTDocument) && values[1])
        {
            TypeInstanceIdentifier tii = TypeIdentifierUtility.getTypeInstanceIdentifier(obj);
            TypeInstance ti = EntityTaskDelegate.getTypeInstance(tii, null, locale);
            AttributeIdentifier attributes[] = ti.getAttributeIdentifiers();
            int i = 0;
            do
            {
                if(i >= attributes.length)
                    break;
                com.ptc.core.meta.common.DefinitionIdentifier di = attributes[i].getDefinitionIdentifier();
                AttributeTypeSummary ats = ti.getAttributeTypeSummary((AttributeTypeIdentifier)di);
                req_default = ats.isRequired() && ats.isEditable() && ti.getState(attributes[i]) == State.DEFAULT;
                if(req_default)
                    break;
                i++;
            } while(true);
            if(!req_default)
                values[1] = false;
        }
        return values;
    }

    /**
     * @deprecated Method hasReqdCustomSchAttributes is deprecated
     */

    public boolean[] hasReqdCustomSchAttributes(Properties parameters, Locale locale)
        throws WTException
    {
        Object obj = getContextObj();
        String form_name = getFormName(parameters);
        TypeIdentifier type = null;
        if(obj != null && (obj instanceof WTDocument))
            type = TypeIdentifierUtility.getTypeIdentifier(obj);
        if(type == null)
        {
            String obj_id = getFormValueFromSession(form_name, "Template", "");
            if(obj_id != null && obj_id.length() > 0)
            {
                WTDocument template = (WTDocument)(new ReferenceFactory()).getReference(obj_id).getObject();
                type = TypeIdentifierUtility.getTypeIdentifier(template);
                obj = template;
            }
        }
        if(type == null)
        {
            String object_type = getFormValueFromSession(form_name, "ObjectType", "");
            if(object_type != null && object_type.length() > 0)
                type = FdnWTContainerHelper.toTypeIdentifier(object_type);
        }
        String baseType = TypeHelper.getBaseType(type);
        boolean values[] = null;
        try
        {
            values = TypeHelper.hasCustomSchemaAttributes(type.toString(), baseType);
        }
        catch(WTPropertyVetoException wtpve)
        {
            throw new WTException(wtpve);
        }
        return values;
    }

    /**
     * @deprecated Method hasCustomSchAttributes is deprecated
     */

    public boolean hasCustomSchAttributes(Properties parameters, Locale locale)
        throws WTException
    {
        Object obj = getContextObj();
        String form_name = getFormName(parameters);
        TypeIdentifier type = null;
        if(obj != null && (obj instanceof WTDocument))
            type = TypeIdentifierUtility.getTypeIdentifier(obj);
        if(obj != null && type == null && (obj instanceof WTPart))
            type = TypeIdentifierUtility.getTypeIdentifier(obj);
        if(type == null)
        {
            String obj_id = getFormValueFromSession(form_name, "Template", "");
            if(obj_id != null && obj_id.length() > 0)
            {
                WTDocument template = (WTDocument)(new ReferenceFactory()).getReference(obj_id).getObject();
                type = TypeIdentifierUtility.getTypeIdentifier(template);
                obj = template;
            }
        }
        if(type == null)
        {
            String object_type = getFormValueFromSession(form_name, "ObjectType", "");
            if(object_type != null && object_type.length() > 0)
                type = FdnWTContainerHelper.toTypeIdentifier(object_type);
        }
        String baseType = TypeHelper.getBaseType(type);
        boolean value = false;
        value = TypeHelper.hasCustomSchemaAttributes2(type.toString(), baseType);
        return value;
    }

    public void generateFooterForSoftTypes(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        boolean hasCustomAttributes = hasCustomSchAttributes(parameters, locale);
        if(hasCustomAttributes)
        {
            boolean hasReqdCustomAttributes[] = hasReqdCustomSchAttributes(parameters, locale);
            if(hasReqdCustomAttributes[1])
                parameters.put("formName", parameters.getProperty("buttonSetIfSoftTyped", "WizardFormMiddleWithoutClose"));
            else
                parameters.put("formName", parameters.getProperty("buttonSetIfSoftTypedNotRequired", "WizardFormMiddleWithoutClose"));
        } else
        {
            parameters.put("formName", parameters.getProperty("buttonSetIfNotSoftTyped", "WizardFormLastWithoutClose"));
        }
        processSubTemplate(parameters, locale, os);
    }

    public void getURLProcessorLinkForSoftTypes(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        boolean value = hasCustomSchAttributes(parameters, locale);
        if(value)
            parameters.put("nextAction", parameters.getProperty("nextActionIfSoftTyped", parameters.getProperty("nextAction")));
        else
            parameters.put("nextAction", parameters.getProperty("nextActionIfNotSoftTyped", parameters.getProperty("nextAction")));
        getURLProcessorLink(parameters, locale, os);
    }

    public void getURLProcessorLinkForObjForSoftTypes(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        boolean value = hasCustomSchAttributes(parameters, locale);
        if(value)
            parameters.put("nextAction", parameters.getProperty("nextActionIfSoftTyped", parameters.getProperty("nextAction")));
        else
            parameters.put("nextAction", parameters.getProperty("nextActionIfNotSoftTyped", parameters.getProperty("nextAction")));
        getURLProcessorLinkForObj(parameters, locale, os);
    }

    public void setFormName(Properties parameters, Locale locale, OutputStream os)
    {
        Properties props = getContextProperties();
        props.put("formName", parameters.getProperty("formName"));
        setContextProperties(props);
    }

    public void getFormName(Properties parameters, Locale locale, OutputStream os)
    {
        Properties props = getContextProperties();
        String formName = props.getProperty("formName");
        PrintWriter out = getPrintWriter(os, locale);
        out.print(formName);
        out.flush();
    }

    public void displayAttachmentsTableHeader(Properties parameters, Locale locale, OutputStream os)
    {
        if(parameters == null)
            parameters = new Properties();
        parameters.put("action", "AttachmentsHeader");
        parameters.put("enable", "false");
        parameters.put("titleResourceClass", "com.ptc.windchill.pdmlink.doc.client.clientRB");
        parameters.put("titleResourceKey", "ATTACHMENTS");
        processSubTemplate(parameters, locale, os);
    }

    public void displayAttachmentsTableFooter(Properties parameters, Locale locale, OutputStream os)
    {
        if(parameters == null)
            parameters = new Properties();
        parameters.put("action", "AttachmentsFooter");
        processSubTemplate(parameters, locale, os);
    }

    private TypeInstance getResult(TypeInstanceIdentifier typeinstanceidentifier)
    {
        TypeInstance typeinstance = null;
        try
        {
            PopulatedAttributeContainerFactory populatedattributecontainerfactory = (PopulatedAttributeContainerFactory)DefaultServiceProvider.getService(com.ptc.core.meta.type.runtime.server.PopulatedAttributeContainerFactory.class, "virtual");
            AttributeTypeIdentifier aattributetypeidentifier[] = populatedattributecontainerfactory.getAttributeContainer(null, (TypeIdentifier)typeinstanceidentifier.getDefinitionIdentifier()).getAttributeTypeIdentifiers();
            AttributeContainerSpec attributecontainerspec = new AttributeContainerSpec();
            attributecontainerspec.putEntries(aattributetypeidentifier, true, true);
            PrepareEntityCommand prepareentitycommand = new PrepareEntityCommand();
            prepareentitycommand.setFilter(attributecontainerspec);
            prepareentitycommand.setFeedbackSpec(new DefaultFeedbackSpec(CLASSNAME, true));
            prepareentitycommand.setSource(typeinstanceidentifier);
            prepareentitycommand.execute();
            typeinstance = prepareentitycommand.getResult();
        }
        catch(CommandException commandexception)
        {
            typeinstance = null;
            commandexception.printStackTrace();
        }
        catch(WTException wtexception)
        {
            typeinstance = null;
            wtexception.printStackTrace();
        }
        catch(WTPropertyVetoException wtpropertyvetoexception)
        {
            typeinstance = null;
            wtpropertyvetoexception.printStackTrace();
        }
        return typeinstance;
    }

    public void getTypeResourceKey(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        PrintWriter out = getPrintWriter(os, locale);
        String form_name = parameters.getProperty("formName");
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        String type = getFormValueFromSession(form_name, "ObjectType", "");
        if(VERBOSE)
            System.out.println("********" + type);
        String object_type = "WCTYPE|" + type;
        if(VERBOSE)
            System.out.println("object_type" + object_type);
        out.print(object_type);
        out.flush();
    }

    public void displayAttachmentsTableRows(Properties props, Locale locale, OutputStream os)
        throws WTException, PropertyVetoException, InvocationTargetException, IllegalAccessException
    {
        StringBuffer output = new StringBuffer("");
        boolean cellColor = true;
        String styleClass1 = "tableRowSel";
        String styleClass2 = "tableRowNSel";
        String curElement = "";
        String displayAttachments = props.getProperty("displayAttachments", "NONE");
        if(!displayAttachments.equals("NONE"))
        {
            if(VERBOSE)
                System.out.println("in displayAttachmentsTableRows, displayAttachments = \"" + displayAttachments + "\"");
            int curPos = 0;
            int startPos = 0;
            int count = 0;
            do
            {
                curPos = displayAttachments.indexOf(RECORD_DELIM, startPos);
                if(curPos >= 0)
                    curElement = displayAttachments.substring(startPos, curPos);
                else
                    curElement = displayAttachments.substring(startPos, displayAttachments.length());
                if(VERBOSE)
                    System.out.println("curElement " + count + " = \"" + curElement + "\"");
                if(!curElement.equals("NONE"))
                {
                    String fileInfo[] = parseIntoArray(curElement, DELIM, 10);
                    if(fileInfo[0].equals("FILE"))
                        output.append(getAttachmentsTableRow(cellColor ? styleClass1 : styleClass2, fileInfo[1], fileInfo[2], fileInfo[3], fileInfo[4], fileInfo[5], fileInfo[6], fileInfo[7], fileInfo[8], curElement, locale, count));
                    else
                    if(fileInfo[0].equals("URL"))
                        output.append(getURLTableRow(cellColor ? styleClass1 : styleClass2, fileInfo[1], fileInfo[2], fileInfo[3], fileInfo[4], fileInfo[5], fileInfo[6], fileInfo[7], fileInfo[8], curElement, locale, count));
                    else
                    if(fileInfo[0].equals("SCM"))
                        output.append(getScmTableRow(cellColor ? styleClass1 : styleClass2, fileInfo[1], fileInfo[2], fileInfo[3], fileInfo[4], fileInfo[5], fileInfo[6], fileInfo[7], fileInfo[8], curElement, locale, count));
                    output.append(getAttachmentsTableSpacerRow(10));
                    cellColor = !cellColor;
                }
                startPos = curPos + RECORD_DELIM.length();
                count++;
            } while(curPos != -1);
        }
        String outputString = output.toString();
        if(outputString != null && outputString.length() > 0)
        {
            if(VERBOSE)
                System.out.println("outputString = \"" + outputString + "\"");
            PrintWriter out = getPrintWriter(os, locale);
            out.print(outputString);
            out.flush();
        }
    }

    public void displayAttachmentsString(Properties parameters, Locale locale, OutputStream os)
        throws WTException, PropertyVetoException, InvocationTargetException, IllegalAccessException
    {
        PrintWriter out = getPrintWriter(os, locale);
        out.print(getDisplayAttachmentsString(getFormName(parameters), locale));
        out.flush();
    }

    public String getDisplayAttachmentsString(String formName, Locale locale)
        throws WTException, PropertyVetoException, InvocationTargetException, IllegalAccessException
    {
        String displayAttachments = getFormValueFromSession(formName, "displayAttachments", "");
        if(displayAttachments.length() == 0)
        {
            Object obj = getContextObj();
            if(obj != null && (obj instanceof ContentHolder))
                displayAttachments = getDisplayPersistedAttachments((ContentHolder)obj, locale);
            if(displayAttachments == null || displayAttachments.length() == 0)
                displayAttachments = "NONE";
        }
        String addURLs = getFormValueFromSession(formName, "addURLs", "");
        if(VERBOSE)
            System.out.println("getDisplayAttachmentsString addURLs = \"" + addURLs + "\"");
        if(addURLs.length() > 0)
        {
            addURLs = wrapperURLAttachmentsForDisplay(addURLs, locale);
            if(displayAttachments == "NONE" || displayAttachments.length() == 0)
                displayAttachments = addURLs;
            else
                displayAttachments = addURLs + RECORD_DELIM + displayAttachments;
        }
        String scmFileAttachments = getFormValueFromSession(formName, "scmFileAttachments", "");
        if(VERBOSE)
            System.out.println("getDisplayAttachmentsString scmFileAttachments = \"" + scmFileAttachments + "\"");
        if(scmFileAttachments.length() > 0)
        {
            scmFileAttachments = wrapperSCMAttachmentsForDisplay(scmFileAttachments, locale);
            if(displayAttachments == "NONE" || displayAttachments.length() == 0)
                displayAttachments = scmFileAttachments;
            else
                displayAttachments = scmFileAttachments + RECORD_DELIM + displayAttachments;
        }
        String addAttachments = getFormValueFromSession(formName, "addAttachments", "");
        if(VERBOSE)
            System.out.println("getDisplayAttachmentsString addAttachments = \"" + addAttachments + "\"");
        if(addAttachments.length() > 0)
        {
            addAttachments = wrapperAttachmentsPathsForDisplay(addAttachments, locale);
            if(displayAttachments == "NONE" || displayAttachments.length() == 0)
                displayAttachments = addAttachments;
            else
                displayAttachments = addAttachments + RECORD_DELIM + displayAttachments;
        }
        if(VERBOSE)
            System.out.println("*** getDisplayAttachmentsString() displayAttachments = \"" + displayAttachments + "\"");
        return displayAttachments;
    }

    public String getDisplayPersistedAttachments(ContentHolder contentholder, Locale locale)
        throws WTException, PropertyVetoException, InvocationTargetException, IllegalAccessException
    {
        ResourceBundle messagesResource = ResourceBundle.getBundle("wt.content.contentResource", locale);
        if(!WorkInProgressHelper.isWorkingCopy((Workable)contentholder))
            contentholder = (ContentHolder)WorkInProgressHelper.service.workingCopyOf((Workable)contentholder);
        contentholder = ContentHelper.service.getContents(contentholder);
        Enumeration enumeration = null;
        enumeration = ContentHelper.getApplicationDataExcludeRoles(contentholder, SECONDARY_EXCLUDE).elements();
        StringBuffer sContent = new StringBuffer("");
        if(enumeration != null && enumeration.hasMoreElements())
        {
            String createdByDisplayName;
            for(; enumeration.hasMoreElements(); sContent.append(createdByDisplayName + DELIM))
            {
                ContentItem contentitem = (ContentItem)enumeration.nextElement();
                ApplicationData applicationdata = (ApplicationData)contentitem;
                if(sContent.length() > 0)
                    sContent.append(RECORD_DELIM);
                sContent.append("FILE" + DELIM);
                sContent.append(getOIDString(contentitem) + DELIM);
                if(InstalledProperties.isInstalled("Windchill.SoftwareConfigMgmtIntegration"))
                {
                    boolean isScmData = ScmFacade.getInstance().isScmData(applicationdata);
                    if(isScmData)
                    {
                        String className = applicationdata.getStreamData().getKey().getClassname();
                        if(className.equalsIgnoreCase("com.ptc.windchill.scm.ScmFileData"))
                            sContent.append(getSCMIcon("FILE") + DELIM);
                        else
                            sContent.append(getSCMIcon("DIRECTORY") + DELIM);
                    } else
                    {
                        sContent.append(displayIcon(contentitem) + DELIM);
                    }
                } else
                {
                    sContent.append(displayIcon(contentitem) + DELIM);
                }
                sContent.append(applicationdata.getFileName() + DELIM);
                String s = DataFormat.getLocalizedFormatName(ContentServerHelper.service.getFormatName(contentitem), locale);
                if(s != null)
                    sContent.append(s + DELIM);
                else
                    sContent.append(WTMessage.getLocalizedMessage("wt.content.contentResource", "28", null, locale) + DELIM);
                sContent.append(getFileSize(applicationdata, locale) + DELIM);
                sContent.append(formatDate(3, PersistenceHelper.getModifyStamp(applicationdata), locale) + DELIM);
                if(applicationdata.getUploadedFromPath() != null)
                    sContent.append(textElement(applicationdata.getUploadedFromPath()) + DELIM);
                else
                    sContent.append(" " + DELIM);
                WTPrincipalReference createdBy = applicationdata.getCreatedBy();
                createdByDisplayName = null;
                if(createdBy != null)
                    createdByDisplayName = createdBy.getDisplayName();
            }

        }
        enumeration = ContentHelper.getURLData(contentholder).elements();
        if(enumeration != null && enumeration.hasMoreElements())
        {
            String createdByDisplayName;
            for(; enumeration.hasMoreElements(); sContent.append(createdByDisplayName + DELIM))
            {
                ContentItem contentitem = (ContentItem)enumeration.nextElement();
                URLData urldata = (URLData)contentitem;
                if(sContent.length() > 0)
                    sContent.append(RECORD_DELIM);
                sContent.append("URL" + DELIM);
                sContent.append(getOIDString(contentitem) + DELIM);
                sContent.append(displayIcon(contentitem) + DELIM);
                sContent.append(getURLDisplayString(urldata) + DELIM);
                String s = ContentServerHelper.service.getFormatName(contentitem);
                if(s != null)
                    sContent.append(s + DELIM);
                else
                    sContent.append(WTMessage.getLocalizedMessage("wt.content.contentResource", "28", null, locale) + DELIM);
                sContent.append(DELIM);
                sContent.append(formatDate(3, PersistenceHelper.getModifyStamp(urldata), locale) + DELIM);
                sContent.append(textElement(urldata.getUrlLocation()) + DELIM);
                WTPrincipalReference createdBy = urldata.getCreatedBy();
                createdByDisplayName = null;
                if(createdBy != null)
                    createdByDisplayName = createdBy.getDisplayName();
            }

        }
        return sContent.toString();
    }

    public String getURLDisplayString(URLData urldata)
    {
        String desc = urldata.getDescription();
        if(desc == null || desc.length() == 0)
            return urldata.getUrlLocation();
        else
            return desc;
    }

    public String wrapperAttachmentsPathsForDisplay(String addAttachments, Locale locale)
    {
        StringBuffer output = new StringBuffer();
        String curElement = "";
        if(VERBOSE)
            System.out.println("in wrapperAttachmentsPathsForDisplay, addAttachments = \"" + addAttachments + "\"");
        int curPos = 0;
        int startPos = 0;
        int count = 0;
        do
        {
            curPos = addAttachments.indexOf(RECORD_DELIM, startPos);
            if(curPos >= 0)
                curElement = addAttachments.substring(startPos, curPos);
            else
                curElement = addAttachments.substring(startPos, addAttachments.length());
            if(VERBOSE)
                System.out.println("curElement " + count + " = \"" + curElement + "\"");
            if(output.length() > 0)
                output.append(RECORD_DELIM);
            output.append("FILE" + DELIM + DELIM + DELIM + curElement + DELIM + DELIM + DELIM + DELIM + curElement + DELIM + DELIM + "ADD");
            startPos = curPos + RECORD_DELIM.length();
            count++;
        } while(curPos != -1);
        if(VERBOSE)
            System.out.println("wrapperAttachmentsPathsForDisplay output = \"" + output + "\"");
        return output.toString();
    }

    public String wrapperURLAttachmentsForDisplay(String addURLs, Locale locale)
    {
        StringBuffer output = new StringBuffer();
        String curElement = "";
        String urlLocation = "";
        String description = "";
        if(VERBOSE)
            System.out.println("in wrapperURLAttachmentsForDisplay, addURLs = \"" + addURLs + "\"");
        int curPos = 0;
        int startPos = 0;
        int count = 0;
        do
        {
            curPos = addURLs.indexOf(RECORD_DELIM, startPos);
            if(curPos >= 0)
                curElement = addURLs.substring(startPos, curPos);
            else
                curElement = addURLs.substring(startPos, addURLs.length());
            if(VERBOSE)
                System.out.println("curElement " + count + " = \"" + curElement + "\"");
            String attachData[] = curElement.split(DELIM);
            urlLocation = attachData[0];
            if(attachData.length > 1)
                description = attachData[1];
            else
                description = "";
            if(output.length() > 0)
                output.append(RECORD_DELIM);
            output.append("URL" + DELIM + DELIM + DELIM + description + DELIM + DELIM + DELIM + DELIM + urlLocation + DELIM + DELIM + "ADD");
            startPos = curPos + RECORD_DELIM.length();
            count++;
        } while(curPos != -1);
        if(VERBOSE)
            System.out.println("wrapperURLAttachmentsForDisplay output = \"" + output + "\"");
        return output.toString();
    }

    public String wrapperSCMAttachmentsForDisplay(String scmFileAttachments, Locale locale)
    {
        StringBuffer output = new StringBuffer();
        String curElement = "";
        if(VERBOSE)
            System.out.println("in wrapperSCMAttachmentsForDisplay, scmFileAttachments = \"" + scmFileAttachments + "\"");
        int curPos = 0;
        int startPos = 0;
        int count = 0;
        do
        {
            curPos = scmFileAttachments.indexOf(RECORD_DELIM, startPos);
            if(curPos >= 0)
                curElement = scmFileAttachments.substring(startPos, curPos);
            else
                curElement = scmFileAttachments.substring(startPos, scmFileAttachments.length());
            if(VERBOSE)
                System.out.println("curElement " + count + " = \"" + curElement + "\"");
            if(VERBOSE)
                System.out.println("curElement " + count + " = \"" + curElement + "\"");
            if(output.length() > 0)
                output.append(RECORD_DELIM);
            output.append("SCM" + DELIM + DELIM + DELIM + curElement + DELIM + DELIM + DELIM + DELIM + curElement + DELIM + DELIM + "ADD");
            startPos = curPos + RECORD_DELIM.length();
            count++;
        } while(curPos != -1);
        if(VERBOSE)
            System.out.println("wrapperSCMPathsForDisplay output = \"" + output + "\"");
        return output.toString();
    }

    public String getFormName(Properties parameters)
        throws WTException
    {
        String form_name = parameters.getProperty("formName");
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        else
            return form_name;
    }

    public void displayAttachmentsTable(Properties parameters, Locale locale, OutputStream os)
        throws WTException, PropertyVetoException, InvocationTargetException, IllegalAccessException
    {
        parameters.put("displayAttachments", getDisplayAttachmentsString(getFormName(parameters), locale));
        displayAttachmentsTableHeader(parameters, locale, os);
        displayAttachmentsTableRows(parameters, locale, os);
        displayAttachmentsTableFooter(parameters, locale, os);
    }

    public String getDocumentIcon()
        throws WTException, PropertyVetoException, InvocationTargetException, IllegalAccessException
    {
        ApplicationData appdata = null;
        if(getContextObj() instanceof ContentHolder)
            appdata = ApplicationData.newApplicationData((ContentHolder)getContextObj());
        else
            appdata = ApplicationData.newApplicationData(null);
        return displayIcon(appdata);
    }

    public String getURLIcon()
        throws WTException, PropertyVetoException, InvocationTargetException, IllegalAccessException
    {
        URLData urldata = URLData.newURLData(null);
        return displayIcon(urldata);
    }

    public String getSCMIcon(String type)
        throws WTException, PropertyVetoException, InvocationTargetException, IllegalAccessException
    {
        URLFactory fact = new URLFactory();
        String image = "";
        if(type.equalsIgnoreCase("DIRECTORY"))
            image = fact.getHREF("/wt/clients/images/cc_config_attach.gif");
        else
            image = fact.getHREF("/wt/clients/images/cc_file_attach.gif");
        return image;
    }

    private static String displayIcon(ContentItem contentitem)
        throws WTException, PropertyVetoException, InvocationTargetException, IllegalAccessException
    {
        IconDelegateFactory icondelegatefactory = new IconDelegateFactory();
        IconDelegate icondelegate = icondelegatefactory.getIconDelegate(contentitem);
        IconSelector iconselector;
        for(iconselector = icondelegate.getStandardIconSelector(); !iconselector.isResourceKey(); iconselector = icondelegate.getStandardIconSelector())
            icondelegate = icondelegate.resolveSelector(iconselector);

        String s = iconselector.getIconKey();
        return s;
    }

    private static String[] parseIntoArray(String parseFrom, String delimiter, int arraySize)
    {
        String newArray[] = new String[arraySize];
        int startPos = 0;
        int curPos = 0;
        for(int i = 0; i < newArray.length; i++)
        {
            curPos = parseFrom.indexOf(delimiter, startPos);
            if(curPos == -1)
                newArray[i] = null;
            else
                newArray[i] = parseFrom.substring(startPos, curPos);
            startPos = curPos + delimiter.length();
            if(VERBOSE)
                System.out.println("newArray[" + i + "] = \"" + newArray[i] + "\"");
        }

        return newArray;
    }

    public String getAttachmentsTableRow(String styleClass, String oid, String icon, String filename, String format, String filesize, String timestamp, 
            String filepath, String createdBy, String curElement, Locale locale, int tableRow)
        throws WTException, PropertyVetoException, InvocationTargetException, IllegalAccessException
    {
        if((filepath == null || filepath.length() == 0) && (filename == null || filename.length() == 0))
            return "";
        if(filename == null || filename.length() == 0)
            filename = filepath;
        else
        if(filepath == null || filepath.length() == 0)
            filepath = filename;
        if(filename.length() > MAXLENGTH)
        {
            StringBuffer formattedFilename = new StringBuffer(filename);
            for(int i = MAXLENGTH - ("<BR>".length() + 6); i < filename.length(); i += MAXLENGTH)
            {
                formattedFilename = formattedFilename.insert(i, "<BR>");
                filename = formattedFilename.toString();
            }

        }
        if(oid == null || oid.length() == 0)
            oid = "newFile" + DELIM + filepath;
        if(format == null || format.length() == 0)
            format = "--";
        if(filesize == null || filesize.length() == 0)
            filesize = "--";
        if(timestamp == null || timestamp.length() == 0)
            timestamp = "--";
        if(createdBy == null || createdBy.length() == 0)
            createdBy = "--";
        if(icon == null || icon.length() == 0)
            icon = "<IMG SRC=\"" + getDocumentIcon() + "\">&nbsp;";
        else
            icon = "<IMG SRC=\"" + icon + "\">&nbsp;";
        String featureName = "DocAttachmentsTableRow";
        String idStr = " ID=\"" + HtmlUtil.createTrailId("PDML", featureName, "Checkbox", Integer.toString(tableRow)) + "\" ";
        if(VERBOSE)
            System.out.println("Trail ID = " + idStr);
        if(VERBOSE)
            System.out.println("styleClass = " + styleClass);
        if(VERBOSE)
            System.out.println("oid = " + oid);
        if(VERBOSE)
            System.out.println("icon = " + icon);
        if(VERBOSE)
            System.out.println("filename = " + filename);
        if(VERBOSE)
            System.out.println("format = " + format);
        if(VERBOSE)
            System.out.println("filesize = " + filesize);
        if(VERBOSE)
            System.out.println("timestamp = " + timestamp);
        if(VERBOSE)
            System.out.println("filepath = " + filepath);
        if(VERBOSE)
            System.out.println("createdBy = " + createdBy);
        if(VERBOSE)
            System.out.println("curElement = " + curElement);
        StringBuffer attachments = new StringBuffer("<TR><TD class=editBar align=center>");
        attachments.append("<INPUT type=checkbox name=\"checkbox__" + oid + "\" value =\"HtmlTable_" + curElement + "\"" + idStr + "></TD>\n");
        attachments.append(getAttachmentsTableSpacerColumn(24) + "\n");
        attachments.append("<TD class=" + styleClass + " colspan=2>&nbsp;" + icon + filename + "&nbsp;</TD>\n");
        attachments.append(getAttachmentsTableSpacerColumn() + "\n");
        attachments.append("<TD class=" + styleClass + ">&nbsp;" + format + "&nbsp;</TD>\n");
        attachments.append(getAttachmentsTableSpacerColumn() + "\n");
        attachments.append("<TD class=" + styleClass + ">&nbsp;" + filesize + "&nbsp;</TD>\n");
        attachments.append(getAttachmentsTableSpacerColumn() + "\n");
        attachments.append("<TD class=" + styleClass + ">&nbsp;" + timestamp + "&nbsp;</TD>\n");
        attachments.append(getAttachmentsTableSpacerColumn() + "\n");
        attachments.append("<TD class=" + styleClass + ">&nbsp;" + createdBy + "&nbsp;</TD></TR>\n");
        return attachments.toString();
    }

    public boolean handleSCMIDirectory(ApplicationData appData)
        throws WTException
    {
        return InstalledProperties.isInstalled("Windchill.SoftwareConfigMgmtIntegration") && ScmFacade.getInstance().isScmData(appData) && appData.getFileSize() == 0L;
    }

    public String getScmTableRow(String styleClass, String oid, String icon, String filename, String format, String filesize, String timestamp, 
            String filepath, String createdBy, String curElement, Locale locale, int tableRow)
        throws WTException, PropertyVetoException, InvocationTargetException, IllegalAccessException
    {
        if(filepath == null || filepath.length() == 0)
            return null;
        if(filename == null || filename.length() == 0)
            filename = filepath;
        if(VERBOSE)
            System.out.println("=> DocumentWizardProcessor.getSCMTableRow() FileName is.." + filename + ", filepath is... " + filepath);
        String to_display = "";
        String type = "";
        String path = "path=";
        String file_type = "type=";
        int index_of_path = filename.indexOf("path=") + path.length();
        int index_of_type = filename.indexOf("type=") + file_type.length();
        to_display = filename.substring(index_of_path).trim();
        type = filename.substring(index_of_type, index_of_path - path.length() - 1).trim();
        String scm_file = to_display;
        int index_of_first_slash = to_display.indexOf("/") + 1;
        int index_of_second_slash = to_display.indexOf("/", index_of_first_slash);
        to_display = to_display.substring(index_of_second_slash);
        if(oid == null || oid.length() == 0)
            oid = "newScm" + DELIM + filepath;
        if(format == null || format.length() == 0)
            format = "--";
        if(filesize == null || filesize.length() == 0)
            filesize = "--";
        if(timestamp == null || timestamp.length() == 0)
            timestamp = "--";
        if(createdBy == null || createdBy.length() == 0)
            createdBy = "--";
        try
        {
            if(icon == null || icon.length() == 0)
                icon = "<IMG SRC=\"" + getSCMIcon(type) + "\">&nbsp;";
            else
                icon = "<IMG SRC=\"" + icon + "\">&nbsp;";
        }
        catch(Exception e)
        {
            throw new WTException(e);
        }
        String featureName = "DocScmTableRow";
        String idStr = " ID=\"" + HtmlUtil.createTrailId("PDML", featureName, "Checkbox", Integer.toString(tableRow)) + "\" ";
        if(VERBOSE)
            System.out.println("Trail ID = " + idStr);
        if(VERBOSE)
            System.out.println("styleClass = " + styleClass);
        if(VERBOSE)
            System.out.println("oid = " + oid);
        if(VERBOSE)
            System.out.println("icon = " + icon);
        if(VERBOSE)
            System.out.println("filename = " + filename);
        if(VERBOSE)
            System.out.println("format = " + format);
        if(VERBOSE)
            System.out.println("filesize = " + filesize);
        if(VERBOSE)
            System.out.println("timestamp = " + timestamp);
        if(VERBOSE)
            System.out.println("filepath = " + filepath);
        if(VERBOSE)
            System.out.println("curElement = " + curElement);
        StringBuffer attachments = new StringBuffer("<TR><TD class=editBar align=center>");
        attachments.append("<INPUT type=checkbox name=\"checkbox__" + oid + "\" value =\"HtmlTable_" + curElement + "\"" + idStr + "></TD>\n");
        attachments.append(getAttachmentsTableSpacerColumn(24) + "\n");
        attachments.append("<TD class=" + styleClass + " colspan=2>&nbsp;" + icon + to_display + "&nbsp;</TD>\n");
        attachments.append(getAttachmentsTableSpacerColumn() + "\n");
        attachments.append("<TD class=" + styleClass + ">&nbsp;" + format + "&nbsp;</TD>\n");
        attachments.append(getAttachmentsTableSpacerColumn() + "\n");
        attachments.append("<TD class=" + styleClass + ">&nbsp;" + filesize + "&nbsp;</TD>\n");
        attachments.append(getAttachmentsTableSpacerColumn() + "\n");
        attachments.append("<TD class=" + styleClass + ">&nbsp;" + timestamp + "&nbsp;</TD>\n");
        attachments.append(getAttachmentsTableSpacerColumn() + "\n");
        attachments.append("<TD class=" + styleClass + ">&nbsp;" + createdBy + "&nbsp;</TD></TR>\n");
        return attachments.toString();
    }

    public String getURLTableRow(String styleClass, String oid, String icon, String description, String format, String filesize, String timestamp, 
            String urlLocation, String createdBy, String curElement, Locale locale, int tableRow)
        throws WTException, PropertyVetoException, InvocationTargetException, IllegalAccessException
    {
        if(urlLocation == null || urlLocation.length() == 0)
            return null;
        if(description == null || description.length() == 0)
            description = urlLocation;
        if(description.length() > MAXLENGTH)
        {
            StringBuffer formattedFilename = new StringBuffer("<PRE>" + description);
            for(int i = MAXLENGTH - ("<BR>".length() + 6); i < description.length(); i += MAXLENGTH)
            {
                formattedFilename = formattedFilename.insert(i, "<BR>");
                description = formattedFilename.toString();
            }

            description = description + "</PRE>";
        }
        if(oid == null || oid.length() == 0)
            oid = "new_url" + DELIM + urlLocation;
        if(format == null || format.length() == 0)
            format = "--";
        if(filesize == null || filesize.length() == 0)
            filesize = "--";
        if(timestamp == null || timestamp.length() == 0)
            timestamp = "--";
        if(createdBy == null || createdBy.length() == 0)
            createdBy = "--";
        if(icon == null || icon.length() == 0)
            icon = "<IMG SRC=\"" + getURLIcon() + "\">&nbsp;";
        else
            icon = "<IMG SRC=\"" + icon + "\">&nbsp;";
        String featureName = "DocAttachmentsTableRow";
        String idStr = " ID=\"" + HtmlUtil.createTrailId("PDML", featureName, "Checkbox", Integer.toString(tableRow)) + "\" ";
        if(VERBOSE)
            System.out.println("Trail ID = " + idStr);
        if(VERBOSE)
            System.out.println("styleClass = " + styleClass);
        if(VERBOSE)
            System.out.println("oid = " + oid);
        if(VERBOSE)
            System.out.println("icon = " + icon);
        if(VERBOSE)
            System.out.println("description = " + description);
        if(VERBOSE)
            System.out.println("format = " + format);
        if(VERBOSE)
            System.out.println("filesize = " + filesize);
        if(VERBOSE)
            System.out.println("timestamp = " + timestamp);
        if(VERBOSE)
            System.out.println("urlLocation = " + urlLocation);
        if(VERBOSE)
            System.out.println("createdBy = " + createdBy);
        if(VERBOSE)
            System.out.println("curElement = " + curElement);
        StringBuffer attachments = new StringBuffer("<TR><TD class=editBar align=center>");
        attachments.append("<INPUT type=checkbox name=\"checkbox__" + oid + "\" value =\"HtmlTable_" + curElement + "\"" + idStr + "></TD>\n");
        attachments.append(getAttachmentsTableSpacerColumn(24) + "\n");
        attachments.append("<TD class=" + styleClass + " colspan=2>&nbsp;" + icon + description + "&nbsp;</TD>\n");
        attachments.append(getAttachmentsTableSpacerColumn() + "\n");
        attachments.append("<TD class=" + styleClass + ">&nbsp;" + format + "&nbsp;</TD>\n");
        attachments.append(getAttachmentsTableSpacerColumn() + "\n");
        attachments.append("<TD class=" + styleClass + ">&nbsp;" + filesize + "&nbsp;</TD>\n");
        attachments.append(getAttachmentsTableSpacerColumn() + "\n");
        attachments.append("<TD class=" + styleClass + ">&nbsp;" + timestamp + "&nbsp;</TD>\n");
        attachments.append(getAttachmentsTableSpacerColumn() + "\n");
        attachments.append("<TD class=" + styleClass + ">&nbsp;" + createdBy + "&nbsp;</TD></TR>\n");
        return attachments.toString();
    }

    public String getAttachmentsTableSpacerRow(int colspan)
    {
        return "<TR><TD class=tableBkgd colspan=12><IMG src=\"" + getSpacerGifURL() + "\" width=1 height=2></TD></TR>";
    }

    public String getAttachmentsTableSpacerColumn()
    {
        return getAttachmentsTableSpacerColumn(2);
    }

    public String getAttachmentsTableSpacerColumn(int height)
    {
        return "<TD class=tableBkgd><IMG src=\"" + getSpacerGifURL() + "\" width=2 height=" + height + "></TD>";
    }

    private String getOIDString(ContentItem contentitem)
    {
        return PersistenceHelper.getObjectIdentifier(contentitem).getStringValue();
    }

    private String textElement(String sPath)
    {
        if(sPath == null)
            return "";
        StringBuffer sNewPath = new StringBuffer(sPath);
        int slashPos = 0;
        int startPos = 0;
        do
        {
            slashPos = sNewPath.toString().indexOf("\\", startPos);
            if(slashPos >= 0)
            {
                sNewPath.insert(slashPos, "\\");
                startPos = slashPos + 2;
            }
        } while(slashPos != -1);
        return sNewPath.toString();
    }

    public void getDelim(Properties params, Locale locale, OutputStream os)
    {
        if(DELIM != null && DELIM.length() > 0)
        {
            PrintWriter out = getPrintWriter(os, locale);
            out.print(DELIM);
            out.flush();
        }
    }

    public void getRecordDelim(Properties params, Locale locale, OutputStream os)
    {
        if(RECORD_DELIM != null && RECORD_DELIM.length() > 0)
        {
            PrintWriter out = getPrintWriter(os, locale);
            out.print(RECORD_DELIM);
            out.flush();
        }
    }

    public void getScmDelim(Properties params, Locale locale, OutputStream os)
    {
        if(SCM_DELIM != null && SCM_DELIM.length() > 0)
        {
            PrintWriter out = getPrintWriter(os, locale);
            out.print(SCM_DELIM);
            out.flush();
        }
    }

    public void getDebug(Properties params, Locale locale, OutputStream os)
    {
        PrintWriter out = getPrintWriter(os, locale);
        out.print(DEBUG);
        out.flush();
    }

    private String getFileSize(ApplicationData file, Locale locale)
    {
        if(handleSCMIDirectory(file))
            return "--";
        break MISSING_BLOCK_LABEL_20;
        WTException wte;
        wte;
        wte.printStackTrace();
        float file_size = (float)file.getFileSize() / 1024F;
        file_size = roundToTwoDecimals(file_size);
        String string_size = Float.toString(file_size);
        try
        {
            ResourceBundle messagesResource = ResourceBundle.getBundle("wt.enterprise.enterpriseResource", locale);
            if(messagesResource != null)
                string_size = string_size + " " + messagesResource.getString("17");
        }
        catch(MissingResourceException mre) { }
        return string_size;
    }

    private float roundToTwoDecimals(float number)
    {
        BigDecimal big = (new BigDecimal(number)).setScale(2, 0);
        return big.floatValue();
    }

    public void getAppletAttachments(Properties props, Locale locale, OutputStream os)
        throws WTException
    {
        String formName = getFormName(props);
        String addAttachments = getFormValueFromSession(formName, "addAttachments", "");
        String removeAttachments = getFormValueFromSession(formName, "removeAttachments", "");
        if(addAttachments != null && addAttachments.length() > 0)
            addAttachments = wrapperPathsForAppletAdd(addAttachments);
        if(removeAttachments != null && removeAttachments.length() > 0)
            removeAttachments = wrapperOidsForAppletRemove(removeAttachments);
        String output = removeAttachments;
        if(addAttachments != null && addAttachments.length() > 0)
            if(output != null && output.length() > 0)
                output = output + RECORD_DELIM + addAttachments;
            else
                output = addAttachments;
        if(output != null && output.length() > 0)
        {
            PrintWriter out = getPrintWriter(os, locale);
            out.print(output);
            out.flush();
        }
    }

    public String wrapperPathsForAppletAdd(String addAttachments)
    {
        StringBuffer output = new StringBuffer();
        String curElement = "";
        if(VERBOSE)
            System.out.println("in wrapperPathsForAppletAdd, addAttachments = \"" + addAttachments + "\"");
        int curPos = 0;
        int startPos = 0;
        int count = 0;
        do
        {
            curPos = addAttachments.indexOf(RECORD_DELIM, startPos);
            if(curPos >= 0)
                curElement = addAttachments.substring(startPos, curPos);
            else
                curElement = addAttachments.substring(startPos, addAttachments.length());
            if(VERBOSE)
                System.out.println("curElement " + count + " = \"" + curElement + "\"");
            if(output.length() > 0)
                output.append(RECORD_DELIM);
            output.append("FILE" + DELIM + "newFile" + DELIM + curElement + DELIM + "ADD");
            startPos = curPos + RECORD_DELIM.length();
            count++;
        } while(curPos != -1);
        if(VERBOSE)
            System.out.println("wrapperPathsForAppletAdd output = \"" + output + "\"");
        return output.toString();
    }

    public String wrapperOidsForAppletRemove(String removeAttachments)
    {
        StringBuffer output = new StringBuffer();
        String curElement = "";
        if(VERBOSE)
            System.out.println("in wrapperOidsForAppletRemove, removeAttachments = \"" + removeAttachments + "\"");
        int curPos = 0;
        int startPos = 0;
        int count = 0;
        do
        {
            curPos = removeAttachments.indexOf(RECORD_DELIM, startPos);
            if(curPos >= 0)
                curElement = removeAttachments.substring(startPos, curPos);
            else
                curElement = removeAttachments.substring(startPos, removeAttachments.length());
            if(VERBOSE)
                System.out.println("curElement " + count + " = \"" + curElement + "\"");
            if(output.length() > 0)
                output.append(RECORD_DELIM);
            output.append("FILE" + DELIM + curElement + DELIM + DELIM + "REMOVE");
            startPos = curPos + RECORD_DELIM.length();
            count++;
        } while(curPos != -1);
        if(VERBOSE)
            System.out.println("wrapperOidsForAppletRemove output = \"" + output + "\"");
        return output.toString();
    }

    public void getChangedPrimaryAttributeFromSession(Properties parameters, Locale locale, OutputStream os)
        throws WTException, PropertyVetoException
    {
        String attributeName = parameters.getProperty("attribute");
        String returnValue = getFormValueFromSession(getFormName(parameters), attributeName, null);
        if(returnValue == null && (getContextObj() instanceof FormatContentHolder))
        {
            if(attributeName.equalsIgnoreCase("File"))
                getPrimaryUploadPath(parameters, locale, os);
            else
                getPrimaryAttribute(parameters, locale, os);
        } else
        if(returnValue != null && returnValue.length() > 0)
        {
            PrintWriter out = getPrintWriter(os, locale);
            out.print(returnValue);
            out.flush();
        }
    }

    public void getChangedContextualValueFromSession(Properties parameters, Locale locale, OutputStream os)
        throws WTException, InvocationTargetException, IllegalAccessException, ClassNotFoundException, InstantiationException
    {
        String propertyName = parameters.getProperty("propertyName");
        String returnValue = getFormValueFromSession(getFormName(parameters), propertyName, null);
        if(returnValue == null)
            contextualValue(parameters, locale, os);
        else
        if(returnValue != null && returnValue.length() > 0)
        {
            String escapeQuotes = parameters.getProperty("escapeContextualValue");
            if(VERBOSE)
                System.out.println("escapeContextualValue: " + escapeQuotes);
            if(escapeQuotes != null && escapeQuotes.equals("true"))
            {
                if(VERBOSE)
                    System.out.println("escaping quotes....");
                returnValue = returnValue.replaceAll("\"", "&#34;");
                returnValue = returnValue.replaceAll("'", "&#39;");
                if(VERBOSE)
                    System.out.println("quotes escaped:  " + returnValue);
                parameters.remove("escapeContextualValue");
                if(VERBOSE)
                {
                    escapeQuotes = parameters.getProperty("escapeContextualValue");
                    System.out.println("escapeContextualValue after remove from parameters:  " + escapeQuotes);
                }
            }
            PrintWriter out = getPrintWriter(os, locale);
            out.print(returnValue);
            out.flush();
        }
    }

    public void getDocSoftAttributesEditTable(Properties parameters, Locale locale, OutputStream os)
        throws Exception
    {
        String form_name = getFormName(parameters);
        parameters.put("cookieWithCurrentVals", form_name);
        String template = getFormValueFromSession(form_name, "Template", "");
        if(template != null && template.length() > 0)
        {
            Persistable obj = (new ReferenceFactory()).getReference(template).getObject();
            setContextObj(obj);
        }
        String objectType = parameters.getProperty("objectType");
        if(objectType != null)
        {
            objectType = objectType.substring(objectType.indexOf("|") + 1);
            parameters.put("objectType", objectType);
        }
        Object contextObj = getContextObj();
        if(objectType == null || contextObj != null && objectType.startsWith(TypedUtilityServiceHelper.service.getPersistedType(getContextObj())))
        {
            parameters.put("displayNoAttributesMessage", "true");
            getCustomAttributesEditTableForUpdate(parameters, locale, os);
        } else
        {
            getCustomAttributesEditTableForCreate(parameters, locale, os);
        }
    }

    public void clearSessionIfFirstTimeOnPage(Properties parameters, Locale locale, OutputStream os)
        throws Exception
    {
        String form_name = getFormData().getProperty("formName");
        if(form_name == null || form_name.length() < 1)
        {
            if(VERBOSE)
                System.out.println("*** must be first time on page - time to wipe the session ***");
            form_name = getFormName(parameters);
            deleteFormDataFromSession(form_name);
        }
    }

    public void deleteFormDataFromSession(String formName)
    {
        getState().getCookieManager().removeCookie(formName);
    }

    public void isPrimaryRequired(Properties parameters, Locale locale, OutputStream os)
    {
        if(PRIMARY_REQUIRED)
        {
            PrintWriter out = getPrintWriter(os, locale);
            out.print(WTMessage.getLocalizedMessage("com.ptc.windchill.pdmlink.doc.client.clientRB", "16", null, locale));
            out.flush();
        }
    }

    public void getEnabledValue(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        String enabled_value = "";
        String label = "";
        String form_name = parameters.getProperty("formName");
        String enabledProperty = getFormData().getProperty("Enabled");
        String featureName = "DocTemplateModAttrEnabled";
        String idStr = " ID=\"" + HtmlUtil.createTrailId("PDML", featureName, "Checkbox", "") + "\" ";
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        if(enabledProperty == null)
            enabledProperty = getFormValueFromSession(form_name, "Enabled", null);
        if(enabledProperty == null || enabledProperty.length() < 1)
        {
            Object obj = getContextObj();
            WTDocument doc = (WTDocument)obj;
            if(doc == null)
            {
                enabled_value = "<INPUT name = \"EnabledforUse\"" + idStr + "type=\"checkbox\" checked>";
            } else
            {
                WTDocument latestVerIter = (WTDocument)TemplatesUtility.getLatestVersionIteration(doc);
                String docVersion = VersionControlHelper.getVersionIdentifier(doc).getValue();
                String docIteration = VersionControlHelper.getIterationIdentifier(doc).getValue();
                String latestVersion = VersionControlHelper.getVersionIdentifier(latestVerIter).getValue();
                String latestIteration = VersionControlHelper.getIterationIdentifier(latestVerIter).getValue();
                WTUser user = (WTUser)SessionHelper.manager.getPrincipal();
                boolean isadmin = WTContainerHelper.service.isAdministrator(doc.getContainerReference(), user);
                if(docVersion.equals(latestVersion) && docIteration.equals(latestIteration) && isadmin)
                {
                    if(VERBOSE)
                        System.out.println("This is the latest iteration of the latest version");
                    TemplateInfo template = doc.getTemplate();
                    if(template != null && template.isTemplated())
                        if(template.isEnabled())
                            enabled_value = "<INPUT name = \"EnabledforUse\"" + idStr + "type=\"checkbox\" checked>";
                        else
                            enabled_value = "<INPUT name = \"EnabledforUse\"" + idStr + "type=\"checkbox\">";
                }
            }
        } else
        {
            String value = getFormValueFromSession(form_name, "Enabled", "true");
            if(value.equalsIgnoreCase("true"))
                enabled_value = "<INPUT name = \"EnabledforUse\"" + idStr + "type=\"checkbox\" checked>";
            else
                enabled_value = "<INPUT name = \"EnabledforUse\"" + idStr + "type=\"checkbox\">";
        }
        PrintWriter out = getPrintWriter(os, locale);
        if(!enabled_value.equals(""))
        {
            label = WTMessage.getLocalizedMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "74", null, locale);
            out.print(enabled_value);
            out.println("      <TD align=left valign=top class=wizFormLabel>");
            out.println("         " + label + " &nbsp");
            out.println("      </TD>");
            out.flush();
        }
    }

    public void getUpdateDocumentDisplayIdentity(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        TemplateInfo template = null;
        WTDocument doc = (WTDocument)getContextObj();
        if(doc != null)
            template = doc.getTemplate();
        if(template != null && template.isTemplated())
            parameters.put("resourceKey", "UPDATE_DOCUMENT_TEMPLATE_TITLE");
        else
            parameters.put("resourceKey", "UPDATE_DOCUMENT_TITLE");
        getDocumentDisplayIdentity(parameters, locale, os);
    }

    public void processSubTemplateforUpdateDocument(Properties parameters, Locale locale, OutputStream os)
    {
        TemplateInfo template = null;
        WTDocument doc = (WTDocument)getContextObj();
        if(doc != null)
            template = doc.getTemplate();
        if(template != null && template.isTemplated())
            parameters.put("titleResourceKey", "UPDATE_DOCUMENT_TEMPLATE_TITLE");
        else
            parameters.put("titleResourceKey", "UPDATE_DOCUMENT_TITLE");
        processSubTemplate(parameters, locale, os);
    }

    public void getTitleValue(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        String value = "";
        String form_name = parameters.getProperty("formName");
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        String titleProperty = getFormData().getProperty("Title");
        if(titleProperty == null)
            titleProperty = getFormValueFromSession(form_name, "Title", null);
        if(titleProperty == null)
        {
            String sessionTemplate = getFormValueFromSession(form_name, "Template", "");
            if(sessionTemplate != null && !sessionTemplate.equals(""))
            {
                WTDocument template = null;
                template = (WTDocument)(new ReferenceFactory()).getReference(sessionTemplate).getObject();
                if(template != null)
                    value = template.getTitle();
            }
        } else
        {
            value = titleProperty;
        }
        PrintWriter out = getPrintWriter(os, locale);
        if(value == null)
            value = "";
        out.print(value);
        out.flush();
    }

    public void getDescValue(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        String value = "";
        String form_name = parameters.getProperty("formName");
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        String descProperty = getFormData().getProperty("Description");
        if(descProperty == null)
            descProperty = getFormValueFromSession(form_name, "Description", null);
        if(descProperty == null)
        {
            String sessionTemplate = getFormValueFromSession(form_name, "Template", "");
            if(sessionTemplate != null && !sessionTemplate.equals(""))
            {
                WTDocument template = null;
                template = (WTDocument)(new ReferenceFactory()).getReference(sessionTemplate).getObject();
                if(template != null)
                    value = template.getDescription();
            }
        } else
        {
            value = descProperty;
        }
        PrintWriter out = getPrintWriter(os, locale);
        if(value == null)
            value = "";
        out.print(value);
        out.flush();
    }

    public void getKeepCheckedOutValue(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        String keepCheckedOut_value = "";
        String label = "";
        String form_name = parameters.getProperty("formName");
        String keepCheckedOutProperty = getFormData().getProperty("KeepCheckedOut");
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        if(keepCheckedOutProperty == null)
        {
            String keepCheckedOutDefault = getPreferenceValue("/com/ptc/windchill/doc", "DefaultCheckoutOnCreateFromTemplate");
            if(keepCheckedOutDefault == null || keepCheckedOutDefault.equals(""))
                keepCheckedOutDefault = "false";
            keepCheckedOutProperty = getFormValueFromSession(form_name, "KeepCheckedOut", keepCheckedOutDefault);
        }
        String featureName = "DocKeepCheckedOut";
        String idStr = " ID=\"" + HtmlUtil.createTrailId("PDML", featureName, "Checkbox", "") + "\" ";
        if(VERBOSE)
            System.out.println("Trail ID = " + idStr);
        if(keepCheckedOutProperty.equalsIgnoreCase("true"))
            keepCheckedOut_value = "<INPUT name = \"KeepCheckedOutField\" type=\"checkbox\"" + idStr + "checked>";
        else
            keepCheckedOut_value = "<INPUT name = \"KeepCheckedOutField\" type=\"checkbox\"" + idStr + ">";
        PrintWriter out = getPrintWriter(os, locale);
        if(!keepCheckedOut_value.equals(""))
        {
            label = WTMessage.getLocalizedMessage("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "77", null, locale);
            out.print(keepCheckedOut_value);
            out.println("      <TD align=left valign=top class=wizFormLabel>");
            out.println("         " + label + " &nbsp");
            out.println("      </TD>");
            out.flush();
        }
    }

    private String getCurrentOrganizationDN(WTContainer container)
        throws WTException
    {
        StandardWTContainerService swtservice = StandardWTContainerService.newStandardWTContainerService();
        OrgContainer oc = (OrgContainer)swtservice.getOrgContainerRef(container).getContainer();
        String orgDn = oc.getOrganizationReference().getDn();
        if(VERBOSE)
            System.out.println("DocumentWizardProcessor.getCurrentOrganizationDN: orgDn=" + orgDn);
        return orgDn;
    }

    public void getCheckinDocumentDisplayIdentity(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        TemplateInfo template = null;
        WTDocument doc = (WTDocument)getContextObj();
        if(doc != null)
            template = doc.getTemplate();
        if(template != null && template.isTemplated())
            parameters.put("resourceKey", "CHECKIN_DOCUMENT_TEMPLATE_TITLE");
        else
            parameters.put("resourceKey", "CHECKIN_DOCUMENT_TITLE");
        getDocumentDisplayIdentity(parameters, locale, os);
    }

    public void getFolder(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        PrintWriter out = getPrintWriter(os, locale);
        ReferenceFactory rf = new ReferenceFactory();
        String form_name = parameters.getProperty("formName");
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        SubFolder folder = getFolderFromForm(form_name);
        if(folder != null)
        {
            out.print(rf.getReferenceString(folder));
            out.flush();
        }
    }

    private SubFolder getFolderFromForm(String form_name)
        throws WTException
    {
        Object context_obj = getContextObj();
        SubFolder folder = null;
        if(context_obj instanceof SubFolder)
        {
            folder = (SubFolder)context_obj;
            ServletSessionCookie cookie = getState().getCookieManager().getCookie(form_name);
            cookie.put("folderRef", (new ReferenceFactory()).getReferenceString(folder));
            if(VERBOSE)
                System.out.println("DocumentWizardProcessor.getFolderFromForm:Context folder=" + folder);
        }
        if(folder == null)
        {
            String folder_strg = getFormValueFromSession(form_name, "folderRef", "");
            if(folder_strg != null && folder_strg.length() != 0)
            {
                folder = (SubFolder)(new ReferenceFactory()).getReference(folder_strg).getObject();
                if(VERBOSE)
                    System.out.println("DocumentWizardProcessor.getFolderFromForm:Session folder=" + folder);
            }
        }
        return folder;
    }

    public void processSubTemplateforCheckinDocument(Properties parameters, Locale locale, OutputStream os)
    {
        TemplateInfo template = null;
        WTDocument doc = (WTDocument)getContextObj();
        if(doc != null)
            template = doc.getTemplate();
        if(template != null && template.isTemplated())
            parameters.put("titleResourceKey", "CHECKIN_DOCUMENT_TEMPLATE_TITLE");
        else
            parameters.put("titleResourceKey", "CHECKIN_DOCUMENT_TITLE");
        processSubTemplate(parameters, locale, os);
    }

    public void getSoid(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        PrintWriter out = getPrintWriter(os, locale);
        ReferenceFactory rf = new ReferenceFactory();
        Object context_obj = getContextObj();
        String soid = null;
        String form_name = parameters.getProperty("formName");
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        if((context_obj instanceof WTContainer) || (context_obj instanceof SubFolder))
        {
            HTTPState state = getState();
            soid = (String)state.getQueryData().get("soid");
            ServletSessionCookie cookie = getState().getCookieManager().getCookie(form_name);
            cookie.put("soid", soid);
            if(VERBOSE)
                System.out.println("DocumentWizardProcessor.getSoid: soid=" + soid + " context Object" + context_obj);
        }
        if(soid == null)
        {
            soid = getFormValueFromSession(form_name, "soid", "");
            if(VERBOSE)
                System.out.println("DocumentWizardProcessor.getSoid:soid=" + soid);
        }
        if(soid != null)
        {
            out.print(soid);
            out.flush();
        }
    }

    public void getTypeIdentifierString(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        TypeIdentifier type = null;
        PrintWriter out = getPrintWriter(os, locale);
        String form_name = parameters.getProperty("formName");
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        if(parameters.getProperty("TemplateType") == null)
        {
            String object_type = getFormValueFromSession(form_name, "ObjectType", "");
            type = FdnWTContainerHelper.toTypeIdentifier(object_type);
        } else
        if(parameters.getProperty("TemplateType").equals("true"))
        {
            String templateStr = getFormValueFromSession(form_name, "Template", "");
            WTDocument template = (WTDocument)(new ReferenceFactory()).getReference(templateStr).getObject();
            if(VERBOSE)
                System.out.println("DocumentWizardProcessor.getTypeIdentifierString Document template = " + template);
            type = TypeIdentifierUtility.getTypeIdentifier(template);
        }
        if(VERBOSE)
            System.out.println("DocumentWizardProcessor.getTypeIdentifierString Document type = " + type.toString());
        out.print(type.toString());
        out.flush();
    }

    public void getContextObjectforLocation(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        Object context_obj = getContextObj();
        Object context = null;
        PrintWriter out = getPrintWriter(os, locale);
        ReferenceFactory rf = new ReferenceFactory();
        String form_name = parameters.getProperty("formName");
        if(form_name == null || form_name.equals(""))
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "2", null);
        if(context_obj instanceof WTContainer)
        {
            context = (WTContainer)context_obj;
            ServletSessionCookie cookie = getState().getCookieManager().getCookie(form_name);
            cookie.put("contextObjectforLocation", (new ReferenceFactory()).getReferenceString((WTContainer)context));
            if(VERBOSE)
                System.out.println("DocumentWizardProcessor.getContextObjectforLocation:Context =" + context);
        }
        if(context_obj instanceof SubFolder)
        {
            context = (SubFolder)context_obj;
            ServletSessionCookie cookie = getState().getCookieManager().getCookie(form_name);
            cookie.put("contextObjectforLocation", (new ReferenceFactory()).getReferenceString((SubFolder)context));
            if(VERBOSE)
                System.out.println("DocumentWizardProcessor.getContextObjectforLocation:Context =" + context);
        }
        if(context == null)
        {
            String context_strg = getFormValueFromSession(form_name, "contextObjectforLocation", "");
            if(context_strg != null && context_strg.length() != 0)
            {
                context = (new ReferenceFactory()).getReference(context_strg).getObject();
                if(VERBOSE)
                    System.out.println("DocumentWizardProcessor.getContextObjectforLocation:Session Context=" + context);
            }
        }
        if(context != null)
        {
            if(context instanceof WTContainer)
                out.print(rf.getReferenceString((WTContainer)context));
            else
            if(context instanceof SubFolder)
                out.print(rf.getReferenceString((SubFolder)context));
            out.flush();
        }
    }

    public void deleteFolderDataFromSessionOnEntry(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        String form_name = parameters.getProperty("formName");
        if(VERBOSE)
            System.out.println("***getFormData***" + getFormData());
        boolean folderLoc = getFormData().getProperty("FOLDERLOCATION") != null || getFormData().getProperty("FolderLocation") != null;
        ServletSessionCookie cookie = getState().getCookieManager().getCookie(form_name);
        if(!folderLoc && cookie != null && cookie.size() > 0)
        {
            if(VERBOSE)
                System.out.println("cookie values" + cookie.toString());
            cookie.remove("FOLDERLOCATION");
            cookie.remove("FolderLocation");
            cookie.remove("FOLDERPICKER");
            cookie.remove("FolderPicker");
            getState().getCookieManager().saveCookies();
        }
    }

    public void getFileSelectionComponent(Properties parameters, Locale locale, OutputStream os)
        throws WTException, PropertyVetoException
    {
        String action = "SingleFileSelectComponent";
        if(parameters != null)
        {
            String actionParam = parameters.getProperty("action");
            if(actionParam != null && actionParam.length() > 0)
                action = actionParam;
        } else
        {
            parameters = new Properties();
        }
        parameters.put("action", action);
        processSubTemplate(parameters, locale, os);
    }

    public void getURLSelectionComponent(Properties parameters, Locale locale, OutputStream os)
        throws WTException, PropertyVetoException
    {
        String action = "SingleURLSelectComponent";
        if(parameters != null)
        {
            String actionParam = parameters.getProperty("action");
            if(actionParam != null && actionParam.length() > 0)
                action = actionParam;
        } else
        {
            parameters = new Properties();
        }
        parameters.put("action", action);
        processSubTemplate(parameters, locale, os);
    }

    public void getSCMSelectionComponent(Properties parameters, Locale locale, OutputStream os)
        throws WTException, PropertyVetoException
    {
        String action = "SingleSCMSelectComponent";
        if(parameters != null)
        {
            String actionParam = parameters.getProperty("action");
            if(actionParam != null && actionParam.length() > 0)
                action = actionParam;
        } else
        {
            parameters = new Properties();
        }
        parameters.put("action", action);
        processSubTemplate(parameters, locale, os);
    }

    public void getUploadChoiceComponent(Properties parameters, Locale locale, OutputStream os)
        throws WTException, PropertyVetoException
    {
        String uploadChoice = getPreferenceValue("/com/ptc/windchill/doc", "UploadChoice");
        if(uploadChoice != null && uploadChoice.equalsIgnoreCase("true"))
        {
            String action = "UploadChoiceComponent";
            if(parameters != null)
            {
                String actionParam = parameters.getProperty("action");
                if(actionParam != null && actionParam.length() > 0)
                    action = actionParam;
            } else
            {
                parameters = new Properties();
            }
            parameters.put("action", action);
            Object obj = getContextObj();
            if(obj instanceof FormatContentHolder)
            {
                FormatContentHolder holder = (FormatContentHolder)getContextObj();
                if(isPrimaryExisting(holder))
                {
                    if(VERBOSE)
                        System.out.println("about to write subtemplate including resetUploadChoice()");
                    processSubTemplate(parameters, locale, os);
                    return;
                }
            }
        }
        if(VERBOSE)
            System.out.println("about to write empty resetUploadChoice()");
        PrintWriter out = getPrintWriter(os, locale);
        out.print("<SCRIPT language=Javascript>\nfunction resetUploadChoice() {\n}\n</SCRIPT>");
        out.flush();
    }

    public void getPrimaryContentComponent(Properties parameters, Locale locale, OutputStream os)
        throws WTException, PropertyVetoException
    {
        Object obj = getContextObj();
        String action = "PrimaryContentFileComponent";
        boolean isTemplate = (obj instanceof WTDocument) && ((WTDocument)obj).isTemplated();
        boolean isPrimaryURLExisting = (obj instanceof FormatContentHolder) && isPrimaryURLExisting((FormatContentHolder)obj);
        if(!isTemplate && ("true".equalsIgnoreCase(getPreferenceValue("/com/ptc/windchill/doc", "exposeUrlContent")) || InstalledProperties.isInstalled("Windchill.SoftwareConfigMgmtIntegration") || isPrimaryURLExisting))
        {
            action = "PrimaryContentNoUploadChoice";
            String uploadChoice = getPreferenceValue("/com/ptc/windchill/doc", "UploadChoice");
            if(uploadChoice != null && uploadChoice.equalsIgnoreCase("true") && obj != null && (obj instanceof FormatContentHolder) && isPrimaryExisting((FormatContentHolder)obj))
                action = "PrimaryContentReplaceUploadChoice";
        }
        if(parameters != null)
            parameters = new Properties();
        parameters.put("action", action);
        if(VERBOSE)
            System.out.println("DWP.getPrimaryContentComponent() - about to process primary content subtemplate " + action);
        processSubTemplate(parameters, locale, os);
    }

    public void getContentSourceOption(Properties parameters, Locale locale, OutputStream os)
        throws WTException, PropertyVetoException
    {
        Object obj = getContextObj();
        if(parameters != null)
        {
            String form_name = getContextProperties().getProperty("formName");
            boolean isPrimaryURLExisting = (obj instanceof FormatContentHolder) && isPrimaryURLExisting((FormatContentHolder)obj);
            String source = parameters.getProperty("source");
            boolean exposeURL = source.equals("URL") && ("true".equalsIgnoreCase(getPreferenceValue("/com/ptc/windchill/doc", "exposeUrlContent")) || isPrimaryURLExisting);
            boolean exposeSCM = source.equals("SCM") && InstalledProperties.isInstalled("Windchill.SoftwareConfigMgmtIntegration");
            boolean exposeOtherOption = !source.equals("URL") && !source.equals("SCM");
            if(exposeURL || exposeSCM || exposeOtherOption)
            {
                StringBuffer output = new StringBuffer("<OPTION");
                String resourceKey = parameters.getProperty("resourceKey");
                String resourceClass = parameters.getProperty("resourceClass");
                if(source != null && source.length() > 0)
                {
                    output.append(" id=\"contentSourceOption" + source + "\" value=\"" + source);
                    if(VERBOSE)
                        System.out.println("DWP.getContentSourceOption: parameters.getProperty(\"source\") = " + source + "\n getFormValueFromSession(form_name,\"targetType\",\"\") = " + getFormValueFromSession(form_name, "targetType", ""));
                    if(source.equalsIgnoreCase(getFormValueFromSession(form_name, "targetType", "")))
                        output.append("\" selected");
                    else
                        output.append("\"");
                    output.append(">");
                }
                PrintWriter out = getPrintWriter(os, locale);
                out.print(output.toString());
                out.flush();
                if(resourceKey != null && resourceKey.length() > 0 && resourceClass != null && resourceClass.length() > 0)
                {
                    getLocalizedMessage(parameters, locale, os);
                } else
                {
                    out.print(source);
                    out.flush();
                }
            }
        }
    }

    public void getAddURLAction(Properties parameters, Locale locale, OutputStream os)
        throws WTException, PropertyVetoException
    {
        if(parameters == null)
            parameters = new Properties();
        if("true".equalsIgnoreCase(getPreferenceValue("/com/ptc/windchill/doc", "exposeUrlContent")))
        {
            parameters.put("action", "AddURLActionComponent");
            processSubTemplate(parameters, locale, os);
        }
    }

    public void getAddSCMAction(Properties parameters, Locale locale, OutputStream os)
        throws WTException, PropertyVetoException
    {
        if(parameters == null)
            parameters = new Properties();
        boolean test = false;
        if(InstalledProperties.isInstalled("Windchill.SoftwareConfigMgmtIntegration"))
        {
            parameters.put("action", "AddSCMActionComponent");
            processSubTemplate(parameters, locale, os);
        }
    }

    public void getSCMWindowLocation(Properties parameters, Locale locale, OutputStream os)
        throws WTException, PropertyVetoException
    {
        if(parameters == null)
            parameters = new Properties();
        String selectorType = parameters.getProperty("selectorType", "multi");
        String form_name = parameters.getProperty("formName");
        if(InstalledProperties.isInstalled("Windchill.SoftwareConfigMgmtIntegration"))
        {
            PrintWriter out = getPrintWriter(os, locale);
            WTContainer wt_container = getRepositoryFromForm(form_name);
            URLFactory urlFactory = getState().getURLFactory();
            String href = ScmFacade.getInstance().getScmBrowserURL(urlFactory, selectorType, wt_container);
            out.print(href);
            if(VERBOSE)
                System.out.println("DocumentWizardProcessor.getSCMWindowLocation() is returning " + href);
            out.flush();
        }
    }

    private boolean isPrimaryExisting(FormatContentHolder holder)
        throws WTException, PropertyVetoException
    {
        holder = (FormatContentHolder)ContentHelper.service.getContents(holder);
        ContentItem item = ContentHelper.getPrimary(holder);
        return item != null;
    }

    private boolean isPrimaryURLExisting(FormatContentHolder holder)
        throws WTException, PropertyVetoException
    {
        holder = (FormatContentHolder)ContentHelper.service.getContents(holder);
        ContentItem item = ContentHelper.getPrimary(holder);
        return item != null && (item instanceof URLData);
    }

    private boolean isPrimaryFileExisting(FormatContentHolder holder)
        throws WTException, PropertyVetoException
    {
        holder = (FormatContentHolder)ContentHelper.service.getContents(holder);
        ContentItem item = ContentHelper.getPrimary(holder);
        return item != null && (item instanceof ApplicationData);
    }

    public static String escapeForJavascriptUse(String origString)
    {
        StringBuffer escapedString = new StringBuffer(origString);
        if(escapedString.length() > 0)
        {
            int i = 0;
            for(int length = escapedString.length(); i < length; length = escapedString.length())
            {
                if(escapedString.charAt(i) == '"')
                {
                    escapedString = escapedString.replace(i, i + 1, "\\\"");
                    i += 2;
                    continue;
                }
                if(escapedString.charAt(i) == '\'')
                {
                    escapedString = escapedString.replace(i, i + 1, "\\'");
                    i += 2;
                    continue;
                }
                if(escapedString.charAt(i) == '\\')
                {
                    escapedString = escapedString.replace(i, i + 1, "\\\\");
                    i += 2;
                } else
                {
                    i++;
                }
            }

        }
        return escapedString.toString();
    }

    private static AdminDomainRef getAdminDomainRef(Object contextObj)
        throws WTException
    {
        WTContainer container = null;
        AdminDomainRef domainRef = null;
        if(contextObj instanceof WTContainer)
        {
            container = (WTContainer)contextObj;
            domainRef = container.getDefaultDomainReference();
        } else
        if(contextObj instanceof WTContained)
        {
            container = ((WTContained)contextObj).getContainer();
            if(contextObj instanceof DomainAdministered)
                domainRef = ((DomainAdministered)contextObj).getDomainRef();
        } else
        {
            if(VERBOSE)
                System.out.println("DocumentWizardProcessor.getAdminDomainRef returning null. Object is not a WTContainer or WTContained.");
            return null;
        }
        return domainRef;
    }

    public void generateFooterForCreateDocFromTemplate(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        if(!templatesExist)
            parameters.put("formName", parameters.getProperty("buttonSet", "WizardFormClose"));
        processSubTemplate(parameters, locale, os);
    }

    public void getPrimaryUploadPath(Properties params, Locale locale, OutputStream os)
        throws WTException
    {
        Object obj = getContextObj();
        if(!(obj instanceof FormatContentHolder))
            throw new WTException("PrimaryContentProcessor: Objects that have primary content must implement FormatContentHolder");
        FormatContentHolder holder = (FormatContentHolder)obj;
        try
        {
            holder = (FormatContentHolder)ContentHelper.service.getContents(holder);
        }
        catch(PropertyVetoException pve)
        {
            System.err.println(pve);
        }
        try
        {
            String primary = null;
            ContentItem item = ContentHelper.getPrimary(holder);
            if(item instanceof ApplicationData)
            {
                ApplicationData app = (ApplicationData)item;
                primary = app.getUploadedFromPath();
                if(primary == null || primary.length() == 0)
                    primary = app.getFileName();
            } else
            {
                if(VERBOSE)
                {
                    System.err.print("getPrimary:");
                    System.err.println(item != null ? item.getClass().getName() : "Primary was null");
                }
                primary = "";
            }
            PrintWriter out = getPrintWriter(os, locale);
            out.print(primary);
            out.flush();
        }
        catch(Exception e)
        {
            System.err.println(e);
        }
    }

    private static final String RESOURCE = "com.ptc.windchill.pdmlink.doc.server.processors.processorsResource";
    private static final String CLASSNAME;
    static final long serialVersionUID = 1L;
    public static final long EXTERNALIZATION_VERSION_UID = 0xa6700984c6548630L;
    protected static final long OLD_FORMAT_VERSION_UID = 0xa423c93b516d760cL;
    private static final String CRESOURCE = "com.ptc.windchill.pdmlink.doc.client.clientRB";
    private static final String DRESOURCE = "wt.doc.docResource";
    private static final String ERESOURCE = "wt.enterprise.enterpriseResource";
    private static final String OBJECT_TYPE_FIELDNAME = "ObjectType";
    private static final String REPOSITORY_FIELDNAME = "Repository";
    private static final String TEMPLATE_FIELDNAME = "Template";
    private static final String FORMNAME = "formName";
    private static final String PAGENAME = "pageName";
    private static final String REPOS_RADIO = "docrepos";
    private static final String REPOS_PROD_RADIO = "prodrepos";
    private static final String REPOS_DROP = "repos_drop";
    private static final String PROD_DROP = "product_drop";
    private static final String REPOS_RADIO_ELEMENT = "repos";
    private static final String FOLDER_FIELDNAME = "folderRef";
    private static final String TYPE_SELECT_STRING = "SelectAType";
    private static final String TYPE_SELECT_BLANK = "blank";
    private static final String VALID_TYPE_SELECT = "ValidType";
    protected static boolean VERBOSE = false;
    public static String DEBUG;
    public static String DELIM;
    public static String RECORD_DELIM;
    public static String SCM_DELIM;
    public static int MAXLENGTH;
    public static boolean PRIMARY_REQUIRED;
    private static String SECONDARY_EXCLUDE;
    private boolean templatesExist;

    static 
    {
        CLASSNAME = (com.ptc.windchill.pdmlink.doc.server.processors.DocumentWizardProcessor.class).getName();
        DEBUG = "false";
        try
        {
            WTProperties properties = WTProperties.getLocalProperties();
            VERBOSE = properties.getProperty("wt.doc.verbose", false);
            DEBUG = properties.getProperty("wt.clients.debug", DEBUG);
            DELIM = properties.getProperty("wt.doc.hiddenFieldDelimiter", ";;;qqq");
            SCM_DELIM = properties.getProperty("com.ptc.windchill.scm.hiddenFieldDelimiter", "#");
            RECORD_DELIM = properties.getProperty("wt.doc.hiddenFieldRecordDelimiter", ";;;zzz");
            MAXLENGTH = properties.getProperty("wt.content.filenameLength.wrapLength", 40);
            PRIMARY_REQUIRED = properties.getProperty("wt.doc.primaryContentRequired", true);
            SECONDARY_EXCLUDE = properties.getProperty("wt.content.secondaryContentExcludeList", "THUMBNAIL,THUMBNAIL3D");
        }
        catch(Throwable t)
        {
            System.err.println("com.ptc.windchill.pdmlink.doc.server.processors.DocumentWizardProcessor : Error reading wt.doc.* properties");
            t.printStackTrace(System.err);
            throw new ExceptionInInitializerError(t);
        }
    }
}
