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

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

import com.ptc.core.HTMLtemplateutil.server.processors.WizardProcessor;
import java.beans.PropertyDescriptor;
import java.beans.PropertyVetoException;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.*;
import wt.clients.beans.query.WTBusinessInfo;
import wt.doc.WTDocumentConfigSpec;
import wt.doc.WTDocumentStandardConfigSpec;
import wt.enterprise.BasicTemplateProcessor;
import wt.enterprise.ErrorProcessor;
import wt.fc.EnumeratedType;
import wt.fc.EvolvableHelper;
import wt.htmlutil.*;
import wt.httpgw.*;
import wt.introspection.ClassInfo;
import wt.introspection.WTIntrospector;
import wt.pds.PDSObjectInput;
import wt.query.SearchTask;
import wt.templateutil.processor.*;
import wt.util.*;

public class ChooseConfigSpecProcessor extends WizardProcessor
    implements Externalizable
{
    public static class ListEntry
    {

        public String getOid()
        {
            return oid;
        }

        public void setOid(String oid)
        {
            this.oid = oid;
        }

        public String getDisplay()
        {
            return display;
        }

        public void setDisplay(String display)
        {
            this.display = display;
        }

        private String oid;
        private String display;

        public ListEntry(String oid, String display)
        {
            this.oid = null;
            this.display = null;
            setOid(oid);
            setDisplay(display);
        }
    }


    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(ChooseConfigSpecProcessor 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 != 0xbbbe4bb993ba6047L)
            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 generateForm(HTTPRequest request, HTTPResponse response)
        throws WTException, PropertyVetoException, IOException, InvocationTargetException, IllegalAccessException, ClassNotFoundException
    {
        try
        {
            HTTPRequest _tmp = request;
            String acceptLanguage = request.getProperty("cgi.http_accept_language");
            Vector preferences = LanguagePreference.getAcceptLanguagePreferences(acceptLanguage);
            Properties args = request.splitQueryString();
            if(request.getFormData() != null)
                args = combineParameters(request.getFormData(), args, false);
            String class_name = null;
            String template_name = null;
            String return_action = "document_structure";
            String return_template = "structure";
            String return_processor = null;
            String return_oid = null;
            String return_oid2 = null;
            String config_spec = null;
            String config_spec_other = null;
            Properties context_props = new Properties();
            class_name = args.getProperty("class");
            if(class_name == null)
                class_name = args.getProperty("Class");
            if(class_name != null)
                context_props.put("Class", class_name);
            template_name = args.getProperty("form");
            if(template_name != null)
                context_props.put("form", template_name);
            return_action = args.getProperty("return_action", return_action);
            context_props.put("return_action", return_action);
            return_template = args.getProperty("return_template", return_template);
            context_props.put("return_template", return_template);
            return_processor = args.getProperty("return_template_processor", return_processor);
            if(return_processor != null)
                context_props.put("return_template_processor", return_processor);
            return_oid = args.getProperty("return_oid");
            if(return_oid != null)
                context_props.put("return_oid", return_oid);
            return_oid2 = args.getProperty("return_oid2");
            if(return_oid2 != null)
                context_props.put("return_oid2", return_oid2);
            config_spec = args.getProperty("DOC_CONFIG_SPEC");
            if(config_spec != null)
                context_props.put("DOC_CONFIG_SPEC", config_spec);
            config_spec_other = args.getProperty("config_spec_other");
            if(config_spec_other != null)
                context_props.put("config_spec_other", config_spec_other);
            template_name = "forms/" + template_name;
            if(VERBOSE)
                System.out.println("VERBOSE: generateForm template_name = " + template_name);
            ChooseConfigSpecProcessor generator = new ChooseConfigSpecProcessor(context_props, request);
            if(VERBOSE)
                System.out.println("VERBOSE: attempting to load template " + template_name);
            HTMLTemplate template = new HTMLTemplate(TemplateName.getWindchill(template_name));
            template.init(preferences);
            OutputStream os = response.getOutputStream();
            template.process(os, generator);
            os.flush();
        }
        catch(Exception e)
        {
            if(VERBOSE)
                System.out.println("VERBOSE: generateForm caught exception " + e.getLocalizedMessage());
            e.printStackTrace();
            HTTPRequest _tmp1 = request;
            String acceptLanguage = request.getProperty("cgi.http_accept_language");
            Vector preferences = LanguagePreference.getAcceptLanguagePreferences(acceptLanguage);
            OutputStream os = response.getOutputStream();
            ErrorProcessor generator = new ErrorProcessor(e);
            HTMLTemplate template = new HTMLTemplate(TemplateName.getWindchill("util/DefaultError"));
            template.init(preferences);
            template.process(os, generator);
            os.flush();
            if(VERBOSE)
                System.out.println("VERBOSE: generateForm done processing template");
        }
    }

    public void outputHiddenFields(Properties parameters, Locale locale, OutputStream os)
        throws WTException, IOException
    {
        PrintWriter out = TemplateOutputStream.getPrintWriter(os, locale);
        Properties props = getFormData();
        props.putAll(getQueryData());
        HashMap m = new HashMap();
        URLFactory urlFactory = getURLFactory();
        String oldURL = (String)props.get("RETURN_URL");
        int index = oldURL.indexOf('?');
        if(index > 0)
        {
            m = urlFactory.parseQueryString(oldURL.substring(index + 1));
            String newURL = GatewayServletHelper.buildAuthenticatedURL(urlFactory, "wt.enterprise.URLProcessor", "URLTemplateAction", m).toExternalForm();
            props.remove("RETURN_URL");
            props.put("RETURN_URL", newURL);
        }
        String propNames[] = {
            "DOC_CONFIG_SPEC", "RETURN_URL", "RETURN_WINDOW", "cookieName"
        };
        for(int i = 0; i < propNames.length; i++)
        {
            String name = propNames[i];
            out.print("<input type=\"hidden\" name=\"");
            out.print(name);
            out.print("\" value=\"");
            out.print(props.get(name));
            out.println("\">");
        }

        out.flush();
    }

    public void printDataList(Properties parameters, Locale locale, OutputStream os)
        throws WTException
    {
        Vector values = null;
        String data_type = null;
        String attribute = null;
        String class_str = null;
        String id_str = null;
        if(parameters != null)
        {
            if(parameters.getProperty("attribute") != null && parameters.getProperty("class") != null)
            {
                class_str = parameters.getProperty("class");
                attribute = parameters.getProperty("attribute");
                try
                {
                    Class attr_class = Class.forName(class_str);
                    PropertyDescriptor pd = getPropertyDescriptor(attr_class, attribute);
                    values = getValueList(pd, locale);
                }
                catch(ClassNotFoundException cnfe)
                {
                    throw new WTException(cnfe);
                }
            }
            if(parameters.getProperty("trailId") != null)
                id_str = "ID=\"" + parameters.getProperty("trailId") + "\"";
        }
        if(values != null)
        {
            PrintWriter out = getPrintWriter(os, locale);
            String select_name = attribute;
            if(parameters.getProperty("name") != null)
                select_name = parameters.getProperty("name");
            if(select_name == null)
                select_name = "datalist";
            boolean empty_entry = false;
            if(parameters.getProperty("allow_empty") != null)
                empty_entry = Boolean.valueOf(parameters.getProperty("allow_empty")).booleanValue();
            String current_value = null;
            if(parameters.getProperty("current_value") != null)
                current_value = parameters.getProperty("current_value");
            String initialize = null;
            if(parameters.getProperty("initialize") != null)
            {
                initialize = parameters.getProperty("initialize");
                current_value = getAttributeValueString(initialize, parameters, locale);
            }
            boolean use_oid = true;
            if(parameters.getProperty("use_oid") != null)
                use_oid = Boolean.valueOf(parameters.getProperty("use_oid")).booleanValue();
            Vector display_values = new Vector();
            Vector opt_values = new Vector();
            int selected_index = -1;
            for(int i = 0; i < values.size(); i++)
            {
                String s = "";
                String value = "";
                if(values.elementAt(i) instanceof ListEntry)
                    s = ((ListEntry)values.elementAt(i)).getDisplay();
                else
                    s = (String)values.elementAt(i);
                if(use_oid && (values.elementAt(i) instanceof ListEntry))
                    value = ((ListEntry)values.elementAt(i)).getOid();
                else
                    value = s;
                if(current_value != null && current_value.equals(s))
                    selected_index = i + 1;
                display_values.addElement(s);
                opt_values.addElement(value);
            }

            out.println(HtmlUtil.createSelectHTML(select_name, id_str, opt_values, display_values, empty_entry, selected_index));
            out.flush();
        }
    }

    public void outputCheckbox(Properties parameters, Locale locale, OutputStream os)
        throws WTException, InvocationTargetException, IllegalAccessException
    {
        PrintWriter out = getPrintWriter(os, locale);
        if(parameters == null)
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "56", null);
        String propertyName = parameters.getProperty("propertyName");
        if(propertyName == null)
            throw new WTException("com.ptc.windchill.pdmlink.doc.server.processors.processorsResource", "56", null);
        out.print("<INPUT TYPE=\"CHECKBOX\" NAME=\"");
        out.print(propertyName);
        String trailId = parameters.getProperty("trailId");
        if(trailId != null)
        {
            out.print("\" ID=\"");
            out.print(trailId);
        }
        out.print("\" onClick=\"this.value=this.checked\"");
        String propertyValue = getAttributeValueString(propertyName, parameters, locale);
        if("true".equals(propertyValue))
            out.print(" VALUE=\"true\" CHECKED");
        else
            out.print(" VALUE=\"false\"");
        out.println(">");
        String label = null;
        String resourceBundle = parameters.getProperty("RESOURCEBUNDLE");
        if(resourceBundle != null)
        {
            String resourceKey = parameters.getProperty("RESOURCEKEY");
            if(resourceKey != null)
            {
                label = "";
                Object noParams[] = null;
                label = BasicTemplateProcessor.getStringFromResourceBundle(resourceKey, resourceBundle, locale);
            }
        }
        if(label == null)
            objectPropertyName(parameters, locale, os);
        else
            out.print(label);
        out.flush();
    }

    public ChooseConfigSpecProcessor(Properties props, HTTPRequest request)
        throws ClassNotFoundException, WTException, PropertyVetoException
    {
        contextProperties = null;
        configSpec = null;
        if(contextProperties == null)
            contextProperties = new Properties();
        initialize(request);
        contextProperties = props;
    }

    public ChooseConfigSpecProcessor()
        throws ClassNotFoundException, WTException, PropertyVetoException
    {
        contextProperties = null;
        configSpec = null;
    }

    public void outputAttributeValue(Properties properties, Locale locale, OutputStream os)
        throws WTException
    {
        String attribute = null;
        String attr_value = "";
        if(properties != null)
        {
            attribute = properties.getProperty("attribute");
            if(attribute != null)
                attr_value = getAttributeValueString(attribute, properties, locale);
        }
        if(attr_value != null)
        {
            PrintWriter out = getPrintWriter(os, locale);
            out.print(attr_value);
            out.flush();
        }
    }

    protected static Properties combineParameters(Properties params_to_add, Properties original_params, boolean strip_oid_and_action)
    {
        if(params_to_add != null)
        {
            if(original_params == null)
                original_params = new Properties();
            if(VERBOSE)
                System.out.println("***** combineParameters() *****");
            Enumeration names = params_to_add.propertyNames();
            do
            {
                if(!names.hasMoreElements())
                    break;
                String name = (String)names.nextElement();
                if(!strip_oid_and_action || !name.equals("action") && !name.equals("Action") && !name.equals("oid"))
                {
                    original_params.put(name, params_to_add.getProperty(name));
                    if(VERBOSE)
                        System.out.println(name + " = " + params_to_add.getProperty(name));
                }
            } while(true);
        }
        return original_params;
    }

    protected static PropertyDescriptor getPropertyDescriptor(Class attr_class, String attribute)
        throws WTException
    {
        PropertyDescriptor prop = null;
        if(attr_class != null)
        {
            ClassInfo class_info = WTIntrospector.getClassInfo(attr_class);
            prop = class_info.getPropertyDescriptor(attribute);
        }
        return prop;
    }

    protected Vector getValueList(PropertyDescriptor pd, Locale locale)
    {
        Vector vector = new Vector();
        Class type = pd.getPropertyType();
        if(type == WTBusinessInfo.BoolTYPE)
        {
            vector.addElement(WTMessage.getLocalizedMessage("wt.clients.beans.query.BeansQueryRB", "17", null, locale));
            vector.addElement(WTMessage.getLocalizedMessage("wt.clients.beans.query.BeansQueryRB", "16", null, locale));
        } else
        if(SearchTask.isEnumType(type))
        {
            EnumeratedType e[] = WTBusinessInfo.getAttributeValueSet(pd);
            if(e.length != 0)
            {
                for(int i = 0; i < e.length; i++)
                {
                    ListEntry entry = new ListEntry(e[i].toString(), e[i].getDisplay(locale));
                    vector.addElement(entry);
                }

            }
        }
        return vector;
    }

    private String getAttributeValueString(String attribute, Properties properties, Locale locale)
    {
        String attr_value = null;
        Object obj = null;
        if(getConfigSpec() != null)
            if((getConfigSpec() instanceof WTDocumentConfigSpec) && getConfigSpec().getActive() != null)
                obj = getConfigSpec().getActive();
            else
                obj = getConfigSpec();
        if(obj == null)
            obj = getContextObj();
        if(obj != null)
            try
            {
                attr_value = getObjectPropertyValueString(attribute, properties, locale, obj);
            }
            catch(Exception e)
            {
                System.err.println("getAttributeValueString() - exception getting  attribute " + attribute);
                e.printStackTrace(System.err);
            }
        if(VERBOSE)
            System.out.println("getAttributeValueString() - value of " + attribute + " is " + attr_value);
        if(attr_value != null && attr_value.equals("&nbsp;"))
            attr_value = null;
        return attr_value;
    }

    public void handleRequest(HTTPRequest req, HTTPResponse resp)
        throws WTException
    {
        initialize(req);
        super.handleRequest(req, resp);
    }

    public void initialize(HTTPRequest req)
        throws WTException
    {
        Properties newProps = getProperties(req);
        WTDocumentConfigSpec spec = null;
        if(newProps.get("DOC_CONFIG_SPEC") != null)
        {
            spec = (WTDocumentConfigSpec)decode(newProps.getProperty("DOC_CONFIG_SPEC"));
        } else
        {
            Properties queryData = getQueryData();
            String cookieName = queryData.getProperty("cookieName");
            ServletSessionCookie cookie = getState().getCookieManager().getCookie(cookieName);
            Object configSpecObj = cookie.get("configSpec");
            if(configSpecObj instanceof WTDocumentConfigSpec)
                spec = (WTDocumentConfigSpec)configSpecObj;
            else
                spec = WTDocumentConfigSpec.newWTDocumentConfigSpec();
            String returnURL = (String)cookie.get("RETURN_URL");
            getFormData().put("RETURN_URL", returnURL);
            String returnWindow = getQueryData().getProperty("RETURN_WINDOW");
            getFormData().put("RETURN_WINDOW", returnWindow);
        }
        String action = newProps.getProperty("action");
        if(action == null)
            setContextObj(spec.getActive());
        else
        if(action.equals("ChooseLatestDocConfigSpec"))
        {
            if(spec.getStandard() == null)
                spec.setStandard(WTDocumentStandardConfigSpec.newWTDocumentStandardConfigSpec());
            spec.setStandardActive(true);
            setContextObj(spec.getStandard());
        } else
        if(action.equals("ChooseBaselineDocConfigSpec"))
        {
            if(spec.getBaseline() != null)
                setContextObj(spec.getBaseline());
            spec.setBaselineActive(true);
        }
        setConfigSpec(spec);
        if(newProps.get("DOC_CONFIG_SPEC") == null)
            getFormData().put("DOC_CONFIG_SPEC", encode(spec));
    }

    protected WTDocumentConfigSpec getConfigSpec()
    {
        return configSpec;
    }

    protected void setConfigSpec(WTDocumentConfigSpec newConfigSpec)
    {
        configSpec = newConfigSpec;
    }

    protected Properties getProperties(HTTPRequest request)
        throws WTException
    {
        Properties context_props = new Properties();
        HTTPRequest _tmp = request;
        String acceptLanguage = request.getProperty("cgi.http_accept_language");
        Vector preferences = LanguagePreference.getAcceptLanguagePreferences(acceptLanguage);
        Properties args = request.splitQueryString();
        if(request.getFormData() != null)
            context_props = combineParameters(request.getFormData(), args, true);
        return context_props;
    }

    protected String encode(Serializable obj)
        throws WTException
    {
        return Encoder.encode(obj);
        IOException ioe;
        ioe;
        throw new WTException(ioe);
    }

    protected Object decode(String encodedConfigSpec)
        throws WTException
    {
        return Encoder.decode(encodedConfigSpec);
        ClassNotFoundException cnfe;
        cnfe;
        throw new WTException(cnfe);
        IOException ioe;
        ioe;
        throw new WTException(ioe);
    }

    static Class _mthclass$(String x0)
    {
        return Class.forName(x0);
        ClassNotFoundException x1;
        x1;
        throw (new NoClassDefFoundError()).initCause(x1);
    }

    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 = 0xbbbe4bb993ba6047L;
    private Properties contextProperties;
    private WTDocumentConfigSpec configSpec;
    private static final String CONFIG_SPEC = "DOC_CONFIG_SPEC";
    public static final String DEFAULT_ACTION = "document_structure";
    public static final String DEFAULT_TEMPLATE = "structure";

    static 
    {
        CLASSNAME = (com.ptc.windchill.pdmlink.doc.server.processors.ChooseConfigSpecProcessor.class).getName();
    }
}
