Пример #1
0
def run(
    CopiesPerParent,
    TargetTagList,
    TemplateXml,
    TemplateXmlFileName,
    TagPrefix,
    AutoExpandTemplate,
    EnableLoadFromFileName,
    StmTemplateMix,
):
    plLogger = PLLogger.GetLogger("methodology")
    plLogger.LogDebug("run LoadTemplateCommand")

    did_expand = False
    ctor = CScriptableCreator()
    stc_sys = CStcSystem.Instance()
    project = stc_sys.GetObject("Project")
    hnd_reg = CHandleRegistry.Instance()

    # Look up the StmTemplateMix
    parent_obj = hnd_reg.Find(StmTemplateMix)
    if parent_obj is None:
        plLogger.LogDebug("Was unable to find a StmTemplateMix with " + str(StmTemplateMix) + " using project ")
        parent_obj = project
    else:
        if not parent_obj.IsTypeOf("StmTemplateMix"):
            plLogger.LogError(
                "Incorrect handle passed in for "
                + "StmTemplateMix.  Expected an "
                + "object of type StmTemplateMix, "
                + "instead received a(n) "
                + parent_obj.GetType()
            )
            return False
        plLogger.LogDebug(
            "Was able to find a StmTemplateMix, using " + parent_obj.Get("Name") + " with id: " + str(StmTemplateMix)
        )

    # Create an empty TemplateConfig object
    temp_conf = ctor.Create("StmTemplateConfig", parent_obj)

    if temp_conf is None:
        plLogger.LogError("ERROR: Failed to create an StmTemplateConfig")
        return False

    xml_value = None
    if not EnableLoadFromFileName:
        xml_value = TemplateXml
    elif TemplateXmlFileName != "":
        xml_value = xml_utils.load_xml_from_file(TemplateXmlFileName)
    if xml_value is None:
        plLogger.LogError("ERROR: No valid template source.")
        return False

    if TagPrefix != "":
        xml_value = xml_utils.add_prefix_to_tags(TagPrefix, xml_value)
    temp_conf.Set("TemplateXml", xml_value)

    # Pass the handles to the commands contained in this group
    cmd_count = config_contained_cmds(get_this_cmd(), temp_conf)

    # Set the output handle (since we already have the object)
    this_cmd = get_this_cmd()
    this_cmd.Set("StmTemplateConfig", temp_conf.GetObjectHandle())

    # FIXME: WORKAROUND: on_last_command_complete() doesn't get called if
    # no children commands exist...
    if cmd_count == 0:
        on_complete([])
        did_expand = True
    if did_expand:
        pass
    # END FIXME: WORKAROUND
    return True
