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

package com.ptc.windchill.enterprise.doc.server;

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.server.TypeIdentifierUtility;
import com.ptc.windchill.enterprise.copy.server.CoreMetaUtility;
import com.ptc.windchill.enterprise.nativeapp.server.WindchillAttributeInformation;
import java.beans.PropertyDescriptor;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.text.Collator;
import java.util.*;
import wt.doc.*;
import wt.enterprise.TemplateInfo;
import wt.fc.*;
import wt.folder.FolderHelper;
import wt.folder.FolderService;
import wt.iba.value.IBAHolder;
import wt.introspection.*;
import wt.lifecycle.*;
import wt.org.WTPrincipalReference;
import wt.prefs.*;
import wt.services.applicationcontext.UnableToCreateServiceException;
import wt.services.applicationcontext.implementation.DefaultServiceProvider;
import wt.team.TeamHelper;
import wt.team.TeamTemplate;
import wt.util.*;
import wt.vc.VersionControlHelper;

public class DocumentUtility
{

    public DocumentUtility()
    {
    }

    public static WTDocument setNumber(WTDocument document, String number)
        throws WTException
    {
        if(number != null && !number.equals(""))
            try
            {
                document.setNumber(number);
            }
            catch(WTPropertyVetoException wtpve)
            {
                Object args[] = {
                    number
                };
                throw new WTException("com.ptc.windchill.enterprise.doc.server.serverResource", "4", args);
            }
        return document;
    }

    public static String getNumber(String number)
    {
        if(number == null || number.length() == 0)
        {
            double dbl = Math.random();
            dbl *= 10000D;
            int intgr = (new Long(Math.round(dbl))).intValue();
            number = Integer.toString(intgr);
        }
        return number;
    }

    public static WTDocument setOldAttributes(WTDocument document)
        throws WTException
    {
        try
        {
            document.setDepartment(DepartmentList.getDepartmentListDefault());
            document.setDocType(DocumentType.getDocumentTypeDefault());
        }
        catch(WTPropertyVetoException wtpve)
        {
            throw new WTException(wtpve, "com.ptc.windchill.enterprise.doc.server.serverResource", "5", null);
        }
        return document;
    }

    public static WTDocument setLocation(WTDocument document, String location)
        throws WTException
    {
        if(location == null || location.length() == 0)
            location = "/Default";
        if(VERBOSE)
            System.out.println("Setting the folder = " + location);
        try
        {
            wt.folder.Folder docloc = FolderHelper.service.getFolder(location);
            FolderHelper.assignLocation(document, docloc);
        }
        catch(WTException wte)
        {
            Object args[] = {
                location
            };
            throw new WTException(wte, "com.ptc.windchill.enterprise.doc.server.serverResource", "6", args);
        }
        return document;
    }

    public static WTDocument setLifeCycleTemplate(WTDocument document, String lifeCycle)
        throws WTException
    {
        if(lifeCycle == null || lifeCycle.length() == 0)
            return document;
        if(VERBOSE)
            System.out.println("Setting the lifecycle = " + lifeCycle);
        try
        {
            LifeCycleTemplate lct = LifeCycleHelper.service.getLifeCycleTemplate(lifeCycle);
            lct = (LifeCycleTemplate)VersionControlHelper.getLatestIteration(lct);
            document = (WTDocument)LifeCycleHelper.setLifeCycle(document, lct);
        }
        catch(WTException wte)
        {
            Object args[] = {
                lifeCycle
            };
            throw new WTException(wte, "com.ptc.windchill.enterprise.doc.server.serverResource", "7", args);
        }
        catch(WTPropertyVetoException pve)
        {
            Object args[] = {
                lifeCycle
            };
            throw new WTException(pve, "com.ptc.windchill.enterprise.doc.server.serverResource", "7", args);
        }
        return document;
    }

    public static WTDocument setTeamTemplate(WTDocument document, String teamTemplate)
        throws WTException
    {
        try
        {
            if(teamTemplate != null && teamTemplate.length() > 0)
            {
                ReferenceFactory rf = new ReferenceFactory();
                TeamTemplate teamTemplateObj = (TeamTemplate)rf.getReference(teamTemplate).getObject();
                document = (WTDocument)TeamHelper.setTeamTemplate(document, (TeamTemplate)PersistenceHelper.manager.refresh(teamTemplateObj));
            }
        }
        catch(WTRuntimeException wtrte)
        {
            Object args[] = {
                teamTemplate
            };
            throw new WTException(wtrte, "com.ptc.windchill.enterprise.doc.server.serverResource", "8", args);
        }
        catch(WTPropertyVetoException pve)
        {
            Object args[] = {
                teamTemplate
            };
            throw new WTException(pve, "com.ptc.windchill.enterprise.doc.server.serverResource", "8", args);
        }
        return document;
    }

