from org.codehaus.jettison.json import JSONObject, JSONArray;
from java.lang import Exception;
import sys;
import types;
import os;
import Queue;
import AdminConfig  # @UnresolvedImport
import AdminControl  # @UnresolvedImport
import AdminApp  # @UnusedImport @UnresolvedImport
import AdminTask  # @UnresolvedImport
import com
import com.ibm.websphere.management.configservice.ConfigServiceFactory as ConfigServiceFactory
import com.urbancode.commons.util.crypto.CryptStringUtil as CryptStringUtil

from WASConfLog import Log;
import traceback;
from java.util import TreeMap, HashMap, Properties

__rolenameToModule__ = {};
__childrenDict__ = {};
__configurationTypes__ = {};
__applicableTypes__ = {};
__curpath__ = [];
__handletypepaths__ = []
__inspectedPaths__ = []
__clustermemberstocreate__ = {};
__attributesToNotUpdateDuringApply__ = [];
__removeSnippet__ = "false";
__applySnippet__ = "false";
__snippetToRemove__ = "";



def hasTypePathForTypeUnderCurrent(newtype):
  Util = sys.modules[__name__];
  thispath = [];
  thispath.extend(Util.__curpath__);
  thispath.append(newtype);
  return thispath in Util.__handletypepaths__;


def isJ2EENode(nodename):
  node = AdminConfig.getid("/Node:%s/" % nodename);
  servers = AdminConfig.list("Server", node);
  hasNoWebServer = 0;
  for x in servers.splitlines():
    if AdminConfig.showAttribute(x, "serverType") != "WEB_SERVER":
      hasNoWebServer = 1;
  return hasNoWebServer;

def getCell():
  return AdminControl.getCell();

def getHandleTypePathsFromJSON(topLevelJson, applicableTypes, configurationTypes = []):
  Util = sys.modules[__name__];
  if len(Util.__handletypepaths__) == 0:
    handletypes = _getHandleTypePathsFromJSON(topLevelJson, applicableTypes, configurationTypes);
    Util.__handletypepaths__ = noDuplicateList(handletypes);
  else:
    newHandleTypes = _getHandleTypePathsFromJSON(topLevelJson, applicableTypes, configurationTypes)
    mergedHandleTypes = Util.__handletypepaths__ + newHandleTypes
    Util.__handletypepaths__ = noDuplicateList(mergedHandleTypes);
  return Util.__handletypepaths__;

def _getHandleTypePathsFromJSON(topLevelJson, applicableTypes, configurationTypes, oldcurpath = None, pathlist = None):
  Util = sys.modules[__name__];
  if pathlist is None:
    pathlist = [];
  curpath = [];
  rolename = topLevelJson.getString("roleName");
  objtype = Util.roleNameToType(rolename);
  if oldcurpath is not None:
    if not applicableTypes.has_key(objtype):
      curpath.extend(oldcurpath);
    else:
      inclusivepath = [];
      inclusivepath.extend(oldcurpath);
      inclusivepath.append(objtype);
      pathlist.append(inclusivepath);
      if (topLevelJson.has("children")):
        for child in Util.getHighestChildrenWithRole(topLevelJson.getJSONArray("children")):
          Util._getHandleTypePathsFromJSON(child, applicableTypes, configurationTypes, inclusivepath, pathlist);
      if objtype == "VariableMap":
        newpath = [];
        newpath.extend(inclusivepath);
        newpath.append("VariableSubstitutionEntry");
        pathlist.append(newpath);
      elif objtype == "VirtualHost":
        newpath = [];
        newpath.extend(inclusivepath);
        newpath.append("HostAlias");
        pathlist.append(newpath);
        newpath = [];
        newpath.extend(inclusivepath);
        newpath.append("MimeEntry");
        pathlist.append(newpath);
  curpath.append(objtype);
  pathlist.append(curpath);
  # __handletypepaths__ is a list of valid object type paths
  # if an object is determined to not have a valid path, it is not updated/created
  # we go through the config data json to build __handletypepaths__
  # if an object is not included in the config data, __handletypepaths__ will not include its path
  # this causes a problem in the case where:
  #   1. config data does not contain objects of type X
  #   2. users manually create objects of type X through admin console
  #   3. config data is applied
  # expected result: objects of type X are removed
  # actual result: objects of type X are not removed because their path is not in __handletypepaths__
  # to fix this, for each object type's role module (ObjectType.py), we will:
  #   1. get the namespace, which includes imported modules
  #   2. go through each item in the namespace
  #      a. if the item in the namespace is a Websphere object type, add its path to __handletypepaths__
  #
  # only do this if the object type is in the list of configuration types OR configuration types list is empty
  # only do this once for each path (use __inspectedPaths__ to keep track of which paths we have inspected)
  if objtype in configurationTypes or len(configurationTypes) == 0:
    if curpath not in Util.__inspectedPaths__:
      Util = sys.modules[__name__];
      # get the module for the object type
      mod = Util.getRoleModule(objtype);
      if mod is not None:
        # get the namespace for the module
        namespace = dir(mod);
        for nsEntry in namespace:
          # determine if nsEntry is a WebSphere config object type
          module = isValidType(nsEntry)
          if module is not None:
            # build a copy of curpath for us to play with
            newPath = []
            for item in curpath:
              newPath.append(item)
            # add the module to the path
            newPath.append(module);
            if newPath not in pathlist:
              # add the path to the pathlist
              pathlist.append(newPath);
      Util.__inspectedPaths__.append(curpath)
  if (topLevelJson.has("children")):
    for child in Util.getHighestChildrenWithRole(topLevelJson.getJSONArray("children")):
      Util._getHandleTypePathsFromJSON(child, applicableTypes, configurationTypes, curpath, pathlist);
  if objtype == "VariableMap":
    newpath = [];
    newpath.extend(curpath);
    newpath.append("VariableSubstitutionEntry");
    pathlist.append(newpath);
  elif objtype == "VirtualHost":
    newpath = [];
    newpath.extend(curpath);
    newpath.append("HostAlias");
    pathlist.append(newpath);
    newpath = [];
    newpath.extend(curpath);
    newpath.append("MimeEntry");
    pathlist.append(newpath);
  return pathlist;

def noDuplicateList(duplist):
  newlist = [];
  for x in duplist:
    if not (x in newlist):
      newlist.append(x);
  return newlist;

def getObjectType(confid):
  return AdminConfig.getObjectType(confid);

def getAllObjectsOfType(type):
  objects = AdminConfig.list(type)
  objList = parseConfigIdList(objects)
  return objList;

def printCurPath():
  curstring = "";
  first = 1;
  for elem in __curpath__:
    if first == 1:
      first =0;
      curstring = elem;
    else:
      curstring = "%(cur)s/%(elem)s" % { 'cur':curstring, 'elem':elem };
  #Log.debug("CurPath : %s" % curstring);

def pushPathElement(name):
  #Log.debug("Pushing path element %s" % name);
  __curpath__.append(name);
  printCurPath();

def popPathElement(name):
  popped = __curpath__.pop();
  #Log.debug("Popping path element %s" % popped);
  if popped != name:
    raise Exception("Popped an element with wrong name. Expected '%(exp)s' Actual '%(act)s'." % { 'exp':name, 'act':popped });
  printCurPath();

def setConfigurationTypes(confTypes):
  Util = sys.modules[__name__];
  Util.__configurationTypes__ = confTypes;
  Log.debug("Configuration types : %s" % Util.__configurationTypes__);

def getChildrenTypes(objtype, objectsDir):
  objdir = findObjectDir(objtype, objectsDir);
  return getChildrenTypesFromDirectory(objdir);

def getChildrenTypesFromDirectory(objdir):
  if __childrenDict__.has_key(objdir):
    return __childrenDict__[objdir];
  children = [];
  f = open("%(dir)s%(fileSep)schildren" % { 'dir':objdir, 'fileSep': os.sep }, "r");
  line = f.readline();
  while line != "":
    childtype = line.strip();
    line = f.readline();
    children.append(childtype);
  f.close();
  __childrenDict__[objdir] = children;
  return children;

def _genStringFromProperties(propslist):
  Util = sys.modules[__name__];
  finString = '[';
  finStringContainsList=0;
  for curlist in propslist:
    value = curlist[1];
    name = curlist[0];
    if value is None:
      value = "";
    useSingleQuotesForValue = 0;#false
    valueIsList = 0;
    if isinstance(value, [].__class__):
      valueIsList = 1;
    if valueIsList == 0:
      #The following 2 lines of code are needed for this reason:
      #http://www-01.ibm.com/support/docview.wss?uid=swg21587193
      #Basically, need to add a space before the initial [ to prevent the jython parser from treating the square
      #bracket as the beginning of a list declaration, which causes a java.lang.IllegalArgumentException exception.
      if value.startswith("[\'") and value.endswith("\']"):
        value = value.replace("[", " [", 1);
      singIndex = value.find("'");
      quotIndex = value.find('"');
      if quotIndex != -1 and singIndex != -1:
        useSingleQuotesForValue = 1;#true
        value = value.replace("'", "\\'");#i'm leaving this in even though it doesn't work. websphere doesn't allow using an escaped '|" inside a parameter the other 2 clauses still work
      elif singIndex != -1:
        useSingleQuotesForValue = 0;#false
      elif quotIndex != -1:
        useSingleQuotesForValue = 1;#true

    if valueIsList == 1:
      #this could be one of two things
      #it could be an actual list of things
      #or it could be a subobject
      #if its a subobject, the first thing should also be a list
      #only support 1 layer of subobjects for now
      if isinstance(value[0], [].__class__):
        substr = Util._genStringFromProperties(value);
        if substr.startswith("[ ["):
          substr = "[[%s" % substr[3:];
        if substr.endswith("] ]"):
          substr = "%s]]" % substr[0:-3];
        finString= "%(cur)s [\"%(name)s\" %(substring)s]" % {'cur':finString, 'name':name, 'substring':substr};
      else:
        listToString = ' '.join(value);
        listToString = listToString.replace("[ [", "[[");
        listToString = listToString.replace("] ]", "]]");
        finString = "%(cur)s [\"%(name)s\" [%(value)s]]" % { 'cur': finString, 'name':name, 'value':listToString };
      finStringContainsList = 1;
    elif useSingleQuotesForValue == 0:
      finString = "%(cur)s [\"%(name)s\" \"%(value)s\"]" % { 'cur': finString, 'name':name, 'value':value };
    else:
      finString = "%(cur)s [\"%(name)s\" '%(value)s']" % { 'cur': finString, 'name':name, 'value':value };
  finString = "%s ]" % finString;
  if finStringContainsList == 1:
    #Replace all double quotes with single quotes
    finString = finString.replace('\"', "\'");
    #AdminConfig.create() forces us to remove space between final two parenthesis
    finString = finString.replace("] ]", "]]");
  return finString;

def _genStringFromPropertiesNoQuotes(propslist):
  finString = '[';
  for curlist in propslist:
    value = curlist[1];
    finString = "%(cur)s[%(name)s %(value)s]" % { 'cur': finString, 'name':curlist[0], 'value':value };
  finString = "%s ]" % finString;
  return finString;

def isValidType(objtype, logWarning = 0):
  if objtype in AdminConfig.types().splitlines():
    return objtype;
  else:
    # if the logWarning value is not 0 and objtype is not valid,
    # display a warning message in the stdOut.txt
    if logWarning != 0:
      Log.log("Invalid configuration object for version %(wasVersion)s of WebSphere: %(objtype)s" % {"wasVersion":getVersion(), 'objtype':objtype});
    return None;

def remove(objid, force = 0):
  # if the Snippet Actions for Individual Configuration Objects field has been set to
  # either Remove or Apply an individual configuration object, we don't want to remove anything
  if __removeSnippet__ == "true" or __applySnippet__ == "true":
    Log.logMsg("Not removing " + str(objid) + " because the configuration data is a snippet for an individual configuration object.", Log.LogLevelDebug);
    return;
  Util = sys.modules[__name__];
  objType = Util.getObjectType(objid);
  curtypepath = [];
  curtypepath.extend(Util.__curpath__);
  curtypepath.append(objType);
  if force == 1 or curtypepath in Util.__handletypepaths__:
    Log.debug("Removing %s" % objid);
    Log.redo("remove(lookupObjId(\"%s\"));" % sanitizeObjId(objid));
    if objid is not None and objid != "(null)":
      return AdminConfig.remove(objid);
  else:
    Log.debug("Not removing obj %(objid)s because the path is determined to be not applicable based on input json: '%(type)s'" % { 'type':curtypepath, 'objid':objid});

def removeCMPConnectorFactory(objid):
  Log.debug("Removing %s" % objid);
  return AdminConfig.remove(objid);

def modify(objid, propsMap, force = 0):
  Util = sys.modules[__name__];
  curtypepath = [];
  curtypepath.extend(Util.__curpath__);
  if force == 1 or curtypepath in Util.__handletypepaths__:
    finString = _genStringFromProperties(propsMap);
    Log.redo("AdminConfig.modify(lookupObjId(\"%(id)s\"), replaceObjRefs(\"\"\"%(finString)s\"\"\"));" % { 'id':sanitizeObjId(objid), 'finString': finString });
    return AdminConfig.modify(objid, finString);
  else:
    Log.debug("Not modifying obj %(objid)s because the path is determined to be not applicable based on input json: '%(type)s'" % { 'type':curtypepath, 'objid':objid});
    return None;

def create(objtype, parentid, propsMap, attName = None, force = 0):
  Util = sys.modules[__name__];
  curtypepath = [];
  curtypepath.extend(Util.__curpath__);
  if curtypepath in Util.__handletypepaths__ or force == 1:
    finString = _genStringFromProperties(propsMap);
    Log.debug("Creating %(type)s on object %(objid)s" % { 'type':objtype, 'objid':parentid });
    objid="";
    logobjid="";
    createCommand="";

    # if the Snippet Actions for Individual Configuration Objects field was set to Remove,
    # and if the objtype of the object we are about to create is the same object type specified
    # in the WebSphere Configuration Types field, we don't want to delete the object instead of create it
    if Util.__removeSnippet__ == "true" and len(Util.__configurationTypes__) != 1:
      raise Exception(("The Snippet Actions for Individual Configuration Objects field "
                     "was set to Remove Individual Configuration Object, however the "
                     "WebSphere Configuration Types field did not contain a single configuration "
                     "object type.  Verify the WebSphere Configuration Type field contains only the "
                     "configuration object type your snippet represents.  If you are not using "
                     "snippets, set the Snippet Actions for Individual Objects field to None."))
    if Util.__removeSnippet__ == "true" and objtype == Util.__configurationTypes__[0]:
      # to determine if this is the object represented by the configuration data, we will:
      #  1. get all objects of the object type
      #  2. for each object we will...
      #     a. get a property from propsMap (these properties are role properties from the config data).
      #     b. get the value for that property from propsMap
      #     c. get the value of the same property from the object we found.
      #     d. see if the property's value from the propsMap is the same as the value for the property from the object
      #     e. repeat a-d as long as the values match
      #     f. if all property values match, we probably found the object represented by the configuration data
      Log.logMsg("Searching for the object of type " + str(objtype) + " to remove.", Log.LogLevelDebug);
      targetObject = "";
      # get all objects of objtype
      allObjsOfType = getAllObjectsOfType(objtype);
      for objOfType in allObjsOfType:
        foundTargetObject = "true"
        for prop in propsMap:
          # get a property name and its value from the property map
          propName = prop[0];
          propValue = prop[1];
          # get the same property from the object we found and see if it has the same value
          objOfTypeValue = AdminConfig.showAttribute(objOfType, propName);
          # if objOfTypeValue is a password, need special handling to get value
          if objOfTypeValue == "*****" or objOfTypeValue == "****":
            passwd = readPassword(objOfType, propName, objtype);
            if passwd is not None:
              # Handle empty/blank passwords
              if passwd == "None":
                objOfTypeValue = ""
              else:
                objOfTypeValue = passwd;
            else:
              objOfTypeValue = ""
          if propValue != objOfTypeValue:
            # the properties don't match, so this is not the object we are looking for
            foundTargetObject = "false"
            break;
        # if we went through all the properties and all property values matched,
        # then foundTargetObject is still "true" and we found the object we were looking for.
        if foundTargetObject == "true":
          if targetObject == "":
            targetObject = objOfType;
          else:
            # throw exception because we found more than one object
            raise Exception(("Could not determine which configuration object to removed based off of the "
                             "snippet configuration data. Found more than one object with the role "
                             "properties " + str(propsMap) + ". Objects found include " + str(targetObject) + " and"
                             " " + str(objOfType)));
      if targetObject != "":
        # we found the object to delete.
        # we won't actually delete it until later, so save it off to the side for now
        Util.__snippetToRemove__ = targetObject;
        # because we don't want to create/remove any more objects, let's set __handletypepaths__ to [].
        # this will cause creates/removes to fail the handletypepaths check, preventing them from occurring
        Log.logMsg("Setting Util.__handletypepaths__ to [].", Log.LogLevelDebug);
        Util.__handletypepaths__ = []
      else:
        raise Exception(("Could not find the object to remove represented by the snippet configuraiton "
                         "data. Looked for an object of type " + str(objtype) + " with role properties " + str(propsMap) + "."))
      return targetObject;

    if attName is not None and len(attName) > 0:
      Log.debug("Creating %(type)s for attribute %(att)s" % { 'type':objtype, 'att':attName});
      objid = AdminConfig.create(objtype, parentid, finString, attName);
      logobjid = sanitizeObjId(objid);
      createCommand = "AdminConfig.create(\"%(type)s\", lookupObjId(\"%(id)s\"), replaceObjRefs(\"\"\"%(finString)s\"\"\"), \"%(attName)s\");" % { 'id':sanitizeObjId(parentid), 'finString': finString, 'attName':attName, 'type':objtype };
    else:
      objid = AdminConfig.create(objtype, parentid, finString);
      logobjid = sanitizeObjId(objid);
      createCommand = "AdminConfig.create(\"%(type)s\", lookupObjId(\"%(id)s\"), replaceObjRefs(\"\"\"%(finString)s\"\"\"));" % { 'id':sanitizeObjId(parentid), 'finString': finString, 'type':objtype }

    Log.redo("objectMap[\"%(id)s\"] = %(command)s" % { 'id':logobjid, 'command':createCommand });
    if objtype == 'ServerCluster':
      clustername = ''
      for proplist in propsMap:
        if proplist[0] == 'name':
          clustername = proplist[1];
          break;
      if Util.__clustermemberstocreate__.has_key(clustername):
        nodeserverlist = Util.__clustermemberstocreate__[clustername];
        for nodeserver in nodeserverlist:
          nodename = nodeserver[0];
          servername = nodeserver[1];
          Util.createClusterMember(clustername, nodename, servername);
    return objid;
  else:
    Log.debug("Not creating obj on parent %(parent)s because the path is determined to be not applicable based on input json: '%(type)s'" % { 'type':curtypepath, 'parent':parentid});