def run(StmTemplateMix, InputJson, AutoExpandTemplate,
        CopiesPerParent, SrcTagList, TargetTagList):
    plLogger = PLLogger.GetLogger('methodology')
    plLogger.LogDebug("CreateTemplateConfigCommand.run")

    hnd_reg = CHandleRegistry.Instance()
    ctor = CScriptableCreator()
    this_cmd = get_this_cmd()
    project = CStcSystem.Instance().GetObject("Project")

    if InputJson == "":
        err_str = "InputJson is an empty string."
        plLogger.LogError(err_str)
        this_cmd.Set("Status", err_str)
        return False

    # Validate the InputJson against the schema
    res = json_utils.validate_json(InputJson,
                                   this_cmd.Get("InputJsonSchema"))
    if res != "":
        err_str = "InputJson is invalid or does not conform to the " + \
            "schema: " + res
        plLogger.LogError(err_str)
        this_cmd.Set("Status", err_str)
        return False

    if StmTemplateMix != "" and StmTemplateMix != 0:
        mix = hnd_reg.Find(StmTemplateMix)
        if mix is None:
            err_str = "StmTemplateMix with given handle: " + \
                str(StmTemplateMix) + " is invalid."
            plLogger.LogError(err_str)
            this_cmd.Set("Status", err_str)
            return False
        elif not mix.IsTypeOf("StmTemplateMix"):
            err_str = "Object with given handle: " + \
                str(StmTemplateMix) + " is a " + \
                mix.GetType() + ".  If StmTemplateMix is " + \
                "specified, object must be an StmTemplateMix."
            plLogger.LogError(err_str)
            this_cmd.Set("Status", err_str)
            return False
        parent = mix
    else:
        parent = project

    template = ctor.Create("StmTemplateConfig", parent)
    this_cmd.Set("StmTemplateConfig", template.GetObjectHandle())

    # Breakdown the json
    err_str, conf_data = json_utils.load_json(InputJson)
    if err_str != "":
        plLogger.LogError(err_str)
        this_cmd.Set("Status", err_str)
        return False

    plLogger.LogDebug("conf_data: " + str(conf_data))

    # Do the load first
    if "baseTemplateFile" not in conf_data.keys():
        plLogger.LogError("InputJson is missing a baseTemplateFile.")
        return False
    xml_file = conf_data["baseTemplateFile"]

    xml_val = xml_utils.load_xml_from_file(xml_file)
    if xml_val is None:
        err_str = "Was unable to load template XML from " + xml_file
        plLogger.LogError(err_str)
        this_cmd.Set("Status", err_str)
        return False

    # Update the prefixes
    tag_prefix = ""
    if ("tagPrefix" in conf_data.keys() and conf_data["tagPrefix"] != ""):
        tag_prefix = conf_data["tagPrefix"]
    plLogger.LogDebug("using tag_prefix: " + tag_prefix)

    xml_val = xml_utils.add_prefix_to_tags(tag_prefix, xml_val)
    template.Set("TemplateXml", xml_val)
    plLogger.LogDebug("conf_data: " + str(conf_data))

    # Iterate over the objects in the array and apply the appropriate
    # template modification.  Order is determined by the list order.
    for mod_data in conf_data.get("modifyList", []):
        plLogger.LogDebug("mod_data: " + str(mod_data))
        plLogger.LogDebug("mod_data.keys(): " + str(mod_data.keys()))
        err_str = ""
        res = True

        # Merge stuff in mergeList
        for merge_data in mod_data.get("mergeList", []):
            res = run_merge(template, tag_prefix, merge_data)
            err_str = "Failed to merge XML into the StmTemplateConfig " + \
                "given JSON specified as: " + str(merge_data)

        # Process objects in the addObjectList
        for obj_data in mod_data.get("addObjectList", []):
            res = run_objectlist(template, tag_prefix, obj_data)
            err_str = "Failed to add object into the StmTemplateConfig " + \
                "given JSON specified as: " + str(obj_data)

        # Modify the stuff in the PropertyValueList
        for prop_set in mod_data.get('propertyValueList', []):
            res = run_modify(template, tag_prefix, prop_set)
            err_str = "Failed to modify properties in the " + \
                "StmTemplateConfig given JSON specified as: " + \
                str(prop_set)

        # Modify the stuff in the StmPropertyModifierList
        for prop_set in mod_data.get("stmPropertyModifierList", []):
            res = run_config_prop_modifier(template, tag_prefix, prop_set)
            err_str = "Failed to add or configure " + \
                "StmPropertyModifier objects in the StmTemplateConfig " + \
                "given JSON specified as: " + str(prop_set)

        # Modify PDUs
        for pdu_mod in mod_data.get("pduModifierList", []):
            res = run_config_pdu(template, tag_prefix, pdu_mod)
            err_str = "Failed to modify PDU data in a streamblock's " + \
                "FrameConfig in the StmTemplateConfig given JSON " + \
                "specified as: " + str(pdu_mod)

        # Modify the stuff in the RelationList
        for rel_mod in mod_data.get("relationList", []):
            res = run_config_relation(template, tag_prefix, rel_mod)
            err_str = "Failed to add or remove a relation in the " + \
                "StmTemplateConfig given JSON specified as " + str(rel_mod)

        if not res:
            plLogger.LogError(err_str)
            this_cmd.Set("Status", err_str)
            return False

    # Handle Expand if necessary
    if AutoExpandTemplate:
        res = run_expand(template, TargetTagList,
                         SrcTagList, CopiesPerParent)
        if not res:
            err_str = "Failed to expand the StmTemplateConfig."
            plLogger.LogError(err_str)
            this_cmd.Set("Status", err_str)
            return False

    this_cmd.Set("Status", "")
    return True