    public static WTDocument setSoftAttributes(WTDocument document, HashMap nameValueData, Locale locale)
        throws WTException
    {
        if(VERBOSE)
            System.out.println("Starting DocumentUtility.setSoftAttributes.");
        return setCustomAttributes(document, nameValueData, locale);
    }

    public static WTDocument setCustomAttributes(WTDocument document, HashMap nameValueData, Locale locale)
        throws WTException
    {
        if(VERBOSE)
            System.out.println("Starting DocumentUtility.setCustomAttributes.");
        if(!(document instanceof IBAHolder))
        {
            Object param[] = {
                document.getClass().getName()
            };
            throw new WTException("com.ptc.windchill.enterprise.doc.server.serverResource", "13", param);
        }
        IdentifierFactory identifierFactory = null;
        try
        {
            identifierFactory = (IdentifierFactory)DefaultServiceProvider.getService(com.ptc.core.meta.common.IdentifierFactory.class, "default");
        }
        catch(UnableToCreateServiceException utcse)
        {
            Object param[] = {
                TypeIdentifierUtility.getTypeIdentifier(document)
            };
            throw new WTException(utcse, "com.ptc.windchill.enterprise.doc.server.serverResource", "14", param);
        }
        HashMap editedSoftAttributes = new HashMap();
        HashMap editedModelledAttributes = new HashMap();
        Set key_set = nameValueData.keySet();
        Iterator iterator = key_set.iterator();
        boolean all_valid = true;
        Vector invalid = null;
        com.ptc.core.meta.container.common.AttributeTypeSummary ats = null;
        do
        {
            if(!iterator.hasNext())
                break;
            String attrib_name = (String)iterator.next();
            if(VERBOSE)
                System.out.println("Processing for " + attrib_name);
            Object value = nameValueData.get(attrib_name);
            if(value instanceof WindchillAttributeInformation)
            {
                WindchillAttributeInformation w_attrib = (WindchillAttributeInformation)value;
                if(VERBOSE)
                    System.out.println("In the attribute section for " + attrib_name);
                Object attrib_value = w_attrib.getValue();
                AttributeIdentifier attrId = (AttributeIdentifier)identifierFactory.get(w_attrib.getLongName());
                com.ptc.core.meta.common.DefinitionIdentifier di = attrId.getDefinitionIdentifier();
                if(!w_attrib.isModeled())
                    editedSoftAttributes.put((AttributeTypeIdentifier)di, attrib_value);
                else
                    editedModelledAttributes.put((AttributeTypeIdentifier)di, attrib_value);
            } else
            if(value == null || (value instanceof String))
            {
                if(VERBOSE)
                    System.out.println("Modeled attribute, will be set in document delegate being used.");
            } else
            if(VERBOSE)
            {
                System.out.println("*****Really shouldn't be here in this else loop of com.ptc.windchill.enterprise.doc.server.DocumentUtility.setSoftAttributes.  ");
                System.out.println("*****attribute = " + attrib_name + " , value = " + value.toString());
            }
        } while(true);
        boolean values[] = null;
        if(VERBOSE)
            System.out.println("Modelled Attributes hashMap" + editedModelledAttributes);
        if(VERBOSE)
            System.out.println("SoftAttributes hashMap" + editedSoftAttributes);
        TypeHelper.setCustomAttributes(document, editedModelledAttributes, editedSoftAttributes, locale);
        return document;
    }

    public static WTDocument setName(WTDocument document, String name)
        throws WTException
    {
        if(name != null)
            try
            {
                if(name.equals(""))
                    name = "temporary";
                document.setName(name);
            }
            catch(WTPropertyVetoException wtpve)
            {
                Object args[] = {
                    name
                };
                throw new WTException("com.ptc.windchill.enterprise.doc.server.serverResource", "17", args);
            }
        return document;
    }

    public static WTDocument setTitle(WTDocument document, String title)
        throws WTException
    {
        if(title != null)
            try
            {
                document.setTitle(title);
            }
            catch(WTPropertyVetoException wtpve)
            {
                Object args[] = {
                    title
                };
                throw new WTException("com.ptc.windchill.enterprise.doc.server.serverResource", "18", args);
            }
        return document;
    }