def removeSnippet():
  Util = sys.modules[__name__];
  if Util.__snippetToRemove__ != "" and __snippetToRemove__ is not None:
    # temporarily set __removeSnippet__ to false so the remove method will complete
    Util.__removeSnippet__ = "false"
    remove(Util.__snippetToRemove__, 1);
    # set __removeSnippet__ back to true
    Util.__removeSnippet__ = "true"

def setRemoveSnippetToFalse():
  Util = sys.modules[__name__];
  Util.__removeSnippet__ = "false";

def setRemoveSnippetToTrue():
  Util = sys.modules[__name__];
  Util.__removeSnippet__ = "true";

def setApplySnippetToFalse():
  Util = sys.modules[__name__];
  Util.__applySnippet__ = "false";

def setApplySnippetToTrue():
  Util = sys.modules[__name__];
  Util.__applySnippet__ = "true";

def sanitizeObjId(objid):
  if objid is not None and (objid.startswith('"') or objid.startswith("'")):
    return objid[1:-1]
  return objid;

def getid(conpath, checkList = None):
  Log.debug("Get ID %s" % conpath);
  #traceback.print_stack();
  doCheck = 1;
  if checkList is not None:
    for item in checkList:
      if not isValidType(item):
        doCheck = 0;
  if doCheck == 1:
    objid = AdminConfig.getid(conpath);
    if len(objid.splitlines()) == 1:
      if objid is not None and len(objid) > 0:
        Log.redo("conpathMap['%(id)s'] = \"%(con)s\";" % { 'con':conpath, 'id':sanitizeObjId(objid) });
    return objid;
  return None;

def unsetAttribute(objid, attribute, objtype, force = 0):
  # if the Snippet Actions for Individual Configuration Objects field has been set to
  # either Remove or Apply an individual configuration object, we don't want to unset anything
  if __removeSnippet__ == "true" or __applySnippet__ == "true":
    Log.logMsg("Not unsetting " + str(objtype) + " " + str(objid) + " because the configuration data is a snippet for an individual configuration object.", Log.LogLevelDebug);
    return;
  Util = sys.modules[__name__];
  curtypepath = [];
  curtypepath.extend(Util.__curpath__);
  if curtypepath in Util.__handletypepaths__ or force == 1:
    # the AdminConfig.unsetAttributes command was not implemented until WAS 7
    if int(getVersion().split(".", 1)[0]) > 6:
      if attIsValidForObject(objtype, attribute):
        Log.redo("AdminConfig.unsetAttributes(lookupObjId(\"%(objid)s\"), [\"%(attributeName)s\"])" % { 'objid':sanitizeObjId(objid), 'attributeName': attribute});
        AdminConfig.unsetAttributes(objid, [attribute]);
  else:
    Log.debug("Not unsetting attributes on obj because the path is determined to be not applicable based on input json: '%s'" % curtypepath);

def getTypeFoldername(objtype):
  if typeNameToFolderNameMap.has_key(objtype):
    return typeNameToFolderNameMap[objtype];
  return "%ss" % objtype;

def createTypeFolder(respath, objtype, typeFolders=None, hardcoded = 0):
  if typeFolders is not None:
    if typeFolders.has_key(objtype):
      return { 'path': typeFolders[objtype] };

  if hardcoded == 0:
    typeFolderName = getTypeFoldername(objtype);
  else:
    typeFolderName = objtype;

  if typeFolders is not None:
    if typeFolders.has_key(typeFolderName):
      return {'path': typeFolders[typeFolderName] } ;

  curchildrespath = "%(cur)s/%(type)s" % { 'cur':respath, 'type': typeFolderName }
  folder = JSONObject();
  folder.put("name", "%s" % typeFolderName);
  folder.put("path", curchildrespath);
  folder.put("teamMappings", JSONArray());
  folder.put("description", "Discovered %s" % typeFolderName);
  folder.put("inheritTeam", "true");
  if typeFolders is not None:
    typeFolders[objtype] = curchildrespath;
    typeFolders[typeFolderName] = curchildrespath;
  return { 'path':curchildrespath, 'object':folder };

def getHighestChildrenWithRole(childrenjson):
  result = [];
  for i in range(childrenjson.length()):
    child = childrenjson.getJSONObject(i);
    if child.has("roleName"):
      if getRoleModule(roleNameToType(child.getString("roleName"))) is not None:
        result.append(child);
      elif child.has("children"):
        for subchild in getHighestChildrenWithRole(child.getJSONArray("children")):
          result.append(subchild);
    elif child.has("children"):
      for subchild in getHighestChildrenWithRole(child.getJSONArray("children")):
        result.append(subchild);
  #sort by name to keep order consistent when we perform a compare to live
  result.sort(lambda first, second:cmp(first.getString('name'), second.getString('name')));
  return result;

def getVersion():
  serverOName = AdminControl.queryNames("type=Server,node=%s,*" % AdminControl.getNode()).splitlines()[0];
  return AdminControl.getAttribute(serverOName, "platformVersion");

def getNodeNameFromObjID(objid):
  if objid.find("/nodes/") == -1:
    raise Exception("Failed to determine the node name for " + str(objid));
  else:
    start = objid.find("/nodes/") + 7;
    end = objid.find("|");
    nodeName = objid[start:end]
    return nodeName;

def addAllFromExport(objlist, exportdict):
  if exportdict is not None:
    if exportdict.has_key('object'):
      addFromExport(objlist, exportdict['object']);
      if exportdict.has_key('extraObjects'):
        for extObj in exportdict['extraObjects']:
          addFromExport(objlist, extObj);

def addFromExport(objlist, obj):
  #objlist should be either a python list or a JSONArray
  #obj is a JSONObject(woohoo dynamically typed languages)
  if not obj.has('roleName'):
    Log.debug("Adding folder at path '%s'" % obj.getString('path'));
  if 'append' in dir(objlist):
    objlist.append(obj);
  else:
    objlist.put(obj);

def attIsValidForObject(objtype, attname):
  Log.debug("Checking %(att)s is valid for %(type)s" % { 'att':attname, 'type':objtype } );
  atts = AdminConfig.attributes(objtype).splitlines();
  for att in atts:
    curattname = att.split(' ', 1)[0];
    if curattname == attname:
      return 1;
  return 0;

def getOptionalAttribute(objid, attname, objtype):
  if objid is not None and len(objid) > 0 and attIsValidForObject(objtype, attname):
    return AdminConfig.showAttribute(objid, attname);
  return None;

def getRequiredAttribute(objid, attname, objtype):
  if objid is not None and len(objid) > 0 and attIsValidForObject(objtype, attname):
    Log.debug("Getting required %(att)s for %(type)s" % { 'att':attname, 'type': objtype } );
    return AdminConfig.showAttribute(objid, attname);
  return None;

def parseConfigIdListAttribute(objid, attname, objtype):
  if objid is not None and len(objid) > 0 and attIsValidForObject(objtype, attname):
    idlist = parseConfigIdList(AdminConfig.showAttribute(objid, attname));
    redoMessage = "parseConfigIdList(lookupObjId(\"%(objid)s\"), \"%(attname)s\", [" % { 'objid':sanitizeObjId(objid), 'attname':attname };
    first = 0;
    for item in idlist:
      if first == 0:
        first = 1;
      else:
        redoMessage = "%s, " % redoMessage;
      redoMessage = "%(cur)s\"%(item)s\"" % {'cur':redoMessage, 'item':sanitizeObjId(item) };
    redoMessage = "%s])" % redoMessage;
    Log.redo(redoMessage);
    return idlist;
  return [];

def parseConfigIdList(idinput):
  if idinput is None:
    return [];
  if idinput.startswith("["):
    idinput = idinput[1:-1]
  lastquote = None;
  inquotes = 0;
  result = [];
  cur = "";
  prev_x = None;
  prev_newlinechar= None;
  consecutivequotes = 0;
  for x in idinput:
    if x == "\'" or x == "\"":
      if inquotes == 0:
        inquotes = 1;
        lastquote = x;
        consecutivequotes = 0;
        cur = cur+x;
      else:
        if x == prev_x:
          consecutivequotes = consecutivequotes + 1;
          cur = cur + x;
        elif x == lastquote:
          if consecutivequotes == 0:
            inquotes = 0;
            lastquote = None;
            cur = cur+x;
          else:
            consecutivequotes = consecutivequotes - 1;
            cur = cur+x;
        else:
          cur = cur + x;
    elif x == " " or x == "\n" or x == "\r":
      if inquotes == 1:
        cur = cur + x;
      elif x == "\n" and prev_newlinechar == "\r":
        #skip it. its a windows line ending
        prev_newlinechar = None;
      elif cur.strip() != "(null)":
        result.append(cur.strip());
        cur = "";
        prev_x = None;
        prev_newlinechar = x;
    else:
      cur = cur + x;
    prev_x = x;
  if cur != "" and cur.strip() != "(null)":
    result.append(cur.strip());
  return result;

def getRoleModule(roleName):
  mod = None;
  if __rolenameToModule__.has_key(roleName):
    return __rolenameToModule__[roleName];
  else:
    try:
      pack = __import__("%(role)s.%(role)s" % { 'role': roleName });
      mod = getattr(pack, roleName);
      __rolenameToModule__[roleName] = mod;
    except ImportError, err:
      Log.debug("Tried to load role module that didn't exist: %s" % roleName);
      Log.debug(err);
      for line in traceback.format_list(traceback.extract_stack()):
        Log.debug(line);
    return mod;

def roleNameToType(roleName):
  curName = roleName.replace("WebSphere","");#strip websphere of of the roleName
  curName = curName.replace("Portal","");#strip websphere of of the roleName
  if curName == "Cluster":
    curName = "ServerCluster";
  return curName;

def recursiveFindHighest(startdir, configType, filetype='f'):
  tocheck = Queue.Queue();
  tocheck.put(startdir)
  while not tocheck.empty():
    curdir = tocheck.get();
    for path in os.listdir(curdir):
      curpath = "%(curdir)s%(fileSep)s%(path)s" % { 'curdir': curdir, 'fileSep': os.sep, 'path':path };
      if filetype == 'f' and os.path.isfile(curpath) and path == configType:
        return curpath
      elif filetype == 'd' and os.path.isdir(curpath) and path == configType:
        return curpath
      elif os.path.isdir(curpath):
        tocheck.put(curpath)
  return None

def findObjectDir(configType, objectsDir):
  return recursiveFindHighest(objectsDir, configType, 'd');

def getObjectNameFromJson(rolename, jsonobject):
  result = None;
  if rolename == "Cell":
    return AdminControl.getCell();
  if getRoleModule(rolename).__name_att__ == None:
    return "";
  if jsonobject.has("roleProperties"):
    roleProps = jsonobject.getJSONObject("roleProperties");
    if roleProps.has(getRoleModule(rolename).__name_att__):
      result = roleProps.getString(getRoleModule(rolename).__name_att__);
    else:
      '''
        There are two types of AuthorizationGroup:
          1)Cell ->  AuthorizationGroup
          2)AuthorizationGroup -> members -> AuthorizationGroup
        For 2), the attribute _name_att_ (name) could be None, so have to ignore it from else part
      '''
      if rolename != "AuthorizationGroup":
        raise Exception("Resource does not have expected name property %s" % getRoleModule(rolename).__name_att__);
  else:
    raise Exception("Resource doesn't have role properties attribute");
  return result;

def findContainmentPath(resourceJson):
  stack = [];
  path = "/";
  curobject = resourceJson;
  while curobject != None:
    if curobject.has("roleName"):
      curdict = {};
      curdict["roleName"] = curobject.getString("roleName");
      if curdict["roleName"].startswith("WebSphere") or curdict["roleName"].startswith("Portal"):
        curdict['roleName'] = roleNameToType(curdict['roleName']);
        curdict["name"] = getObjectNameFromJson(curdict['roleName'], curobject);
        stack.append(curdict);
    if curobject.has("parent"):
      curobject = curobject.getJSONObject("parent");
    else:
      curobject = None;

  while len(stack) != 0:
    curdict = stack.pop();
    path = "%(curpath)s%(type)s:%(name)s/" % { 'curpath': path, 'type': curdict["roleName"], 'name': curdict['name'] };
  if path == "/":
    path = "";
  return path;

def addAttributePathPropertyToJson(jsonobject, propName, objid, attName, objtype):
  if objid is not None and len(objid) > 0 and attIsValidForObject(objtype, attName):
    return addPathPropertyToJson(jsonobject, propName, AdminConfig.showAttribute(objid, attName));
  return None;

def addPathPropertyToJson(jsonobject, propName, propValue):
  if propValue != None and propValue != "[]":
    parts = propValue.split(";");
    finString = "";
    first = 0;
    for part in parts:
      if first == 0:
        first = 1;
      else:
        finString = "%s\n" % finString;
      finString = "%(st)s%(pa)s" % { 'st': finString, 'pa': part };
    jsonobject.put(propName, finString);

def addPathProperty(props, attName, attValue, objtype=None):
  if objtype is None:
    objtype = __curpath__[-1];
  if objtype is not None and attIsValidForObject(objtype, attName) == 0:
    Log.debug("addPathProperty objecttype: %(objType)s, attribute: %(objAttr)s not valid" % { 'objType':objtype, 'objAttr':attName } );
    return;

  if attValue != None:
    prop = [attName];
    parts = attValue.split("\n");
    finString = "";
    first = 0;
    for part in parts:
      if first == 0:
        first = 1;
      else:
        finString = "%s;" % finString;
      finString = "%(st)s%(pa)s" % { 'st': finString, 'pa': part };
    prop.append(finString);
    props.append(prop);

def addIfNotNone(props, attName, value, objtype=None):
  if objtype is None:
    objtype = __curpath__[-1];
  if objtype is not None and attIsValidForObject(objtype, attName) == 0:
    Log.debug("addIfNotNone objecttype: %(objType)s, attribute: %(objAttr)s not valid" % { 'objType':objtype, 'objAttr':attName } );
    return;

  if value != None:
    if isinstance(value, types.StringType) and value.startswith("pbe{"):
      value = CryptStringUtil.decrypt(value);
      # Log.debug("addIfNotNone decrypted value: %(value)s" % {'value':value});
    prop = [attName, value]
    props.append(prop);

def addIfNotNoneOrEmpty(props, attName, value, objtype=None):
  if objtype is None:
    objtype = __curpath__[-1];
  if objtype is not None and attIsValidForObject(objtype, attName) == 0:
    Log.debug("addIfNotNoneOrEmpty objecttype: %(objType)s, attribute: %(objAttr)s not valid" % { 'objType':objtype, 'objAttr':attName } );
    return;

  if value != None and len(value) > 0:
    prop = [attName, value]
    props.append(prop);

def addAttributeToJsonIfNotNone(jsonobj, attName, objid, objAttName, objtype, required=None):
  if objid is not None and len(objid) > 0 and attIsValidForObject(objtype, objAttName):
    value = AdminConfig.showAttribute(objid, objAttName);
    # Check for WebSphere secure value, WAS 7 uses "****", WAS 8 uses "*****"
    if value == "*****" or value == "****":
      passwd = readPassword(objid, objAttName, objtype);
      if passwd is not None:
        # Handle empty/blank passwords
        if passwd == "None":
          value = ""
        else:
          value = passwd;
      else:
        value = ""
      value = CryptStringUtil.encrypt(value);
    if required is not None and value is None:
      value = ""
    return addToJsonIfNotNone(jsonobj, attName, value);
  return None;

def addToJsonIfNotNone(jsonobj, attName, value):
  if value != None:
    jsonobj.put(attName, value);

def addPathAttIfChanged(objid, atts, path, propname, objtype):
  if objid is None or len(objid) < 1 or not attIsValidForObject(objtype, propname):
    return None;
  curvalue = AdminConfig.showAttribute(objid, propname);
  if curvalue == '[]':#this is an empty path. i think was does this just to piss people off.
    if path != None:
      if path.strip() != "":
        Log.redo("AdminConfig.modify(\"lookupObjId(\"%(id)s\"), [[\"%(propname)s\", '']]);" % { 'id':sanitizeObjId(objid), 'propname':propname });
        AdminConfig.modify(objid, [[propname, '']]); # patt attribute has to be cleared first
        addPathProperty(atts, propname, path);
  else:#curvalue != '[]'
    #curvalue will be a ; separated list
    #path will be a \n separated list
    #if order is different we will still update just in case
    curparts = curvalue.split(';');
    if path == None or len(path) < 1:
      newparts = [];
    else:
      newparts = path.split('\n');
    if len(curparts) != len(newparts):
      Log.redo("AdminConfig.modify(\"lookupObjId(\"%(id)s\"), [[\"%(propname)s\", '']]);" % { 'id':sanitizeObjId(objid), 'propname':propname });
      AdminConfig.modify(objid, [[propname, '']]); # patt attribute has to be cleared first
      addPathProperty(atts, propname, path);
    else:
      for x in range(len(curparts)):
        if newparts[x].strip() != curparts[x]:
          Log.redo("AdminConfig.modify(\"lookupObjId(\"%(id)s\"), [[\"%(propname)s\", '']]);" % { 'id':sanitizeObjId(objid), 'propname':propname });
          AdminConfig.modify(objid, [[propname, '']]); # patt attribute has to be cleared first
          addPathProperty(atts, propname, path);
          break;

def addAttIfChanged(objid, atts, expected, attName, objtype):
  if objid is None or len(objid) < 1 or not attIsValidForObject(objtype, attName):
    return None;
  curVal = AdminConfig.showAttribute(objid, attName);
  # Check for WebSphere secure value, WAS 7 uses "****", WAS 8 uses "*****"
  if curVal == "*****" or curVal == "****" or curVal is None:
    if curVal is not None:
      curVal = readPassword(objid, attName, objtype);
    if isinstance(expected, types.StringType) and expected.startswith("pbe{"):
      expected = CryptStringUtil.decrypt(expected);
      # Log.debug("addAttIfChanged decrypted expected: %(expected)s curVal: %(curVal)s" % {'expected':expected, 'curVal':curVal});

  if curVal != expected:
    if curVal == None and expected == "":
      pass
    elif expected == None and curVal.strip() == "":
      pass
    else:
      # determine if this is an attribute we do NOT wish to update during apply
      if (objtype + ":" + attName) in __attributesToNotUpdateDuringApply__:
        Log.logMsg(("Not updating attribute " + str(attName) + "'s value from " + str(curVal) + " to " +
          str(expected) + " for " + str(objtype) + " " + str(objid) + " because this attribute is read only or " +
          "environment-specific and should not be updated."), Log.LogLevelWarn);
      else:
        prop = [attName, expected];
        atts.append(prop);