Пример #3
0
def run(
    StmTemplateConfig, SrcTagList, TargetTagList, TagPrefix, TemplateXml, TemplateXmlFileName, EnableLoadFromFileName
):
    plLogger = PLLogger.GetLogger("methodology")
    plLogger.LogDebug("run MergeTemplateCommand")

    hnd_reg = CHandleRegistry.Instance()
    temp_conf = hnd_reg.Find(StmTemplateConfig)

    if temp_conf is None:
        plLogger.LogError("ERROR: Failed to find a valid StmTemplateConfig")
        return False

    # Get the template XML (target XML) and renormalize the IDs
    template = temp_conf.Get("TemplateXml")
    target_root = etree.fromstring(template)

    # FIXME:
    # RENORMALIZE must ALSO remove invalid relations and potentially invalid
    # property values (for type handle).  Otherwise, renumbering the objects
    # may end up relating things that shouldn't be related.
    # Example:
    # <Relation type="DefaultSelection" target="15"/>
    #  Object with ID 15 doesn't exist if the XML was stripped incorrectly
    #  but it will probably exist when the objects are renumbered.

    xml_utils.renormalize_xml_obj_ids(target_root)

    # Get the new current object ID (1 + maximum object ID)
    curr_id = xml_utils.get_max_object_id(target_root, 0) + 1

    # Find the target elements
    target_ele_list = find_tagged_filtered_elements(target_root, TargetTagList)
    if len(target_ele_list) < 1:
        plLogger.LogError(
            "Found no target elements in the " + "StmTemplateConfig in to which the " + "new XML should be merged into."
        )
        return False

    # Get the source XML
    merge_xml = None
    if not EnableLoadFromFileName:
        merge_xml = TemplateXml
        if merge_xml == "":
            plLogger.LogError("No valid XML Template String defined.")
            return False
    elif TemplateXmlFileName != "":
        merge_xml = xml_utils.load_xml_from_file(TemplateXmlFileName)
        if merge_xml is None:
            plLogger.LogError("No valid XML Template File defined.")
            return False

    source_root = etree.fromstring(merge_xml)

    # Find the source elements
    src_ele_list = find_tagged_filtered_elements(source_root, SrcTagList)
    if len(src_ele_list) < 1:
        plLogger.LogError(
            "Found no source elements in the input XML "
            + "from which XML should be copied into the "
            + "StmTemplateConfig from."
        )
        return False

    # FIXME:
    # Source elements should not contain other source elements
    # Need to prevent this from happening

    # Find the Tags object in the target XML
    target_tags_ele = target_root.find(".//Tags")
    if target_tags_ele is None:
        plLogger.LogError("ERROR: Target XML has no Tags element!")
        return False

    # Merge Tag objects from the XML source if necessary
    copy_src_tag_list = []
    for src_ele in src_ele_list:
        tag_ele_list = src_ele.findall(".//Relation")
        for tag_ele in tag_ele_list:
            if tag_ele.get("type") == "UserTag":
                copy_src_tag_list.append(tag_ele.get("target"))
    copy_src_tag_list = set(copy_src_tag_list)
    plLogger.LogDebug("copy_src_tag_list: " + str(copy_src_tag_list))

    # Find the tags in the source XML and extract the ones of interest
    copy_src_tag_ele_list = []
    src_tag_ele_list = source_root.findall(".//Tag")
    for src_tag_ele in src_tag_ele_list:
        if src_tag_ele.get("id") in copy_src_tag_list:
            copy_src_tag_ele_list.append(src_tag_ele)
    plLogger.LogDebug("copy_src_tag_ele_list: " + str(copy_src_tag_ele_list))
    # Store the mappings between the old ID, new ID, old and new name
    # These will be used later to update relations and
    # StmPropertyModifier objects
    new_src_tag_id_map = {}
    new_src_tag_name_map = {}
    for src_tag_ele in copy_src_tag_ele_list:
        src_tag_ele_copy = xml_utils.get_etree_copy(src_tag_ele)

        # Update the tag's Name if the TagPrefix is defined
        old_name = src_tag_ele_copy.get("Name")
        if TagPrefix != "":
            new_name = TagPrefix + old_name
        else:
            new_name = old_name
        src_tag_ele_copy.set("Name", new_name)

        # Update the ID
        old_id = src_tag_ele_copy.get("id")
        src_tag_ele_copy.set("id", str(curr_id))

        # Store both for use later
        new_src_tag_id_map[old_id] = curr_id
        new_src_tag_name_map[old_name] = new_name

        target_tags_ele.append(src_tag_ele_copy)
        xml_utils.create_relation_element(target_tags_ele, "UserTag", str(curr_id))

        curr_id = curr_id + 1
    plLogger.LogDebug("new_src_tag_id_map: " + str(new_src_tag_id_map))
    plLogger.LogDebug("new_src_tag_name_map: " + str(new_src_tag_name_map))

    # Merge the sources into the target(s)
    for target_ele in target_ele_list:
        for src_ele in src_ele_list:
            plLogger.LogInfo("merging " + str(src_ele) + " into " + str(target_ele))
            # Renumber the object IDs
            src_ele_copy = xml_utils.get_etree_copy(src_ele)
            xml_utils.renormalize_xml_obj_ids(src_ele_copy, start_id=curr_id)

            # Update the tag IDs (should have been lost
            # unless src_ele is Tags...which is not allowed).
            update_relation_targets(src_ele_copy, new_src_tag_id_map)

            # Update the StmPropertyModifiers
            update_property_modifier_tag_names(src_ele_copy, new_src_tag_name_map)

            plLogger.LogInfo(" src_ele_copy: " + etree.tostring(src_ele_copy))
            target_ele.append(src_ele_copy)

            # Increment the current max ID
            curr_id = curr_id + 1

    # Clean up the invalid handles
    xml_utils.remove_invalid_stc_handles(target_root)
    xml_value = etree.tostring(target_root)
    plLogger.LogInfo("FINAL xml_value: " + etree.tostring(target_root))
    temp_conf.Set("TemplateXml", xml_value)

    return True