    public static WTDocument setDescription(WTDocument document, String desc)
        throws WTException
    {
        if(desc != null)
            try
            {
                document.setDescription(desc);
            }
            catch(WTPropertyVetoException wtpve)
            {
                Object args[] = {
                    desc
                };
                throw new WTException("com.ptc.windchill.enterprise.doc.server.serverResource", "19", args);
            }
        return document;
    }

    public static WTDocument setTemplate(WTDocument document, boolean templated)
        throws WTException
    {
        if(templated)
            try
            {
                TemplateInfo template = TemplateInfo.newTemplateInfo();
                template.setTemplated(templated);
                document.setTemplate(template);
            }
            catch(WTPropertyVetoException wtpve)
            {
                throw new WTException("com.ptc.windchill.enterprise.doc.server.serverResource", "20", null);
            }
        return document;
    }

    public static WTDocument setEnabled(WTDocument document, boolean enabled)
        throws WTException
    {
        TemplateInfo template = document.getTemplate();
        if(template != null && template.isTemplated())
            template.setEnabled(enabled);
        return document;
    }

    public static WTDocument setDept(WTDocument document, String dept)
        throws WTException
    {
        try
        {
            wt.fc.EnumeratedType depts[] = DepartmentList.getDepartmentListDefault().getSelectableValueSet();
            if(!document.getDepartment().equals(depts[Integer.parseInt(dept)]) && dept != null && dept.length() > 0)
                document.setDepartment((DepartmentList)depts[Integer.parseInt(dept)]);
        }
        catch(WTPropertyVetoException wtpve)
        {
            throw new WTException("com.ptc.windchill.enterprise.doc.server.serverResource", "22", null);
        }
        return document;
    }

    public static WTDocument setDocType(WTDocument document, String docType)
        throws WTException
    {
        try
        {
            wt.fc.EnumeratedType types[] = DocumentType.getDocumentTypeDefault().getSelectableValueSet();
            if(!document.getDocType().equals(types[Integer.parseInt(docType)]) && docType != null && docType.length() > 0)
                document.setDocType((DocumentType)types[Integer.parseInt(docType)]);
        }
        catch(WTPropertyVetoException wtpve)
        {
            throw new WTException("com.ptc.windchill.enterprise.doc.server.serverResource", "23", null);
        }
        return document;
    }

    public static Vector getTypeDisplayInfo(String solution, TypeIdentifier types[], Locale locale)
        throws WTException
    {
        String defaultPJLTypeString = WTMessage.getLocalizedMessage("com.ptc.netmarkets.document.documentResource", "80", null, locale);
        String default_value = null;
        String type_general = null;
        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 = getInsertLocation(type_localized, localizedString, locale);
                type_localized.insertElementAt(localizedString, pos);
                type_string.insertElementAt(((WCTypeIdentifier)type_id).getTypename(), pos);
                if(type_localized.get(pos).equals(defaultPJLTypeString))
                    type_general = (String)type_string.get(pos);
            }