def getAssociatedObjects(objid, attName, force = 0):
  if force == 1 or isValidType(attName):
    objects = AdminConfig.list(attName, objid);
    objList = parseConfigIdList(objects);
    redoMessage = "list(lookupObjId(\"%(objid)s\"), \"%(attname)s\", [" % { 'objid':sanitizeObjId(objid), 'attname':attName };
    first = 0;
    for item in objList:
      if first == 0:
        first = 1;
      else:
        redoMessage = "%s, " % redoMessage;
      redoMessage = "%(cur)s\"%(item)s\"" % {'cur':redoMessage, 'item':sanitizeObjId(item) };
    redoMessage = "%s])" % redoMessage;
    Log.redo(redoMessage);
    return objList;
  else:
    return None;

def getScope(parentid):
  # to find the scope of the object we are looking for,
  # take the parentid and get everything between the first / and |
  # example parentid = (cells/CloudBurstCell_1/nodes/CloudBurstNode_1|resources.xml#J2CResourceAdapter_1338435011824)
  # this would make parentScope below = CloudBurstCell_1/nodes/CloudBurstNode_1
  parentScope = parentid[parentid.find("/"):(parentid.find("|") + 1)];
  return parentScope;

def findChildToUpdate(parentid, jsonobject, objtype, targetpropertyname, attribute):
  if not jsonobject.has("roleProperties"):
    raise Exception(objtype + " resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has(targetpropertyname):
    raise Exception(objtype + " resource has no property named " + targetpropertyname);

  targetProperty = roleProperties.getString(targetpropertyname);
  targetObject = None;
  parentScope = getScope(parentid);

  # get all objects of the desired type
  objects = getid("/" + objtype + ":/").splitlines();
  if len(objects) > 0:
    for thisobject in objects:
      if len(thisobject) > 0:
        # see if this object id contains the same scope as the parentid
        if thisobject.find(parentScope) != -1:
          # get the specified attribute for this type and compare
          prop = getOptionalAttribute(thisobject, attribute, objtype);
          if prop != None and len(prop) > 0:
            if prop == targetProperty:
              targetObject = thisobject;
              break;

  if targetObject == None or len(targetObject) == 0:
      raise Exception("Could not find " + objtype + " with property " + targetProperty + " in scope " + parentScope + ".");
  return targetObject;

def replaceColonWithDash(string):
  if string != None:
    string = string.replace(":", "-");
  return string;

# some WebSphere objects may contain slashes in the object name.
# having slashes in the object name breaks JSON paths (if the object name is in the path)
# this method replaces the / charcters in a string and may be called to prevent object names from
# containing slashes
def replaceSlash(string):
  if string != None:
    string = string.replace("/", "-SLASH-");
  return string;

# From a string of parameters, get the value of a parameter whose value is a string
def getStringParam(params, param):
  indexOfParam = params.find(param);
  indexOfEqualSign = params.find("=", indexOfParam);
  indexOfBracket = params.find("}", indexOfParam);
  if indexOfEqualSign != -1 and indexOfEqualSign < indexOfBracket:
    value = params[indexOfEqualSign+1:params.find(", ", indexOfEqualSign)];
  else:
    value = params[indexOfEqualSign+1:params.find(", ", indexOfBracket)];
  return value;

# From a string of parameters, get the value of a parameter whose value is a list
def getListParam(params, param):
  indexOfParam = params.find(param);
  indexOfBracket = params.find("[", indexOfParam);
  value = params[indexOfBracket+1:params.find("]", indexOfBracket)];
  return value;

def addParmIfNotNone(roleProperties, parm, parms):
  value = roleProperties.optString(parm, None);
  if value != None and value != "null" and len(value) > 0:
    value = value.replace(", ", ";");
    if value.find(' ') > -1: value = "\"%s\"" % (value);
    parms = parms + " -" + parm + " " + value;
  return parms;

def setIdMgrCustomProperty(setIdMgrCustomPropertyParams):
  message = AdminTask.setIdMgrCustomProperty(setIdMgrCustomPropertyParams);
  if message.find("CWWIM5028I") == -1 and message.find("CWWIM5027W") == -1:
    print ("Warning: Unexpected result when running command AdminTask.setIdMgrCustomProperty(" + setIdMgrCustomPropertyParams +"). " +
           "Expected message: CWWIM5028I or CWWIM5027W.  Received: " + message);

def getIdMgrLDAPEntityType(params):
  config = AdminTask.getIdMgrLDAPEntityType(params);
  return config;

def addIdMgrLDAPEntityType(addIdMgrLDAPEntityTypeParams):
  message = AdminTask.addIdMgrLDAPEntityType(addIdMgrLDAPEntityTypeParams);
  if message.find("CWWIM5028I") == -1 and message.find("CWWIM5027W") == -1:
    print ("Warning: Unexpected result when running command AdminTask.addIdMgrLDAPEntityType(" + addIdMgrLDAPEntityTypeParams +"). " +
           "Expected message: CWWIM5028I or CWWIM5027W.  Received: " + message);

def listIdMgrLDAPEntityTypes(params):
  entityTypes = AdminTask.listIdMgrLDAPEntityTypes(params);
  # Windows adds \r
  entityTypes = entityTypes.replace('\r','');
  return entityTypes;

def updateIdMgrLDAPEntityType(updateIdMgrLDAPEntityTypeParams):
  message = AdminTask.updateIdMgrLDAPEntityType(updateIdMgrLDAPEntityTypeParams);
  if message.find("CWWIM5028I") == -1 and message.find("CWWIM5027W") == -1:
    print ("Warning: Unexpected result when running command AdminTask.updateIdMgrLDAPEntityType(" + updateIdMgrLDAPEntityTypeParams +"). " +
           "Expected message: CWWIM5028I or CWWIM5027W.  Received: " + message);

def deleteIdMgrLDAPEntityType(deleteIdMgrLDAPEntityTypeParams):
  message = AdminTask.deleteIdMgrLDAPEntityType(deleteIdMgrLDAPEntityTypeParams);
  if message.find("CWWIM5028I") == -1 and message.find("CWWIM5027W") == -1:
    print ("Warning: Unexpected result when running command AdminTask.deleteIdMgrLDAPEntityType(" + deleteIdMgrLDAPEntityTypeParams +"). " +
           "Expected message: CWWIM5028I or CWWIM5027W.  Received: " + message);

def addIdMgrLDAPBackupServer(addIdMgrLDAPBackupServerParams):
  message = AdminTask.addIdMgrLDAPBackupServer(addIdMgrLDAPBackupServerParams);
  if message.find("CWWIM5028I") == -1 and message.find("CWWIM5027W") == -1:
    print ("Warning: Unexpected result when running command AdminTask.addIdMgrLDAPBackupServer(" + addIdMgrLDAPBackupServerParams +"). " +
             "Expected message: CWWIM5028I or CWWIM5027W.  Received: " + message);

def removeIdMgrLDAPBackupServer(removeIdMgrLDAPBackupServerParams):
  message = AdminTask.removeIdMgrLDAPBackupServer(removeIdMgrLDAPBackupServerParams);
  if message.find("CWWIM5028I") == -1 and message.find("CWWIM5027W") == -1:
    print ("Warning: Unexpected result when running command AdminTask.removeIdMgrLDAPBackupServer(" + removeIdMgrLDAPBackupServerParams +"). " +
           "Expected message: CWWIM5028I or CWWIM5027W.  Received: " + message);

def getIdMgrRepository(params):
  config = AdminTask.getIdMgrRepository(params)
  return config;

def listIdMgrRepositoryBaseEntries(params):
  baseEntries = AdminTask.listIdMgrRepositoryBaseEntries(params);
  return baseEntries;

def listIdMgrLDAPServers(params):
  host = AdminTask.listIdMgrLDAPServers(params);
  return host;

def configureAdminWIMUserRegistry(configureAdminWIMUserRegistryParams):
  message = AdminTask.configureAdminWIMUserRegistry(configureAdminWIMUserRegistryParams);
  if len(message) > 0:
    print ("Warning: Unexpected result when running command AdminTask.configureAdminWIMUserRegistry(" + configureAdminWIMUserRegistryParams +"). " +
           "Expected no message. Received: " + message);

def listIdMgrRepositories():
  repolist = AdminTask.listIdMgrRepositories();
  return repolist;

def updateIdMgrLDAPRepository(updateIdMgrLDAPRepositoryParams):
  message = AdminTask.updateIdMgrLDAPRepository(updateIdMgrLDAPRepositoryParams);
  if message.find("CWWIM5028I") == -1 and message.find("CWWIM5027W") == -1:
    print ("Warning: Unexpected result when running command AdminTask.updateIdMgrLDAPRepository(" + updateIdMgrLDAPRepositoryParams +"). " +
           "Expected message: CWWIM5028I or CWWIM5027W.  Received: " + message);

def createIdMgrLDAPRepository(createIdMgrLDAPRepositoryParams):
  message = AdminTask.createIdMgrLDAPRepository(createIdMgrLDAPRepositoryParams);
  if message.find("CWWIM5046W Each configured repository must contain at least one base entry") == -1:
    print ("Warning: Unexpected result when running command AdminTask.createIdMgrLDAPRepository(" + createIdMgrLDAPRepositoryParams +"). " +
           "Expected message: CWWIM5046W Each configured repository must contain at least one base entry. Received: " + message);

def addIdMgrRepositoryBaseEntry(addIdMgrRepositoryBaseEntryParams):
  message = AdminTask.addIdMgrRepositoryBaseEntry(addIdMgrRepositoryBaseEntryParams);
  if message.find("CWWIM5028I") == -1 and message.find("CWWIM5027W") == -1:
    print ("Warning: Unexpected result when running command AdminTask.addIdMgrRepositoryBaseEntry(" + addIdMgrRepositoryBaseEntryParams +"). " +
           "Expected message: CWWIM5028I or CWWIM5027W.  Received: " + message);

def addIdMgrRealmBaseEntry(addIdMgrRealmBaseEntryParams):
  message = AdminTask.addIdMgrRealmBaseEntry(addIdMgrRealmBaseEntryParams);
  if message.find("CWWIM5028I") == -1 and message.find("CWWIM5027W") == -1:
    print ("Warning: Unexpected result when running command AdminTask.addIdMgrRealmBaseEntry(" + addIdMgrRealmBaseEntryParams +"). " +
           "Expected message: CWWIM5028I or CWWIM5027W.  Received: " + message);

def deleteIdMgrRealmBaseEntry(deleteIdMgrRealmBaseEntryParams):
  message = AdminTask.deleteIdMgrRealmBaseEntry(deleteIdMgrRealmBaseEntryParams);
  if message.find("CWWIM5028I") == -1 and message.find("CWWIM5027W") == -1:
    print ("Warning: Unexpected result when running command AdminTask.deleteIdMgrRealmBaseEntry(" + deleteIdMgrRealmBaseEntryParams +"). " +
           "Expected message: CWWIM5028I or CWWIM5027W.  Received: " + message);

def deleteIdMgrRepositoryBaseEntry(deleteIdMgrRepositoryBaseEntryParams):
  message = AdminTask.deleteIdMgrRepositoryBaseEntry(deleteIdMgrRepositoryBaseEntryParams);
  if message.find("CWWIM5028I") == -1 and message.find("CWWIM5027W") == -1:
    print ("Warning: Unexpected result when running command AdminTask.deleteIdMgrRepositoryBaseEntry(" + deleteIdMgrRepositoryBaseEntryParams +"). " +
           "Expected message: CWWIM5028I or CWWIM5027W.  Received: " + message);

def deleteIdMgrRepository(deleteIdMgrRepositoryParams):
  message = AdminTask.deleteIdMgrRepository(deleteIdMgrRepositoryParams);
  if message.find("CWWIM5028I") == -1 and message.find("CWWIM5027W") == -1:
    print ("Warning: Unexpected result when running command AdminTask.deleteIdMgrRepository(" + deleteIdMgrRepositoryParams +"). " +
           "Expected message: CWWIM5028I or CWWIM5027W.  Received: " + message);

def getIdMgrLDAPServer(params):
  config = AdminTask.getIdMgrLDAPServer(params);
  return config;

def listIdMgrLDAPBackupServers(listIdMgrLDAPBackupServersParams):
  failoverServers = AdminTask.listIdMgrLDAPBackupServers(listIdMgrLDAPBackupServersParams);
  return failoverServers;

def listIdMgrCustomProperties(listIdMgrCustomPropertiesParams):
  customProperties = AdminTask.listIdMgrCustomProperties(listIdMgrCustomPropertiesParams);
  return customProperties;

def addIdMgrLDAPServer(addIdMgrLDAPServerParams):
  message = AdminTask.addIdMgrLDAPServer(addIdMgrLDAPServerParams);
  if message.find("CWWIM5028I") == -1 and message.find("CWWIM5027W") == -1:
    print ("Warning: Unexpected result when running command AdminTask.addIdMgrLDAPServer(" + addIdMgrLDAPServerParams +"). " +
           "Expected message: CWWIM5028I or CWWIM5027W.  Received: " + message);

def updateIdMgrLDAPServer(updateIdMgrLDAPServerParams):
  message = AdminTask.updateIdMgrLDAPServer(updateIdMgrLDAPServerParams);
  if message.find("CWWIM5028I") == -1 and message.find("CWWIM5027W") == -1:
    print ("Warning: Unexpected result when running command AdminTask.updateIdMgrLDAPServer(" + updateIdMgrLDAPServerParams +"). " +
           "Expected message: CWWIM5028I or CWWIM5027W.  Received: " + message);

def createIdMgrCustomRepository(createIdMgrCustomRepositoryParams):
  message = AdminTask.createIdMgrCustomRepository(createIdMgrCustomRepositoryParams);
  if message.find("CWWIM5046W Each configured repository must contain at least one base entry") == -1:
    print ("Warning: Unexpected result when running command AdminTask.createIdMgrCustomRepository(" + createIdMgrCustomRepositoryParams +"). " +
           "Expected message: CWWIM5046W Each configured repository must contain at least one base entry.  Received: " + message);

def createIdMgrFileRepository(createIdMgrFileRepositoryParams):
  message = AdminTask.createIdMgrFileRepository(createIdMgrFileRepositoryParams);
  if message.find("CWWIM5046W Each configured repository must contain at least one base entry") == -1:
    print ("Warning: Unexpected result when running command AdminTask.createIdMgrFileRepository(" + createIdMgrFileRepositoryParams +"). " +
           "Expected message: CWWIM5046W Each configured repository must contain at least one base entry.  Received: " + message);

def updateIdMgrFileRepository(updateIdMgrFileRepositoryParams):
  message = AdminTask.updateIdMgrFileRepository(updateIdMgrFileRepositoryParams);
  if message.find("CWWIM5028I") == -1 and message.find("CWWIM5027W") == -1:
    print ("Warning: Unexpected result when running command AdminTask.updateIdMgrFileRepository(" + updateIdMgrFileRepositoryParams +"). " +
           "Expected message: CWWIM5028I or CWWIM5027W.  Received: " + message);

def updateIdMgrRepository(updateIdMgrRepositoryParams):
  message = AdminTask.updateIdMgrRepository(updateIdMgrRepositoryParams);
  if message.find("CWWIM5028I") == -1 and message.find("CWWIM5027W") == -1:
    print ("Warning: Unexpected result when running command AdminTask.updateIdMgrRepository(" + updateIdMgrRepositoryParams +"). " +
           "Expected message: CWWIM5028I or CWWIM5027W.  Received: " + message);

def updateIdMgrRepositoryBaseEntry(updateIdMgrRepositoryBaseEntryParams):
  message = AdminTask.updateIdMgrRepositoryBaseEntry(updateIdMgrRepositoryBaseEntryParams);
  if message.find("CWWIM5028I") == -1 and message.find("CWWIM5027W") == -1:
    print ("Warning: Unexpected result when running command AdminTask.updateIdMgrRepositoryBaseEntry(" + updateIdMgrRepositoryBaseEntryParams +"). " +
           "Expected message: CWWIM5028I or CWWIM5027W.  Received: " + message);

# returns a list where the first value is distinguished name of the base entry
# and the second value is the distinguished name of a subtree in the main repository
def interpretBaseEntries(baseEntries):
  # baseEntries are returned by AdminTask.listIdMgrRepositoryBaseEntries()
  # The format is name=nameInRepository (name and nameInRepository separated by an equal sign).
  # This can get ugly, as names and nameInRepository may contain a series of values each containing equal signs
  # For example, we can receive base entries in formats such as:
  # example 1: {o=ibm.com=o=ibm.com}
  # example 2: {o=test.com,uid=ibm.com=o=one.com,uid=two.com}
  # example 3: {o=test.com=o=one.com,uid=two.com}
  # example 4: {o=test.com,uid=ibm.com=o=one.com}
  # To split this string into name and nameInRepository, find the set of three equal signs
  # that don't have a comma between them, then split on that second equal sign

  formattedBaseEntries = [];
  # First, remove the brackets if needed
  if baseEntries.find("{", 0, 1) != -1:
    baseEntries = baseEntries[1:-1];
  # There is a special case for the built-in InternalFileRepository.
  # It's format is {o=defaultWIMFileBasedRealm=null}
  if baseEntries.endswith("=null"):
    name = baseEntries[0:baseEntries.find("=null")];
    formattedBaseEntries.append(name);
    formattedBaseEntries.append("null");
  else:
    numberOfEqualSigns = baseEntries.count("=");
    i = 0;
    indexOfEqualSign1 = baseEntries.index("=");
    while i < numberOfEqualSigns:
      indexOfEqualSign2 = baseEntries.find("=", indexOfEqualSign1+1);
      indexOfEqualSign3 = baseEntries.find("=", indexOfEqualSign2+1);
      indexOfNextComma = baseEntries.find(",", indexOfEqualSign1+1);
      if (indexOfEqualSign1 != -1 and
          indexOfEqualSign2 != -1 and
          indexOfEqualSign3 != -1):
        if (indexOfNextComma == -1 or
            indexOfEqualSign3 < indexOfNextComma):
          name = baseEntries[0:indexOfEqualSign2];
          nameInRepository = baseEntries[indexOfEqualSign2+1:];
          formattedBaseEntries.append(name);
          formattedBaseEntries.append(nameInRepository);
          break;
      indexOfEqualSign1 = indexOfEqualSign2;
      i = i + 1;
  return formattedBaseEntries;

def listIdMgrSupportedEntityTypes():
  return AdminTask.listIdMgrSupportedEntityTypes();

def getIdMgrSupportedEntityType(getIdMgrSupportedEntityTypeParams):
  return AdminTask.getIdMgrSupportedEntityType(getIdMgrSupportedEntityTypeParams);

def updateIdMgrSupportedEntityType(updateIdMgrSupportedEntityTypeParams):
  message = AdminTask.updateIdMgrSupportedEntityType(updateIdMgrSupportedEntityTypeParams);
  if message.find("CWWIM5028I") == -1 and message.find("CWWIM5027W") == -1 and message.find("CWWIM5048W") == -1:
    print ("Warning: Unexpected result when running command AdminTask.updateIdMgrSupportedEntityType(" + updateIdMgrSupportedEntityTypeParams +"). " +
           "Expected message: CWWIM5028I or CWWIM5027W or CWWIM5048W.  Received: " + message);

def getRealmURAttrMappings():
  realmURAttrMappings = [];
  attMappings = AdminTask.listIdMgrRealmURAttrMappings();
  # remove brackets
  attMappings = attMappings[1:-2];
  attMappings = attMappings.split("}, ");
  # attMapping may be in the format:
  #   {userDisplayName={propertyForInput=MyIN, propertyForOutput=MyOUT}
  # or
  #   {userDisplayName={propertyForOutput=MyOUT, propertyForInput=MyIN}
  for attMapping in attMappings:
    attribute = attMapping[0:attMapping.find("=")];
    propertyForOutputIndex = attMapping.find("propertyForOutput=");
    propertyForInputIndex = attMapping.find("propertyForInput=");
    if propertyForInputIndex > propertyForOutputIndex:
      propertyForOutput = attMapping[attMapping.find("propertyForOutput=")+18:attMapping.find(", propertyForInput")];
      propertyForInput = attMapping[attMapping.find("propertyForInput=")+17:];
    else:
      propertyForInput = attMapping[attMapping.find("propertyForInput=")+17:attMapping.find(", propertyForOutput")];
      propertyForOutput = attMapping[attMapping.find("propertyForOutput=")+18:];
    mapping = [attribute, propertyForOutput, propertyForInput];
    realmURAttrMappings.append(mapping);
  return realmURAttrMappings;

def setIdMgrRealmURAttrMapping(setIdMgrRealmURAttrMappingParams):
  message = AdminTask.setIdMgrRealmURAttrMapping(setIdMgrRealmURAttrMappingParams);
  if message.find("CWWIM5028I") == -1 and message.find("CWWIM5027W") == -1:
    print ("Warning: Unexpected result when running command AdminTask.updateIdMgrLDAPServer(" + setIdMgrRealmURAttrMappingParams +"). " +
           "Expected message: CWWIM5028I or CWWIM5027W.  Received: " + message);

def getApplicableTypes(pluginxmlloc):
  if len(__applicableTypes__) == 0:
    searchstartfor = "<server:role>";
    searchendfor = "</server:role>";
    f = open(pluginxmlloc);
    line = f.readline();
    while line != "":
      startInd = line.find(searchstartfor);
      endInd = line.find(searchendfor);
      if startInd != -1 and endInd != -1:
        applicableType = roleNameToType(line[startInd+len(searchstartfor):endInd]);
        __applicableTypes__[applicableType] = applicableType;
      line = f.readline();
  return __applicableTypes__;

def getAdminConfigTypes():
  adminConfigTypes = AdminConfig.types().splitlines();
  for customObjectType in customObjectTypes:
    adminConfigTypes.append(customObjectType);
  return adminConfigTypes;

def createClusterMember(clustername, nodename, servername):
  Util = sys.modules[__name__];
  clusid = Util.getid("/ServerCluster:%s/" % clustername);
  if clusid is None or clusid.strip() == "":
    nodeserverlist = [nodename, servername];
    if Util.__clustermemberstocreate__.has_key(clustername):
      Util.__clustermemberstocreate__[clustername].append(nodeserverlist);
    else:
      Util.__clustermemberstocreate__[clustername]= [nodeserverlist];
  else:
    Log.redo("AdminTask.createClusterMember('[-clusterName \"%(clus)s\" -memberConfig [-memberNode \"%(node)s\" -memberName \"%(ser)s\"]]')" % { 'clus':clustername, 'node':nodename, 'ser':servername });
    AdminTask.createClusterMember('[-clusterName "%(clus)s" -memberConfig [-memberNode "%(node)s" -memberName "%(ser)s"]]' % { 'clus':clustername, 'node':nodename, 'ser':servername });

def getSecurityScopename(objid):
  Util = sys.modules[__name__];
  cellid = Util.getid("/Cell:/");
  cellname = AdminConfig.showAttribute(cellid, 'name');
  if objid.find("#Cell_") != -1:
    return "(cell):%s" % cellname;
  elif objid.find("/dynamicclusters/") != -1:
    if objid.find("#ServerEntry_") != -1:
      serverName = AdminConfig.showAttribute(objid, 'serverName');
      return "(cell):%(cell)s:(cluster):%(cluster)s" % { 'cell':cellname, 'cluster':serverName };
    else:
      name = AdminConfig.showAttribute(objid, 'name');
      return "(cell):%(cell)s:(cluster):%(cluster)s" % { 'cell':cellname, 'cluster':name };
  elif objid.find("#Node_") != -1:
    name = AdminConfig.showAttribute(objid, 'name');
    return "(cell):%(cell)s:(node):%(node)s" % { 'cell':cellname, 'node':name };
  elif objid.find("#ServerCluster_") != -1:
    name = AdminConfig.showAttribute(objid, 'name');
    return "(cell):%(cell)s:(cluster):%(cluster)s" % { 'cell':cellname, 'cluster':name };
  elif objid.find("#Server_") != -1:
    name = AdminConfig.showAttribute(objid, 'name');
    nodename = Util.getNodeName(objid);
    return "(cell):%(cell)s:(node):%(node)s:(server):%(server)s" % { 'cell':cellname, 'node':nodename, 'server':name };
  elif objid.find("#ServerEntry_") != -1:
    serverName = AdminConfig.showAttribute(objid, 'serverName');
    nodename = Util.getNodeName(objid);
    return "(cell):%(cell)s:(node):%(node)s:(server):%(server)s" % { 'cell':cellname, 'node':nodename, 'server':serverName };
  elif objid.find("#NodeGroup_") != -1 or objid.find("#builtin_DefaultNodeGroup") != -1 or objid.find("#builtin_NodeGroup_") != -1:
    name = AdminConfig.showAttribute(objid, 'name');
    return "(cell):%(cell)s:(nodeGroup):%(nodeGroup)s" % { 'cell':cellname, 'nodeGroup':name };
  return None;

def getSecurityObjId():
  cellId = getid("/Cell:/");
  cellName = AdminConfig.showAttribute(cellId, 'name');
  securityObjId = getid("/Cell:%s/Security:/" % cellName);
  return securityObjId;

def getNodeName(serid):
  if serid.find("/nodes/") == -1:
    raise Exception("Failed to determine the node name for " + str(serid));
  else:
    Util = sys.modules[__name__];
    #find the nodeid for the server
    #parse node name from the serid... i'm sorry...
    serScope = Util.getScope(serid);
    #CloudBurstCell_1/nodes/CloudBurstNode_3/servers/KASCLUSTER_1
    nodenamestartidx = serScope.find("/nodes/") + 7;
    nodenameendidx = serScope.find("/", nodenamestartidx);
    nodename = serScope[nodenamestartidx:nodenameendidx];
    return nodename;

def getNodeNameList(nodes):
  Util = sys.modules[__name__];
  nodenamelist = []
  if nodes is None or nodes.strip() == "" or nodes.strip() == "*":
    nodeobjids = Util.getid("/Node:/")
    for nodeobj in nodeobjids.splitlines():
      nodenamelist.append(Util.getRequiredAttribute(nodeobj, "name", "Node"))
  else:
    nodenamelist = nodes.split(",")
  return nodenamelist

def getServerNameFormats(servernameformats):
  nameformats = {}
  if servernameformats is not None:
    nameformatstringlist = servernameformats.splitlines()
    for nameformatstring in nameformatstringlist:
      namefmtparts = nameformatstring.split("->", 2)
      nameformats[namefmtparts[0]] = namefmtparts[1]

  return nameformats

def getTimeStampFromObjectId(objid):
  #len -1 to remove trailing )
  #(cells/CloudBurstCell_1|security.xml#JAASLoginModule_12)
  if objid is not None and len(objid) > 0:
    return long(objid[objid.rfind("_")+1:len(objid)-1]);
  return None;

def moveClusterToCoreGroup(clustername, sourcecgname, targetcgname):
  objMap = { 'src':sourcecgname, 'tar':targetcgname, 'clus':clustername };
  Log.debug('Moving cluster "%(clus)s" to coregroup "%(tar)s" from "%(src)s"' % objMap);
  AdminTask.moveClusterToCoreGroup('[ -source "%(src)s" -target "%(tar)s" -clusterName "%(clus)s" -checkConfig false ]' % objMap);

def moveServerToCoreGroup(servername, nodeName, sourcecgname, targetcgname):
  objMap = { 'src':sourcecgname, 'tar':targetcgname, 'ser':servername, 'nod': nodeName };
  Log.debug('Moving server "%(nod)s:%(ser)s" to coregroup "%(tar)s" from "%(src)s"' % objMap);
  AdminTask.moveServerToCoreGroup('[ -source "%(src)s" -target "%(tar)s" -serverName "%(ser)s" -nodeName "%(nod)s" ]' % objMap);

def getClusterNameForServer(servername, nodename):
  serverClusters = getid('/ServerCluster:/');
  if serverClusters is not None:
    serverClusters = serverClusters.splitlines();
    for y in serverClusters:
      clustername = getRequiredAttribute(y, 'name', 'ServerCluster');
      clusterMembers = getid("/ServerCluster:%s/ClusterMember:/" % clustername)
      if clusterMembers is not None:
        clusterMembers = clusterMembers.splitlines();
        for x in clusterMembers:
          curSerName = getRequiredAttribute(x, 'memberName', 'ClusterMember');
          curNodeName = getRequiredAttribute(x, 'nodeName', 'ClusterMember');
          if curSerName == servername and curNodeName == nodename:
            return clustername;
  return None;

def getEndPointMappings(epmappingstring):
  epmappings = None
  if epmappingstring is not None and epmappingstring.strip() != "":
    epmappings = []
    for x in epmappingstring.splitlines():
      mapparts = x.split("->", 3)
      epname = mapparts[0]
      ephost = mapparts[1]
      epport = mapparts[2]
      epmappings.append([epname, ephost, epport])

  return epmappings

# used when attributes and values are returned as a ", " (comma space) separated string
# and values may also contain ", ".  For example:
# "port=999, connectionPool=false, bindDN=cn=something, ou=Something Else, referal=ignore";
def getAttributeValueListFromString(providedString, validAttributes):
  # create a list of all attributes and their index in conifg. Example:
  # [['connectionPool', 32], ['referal', 138], ['port', 10]]
  allEntries = [];
  for att in validAttributes:
    oneEntry = [];
    # get the index of the attriubute in config
    index = providedString.find(att);
    # only add it to our list if it appears in providedString
    if index != -1:
      oneEntry.append(att);
      oneEntry.append(index);
      allEntries.append(oneEntry);

  # build a copy of allEntries
  copyAllEntries = [];
  for x in allEntries:
    copyAllEntries.append(x);

  # sort the list on the index value
  allEntriesSorted = [];
  earliestEntry = [];
  for y in allEntries:
    smallestIndex = len(providedString);
    for ent in copyAllEntries:
      index = ent[1];
      if index < smallestIndex:
        earliestEntry = ent;
        smallestIndex = index;
    allEntriesSorted.append(earliestEntry);
    copyAllEntries.remove(earliestEntry);

  # build a list of [attribute, value]
  attValueList = [];
  lastEntry = len(allEntriesSorted) - 1;
  i = 0;
  while i < len(allEntriesSorted):
    attValue = [];
    entry = allEntriesSorted[i];
    attName = entry[0];
    valueStart = entry[1] + len(attName) + 1;
    if i == lastEntry:
      value = providedString[valueStart:]
    else:
      # get the index of the following entry
      nextEntryIndex = allEntriesSorted[i + 1][1];
      valueEnd = nextEntryIndex - 2;
      value = providedString[valueStart:valueEnd]
    attValue.append(attName);
    attValue.append(value);
    attValueList.append(attValue);
    i = i + 1;
  return attValueList;

def filterExportForTypes(resourceJSONArray, applicableTypes, configurationTypes):
  Util = sys.modules[__name__];
  if len(configurationTypes) == 0:
    return resourceJSONArray;
  filteredArray = JSONArray();
  treemap = TreeMap();
  typemap = HashMap();
  MapHelper = __import__("utilities.MapHelper").MapHelper;
  mapHelper = MapHelper.MapHelper(treemap);  # @UndefinedVariable
  addedpaths = {};
  for i in range(resourceJSONArray.length()):
    resourceJSONObject = resourceJSONArray.getJSONObject(i);
    thispath = resourceJSONObject.getString('path');
    Log.debug("Path in export json '%s'" % thispath);
    mapHelper.put(thispath, resourceJSONObject);
    reslist = None;
    if resourceJSONObject.has('roleName'):
      thisrole = resourceJSONObject.getString('roleName');
      thistype = Util.roleNameToType(thisrole);
      if typemap.containsKey(thistype):
        reslist = typemap.get(thistype);
      else:
        reslist = [];
        typemap.put(thistype, reslist);
      reslist.append(thispath);

  for configType in configurationTypes.keys():
    if typemap.containsKey(configType):
      reslist = typemap.get(configType);
      for resourcepath in reslist:
        resourceToExportPath = mapHelper.findHighestNoneApplicablePath(resourcepath, applicableTypes);
        if not addedpaths.has_key(resourceToExportPath):
          filteredArray.put(mapHelper.get(resourceToExportPath));
          addedpaths[resourceToExportPath] = resourceToExportPath;

        for resourceJSON in mapHelper.getDescendentsFromTreeMap(resourceToExportPath).values():
          curpath = resourceJSON.getString("path");
          if not addedpaths.has_key(curpath):
            filteredArray.put(resourceJSON);
            addedpaths[curpath] = curpath;

        for resourceJSON in mapHelper.getAncestorsFromTreeMap(resourceToExportPath):
          curpath = resourceJSON.getString("path");
          if not addedpaths.has_key(curpath):
            filteredArray.put(resourceJSON);
            addedpaths[curpath] = curpath;

  return filteredArray;

def formatConfigurationTypes(configurationTypes, fromDelimiter=",", toDelimiter="\n"):
  if not configurationTypes:
    return configurationTypes

  #1. remove all whitespace
  #2. change all literal "\n" into actual newlines so that they are treated as such later (ie .splitlines() works)
  #3. from and to delimiters after all the preprocessing work
  #4. strip any trailing whitespace/newlines
  return configurationTypes.replace(" ", "").replace("\\n", "\n").replace(fromDelimiter, toDelimiter).strip()

def exportObjectToResources(stack, objectsDir, objdir, objid, respath, containmentpath, roleName, limitDiscovery, typePaths = None):
  # build a list of objects to skip
  # objects in this list will not be discovered if they are in the children file of a object
  skipList = []
  if limitDiscovery == "Cell":
    skipList.append("Node");
    skipList.append("ServerCluster");
    skipList.append("DynamicCluster");
    skipList.append("Server");
  if limitDiscovery == "Cell and Clusters":
    skipList.append("Node");
    skipList.append("Server");
  if limitDiscovery == "Node":
    skipList.append("Server");
  Log.logMsg("Config objects in the skipList which will not be discovered: " + str(skipList), Log.LogLevelDebug);

  Util = sys.modules[__name__];
  stack.append(roleName);
  finalResult = JSONArray();
  if typePaths is not None:
    if stack not in typePaths:
      Log.debug("Skiping type path %s" % stack);
      stack.pop();
      return finalResult;
  mod = Util.getRoleModule(roleName);
  if mod is not None:
    if 'export' in dir(mod):
      #some objects are reliant on their parents to export them, so they don't implement an export method
      execFileDict = mod.export(objid, containmentpath, respath);
      dictKeys = execFileDict.keys();
      if 'object' in dictKeys:
        exportedObject = execFileDict['object']
        curcontainmentpath = execFileDict['conpath'];
        Log.debug("Exported %s" % curcontainmentpath)
        currespath = execFileDict['respath'];
        if exportedObject != None:
          typeFolders = {}
          for childtype in Util.getChildrenTypesFromDirectory(objdir):
            if childtype not in skipList:
              folderadded = 0;
              folderobject = None;
              if childtype != "" and Util.isValidType(childtype):
                childdir = Util.findObjectDir(childtype, objectsDir);
                childsearchpath = "%(curpath)s%(type)s:/" % { 'curpath': curcontainmentpath, 'type':childtype }
                Log.debug("Checking child searchpath %s" % childsearchpath);
                for x in Util.getid(childsearchpath).splitlines():
                  returndict = Util.createTypeFolder(currespath, childtype, typeFolders);
                  if returndict.has_key('object'):
                    folderobject = returndict['object'];
                  curchildrespath = returndict['path'];
                  Log.debug("Exporting %s" % x);
                  curresources = Util.exportObjectToResources(stack, objectsDir, childdir, x, curchildrespath, curcontainmentpath, childtype, limitDiscovery, typePaths)
                  if curresources is not None:
                    if not folderadded and folderobject is not None:
                      folderadded = 1;
                      Util.addFromExport(finalResult, folderobject);
                    for y in range(curresources.length()):
                      Util.addFromExport(finalResult, curresources.get(y));
          Util.addAllFromExport(finalResult, execFileDict);
  stack.pop();
  return finalResult

def readPassword(id, attrName, objType):
  found=0;
  objMap = { 'objID':id, 'attr':attrName, 'type':objType };
  Log.debug('Retrieving password for %(type)s %(objID)s.%(attr)s' % objMap );

  if (id.find('(') > -1):
    id = id[id.find('(')+1:len(id)]
  if (id.find(')') > 0):
    id = id[0:id.find(')')]

  configService = ConfigServiceFactory.getConfigService()
  if (configService is None):
    Log.debug('Creating ConfigService');
    props = Properties();
    props.setProperty("location", "local");
    configService = ConfigServiceFactory.createConfigService(1, props);
  #endIf
  Log.debug('ConfigService has been created');
  session = com.ibm.websphere.management.Session()

  objectNameMatches = configService.resolve(session, objType)
  # find the object who's id matches
  attrValue = None
  for objectName in objectNameMatches:
    thisConfigId = objectName.getKeyProperty('_Websphere_Config_Data_Id')
    Log.debug("Comparing ids found:" + str(thisConfigId) + " match against:" + str(id))
    if (thisConfigId == id):
      found=1;
      Log.debug("resolved object " + str(objectName))
      attrValue = configService.getAttribute(session, objectName, attrName)
    #endIf
  #endFor

  if not found:
    message = 'Unable to retrieve password for %(type)s (objID)s.%(attr)s' % objMap;
    Log.logMsg(message, Log.LogLevelWarn);

  configService.discard(session)

  #encrypted = CryptStringUtil.encrypt(attrValue);
  #roundtrip = CryptStringUtil.decrypt(encrypted);
  #objMap = { 'attrValue':attrValue, 'encrypted':encrypted, 'roundtrip':roundtrip };
  #Log.debug("Cleartext: %(attrValue)s  Encrypted: %(encrypted)s RoundTrip: %(roundtrip)s" % objMap);

  if attrValue is None:
    attrValue = "";

  return str(attrValue)
#endDef

# modify config data (JSON) so attributes that are never updated by our code
# do not show as differences during live compare
def modifyJsonForAttributesToNotUpdate(jsonObj, objType):
  attributesToNotUpdateForObject = getAttributesToNotUpdateForObject(objType)
  # get the role properties from the JSONObject
  roleProperties = jsonObj.optJSONObject("roleProperties")
  for attribute in attributesToNotUpdateForObject:
    roleProperty = roleProperties.optString(attribute);
    if roleProperty is not None and roleProperty is not "":
      roleProperties.put(attribute, "Value suppressed during comparison")
  return jsonObj;

def removeAttributesToNotUpdate(origJSONArray):
  # get list of objects (roleNames) which have one or more attributes we don't want to update
  objectsWithAttributesToNotUpdateList = getObjectsWithAttributesToNotUpdateList();

  # go through the JSON checking to see if the the roleName property is in our list
  jObj = origJSONArray.getJSONObject(0)
  for x in range(origJSONArray.length()):
    jObj = origJSONArray.getJSONObject(x)
    # get the role name
    testName = jObj.optString("name");
    roleName = jObj.optString("roleName");
    if roleName is not None and roleName is not "" and roleName in objectsWithAttributesToNotUpdateList:
      # trim "WebSphere" from role name
      objType = roleName[9:];
      updatedRootChild = modifyJsonForAttributesToNotUpdate(jObj, objType);
      origJSONArray.put(updatedRootChild)
  return origJSONArray;

# get all of the attributes that should never be updated for a specific object type
def getAttributesToNotUpdateForObject(objType):
  attributesToNotUpdate = getAttributesToNotUpdate();
  attributeList = [];
  for att in attributesToNotUpdate:
    if objType == att[0]:
      attributeList.append(att[2]);
  return attributeList;

def getAttributesToNotUpdate():
  return attributesToNotUpdate;

# return a list of object types from attributesToNotUpdate
# object types are returned with the WebSphere prefix
def getObjectsWithAttributesToNotUpdateList():
  objectsWithAttributesToNotUpdateList = [];
  for att in attributesToNotUpdate:
    targetRoleName = "WebSphere" + str(att[0]);
    # make sure we don't add the same object type multiple times
    if targetRoleName not in objectsWithAttributesToNotUpdateList:
      objectsWithAttributesToNotUpdateList.append(targetRoleName)
  return objectsWithAttributesToNotUpdateList;

# attributesToNotUpdate is in the format objectType,attributeName,JsonRoleProperty
# during an apply, we don't know the JsonRoleProperty
# so, let's build a list in the format objectType:attributeName
# so we may easily identify attributes to not modify during an apply
def getAttributesToNotUpdateDuringApply():
  attributesToNotUpdateDuringApply = [];
  for att in attributesToNotUpdate:
    listItem = str(att[0]) + ":" + str(att[1]);
    attributesToNotUpdateDuringApply.append(listItem)
  return attributesToNotUpdateDuringApply;

def setAttributesToNotUpdateDuringApply():
  Util = sys.modules[__name__];
  Util.__attributesToNotUpdateDuringApply__ = getAttributesToNotUpdateDuringApply();

# list of attributes that we do not update duing an apply
# format is [objectType,attributeName,JsonRoleProperty]
attributesToNotUpdate = [
  ['Connector','version','websphere.connector.version'],
  ['CoreGroup','coreGroupUID','websphere.coregroup.coregroupuid'],
  ['DataSource','providerType','websphere.datasource.providertype'],
  ['JDBCProvider','providerType','websphere.jdbcprovider.providertype']
]

# object types that are not part of WebSphere Common Configuration Model
customObjectTypes = [
  'LDAPRepository',
  'LDAPCustomProperty',
  'LDAPEntityType',
  'LDAPFailoverServer',
  'LDAPServer',
  'CustomRepository',
  'RepositoryCustomProperty',
  'FileRepository',
  'FederatedRepositoryAttributeMapping',
  'SupportedEntityType'
  ];

typeNameToFolderNameMap = {
  'AccessPointGroup': 'Access Point Groups',
  'Action': 'Actions',
  'ActivationSpec': 'Activation Specs',
  'ActivationSpecTemplateProps': 'Activation Spec Template Props',
  'ActiveAffinityType': 'Active Affinity Types',
  'ActivitySessionService': 'Services',
  'AdminAgentRegistration': 'Admin Agent Registrations',
  'AdminObject': 'Admin Objects',
  'AdminObjectRef': 'Admin Object Refs',
  'AdminObjectTemplateProps': 'Admin Object Template Props',
  'AdminServerAuthentication': 'Admin Server Authentications',
  'AdminService': 'Services',
  'AffinityType': 'Affinity Types',
  'AgeCondition': 'Age Conditions',
  'Agent': 'Agents',
  'AllActivePolicy': 'All Active Policies',
  'AllAuthenticatedUsersExt': 'All Authenticated Users Exts',
  'AllAuthenticatedUsersInTrustedRealmsExt': 'All Authenticated Users In Trusted Realms Exts',
  'AppAudit': 'App Audits',
  'AppPlacementController': 'Services',
  'AppSecurity': 'App Securities',
  'Application': 'Applications',
  'ApplicationClientFile': 'Application Client Files',
  'ApplicationConfig': 'Application Configs',
  'ApplicationContainer': 'Application Containers',
  'ApplicationDeployment': 'Application Deployments',
  'ApplicationManagementService': 'Services',
  'ApplicationProfileService': 'Services',
  'ApplicationResources': 'Application Resources',
  'ApplicationServer': 'Application Servers',
  'ApplicationServerClusterMapping': 'Application Server Cluster Mappings',
  'ApplicationServerClusterMember': 'Application Server Cluster Members',
  'ApplicationServerEndpoint': 'Application Server Endpoints',
  'ApplicationServerMapping': 'Application Server Mappings',
  'ApplicationServerRoute': 'Application Server Routes',
  'ApplicationServerTimeMapping': 'Application Server Time Mappings',
  'Archive': 'Archives',
  'Audit': 'Audits',
  'AuditCommon': 'Audit Commons',
  'AuditEventFactory': 'Audit Event Factories',
  'AuditNotificationMonitor': 'Audit Notification Monitors',
  'AuditPolicy': 'Audit Policies',
  'AuditServiceProvider': 'Audit Service Providers',
  'AuditSpecification': 'Audit Specifications',
  'AuthConfigProvider': 'Auth Config Providers',
  'AuthConfigProviderEntry': 'Auth Config Provider Entries',
  'AuthMechanism': 'Auth Mechanisms',
  'AuthModule': 'Auth Modules',
  'AuthenticationMechanism': 'Authentication Mechanisms',
  'AuthenticationTarget': 'Authentication Targets',
  'AuthorizationConfig': 'Authorization Configs',
  'AuthorizationGroup': 'Authorization Groups',
  'AuthorizationGroupMember': 'Authorization Group Members',
  'AuthorizationProvider': 'Authorization Providers',
  'AuthorizationTableExt': 'Authorization Table Exts',
  'AuthorizationTableImpl': 'Authorization Table Impls',
  'AutonomicRequestFlowManager': 'Autonomic Request Flow Managers',
  'AverageResponseTimeGoal': 'Average Response Time Goals',
  'BackupCluster': 'Backup Clusters',
  'BridgeInterface': 'Bridge Interfaces',
  'CACertificate': 'CA Certificates',
  'CAClient': 'CA Clients',
  'CEASettings': 'CEA Settings',
  'CMPConnectorFactory': 'CMP Connector Factories',
  'CORBAObjectNameSpaceBinding': 'CORBA Object Name Space Bindings',
  'CTIGateway': 'CTI Gateways',
  'CacheInstance': 'Cache Instances',
  'CacheInstanceService': 'Services',
  'CacheProvider': 'Cache Providers',
  'CachingAction': 'Caching Actions',
  'CellManager': 'Cell Managers',
  'CellRoute': 'Cell Routes',
  'CentralizedInstallManager': 'Centralized Install Managers',
  'Certificate': 'Certificates',
  'Chain': 'Chains',
  'Checkpoint': 'Checkpoints',
  'CheckpointDocument': 'Checkpoint Documents',
  'Classloader': 'Classloaders',
  'ClientModuleDeployment': 'Client Module Deployments',
  'ClientModuleRef': 'Client Module Refs',
  'ClientSecurityProperties': 'Client Security Properties',
  'ClusterAddressEndPoint': 'Cluster Address End Points',
  'ClusterAddressProperties': 'Cluster Address Properties',
  'ClusterAdvisor': 'Cluster Advisors',
  'ClusterMember': 'Cluster Members',
  'ClusteredTarget': 'Clustered Targets',
  'CommonSecureInterop': 'Common Secure Interops',
  'Commsvc': 'Commsvcs',
  'CompatibilityDescriptionGroup': 'Compatibility Description Groups',
  'CompensationService': 'Services',
  'CompletionTimeGoal': 'Completion Time Goals',
  'Component': 'Components',
  'CompressionAction': 'Compression Actions',
  'ConfigProperty': 'Config Properties',
  'ConfigSynchronizationService': 'Services',
  'ConnectionDefTemplateProps': 'Connection Def Template Props',
  'ConnectionDefinition': 'Connection Definitions',
  'ConnectionPool': 'Connection Pools',
  'ConnectionTest': 'Connection Tests',
  'Connector': 'Connectors',
  'ConnectorModuleDeployment': 'Connector Module Deployments',
  'ConnectorModuleRef': 'Connector Module Refs',
  'Container': 'Containers',
  'ContentMapping': 'Content Mappings',
  'Contributor': 'Contributors',
  'Cookie': 'Cookies',
  'CookieMapping': 'Cookie Mappings',
  'CoreGroup': 'Core Groups',
  'CoreGroupAccessPoint': 'Core Group Access Points',
  'CoreGroupBridgeService': 'Services',
  'CoreGroupBridgeSettings': 'Core Group Bridge Settings',
  'CoreGroupServer': 'Core Group Servers',
  'CoreGroupServerRef': 'Core Group Server Refs',
  'CryptoHardwareToken': 'Crypto Hardware Tokens',
  'CustomAdvisor': 'Custom Advisors',
  'CustomAdvisorMapping': 'Custom Advisor Mappings',
  'CustomAdvisorPolicy': 'Custom Advisor Policies',
  'CustomAuthMechanism': 'Custom Auth Mechanisms',
  'CustomConditionTemplate': 'Custom Condition Templates',
  'CustomConditionTemplates': 'Custom Condition Templates Sets',
  'CustomElasticityAction': 'Custom Elasticity Actions',
  'CustomErrorPagePolicy': 'Custom Error Page Policies',
  'CustomHealthAction': 'Custom Health Actions',
  'CustomProcessDefs': 'Custom Process Defs',
  'CustomRepository' : 'Custom Repositories',
  'CustomService': 'Services',
  'CustomUserRegistry': 'Custom User Registries',
  'DCSInboundChannel': 'Channels',
  'DPClonableDeviceSettings': 'DP Clonable Device Settings',
  'DPClonableDeviceSettingsVersion': 'DP Clonable Device Settings Versions',
  'DPDeployableConfiguration': 'DP Deployable Configurations',
  'DPDevice': 'DP Devices',
  'DPDomain': 'DP Domains',
  'DPDomainVersion': 'DP Domain Versions',
  'DPFirmware': 'DP Firmwares',
  'DPFirmwareVersion': 'DP Firmware Versions',
  'DPManagedSet': 'DP Managed Sets',
  'DPManager': 'DP Managers',
  'DPVersion': 'DP Versions',
  'DRSConnectionPool': 'DRS Connection Pools',
  'DRSPartition': 'DRS Partitions',
  'DRSSerialization': 'DRS Serializations',
  'DRSSettings': 'DRS Settings',
  'DataPowerMgrInboundChannel': 'Channels',
  'DataReplication': 'Data Replications',
  'DataReplicationDomain': 'Data Replication Domains',
  'DataSource': 'Data Sources',
  'DataSourceDefinition': 'Data Source Definitions',
  'DataStoreProfile': 'Data Store Profiles',
  'DebugService': 'Services',
  'DefaultSIPApplicationRouter': 'Default SIP Application Routers',
  'DeployedMiddlewareApp': 'Deployed Middleware Apps',
  'DeployedMiddlewareAppEdition': 'Deployed Middleware App Editions',
  'DeployedObject': 'Deployed Objects',
  'DeployedObjectConfig': 'Deployed Object Configs',
  'DeployedObjectProxyConfig': 'Deployed Object Proxy Configs',
  'Deployment': 'Deployments',
  'DeploymentTarget': 'Deployment Targets',
  'DeploymentTargetMapping': 'Deployment Target Mappings',
  'Description': 'Descriptions',
  'DescriptionGroup': 'Description Groups',
  'DescriptiveProperty': 'Descriptive Properties',
  'DescriptivePropertyGroup': 'Descriptive Property Groups',
  'DiagnosticProviderService': 'Services',
  'DigestAuthentication': 'Digest Authentications',
  'DiscoverableDescriptiveProperty': 'Discoverable Descriptive Properties',
  'DiscretionaryGoal': 'Discretionary Goals',
  'DiskCacheCustomPerformanceSettings': 'Disk Cache Custom Performance Settings',
  'DiskCacheEvictionPolicy': 'Disk Cache Eviction Policies',
  'DisplayDescriptor': 'Display Descriptors',
  'DisplayName': 'Display Names',
  'DistributionQueue': 'Distribution Queues',
  'DynamicCache': 'Services',
  'DynamicCluster': 'Dynamic Clusters',
  'DynamicReload': 'Dynamic Reloads',
  'DynamicSSLConfigSelection': 'Dynamic SSL Config Selections',
  'DynamicWtCtrlr': 'Dynamic Wt Ctrlrs',
  'EARFile': 'EAR Files',
  'EJBAsync': 'EJB Asyncs',
  'EJBCache': 'EJB Caches',
  'EJBContainer': 'EJB Containers',
  'EJBDeployment': 'EJB Deployments',
  'EJBJarFile': 'EJB Jar Files',
  'EJBLocalRef': 'EJB Local Refs',
  'EJBModuleConfiguration': 'EJB Module Configurations',
  'EJBModuleDeployment': 'EJB Module Deployments',
  'EJBModuleRef': 'EJB Module Refs',
  'EJBTimer': 'EJB Timers',
  'EXtremeScaleDomain': 'EXtreme Scale Domains',
  'EXtremeScaleDomainEndpoint': 'EXtreme Scale Domain Endpoints',
  'EXtremeScaleDomains': 'EXtreme Scale Domains Sets',
  'EjbNameSpaceBinding': 'Ejb Name Space Bindings',
  'EjbRef': 'Ejb Refs',
  'ElasticityAction': 'Elasticity Actions',
  'ElasticityClass': 'Elasticity Classes',
  'ElasticityCustomProcessDefs': 'Elasticity Custom Process Defs',
  'ElasticityType': 'Elasticity Types',
  'EmailNotifications': 'Email Notifications',
  'EmitterFactoryProfile': 'Emitter Factory Profiles',
  'EndPoint': 'End Points',
  'EndPointRef': 'End Point Refs',
  'EnterpriseBeanConfig': 'Enterprise Bean Configs',
  'EnvEntry': 'Env Entries',
  'ErrorMapping': 'Error Mappings',
  'EventBusTransmissionProfile': 'Event Bus Transmission Profiles',
  'EventGroupProfile': 'Event Group Profiles',
  'EventGroupProfileList': 'Event Group Profile Lists',
  'EventInfrastructureProvider': 'Event Infrastructure Providers',
  'EventInfrastructureService': 'Services',
  'EventServerProfile': 'Event Server Profiles',
  'EveryoneExt': 'Everyone Exts',
  'ExecutionTimeAndThreadLimit': 'Execution Time And Thread Limits',
  'ExtendedApplicationData': 'Extended Application Data',
  'ExtendedRepositoryService': 'Extended Repository Services',
  'Extension': 'Extensions',
  'ExtensionMBean': 'Extension MBeans',
  'ExtensionMBeanProvider': 'Extension MBean Providers',
  'ExternalCacheGroup': 'External Cache Groups',
  'ExternalCacheGroupMember': 'External Cache Group Members',
  'ExternalDomain': 'External Domains',
  'ExternalFile': 'External Files',
  'ExternalFileService': 'External File Services',
  'ExternallyManagedHTTPServer': 'Externally Managed HTTP Servers',
  'FRCACacheGroupMember': 'FRCA Cache Group Members',
  'FailRoute': 'Fail Routes',
  'FederatedRepositoryAttributeMapping' : 'Federated Repository Attribute Mappings',
  'File': 'Files',
  'FileRepository': 'File Repositories',
  'FileTransferService': 'Services',
  'Filter': 'Filters',
  'FilterFactoryProfile': 'Filter Factory Profiles',
  'ForeignCell': 'Foreign Cells',
  'ForeignServer': 'Foreign Servers',
  'GCPercentageCondition': 'GC Percentage Conditions',
  'GSCMember': 'GSC Members',
  'GSCMemberEndpoint': 'GSC Member Endpoints',
  'GenericChannelData': 'Generic Channel Data',
  'GenericChannelFactory': 'Generic Channel Factories',
  'GenericClusterRoute': 'Generic Cluster Routes',
  'GenericInboundChannel': 'Channels',
  'GenericJMSConnectionFactory': 'Generic JMS Connection Factories',
  'GenericJMSDestination': 'Generic JMS Destinations',
  'GenericOutboundChannel': 'Channels',
  'GenericServerCluster': 'Generic Server Clusters',
  'GenericServerClusterMapping': 'Generic Server Cluster Mappings',
  'GenericServerClusterRoute': 'Generic Server Cluster Routes',
  'GenericServerClusterTimeMapping': 'Generic Server Cluster Time Mappings',
  'GenericServerEndpoint': 'Generic Server Endpoints',
  'GridClassRules': 'Grid Class Rules',
  'GridMatchRule': 'Grid Match Rules',
  'GridScheduler': 'Grid Schedulers',
  'GridWorkGoal': 'Grid Work Goals',
  'GroupExt': 'Group Exts',
  'HAManagerService': 'Services',
  'HPELLog': 'HPEL Logs',
  'HPELTextLog': 'HPEL Text Logs',
  'HPELTrace': 'HPEL Traces',
  'HTTPAccessLoggingService': 'Services',
  'HTTPConnector': 'HTTP Connectors',
  'HTTPInboundChannel': 'Channels',
  'HTTPInboundChannelLogging': 'HTTP Inbound Channel Loggings',
  'HTTPOutboundChannel': 'Channels',
  'HTTPProxyServerSettings': 'HTTP Proxy Server Settings',
  'HTTPQueueInboundChannel': 'Channels',
  'HTTPRequestCompressionAction': 'HTTP Request Compression Actions',
  'HTTPRequestHeaderAction': 'HTTP Request Header Actions',
  'HTTPResponseCompressionAction': 'HTTP Response Compression Actions',
  'HTTPResponseHeaderAction': 'HTTP Response Header Actions',
  'HTTPTransport': 'HTTP Transports',
  'HTTPTunnelInboundChannel': 'Channels',
  'HTTPTunnelOutboundChannel': 'Channels',
  'HeaderAction': 'Header Actions',
  'HeaderCondition': 'Header Conditions',
  'HealthAction': 'Health Actions',
  'HealthClass': 'Health Classes',
  'HealthCondition': 'Health Conditions',
  'HealthController': 'Services',
  'HealthTime': 'Health Times',
  'HighPerformanceExtensibleLogging': 'Services',
  'I18NService': 'Services',
  'IIOPLayer': 'IIOP Layers',
  'IIOPSecurityProtocol': 'IIOP Security Protocols',
  'IIOPTransport': 'IIOP Transports',
  'IPCConnector': 'IPC Connectors',
  'IPSprayer': 'IP Sprayers',
  'IconType': 'Icon Types',
  'Identity': 'Identities',
  'IdentityAssertionLayer': 'Identity Assertion Layers',
  'IdentityAssertionQOP': 'Identity Assertion QOPs',
  'IdentityAssertionTypeAssociation': 'Identity Assertion Type Associations',
  'InboundResourceAdapter': 'Inbound Resource Adapters',
  'InboundTransportChannel': 'Channels',
  'IndirectLookupNameSpaceBinding': 'Indirect Lookup Name Space Bindings',
  'InjectionTarget': 'Injection Targets',
  'InstallTarget': 'Install Targets',
  'InstancePool': 'Instance Pools',
  'Interceptor': 'Interceptors',
  'InvalidationSchedule': 'Invalidation Schedules',
  'J2CActivationSpec': 'J2C Activation Specs',
  'J2CAdminObject': 'J2C Admin Objects',
  'J2CConnectionFactory': 'J2C Connection Factories',
  'J2CResourceAdapter': 'J2C Resource Adapters',
  'J2EEEAttribute': 'J2EEE Attributes',
  'J2EEEObject': 'J2EEE Objects',
  'J2EEResourceFactory': 'J2EE Resource Factories',
  'J2EEResourceProperty': 'J2EE Resource Properties',
  'J2EEResourcePropertySet': 'J2EE Resource Property Sets',
  'J2EEResourceProvider': 'J2EE Resource Providers',
  'JAASAuthData': 'JAAS Auth Data',
  'JAASConfiguration': 'JAAS Configurations',
  'JAASConfigurationEntry': 'JAAS Configuration Entries',
  'JAASLoginModule': 'JAAS Login Modules',
  'JASPIConfiguration': 'JASPI Configurations',
  'JAXRPCHandler': 'JAXRPC Handlers',
  'JAXRPCHandlerList': 'JAXRPC Handler Lists',
  'JAXRPCHeader': 'JAXRPC Headers',
  'JAXWSHandler': 'JAXWS Handlers',
  'JAXWSHandlerList': 'JAXWS Handler Lists',
  'JDBCProvider': 'JDBC Providers',
  'JFAPFactory': 'JFAP Factories',
  'JFAPInboundChannel': 'Channels',
  'JFAPOutboundChannel': 'Channels',
  'JMSConnector': 'JMS Connectors',
  'JMSDestination': 'JMS Destinations',
  'JMSProvider': 'JMS Providers',
  'JMSServer': 'JMS Servers',
  'JMSTransmissionProfile': 'JMS Transmission Profiles',
  'JMSTransport': 'JMS Transports',
  'JMXConnector': 'JMX Connectors',
  'JNDIEnvRefsGroup': 'JNDI Env Refs Groups',
  'JSR160RMIConnector': 'JSR160RMI Connectors',
  'JavaPersistenceAPIService': 'Services',
  'JavaProcessDef': 'Java Process Defs',
  'JavaVirtualMachine': 'Java Virtual Machines',
  'JavaVirtualMachinePreset': 'Java Virtual Machine Presets',
  'JobClass': 'Job Classes',
  'JobLogLimit': 'Job Log Limits',
  'JobManager': 'Job Managers',
  'JobManagerRegistration': 'Job Manager Registrations',
  'KRB5': 'KRB5s',
  'Key': 'Keys',
  'KeyManager': 'Key Managers',
  'KeyReference': 'Key References',
  'KeySet': 'Key Sets',
  'KeySetGroup': 'Key Set Groups',
  'KeyStore': 'Key Stores',
  'KeyStoreFile': 'Key Store Files',
  'LDAPSearchFilter': 'LDAP Search Filters',
  'LDAPRepository': 'LDAP Repositories',
  'LDAPUserRegistry': 'LDAP User Registries',
  'LDAPServer': 'LDAP Servers',
  'LDAPEntityType': 'LDAP Entity Types',
  'LDAPFailoverServer': 'LDAP Failover Servers',
  'LDAPCustomProperty': 'LDAP Custom Properties',
  'LSDConnection': 'LSD Connections',
  'LTPA': 'LTPAs',
  'Library': 'Libraries',
  'LibraryRef': 'Library Refs',
  'License': 'Licenses',
  'LifecycleCallbackType': 'Lifecycle Callback Types',
  'Listener': 'Listeners',
  'ListenerPort': 'Listener Ports',
  'Liveness': 'Livenesses',
  'LocalErrorPagePolicy': 'Local Error Page Policies',
  'LocalOSUserRegistry': 'Local OS User Registries',
  'LocalRoute': 'Local Routes',
  'LogFile': 'Log Files',
  'LooseApplication': 'Loose Applications',
  'LooseArchive': 'Loose Archives',
  'LooseArchiveMetadata': 'Loose Archive Metadata',
  'LooseConfiguration': 'Loose Configurations',
  'LooseLibrary': 'Loose Libraries',
  'LooseModule': 'Loose Modules',
  'LooseWARFile': 'Loose WAR Files',
  'MOfNPolicy': 'M Of N Policies',
  'MQConnectionFactory': 'MQ Connection Factories',
  'MQFAPInboundChannel': 'Channels',
  'MQFAPOutboundChannel': 'Channels',
  'MQQueue': 'MQ Queues',
  'MQQueueConnectionFactory': 'MQ Queue Connection Factories',
  'MQTopic': 'MQ Topics',
  'MQTopicConnectionFactory': 'MQ Topic Connection Factories',
  'MailProvider': 'Mail Providers',
  'MailSession': 'Mail Sessions',
  'ManagedMiddlewareAppEdition': 'Managed Middleware App Editions',
  'ManagedNode': 'Managed Nodes',
  'ManagedObject': 'Managed Objects',
  'ManagementScope': 'Management Scopes',
  'MappingModule': 'Mapping Modules',
  'MatchCriteria': 'Match Criteria',
  'MatchRule': 'Match Rules',
  'MemoryCacheEvictionPolicy': 'Memory Cache Eviction Policies',
  'MemoryCondition': 'Memory Conditions',
  'MemoryLeakAlgorithm': 'Memory Leak Algorithms',
  'MessageAdapter': 'Message Adapters',
  'MessageCondition': 'Message Conditions',
  'MessageDestination': 'Message Destinations',
  'MessageDestinationRef': 'Message Destination Refs',
  'MessageLayer': 'Message Layers',
  'MessageListener': 'Message Listeners',
  'MessageListenerService': 'Services',
  'MessageQOP': 'Message QOPs',
  'MethodMessageCondition': 'Method Message Conditions',
  'MiddlewareApp': 'Middleware Apps',
  'MiddlewareAppEdition': 'Middleware App Editions',
  'MiddlewareAppScript': 'Middleware App Scripts',
  'MiddlewareClusterTarget': 'Middleware Cluster Targets',
  'MiddlewareDescriptor': 'Middleware Descriptors',
  'MiddlewareModule': 'Middleware Modules',
  'MiddlewareServerTarget': 'Middleware Server Targets',
  'MiddlewareTarget': 'Middleware Targets',
  'MiddlewareVersionDescriptor': 'Middleware Version Descriptors',
  'MiddlewareWebModule': 'Middleware Web Modules',
  'ModuleConfig': 'Module Configs',
  'ModuleDeployment': 'Module Deployments',
  'ModuleFile': 'Module Files',
  'ModuleRef': 'Module Refs',
  'ModuleShare': 'Module Shares',
  'MonitoredDirectoryDeployment': 'Monitored Directory Deployments',
  'MonitoringPolicy': 'Monitoring Policies',
  'MultiBrokerRoutingEntry': 'Multi Broker Routing Entries',
  'MultiCellOverlayBridge': 'Multi Cell Overlay Bridges',
  'MultibrokerDomain': 'Multibroker Domains',
  'NameBinding': 'Name Bindings',
  'NameServer': 'Name Servers',
  'NameSpaceBinding': 'Name Space Bindings',
  'NamedEndPoint': 'Named End Points',
  'NamedJavaProcessDef': 'Named Java Process Defs',
  'NamedProcessDef': 'Named Process Defs',
  'NamingContext': 'Naming Contexts',
  'NewClass': 'New Classes',
  'NoOpPolicy': 'No Op Policies',
  'NodeAgent': 'Node Agents',
  'NodeGroup': 'Node Groups',
  'NodeGroupMember': 'Node Group Members',
  'OLTPWorkGoal': 'OLTP Work Goals',
  'ORBInboundChannel': 'Channels',
  'ORBPlugin': 'ORB Plugins',
  'ObjectCacheInstance': 'Object Cache Instances',
  'ObjectPool': 'Object Pools',
  'ObjectPoolManagerInfo': 'Object Pool Manager Infos',
  'ObjectPoolProvider': 'Object Pool Providers',
  'ObjectPoolService': 'Services',
  'ObjectRequestBroker': 'Services',
  'OnDemandRouter': 'On Demand Routers',
  'OneOfNPolicy': 'One Of N Policies',
  'OutboundResourceAdapter': 'Outbound Resource Adapters',
  'OutboundTransportChannel': 'Channels',
  'OutputQueueLimit': 'Output Queue Limits',
  'OutputRedirect': 'Output Redirects',
  'OverlayEndpoint': 'Overlay Endpoints',
  'PME502ServerExtension': 'PME502Server Extensions',
  'PME51ServerExtension': 'PME51Server Extensions',
  'PMEClusterExtension': 'PME Cluster Extensions',
  'PMEServerExtension': 'PME Server Extensions',
  'PMIModule': 'PMI Modules',
  'PMIRMFilter': 'PMIRM Filters',
  'PMIRMFilterValue': 'PMIRM Filter Values',
  'PMIRequestMetrics': 'PMI Request Metrics',
  'PMIService': 'Services',
  'ParamValue': 'Param Values',
  'PassiveAffinityType': 'Passive Affinity Types',
  'PeerAccessPoint': 'Peer Access Points',
  'PeerCoreGroup': 'Peer Core Groups',
  'PercentileResponseTimeGoal': 'Percentile Response Time Goals',
  'PerformanceGoal': 'Performance Goals',
  'PersistenceContextRef': 'Persistence Context Refs',
  'PersistenceUnitRef': 'Persistence Unit Refs',
  'PluginConfigPolicy': 'Plugin Config Policies',
  'PluginConfigService': 'Services',
  'PluginProperties': 'Plugin Properties',
  'PluginServerClusterProperties': 'Plugin Server Cluster Properties',
  'Policy': 'Policies',
  'PortletContainer': 'Portlet Containers',
  'PreferenceSet': 'Preference Sets',
  'Preferences': 'Preferences',
  'PrimaryAdminExt': 'Primary Admin Exts',
  'ProcessDef': 'Process Defs',
  'ProcessExecution': 'Process Executions',
  'Property': 'Properties',
  'PropertySet': 'Property Sets',
  'ProtocolProvider': 'Protocol Providers',
  'Proxy': 'Proxies',
  'ProxyAction': 'Proxy Actions',
  'ProxyInboundChannel': 'Channels',
  'ProxyOverrides': 'Proxy Overrides',
  'ProxyRuleExpression': 'Proxy Rule Expressions',
  'ProxyServer': 'Proxy Servers',
  'ProxySettings': 'Proxy Settings',
  'ProxyVirtualHost': 'Proxy Virtual Hosts',
  'ProxyVirtualHostConfig': 'Proxy Virtual Host Configs',
  'ProxyVirtualHostSettings': 'Proxy Virtual Host Settings',
  'QName': 'QNames',
  'QualityOfProtection': 'Quality Of Protections',
  'QueueTimeGoal': 'Queue Time Goals',
  'RARFile': 'RAR Files',
  'RASLoggingService': 'Services',
  'RMIConnector': 'RMI Connectors',
  'RMQChannelFactory': 'RMQ Channel Factories',
  'RMQOutboundChannel': 'Channels',
  'RSAToken': 'RSA Tokens',
  'ReadOnlyDirectory': 'Read Only Directories',
  'RecoveryLog': 'Recovery Logs',
  'RedirectRoute': 'Redirect Routes',
  'Referenceable': 'Referenceables',
  'RemoteCellAccessPoint': 'Remote Cell Access Points',
  'RemoteCellOverrides': 'Remote Cell Overrides',
  'RepositoryCustomProperty': 'Repository Custom Properties',
  'RepositoryService': 'Repository Services',
  'RequiredConfigPropertyType': 'Required Config Property Types',
  'ResourceAdapter': 'Resource Adapters',
  'ResourceEnvEntry': 'Resource Env Entries',
  'ResourceEnvRef': 'Resource Env Refs',
  'ResourceEnvironmentProvider': 'Resource Environment Providers',
  'ResourceRef': 'Resource Refs',
  'ResponseCondition': 'Response Conditions',
  'RestartTime': 'Restart Times',
  'RewritingAction': 'Rewriting Actions',
  'RewritingPolicy': 'Rewriting Policies',
  'RewritingRule': 'Rewriting Rules',
  'RoleAssignmentExt': 'Role Assignment Exts',
  'RoleBasedAuthorization': 'Role Based Authorizations',
  'Route': 'Routes',
  'RoutingAction': 'Routing Actions',
  'RoutingPolicy': 'Routing Policies',
  'RoutingRule': 'Routing Rules',
  'Rule': 'Rules',
  'Rules': 'Rule Groups',
  'Ruleset': 'Rulesets',
  'RunAsSpecifiedIdentity': 'Run As Specified Identities',
  'SARClusterTarget': 'SAR Cluster Targets',
  'SARDeploymentTarget': 'SAR Deployment Targets',
  'SARServerTarget': 'SAR Server Targets',
  'SIBAbstractDestination': 'SIB Abstract Destinations',
  'SIBAudit': 'SIB Audits',
  'SIBAuthAlias': 'SIB Auth Aliases',
  'SIBAuthBrowser': 'SIB Auth Browsers',
  'SIBAuthBusConnect': 'SIB Auth Bus Connects',
  'SIBAuthCreator': 'SIB Auth Creators',
  'SIBAuthDefault': 'SIB Auth Defaults',
  'SIBAuthForeignBus': 'SIB Auth Foreign Buss',
  'SIBAuthForeignDestination': 'SIB Auth Foreign Destinations',
  'SIBAuthGroup': 'SIB Auth Groups',
  'SIBAuthIdentityAdopter': 'SIB Auth Identity Adopters',
  'SIBAuthPort': 'SIB Auth Ports',
  'SIBAuthQueue': 'SIB Auth Queues',
  'SIBAuthReceiver': 'SIB Auth Receivers',
  'SIBAuthSender': 'SIB Auth Senders',
  'SIBAuthSpace': 'SIB Auth Spaces',
  'SIBAuthTopic': 'SIB Auth Topics',
  'SIBAuthTopicSpace': 'SIB Auth Topic Spaces',
  'SIBAuthTopicSpaceBase': 'SIB Auth Topic Space Bases',
  'SIBAuthTopicSpaceRoot': 'SIB Auth Topic Space Roots',
  'SIBAuthUser': 'SIB Auth Users',
  'SIBAuthWebService': 'SIB Auth Web Services',
  'SIBBootstrapMember': 'SIB Bootstrap Members',
  'SIBContextInfo': 'SIB Context Infos',
  'SIBDatastore': 'SIB Datastores',
  'SIBDestination': 'SIB Destinations',
  'SIBDestinationAlias': 'SIB Destination Aliases',
  'SIBDestinationDefault': 'SIB Destination Defaults',
  'SIBDestinationForeign': 'SIB Destination Foreign Objects',
  'SIBDestinationMediation': 'SIB Destination Mediations',
  'SIBDestinationMediationRef': 'SIB Destination Mediation Refs',
  'SIBFilestore': 'SIB Filestores',
  'SIBForeignBus': 'SIB Foreign Buses',
  'SIBForeignBusRef': 'SIB Foreign Bus Refs',
  'SIBGatewayLink': 'SIB Gateway Links',
  'SIBJMSConnectionFactory': 'SIBJMS Connection Factories',
  'SIBJMSProvider': 'SIBJMS Providers',
  'SIBJMSQueue': 'SIBJMS Queues',
  'SIBJMSQueueConnectionFactory': 'SIBJMS Queue Connection Factories',
  'SIBJMSTopic': 'SIBJMS Topics',
  'SIBJMSTopicConnectionFactory': 'SIBJMS Topic Connection Factories',
  'SIBLinkRef': 'SIB Link Refs',
  'SIBLocalizationPoint': 'SIB Localization Points',
  'SIBLocalizationPointRef': 'SIB Localization Point Refs',
  'SIBMQClientLink': 'SIBMQ Client Links',
  'SIBMQClientLinkAdvancedProperties': 'SIBMQ Client Link Advanced Properties',
  'SIBMQLink': 'SIBMQ Links',
  'SIBMQLinkReceiverChannel': 'SIBMQ Link Receiver Channels',
  'SIBMQLinkSenderChannel': 'SIBMQ Link Sender Channels',
  'SIBMQLinkSenderChannelLocalizationPoint': 'SIB Localization Points',
  'SIBMQLocalizationPointProxy': 'SIBMQ Localization Point Proxies',
  'SIBMQMediationPointProxy': 'SIBMQ Mediation Point Proxies',
  'SIBMQQueueLocalizationPointProxy': 'SIBMQ Queue Localization Point Proxies',
  'SIBMQServer': 'SIBMQ Servers',
  'SIBMQServerBusMember': 'SIBMQ Server Bus Members',
  'SIBMediation': 'SIB Mediations',
  'SIBMediationExecutionPoint': 'SIB Mediation Execution Points',
  'SIBMediationInstance': 'SIB Mediation Instances',
  'SIBMediationLocalizationPoint': 'SIB Localization Points',
  'SIBMessagingEngine': 'SIB Messaging Engines',
  'SIBPSBBrokerProfile': 'SIBPSB Broker Profiles',
  'SIBPSBBrokerTransactionality': 'SIBPSB Broker Transactionalities',
  'SIBPSBTopicMapping': 'SIBPSB Topic Mappings',
  'SIBPSBTopicTransactionality': 'SIBPSB Topic Transactionalities',
  'SIBPermittedChain': 'SIB Permitted Chains',
  'SIBPort': 'SIB Ports',
  'SIBQualifiedDestinationName': 'SIB Qualified Destination Names',
  'SIBQueue': 'SIB Queues',
  'SIBQueueLocalizationPoint': 'SIB Localization Points',
  'SIBService': 'SIB Services',
  'SIBTopicSpace': 'SIB Topic Spaces',
  'SIBTopicSpaceAudit': 'SIB Topic Space Audits',
  'SIBTopicSpaceLocalizationPoint': 'SIB Localization Points',
  'SIBTopicSpaceMapEntry': 'SIB Topic Space Map Entries',
  'SIBTopicSpaceMapping': 'SIB Topic Space Mappings',
  'SIBVirtualGatewayLink': 'SIB Virtual Gateway Links',
  'SIBVirtualLink': 'SIB Virtual Links',
  'SIBVirtualMQLink': 'SIB Virtual MQ Links',
  'SIBWMQServerEndpoint': 'SIBWMQ Server Endpoints',
  'SIBWMQServerSvrconnChannel': 'SIBWMQ Server Svrconn Channels',
  'SIBWSBusConnectionProperty': 'SIBWS Bus Connection Properties',
  'SIBWSEndpointListener': 'SIBWS Endpoint Listeners',
  'SIBWSEndpointListenerReference': 'SIBWS Endpoint Listener References',
  'SIBWSInboundPort': 'SIBWS Inbound Ports',
  'SIBWSInboundPortReference': 'SIBWS Inbound Port References',
  'SIBWSInboundService': 'SIBWS Inbound Services',
  'SIBWSOutboundPort': 'SIBWS Outbound Ports',
  'SIBWSOutboundService': 'SIBWS Outbound Services',
  'SIBWSSecurityInboundConfig': 'SIBWS Security Inbound Configs',
  'SIBWSSecurityOutboundConfig': 'SIBWS Security Outbound Configs',
  'SIBWSSecurityRequestConsumerBindingConfig': 'SIBWS Security Request Consumer Binding Configs',
  'SIBWSSecurityRequestGeneratorBindingConfig': 'SIBWS Security Request Generator Binding Configs',
  'SIBWSSecurityRequestReceiverBindingConfig': 'SIBWS Security Request Receiver Binding Configs',
  'SIBWSSecurityRequestSenderBindingConfig': 'SIBWS Security Request Sender Binding Configs',
  'SIBWSSecurityResponseConsumerBindingConfig': 'SIBWS Security Response Consumer Binding Configs',
  'SIBWSSecurityResponseGeneratorBindingConfig': 'SIBWS Security Response Generator Binding Configs',
  'SIBWSSecurityResponseReceiverBindingConfig': 'SIBWS Security Response Receiver Binding Configs',
  'SIBWSSecurityResponseSenderBindingConfig': 'SIBWS Security Response Sender Binding Configs',
  'SIBWSUDDIPublication': 'SIBWSUDDI Publications',
  'SIBWSWSDLLocation': 'SIBWSWSDL Locations',
  'SIBWebService': 'SIB Web Services',
  'SIBus': 'SIBuses',
  'SIBusMember': 'SIBus Members',
  'SIBusMemberTarget': 'SIBus Member Targets',
  'SIBusMemberTargetRef': 'SIBus Member Target Refs',
  'SIPApplicationRouter': 'SIP Application Routers',
  'SIPApplicationRouters': 'SIP Application Routers Sets',
  'SIPContainer': 'SIP Containers',
  'SIPContainerInboundChannel': 'Channels',
  'SIPInboundChannel': 'Channels',
  'SIPMessageCondition': 'SIP Message Conditions',
  'SIPOutboundChannel': 'Channels',
  'SIPProxyInboundChannel': 'Channels',
  'SIPProxyServerSettings': 'SIP Proxy Server Settings',
  'SIPProxySettings': 'SIP Proxy Settings',
  'SIPRoutingRule': 'SIP Routing Rules',
  'SOAPConnector': 'SOAP Connectors',
  'SPNEGO': 'SPNEGOs',
  'SSLConfig': 'SSL Configs',
  'SSLConfigGroup': 'SSL Config Groups',
  'SSLInboundChannel': 'Channels',
  'SSLOutboundChannel': 'Channels',
  'SWAMAuthentication': 'SWAM Authentications',
  'SchedulerConfiguration': 'Scheduler Configurations',
  'SchedulerProvider': 'Scheduler Providers',
  'SchedulerService': 'Services',
  'SecureAssociationService': 'Secure Association Services',
  'SecureClusterAddressEndPoint': 'Secure Cluster Address End Points',
  'SecureSessionCookie': 'Secure Session Cookies',
  'SecureSocketLayer': 'Secure Socket Layers',
  'Security': 'Securities',
  'SecurityCommon': 'Security Commons',
  'SecurityDomain': 'Security Domains',
  'SecurityDomainMember': 'Security Domain Members',
  'SecurityIdentity': 'Security Identities',
  'SecurityPermission': 'Security Permissions',
  'SecurityProtocolConfig': 'Security Protocol Configs',
  'SecurityProtocolQOP': 'Security Protocol QOPs',
  'SecurityRole': 'Security Roles',
  'SecurityRoleExt': 'Security Role Exts',
  'SecurityRoleRef': 'Security Role Refs',
  'SecurityServer': 'Security Servers',
  'ServerComponent': 'Server Components',
  'ServerEntry': 'Server Entries',
  'ServerExt': 'Server Exts',
  'ServerIdentity': 'Server Identities',
  'ServerIndex': 'Server Indices',
  'ServerInstance': 'Server Instances',
  'ServerTarget': 'Server Targets',
  'Service': 'Services',
  'ServiceClass': 'Service Classes',
  'ServiceClassGoal': 'Service Class Goals',
  'ServiceContext': 'Service Contexts',
  'ServiceLog': 'Service Logs',
  'ServletCacheInstance': 'Servlet Cache Instances',
  'SessionBeanConfig': 'Session Bean Configs',
  'SessionDatabasePersistence': 'Session Database Persistences',
  'SessionManager': 'Services',
  'SessionSecurity': 'Session Securities',
  'SingleSignon': 'Single Signons',
  'SpecialSubjectExt': 'Special Subject Exts',
  'Stack': 'Stacks',
  'StandAloneApplicationServerMapping': 'Stand Alone Application Server Mappings',
  'StartupBeansService': 'Services',
  'StateManageable': 'State Manageables',
  'StatefulSessionBeanConfig': 'Stateful Session Bean Configs',
  'StaticCachePolicy': 'Static Cache Policies',
  'StaticCacheRule': 'Static Cache Rules',
  'StaticFileServingPolicy': 'Static File Serving Policies',
  'StaticPolicy': 'Static Policies',
  'StatisticsProvider': 'Statistics Providers',
  'StormDrainCondition': 'Storm Drain Conditions',
  'StreamRedirect': 'Stream Redirects',
  'StringNameSpaceBinding': 'String Name Space Bindings',
  'StuckRequestCondition': 'Stuck Request Conditions',
  'SubjectExt': 'Subject Exts',
  'SupportedEntityType': 'Supported Entity Types',
  'SystemMessageServer': 'System Message Servers',
  'TAInterceptor': 'TA Interceptors',
  'TCPFactory': 'TCP Factories',
  'TCPInboundChannel': 'Channels',
  'TCPOutboundChannel': 'Channels',
  'TPVService': 'Services',
  'TargetMembership': 'Target Memberships',
  'TaskProvider': 'Task Providers',
  'ThreadPool': 'Thread Pools',
  'ThreadPoolManager': 'Services',
  'TimeMapping': 'Time Mappings',
  'TimerManagerInfo': 'Timer Manager Infos',
  'TimerManagerProvider': 'Timer Manager Providers',
  'Timers': 'Timers',
  'TivoliPerfViewer': 'Tivoli Perf Viewers',
  'TraceLog': 'Trace Logs',
  'TraceService': 'Services',
  'TransactionClass': 'Transaction Classes',
  'TransactionClassModule': 'Transaction Class Modules',
  'TransactionService': 'Services',
  'Transport': 'Transports',
  'TransportChannel': 'Channels',
  'TransportChannelFactory': 'Transport Channel Factories',
  'TransportChannelService': 'Services',
  'TransportLayer': 'Transport Layers',
  'TransportQOP': 'Transport QOPs',
  'TrustAssociation': 'Trust Associations',
  'TrustManager': 'Trust Managers',
  'TrustedAuthenticationRealm': 'Trusted Authentication Realms',
  'TuningParams': 'Tuning Params',
  'TunnelAccessPointGroup': 'Tunnel Access Point Groups',
  'TunnelPeerAccessPoint': 'Tunnel Peer Access Points',
  'TunnelTemplate': 'Tunnel Templates',
  'TypedProperty': 'Typed Properties',
  'UDDIConfig': 'UDDI Configs',
  'UDDIReference': 'UDDI References',
  'UDPInboundChannel': 'Channels',
  'UDPOutboundChannel': 'Channels',
  'URIGroup': 'URI Groups',
  'URL': 'URLs',
  'URLProvider': 'URL Providers',
  'UnmanagedMiddlewareAppEdition': 'Unmanaged Middleware App Editions',
  'UseCallerIdentity': 'Use Caller Identities',
  'UserExt': 'User Exts',
  'UserRegistry': 'User Registries',
  'UserRegistryRef': 'User Registry Refs',
  'VariableMap': 'Variable Maps',
  'VirtualHost': 'Virtual Hosts',
  'VisualizationDataLog': 'Visualization Data Logs',
  'VisualizationDataService': 'Services',
  'WARFile': 'WAR Files',
  'WARFragmentFile': 'WAR Fragment Files',
  'WAS40ConnectionPool': 'WAS40Connection Pools',
  'WAS40DataSource': 'WAS40Data Sources',
  'WASAbstractAuthData': 'WAS Abstract Auth Data',
  'WASAddressingType': 'WAS Addressing Types',
  'WASBasicAuthData': 'WAS Basic Auth Data',
  'WASDataSourceDefinition': 'WAS Data Source Definitions',
  'WASDataSourceDefinitionBinding': 'WAS Data Source Definition Bindings',
  'WASEjbRef': 'WAS Ejb Refs',
  'WASEjbRefBinding': 'WAS Ejb Ref Bindings',
  'WASEnvEntry': 'WAS Env Entries',
  'WASHandler': 'WAS Handlers',
  'WASHandlerChain': 'WAS Handler Chains',
  'WASHandlerChains': 'WAS Handler Chain Sets',
  'WASMessageDestinationRef': 'WAS Message Destination Refs',
  'WASMessageDestinationRefBinding': 'WAS Message Destination Ref Bindings',
  'WASParamValue': 'WAS Param Values',
  'WASPersistenceContextRef': 'WAS Persistence Context Refs',
  'WASPersistenceUnitRef': 'WAS Persistence Unit Refs',
  'WASPortComponentRef': 'WAS Port Component Refs',
  'WASQName': 'WAS QNames',
  'WASQueue': 'WAS Queues',
  'WASQueueConnectionFactory': 'WAS Queue Connection Factories',
  'WASResourceEnvRef': 'WAS Resource Env Refs',
  'WASResourceEnvRefBinding': 'WAS Resource Env Ref Bindings',
  'WASResourceRef': 'WAS Resource Refs',
  'WASResourceRefBinding': 'WAS Resource Ref Bindings',
  'WASResourceRefExtension': 'WAS Resource Ref Extensions',
  'WASRespectBindingType': 'WAS Respect Binding Types',
  'WASServiceRef': 'WAS Service Refs',
  'WASTopic': 'WAS Topics',
  'WASTopicConnectionFactory': 'WAS Topic Connection Factories',
  'WIMUserRegistry': 'WIM User Registries',
  'WLMCoreGroupBridgePlugin': 'WLM Core Group Bridge Plugins',
  'WSByteBufferService': 'Services',
  'WSCertificateExpirationMonitor': 'WS Certificate Expiration Monitors',
  'WSGWGatewayService': 'WSGW Gateway Services',
  'WSGWInstance': 'WSGW Instances',
  'WSGWProxyService': 'WSGW Proxy Services',
  'WSGWTargetService': 'WSGW Target Services',
  'WSNAdministeredSubscriber': 'WSN Administered Subscribers',
  'WSNInstanceDocument': 'WSN Instance Documents',
  'WSNService': 'WSN Services',
  'WSNServicePoint': 'WSN Service Points',
  'WSNTopicNamespace': 'WSN Topic Namespaces',
  'WSNotification': 'WS Notifications',
  'WSPassword': 'WS Passwords',
  'WSPasswordEncryption': 'WS Password Encryptions',
  'WSPasswordLocator': 'WS Password Locators',
  'WSSchedule': 'WS Schedules',
  'WSSecurityScannerMonitor': 'WS Security Scanner Monitors',
  'WebContainer': 'Web Containers',
  'WebContainerInboundChannel': 'Channels',
  'WebModuleConfig': 'Web Module Configs',
  'WebModuleDeployment': 'Web Module Deployments',
  'WebModuleRef': 'Web Module Refs',
  'WebServer': 'Web Servers',
  'WebserverPluginSettings': 'Webserver Plugin Settings',
  'WeightAdvisor': 'Weight Advisors',
  'WorkAreaPartition': 'Work Area Partitions',
  'WorkAreaPartitionService': 'Services',
  'WorkAreaService': 'Services',
  'WorkClass': 'Work Class Modules',
  'WorkClassModule': 'Work Classes',
  'WorkManagerInfo': 'Work Manager Infos',
  'WorkManagerProvider': 'Work Manager Providers',
  'WorkManagerService': 'Services',
  'WorkloadCondition': 'Workload Conditions',
  'WorkloadManagementPolicy': 'Workload Management Policies',
  'WorkloadManagementServer': 'Workload Management Servers',
  'com.ibm.etools.webservice.wsbnd.DefaultEndpointURIPrefix': 'com.ibm.etools.webservice.wlsbnd.Default Endpoint URI Prefixes',
  'com.ibm.etools.webservice.wsbnd.PCBinding': 'com.ibm.etools.webservice.wsbnd.PC Bindings',
  'com.ibm.etools.webservice.wsbnd.RouterModule': 'com.ibm.etools.webservice.wsbnd.Router Modules',
  'com.ibm.etools.webservice.wsbnd.SecurityRequestConsumerBindingConfig': 'com.ibm.etools.webservice.wsbnd.Security Request Consumer Binding Configs',
  'com.ibm.etools.webservice.wsbnd.SecurityRequestReceiverBindingConfig': 'com.ibm.etools.webservice.wsbnd.Security Request Receiver Binding Configs',
  'com.ibm.etools.webservice.wsbnd.SecurityResponseGeneratorBindingConfig': 'com.ibm.etools.webservice.wsbnd.Security Response Generator Binding Configs',
  'com.ibm.etools.webservice.wsbnd.SecurityResponseSenderBindingConfig': 'com.ibm.etools.webservice.wsbnd.Security Response Sender Binding Configs',
  'com.ibm.etools.webservice.wsbnd.WSBinding': 'com.ibm.etools.webservice.wsbnd.WS Bindings',
  'com.ibm.etools.webservice.wsbnd.WSDescBinding': 'com.ibm.etools.webservice.wsbnd.WS Desc Bindings',
  'com.ibm.etools.webservice.wscbnd.BasicAuth': 'com.ibm.etools.webservice.wscbnd.Basic Auths',
  'com.ibm.etools.webservice.wscbnd.ClientBinding': 'com.ibm.etools.webservice.wscbnd.Client Bindings',
  'com.ibm.etools.webservice.wscbnd.ComponentScopedRefs': 'com.ibm.etools.webservice.wscbnd.Component Scoped Refss',
  'com.ibm.etools.webservice.wscbnd.DefaultMapping': 'com.ibm.etools.webservice.wscbnd.Default Mappings',
  'com.ibm.etools.webservice.wscbnd.LoginBinding': 'com.ibm.etools.webservice.wscbnd.Login Bindings',
  'com.ibm.etools.webservice.wscbnd.PortQnameBinding': 'com.ibm.etools.webservice.wscbnd.Port Qname Bindings',
  'com.ibm.etools.webservice.wscbnd.SecurityRequestGeneratorBindingConfig': 'com.ibm.etools.webservice.wscbnd.Security Request Generator Binding Configs',
  'com.ibm.etools.webservice.wscbnd.SecurityRequestSenderBindingConfig': 'com.ibm.etools.webservice.wscbnd.Security Request Sender Binding Configs',
  'com.ibm.etools.webservice.wscbnd.SecurityResponseConsumerBindingConfig': 'com.ibm.etools.webservice.wscbnd.Security Response Consumer Binding Configs',
  'com.ibm.etools.webservice.wscbnd.SecurityResponseReceiverBindingConfig': 'com.ibm.etools.webservice.wscbnd.Security Response Receiver Binding Configs',
  'com.ibm.etools.webservice.wscbnd.ServiceRef': 'com.ibm.etools.webservice.wscbnd.Service Refs',
  'com.ibm.etools.webservice.wscext.ClientServiceConfig': 'com.ibm.etools.webservice.wscext.Client Service Configs',
  'com.ibm.etools.webservice.wscext.ComponentScopedRefs': 'com.ibm.etools.webservice.wscext.Component Scoped Refs',
  'com.ibm.etools.webservice.wscext.DefaultMapping': 'com.ibm.etools.webservice.wscext.Default Mappings',
  'com.ibm.etools.webservice.wscext.LoginConfig': 'com.ibm.etools.webservice.wscext.Login Configs',
  'com.ibm.etools.webservice.wscext.PortQnameBinding': 'com.ibm.etools.webservice.wscext.Port Qname Bindings',
  'com.ibm.etools.webservice.wscext.SecurityRequestGeneratorServiceConfig': 'com.ibm.etools.webservice.wscext.Security Request Generator Service Configs',
  'com.ibm.etools.webservice.wscext.SecurityRequestSenderServiceConfig': 'com.ibm.etools.webservice.wscext.Security Request Sender Service Configs',
  'com.ibm.etools.webservice.wscext.SecurityResponseConsumerServiceConfig': 'com.ibm.etools.webservice.wscext.Security Response Consumer Service Configs',
  'com.ibm.etools.webservice.wscext.SecurityResponseReceiverServiceConfig': 'com.ibm.etools.webservice.wscext.Security Response Receiver Service Configs',
  'com.ibm.etools.webservice.wscext.ServiceRef': 'com.ibm.etools.webservice.wscext.Service Refs',
  'com.ibm.etools.webservice.wscext.WsClientExtension': 'com.ibm.etools.webservice.wscext.Ws Client Extensions',
  'com.ibm.etools.webservice.wscommonbnd.AlgorithmMapping': 'com.ibm.etools.webservice.wscommonbnd.Algorithm Mappings',
  'com.ibm.etools.webservice.wscommonbnd.AlgorithmURI': 'com.ibm.etools.webservice.wscommonbnd.Algorithm URIs',
  'com.ibm.etools.webservice.wscommonbnd.CRL': 'com.ibm.etools.webservice.wscommonbnd.CRLs',
  'com.ibm.etools.webservice.wscommonbnd.CallbackHandler': 'com.ibm.etools.webservice.wscommonbnd.Callback Handler Factories',
  'com.ibm.etools.webservice.wscommonbnd.CallbackHandlerFactory': 'com.ibm.etools.webservice.wscommonbnd.Callback Handlers',
  'com.ibm.etools.webservice.wscommonbnd.CanonicalizationMethod': 'com.ibm.etools.webservice.wscommonbnd.Canonicalization Methods',
  'com.ibm.etools.webservice.wscommonbnd.CertPathSettings': 'com.ibm.etools.webservice.wscommonbnd.Cert Path Settings',
  'com.ibm.etools.webservice.wscommonbnd.CertStoreList': 'com.ibm.etools.webservice.wscommonbnd.Cert Store Lists',
  'com.ibm.etools.webservice.wscommonbnd.CertStoreRef': 'com.ibm.etools.webservice.wscommonbnd.Cert Store Refs',
  'com.ibm.etools.webservice.wscommonbnd.CollectionCertStore': 'com.ibm.etools.webservice.wscommonbnd.Collection Cert Stores',
  'com.ibm.etools.webservice.wscommonbnd.Consumerbindingref': 'com.ibm.etools.webservice.wscommonbnd.Consumerbindingrefs',
  'com.ibm.etools.webservice.wscommonbnd.DataEncryptionMethod': 'com.ibm.etools.webservice.wscommonbnd.Data Encryption Methods',
  'com.ibm.etools.webservice.wscommonbnd.DigestMethod': 'com.ibm.etools.webservice.wscommonbnd.Digest Methods',
  'com.ibm.etools.webservice.wscommonbnd.EncryptionInfo': 'com.ibm.etools.webservice.wscommonbnd.Encryption Infos',
  'com.ibm.etools.webservice.wscommonbnd.EncryptionKey': 'com.ibm.etools.webservice.wscommonbnd.Encryption Key Infos',
  'com.ibm.etools.webservice.wscommonbnd.EncryptionKeyInfo': 'com.ibm.etools.webservice.wscommonbnd.Encryption Keys',
  'com.ibm.etools.webservice.wscommonbnd.Generatorbindingref': 'com.ibm.etools.webservice.wscommonbnd.Generatorbindingrefs',
  'com.ibm.etools.webservice.wscommonbnd.JAASConfig': 'com.ibm.etools.webservice.wscommonbnd.JAAS Configs',
  'com.ibm.etools.webservice.wscommonbnd.KeyEncryptionMethod': 'com.ibm.etools.webservice.wscommonbnd.Key Encryption Methods',
  'com.ibm.etools.webservice.wscommonbnd.KeyInfo': 'com.ibm.etools.webservice.wscommonbnd.Key Infos',
  'com.ibm.etools.webservice.wscommonbnd.KeyInfoSignature': 'com.ibm.etools.webservice.wscommonbnd.Key Info Signatures',
  'com.ibm.etools.webservice.wscommonbnd.KeyLocator': 'com.ibm.etools.webservice.wscommonbnd.Key Locators',
  'com.ibm.etools.webservice.wscommonbnd.KeyLocatorMapping': 'com.ibm.etools.webservice.wscommonbnd.Key Locator Mappings',
  'com.ibm.etools.webservice.wscommonbnd.KeyStore': 'com.ibm.etools.webservice.wscommonbnd.Key Stores',
  'com.ibm.etools.webservice.wscommonbnd.LDAPCertStore': 'com.ibm.etools.webservice.wscommonbnd.LDAP Cert Stores',
  'com.ibm.etools.webservice.wscommonbnd.LDAPServer': 'com.ibm.etools.webservice.wscommonbnd.LDAP Servers',
  'com.ibm.etools.webservice.wscommonbnd.LoginMapping': 'com.ibm.etools.webservice.wscommonbnd.Login Mappings',
  'com.ibm.etools.webservice.wscommonbnd.NonceCaching': 'com.ibm.etools.webservice.wscommonbnd.Nonce Cachings',
  'com.ibm.etools.webservice.wscommonbnd.Parameter': 'com.ibm.etools.webservice.wscommonbnd.Parameters',
  'com.ibm.etools.webservice.wscommonbnd.PartReference': 'com.ibm.etools.webservice.wscommonbnd.Part References',
  'com.ibm.etools.webservice.wscommonbnd.SignatureMethod': 'com.ibm.etools.webservice.wscommonbnd.Signature Methods',
  'com.ibm.etools.webservice.wscommonbnd.SigningInfo': 'com.ibm.etools.webservice.wscommonbnd.Signing Infos',
  'com.ibm.etools.webservice.wscommonbnd.SigningKey': 'com.ibm.etools.webservice.wscommonbnd.Signing Keys',
  'com.ibm.etools.webservice.wscommonbnd.SigningKeyInfo': 'com.ibm.etools.webservice.wscommonbnd.Signing Key Infos',
  'com.ibm.etools.webservice.wscommonbnd.TokenConsumer': 'com.ibm.etools.webservice.wscommonbnd.Token Consumers',
  'com.ibm.etools.webservice.wscommonbnd.TokenGenerator': 'com.ibm.etools.webservice.wscommonbnd.Token Generators',
  'com.ibm.etools.webservice.wscommonbnd.TokenReference': 'com.ibm.etools.webservice.wscommonbnd.Token References',
  'com.ibm.etools.webservice.wscommonbnd.TokenValueType': 'com.ibm.etools.webservice.wscommonbnd.Token Value Types',
  'com.ibm.etools.webservice.wscommonbnd.Transform': 'com.ibm.etools.webservice.wscommonbnd.Transforms',
  'com.ibm.etools.webservice.wscommonbnd.TrustAnchor': 'com.ibm.etools.webservice.wscommonbnd.Trust Anchors',
  'com.ibm.etools.webservice.wscommonbnd.TrustAnchorRef': 'com.ibm.etools.webservice.wscommonbnd.Trust Anchor Refs',
  'com.ibm.etools.webservice.wscommonbnd.TrustAnyCertificate': 'com.ibm.etools.webservice.wscommonbnd.Trust Any Certificates',
  'com.ibm.etools.webservice.wscommonbnd.TrustedIDEvaluator': 'com.ibm.etools.webservice.wscommonbnd.Trusted ID Evaluators',
  'com.ibm.etools.webservice.wscommonbnd.TrustedIDEvaluatorRef': 'com.ibm.etools.webservice.wscommonbnd.Trusted ID Evaluator Refs',
  'com.ibm.etools.webservice.wscommonbnd.ValueType': 'com.ibm.etools.webservice.wscommonbnd.Value Types',
  'com.ibm.etools.webservice.wscommonbnd.X509Certificate': 'com.ibm.etools.webservice.wscommonbnd.X509Certificates',
  'com.ibm.etools.webservice.wscommonext.AddCreatedTimeStamp': 'com.ibm.etools.webservice.wscommonext.Add Created Time Stamps',
  'com.ibm.etools.webservice.wscommonext.AddReceivedTimestamp': 'com.ibm.etools.webservice.wscommonext.Add Received Timestamps',
  'com.ibm.etools.webservice.wscommonext.AddTimestamp': 'com.ibm.etools.webservice.wscommonext.Add Timestamps',
  'com.ibm.etools.webservice.wscommonext.AuthMethod': 'com.ibm.etools.webservice.wscommonext.Auth Methods',
  'com.ibm.etools.webservice.wscommonext.Caller': 'com.ibm.etools.webservice.wscommonext.Callers',
  'com.ibm.etools.webservice.wscommonext.ConfidentialPart': 'com.ibm.etools.webservice.wscommonext.Confidential Parts',
  'com.ibm.etools.webservice.wscommonext.Confidentiality': 'com.ibm.etools.webservice.wscommonext.Confidentialities',
  'com.ibm.etools.webservice.wscommonext.IDAssertion': 'com.ibm.etools.webservice.wscommonext.ID Assertions',
  'com.ibm.etools.webservice.wscommonext.Integrity': 'com.ibm.etools.webservice.wscommonext.Integrities',
  'com.ibm.etools.webservice.wscommonext.MessageParts': 'com.ibm.etools.webservice.wscommonext.Message Parts',
  'com.ibm.etools.webservice.wscommonext.Nonce': 'com.ibm.etools.webservice.wscommonext.Nonces',
  'com.ibm.etools.webservice.wscommonext.Reference': 'com.ibm.etools.webservice.wscommonext.References',
  'com.ibm.etools.webservice.wscommonext.RequiredConfidentiality': 'com.ibm.etools.webservice.wscommonext.Required Confidentialities',
  'com.ibm.etools.webservice.wscommonext.RequiredIntegrity': 'com.ibm.etools.webservice.wscommonext.Required Integrities',
  'com.ibm.etools.webservice.wscommonext.RequiredSecurityToken': 'com.ibm.etools.webservice.wscommonext.Required Security Tokens',
  'com.ibm.etools.webservice.wscommonext.SecurityToken': 'com.ibm.etools.webservice.wscommonext.Security Tokens',
  'com.ibm.etools.webservice.wscommonext.Timestamp': 'com.ibm.etools.webservice.wscommonext.Timestamps',
  'com.ibm.etools.webservice.wscommonext.TrustMethod': 'com.ibm.etools.webservice.wscommonext.Trust Methods',
  'com.ibm.etools.webservice.wsext.LoginConfig': 'com.ibm.etools.webservice.wsext.Login Configs',
  'com.ibm.etools.webservice.wsext.PcBinding': 'com.ibm.etools.webservice.wsext.Pc Bindings',
  'com.ibm.etools.webservice.wsext.SecurityRequestConsumerServiceConfig': 'com.ibm.etools.webservice.wsext.Security Request Consumer Service Configs',
  'com.ibm.etools.webservice.wsext.SecurityRequestReceiverServiceConfig': 'com.ibm.etools.webservice.wsext.Security Request Receiver Service Configs',
  'com.ibm.etools.webservice.wsext.SecurityResponseGeneratorServiceConfig': 'com.ibm.etools.webservice.wsext.Security Response Generator Service Configs',
  'com.ibm.etools.webservice.wsext.SecurityResponseSenderServiceConfig': 'com.ibm.etools.webservice.wsext.Security Response Sender Service Configs',
  'com.ibm.etools.webservice.wsext.ServerServiceConfig': 'com.ibm.etools.webservice.wsext.Server Service Configs',
  'com.ibm.etools.webservice.wsext.WsDescExt': 'com.ibm.etools.webservice.wsext.Ws Desc Exts',
  'com.ibm.etools.webservice.wsext.WsExtension': 'com.ibm.etools.webservice.wsext.Ws Extensions',
  'com.ibm.etools.webservice.wssecurity.Binding': 'com.ibm.etools.webservice.wssecurity.Bindings',
  'com.ibm.etools.webservice.wssecurity.Commonbindings': 'com.ibm.etools.webservice.wssecurity.Commonbindings',
  'com.ibm.etools.webservice.wssecurity.Consumer': 'com.ibm.etools.webservice.wssecurity.Consumers',
  'com.ibm.etools.webservice.wssecurity.Consumerbinding': 'com.ibm.etools.webservice.wssecurity.Consumerbindings',
  'com.ibm.etools.webservice.wssecurity.Defaultbindings': 'com.ibm.etools.webservice.wssecurity.Defaultbindings',
  'com.ibm.etools.webservice.wssecurity.Generator': 'com.ibm.etools.webservice.wssecurity.Generators',
  'com.ibm.etools.webservice.wssecurity.Generatorbinding': 'com.ibm.etools.webservice.wssecurity.Generatorbindings',
  'com.ibm.etools.webservice.wssecurity.WSSecurity': 'com.ibm.etools.webservice.wssecurity.WS Securities',
  'PeerAccessPointRef': 'Peer Access Point Refs',
  'TunnelAccessPointGroupRef': 'Tunnel Access Point Group Refs',
  'CoreGroupAccessPointRef' : 'Core Group Access Point Refs',
  'AccessPointGroupRef' : 'Access Point Group Refs',
  'TunnelPeerAccessPointRef' : 'Tunnel Peer Access Point Refs',
  'SIBMQLinkSenderChannelLocalizationPointRef': 'SIBMQ Link Sender Channel Localization Point Refs',
  'PropertyAttrs': 'Property Attributes',
  'AdditionalSecAttrs': 'Additional Security Attributes',
  'WebAuthAttrs': 'Web Auth Attributes',
  'ApplicationLoginConfig': 'Application Login Config',
  'SystemLoginConfig': 'System Login Config',
  'AdditionalKeyStoreAttrs': 'Additional KeyStore Attributes',
  'AdditionalKeySetAttrs': 'Additional KeySet Attributes',
  'AdditionalKeyManagerAttrs': 'Additional KeyManager Attributes',
  'AdditionalTrustManagerAttrs': 'Additional TrustManager Attributes',
  'ManagementScopeRef': 'Management Scope Refs',
  'KeyStoreRef': 'Key Store Refs',
  'TrustManagerRef': 'Trust Manager Refs',
  'KeyManagerRef': 'Key Manager Refs',
  'SSLConfigRef': 'SSL Config Refs',
  'KeySetRef': 'Key Set Refs',
  'WSScheduleRef': 'WS Schedule Refs',
  'KeySetGroupRef': 'Key Set Group Refs',
  'CertificateRef': 'Certificate Refs',
  'ProxyVirtualHostRef': 'Proxy Virtual Host Refs',
  'ProxyRuleExpressionRef': 'Proxy Rule Expression Refs',
  'RoutingActionRef': 'Routing Action Refs',
  'HTTPRequestHeaderActionRef': 'HTTP Request Header Action Refs',
  'HTTPResponseHeaderActionRef': 'HTTP Response Header Action Refs',
  'HTTPRequestCompressionActionRef': 'HTTP Request Compression Action Refs',
  'HTTPResponseCompressionActionRef': 'HTTP Response Compression Action Refs',
  'CachingActionRef': 'Caching Action Refs',
  'RewritingActionRef': 'Rewriting Action Refs',
  'ActivationSpecRef': 'Activation Spec Refs',
  'EnabledProxyVirtualHostAttrs': 'Enabled Proxy Virtual Host Attributes',
  'PostConstruct': 'PostConstruct Lifecycle Callback Types',
  'PreDestroy': 'PreDestroy Lifecycle Callback Types',
  'ConnectionDefinitionRef': 'Connection Definition Refs',
  'DataSourceRef': 'Data Source Refs',
  'SecurityRoleExtRef': 'Security Role Ext Refs',
  'CoreGroupMapping': 'Core Group Mapping',
  'PolicyRef': 'Policies',
  'NodeGroupMapping': 'Node Group Mapping',
  'AuditSpecificationRef': 'Audit Specification Refs',
  'AuditServiceProviderRef': 'Audit Service Provider Refs',
  'DynamicClusterServerTemplate': 'Dynamic Cluster Server Templates',
  'ProtocolProviderRef': 'Protocol Provider Refs',
  'SIBAuthGroupRef': 'SIB Auth Group Refs',
  'SIBAuthUserRef': 'SIB Auth User Refs'
}