            String type_one = size <= 0 ? null : (String)type_string.get(0);
            if(solution.equals("project"))
            {
                if(type_general != null)
                    default_value = type_general;
                else
                    default_value = type_one;
                if(VERBOSE)
                    System.out.println("default_value: " + default_value);
            } else
            {
                String localizedStr = "";
                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(VERBOSE)
                    System.out.println("default_value: " + default_value);
                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);
                }
            }
            Vector display_info = new Vector(3);
            display_info.add(type_localized);
            display_info.add(type_string);
            display_info.add(default_value);
            return display_info;
        } else
        {
            return null;
        }
    }

    public static int getNameUpperLimit()
    {
        int nameULimit = 0;
        try
        {
            nameULimit = ((Integer)WTIntrospector.getClassInfo((wt.doc.WTDocument.class).getName()).getPropertyDescriptor("name").getValue("UpperLimit")).intValue();
        }
        catch(WTIntrospectionException e)
        {
            nameULimit = 60;
        }
        return nameULimit;
    }

    public static boolean checkNameLength(String name)
    {
        return name == null || PersistenceHelper.checkStoredLength(name, getNameUpperLimit());
    }

    public static int getNumberUpperLimit()
    {
        int numberULimit = 0;
        try
        {
            numberULimit = ((Integer)WTIntrospector.getClassInfo((wt.doc.WTDocument.class).getName()).getPropertyDescriptor("number").getValue("UpperLimit")).intValue();
        }
        catch(WTIntrospectionException e)
        {
            numberULimit = 32;
        }
        return numberULimit;
    }

    public static boolean checkNumberLength(String number)
    {
        return number == null || PersistenceHelper.checkStoredLength(number, getNumberUpperLimit());
    }

    public static int getTitleUpperLimit()
    {
        int titleULimit = 0;
        try
        {
            titleULimit = ((Integer)WTIntrospector.getClassInfo((wt.doc.WTDocument.class).getName()).getPropertyDescriptor("title").getValue("UpperLimit")).intValue();
        }
        catch(WTIntrospectionException e)
        {
            titleULimit = 64;
        }
        return titleULimit;
    }

    public static boolean checkTitleLength(String title)
    {
        return title == null || PersistenceHelper.checkStoredLength(title, getTitleUpperLimit());
    }

    public static WTDocument setOrganization(WTDocument document, String docOrg)
        throws WTException
    {
        try
        {
            if(VERBOSE)
                System.out.println("DocumentUtility:setOrganization docOrg= " + docOrg);
            if(docOrg != null && docOrg.length() > 0)
                document.setOrganizationReference(WTPrincipalReference.newWTPrincipalReference(new ObjectIdentifier(docOrg)));
        }
        catch(WTPropertyVetoException wtpve)
        {
            throw new WTException("com.ptc.windchill.enterprise.doc.server.serverResource", "24", null);
        }
        return document;
    }

    public static int getInsertLocation(Vector vector, Object object, Locale locale)
    {
        int size = vector.size();
        if(size == 0)
            return size;
        Collator collator = Collator.getInstance(locale);
        int start = 0;
        int end = size - 1;
        int mid = (start + end) / 2;
        String str1 = object.toString();
        while(start <= end) 
        {
            mid = (start + end) / 2;
            String str2 = vector.elementAt(mid).toString();
            int res = collator.compare(str2, str1);
            if(res == 0)
                return mid;
            if(res > 0)
                end = mid - 1;
            else
                start = mid + 1;
        }
        if(start >= mid)
            return start;
        if(end < mid)
            return end;
        else
            return mid;
    }

    private static 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_429;
        resName = null;
        index = prefValue.indexOf(":");
        if(index == -1)
            break MISSING_BLOCK_LABEL_339;
        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.enterprise.doc.server.serverResource", "25", params);
        NoSuchFieldException nsfe;
        nsfe;
        Object params[] = {
            prefValue
        };
        throw new WTException("com.ptc.windchill.enterprise.doc.server.serverResource", "25", params);
        Exception e;
        e;
        e.printStackTrace();
        break MISSING_BLOCK_LABEL_429;
        int indexC = prefValue.indexOf(".");
        if(indexC != -1)
            if(type_string.contains(prefValue))
            {
                return prefValue;
            } else
            {
                Object params[] = {
                    prefValue
                };
                throw new WTException("com.ptc.windchill.enterprise.doc.server.serverResource", "25", params);
            }
        if(prefValue.equals("blank"))
        {
            return "blank";
        } else
        {
            Object params[] = {
                prefValue
            };
            throw new WTException("com.ptc.windchill.enterprise.doc.server.serverResource", "25", params);
        }
        return "SelectAType";
    }

    private static String getPreferenceValue(String node, String key)
    {
        Preferences root = WTPreferences.root();
        WTPreferences myPrefs = (WTPreferences)root.node(node);
        myPrefs.setContextMask(PreferenceHelper.createContextMask());
        return myPrefs.get(key, "");
    }

    private static final String RESOURCE = "com.ptc.windchill.enterprise.doc.server.serverResource";
    private static final String CLASSNAME;
    private static final boolean VERBOSE;
    public static final String TYPE_SELECT_STRING = "SelectAType";
    public static final String TYPE_SELECT_BLANK = "blank";
    private static final String DRESOURCE = "wt.doc.docResource";

    static 
    {
        CLASSNAME = (com.ptc.windchill.enterprise.doc.server.DocumentUtility.class).getName();
        try
        {
            WTProperties properties = WTProperties.getLocalProperties();
            VERBOSE = properties.getProperty("com.ptc.windchill.enterprise.verboseServer", false);
        }
        catch(Throwable t)
        {
            System.err.println("com.ptc.windchill.enterprise.doc.server.DocumentUtility: Error reading com.ptc.windchill.enterprise.* properties");
            t.printStackTrace(System.err);
            throw new ExceptionInInitializerError(t);
        }
    }
}
