<commit_before>from fmcapi.api_objects.apiclasstemplate import APIClassTemplate
from fmcapi.api_objects.policy_services.accesspolicies import AccessPolicies
from fmcapi.api_objects.policy_services.intrusionpolicies import IntrusionPolicies
from fmcapi.api_objects.object_services.variablesets import VariableSets
from fmcapi.api_objects.object_services.securityzones import SecurityZones
from fmcapi.api_objects.object_services.vlantags import VlanTags
from fmcapi.api_objects.object_services.portobjectgroups import PortObjectGroups
from fmcapi.api_objects.object_services.protocolportobjects import ProtocolPortObjects
from fmcapi.api_objects.object_services.fqdns import FQDNS
from fmcapi.api_objects.object_services.networkgroups import NetworkGroups
from fmcapi.api_objects.object_services.networkaddresses import NetworkAddresses
from fmcapi.api_objects.policy_services.filepolicies import FilePolicies
from fmcapi.api_objects.object_services.isesecuritygrouptags import ISESecurityGroupTags
from fmcapi.api_objects.helper_functions import get_networkaddress_type
import logging
import sys
import warnings


class AccessRules(APIClassTemplate):
    """
    The AccessRules Object in the FMC.
    """

    VALID_JSON_DATA = [
        "id",
        "name",
        "type",
        "action",
        "enabled",
        "sendEventsToFMC",
        "logFiles",
        "logBegin",
        "logEnd",
        "variableSet",
        "originalSourceNetworks",
        "vlanTags",
        "sourceNetworks",
        "destinationNetworks",
        "sourcePorts",
        "destinationPorts",
        "ipsPolicy",
        "urls",
        "sourceZones",
        "destinationZones",
        "applications",
        "filePolicy",
        "sourceSecurityGroupTags",
        "destinationSecurityGroupTags",
    ]
    VALID_FOR_KWARGS = VALID_JSON_DATA + [
        "acp_id",
        "acp_name",
        "insertBefore",
        "insertAfter",
        "section",
    ]
    PREFIX_URL = "/policy/accesspolicies"
    REQUIRED_FOR_POST = ["name", "acp_id"]
    REQUIRED_FOR_GET = ["acp_id"]
    VALID_FOR_ACTION = [
        "ALLOW",
        "TRUST",
        "BLOCK",
        "MONITOR",
        "BLOCK_RESET",
        "BLOCK_INTERACTIVE",
        "BLOCK_RESET_INTERACTIVE",
    ]
    VALID_CHARACTERS_FOR_NAME = """[.\w\d_\- ]"""

    @property
    def URL_SUFFIX(self):
        """
        Add the URL suffixes for categories, insertBefore and insertAfter
        NOTE: You must specify these at the time the object is initialized (created) for this feature
        to work correctly. Example:
            This works:
                new_rule = AccessRules(fmc=fmc, acp_name='acp1', insertBefore=2)

            This does not:
                new_rule = AccessRules(fmc=fmc, acp_name='acp1')
                new_rule.insertBefore = 2
        """
        url = "?"

        if "category" in self.__dict__:
            url = f"{url}category={self.category}&"
        if "insertBefore" in self.__dict__:
            url = f"{url}insertBefore={self.insertBefore}&"
        if "insertAfter" in self.__dict__:
            url = f"{url}insertAfter={self.insertAfter}&"
        if "insertBefore" in self.__dict__ and "insertAfter" in self.__dict__:
            logging.warning("ACP rule has both insertBefore and insertAfter params")
        if "section" in self.__dict__:
            url = f"{url}section={self.section}&"

        return url[:-1]

    def __init__(self, fmc, **kwargs):
        super().__init__(fmc, **kwargs)
        logging.debug("In __init__() for AccessRules class.")
        self.type = "AccessRule"
        self.parse_kwargs(**kwargs)
        self.URL = f"{self.URL}{self.URL_SUFFIX}"

    def format_data(self, filter_query=""):
        json_data = super().format_data(filter_query=filter_query)
        logging.debug("In format_data() for AccessRules class.")
        if "sourceNetworks" in self.__dict__:
            json_data["sourceNetworks"] = {"objects": self.sourceNetworks["objects"]}
            json_data["sourceNetworks"]["literals"] = [
                {"type": v, "value": k}
                for k, v in self.sourceNetworks["literals"].items()
            ]
        if "destinationNetworks" in self.__dict__:
            json_data["destinationNetworks"] = {
                "objects": self.destinationNetworks["objects"]
            }
            json_data["destinationNetworks"]["literals"] = [
                {"type": v, "value": k}
                for k, v in self.destinationNetworks["literals"].items()
            ]
        if "action" in self.__dict__:
            if self.action not in self.VALID_FOR_ACTION:
                logging.warning(f"Action {self.action} is not a valid action.")
                logging.warning(f"\tValid actions are: {self.VALID_FOR_ACTION}.")
        return json_data

    def parse_kwargs(self, **kwargs):
        super().parse_kwargs(**kwargs)
        logging.debug("In parse_kwargs() for AccessRules class.")
        if "acp_id" in kwargs:
            self.acp(id=kwargs["acp_id"])
        if "acp_name" in kwargs:
            self.acp(name=kwargs["acp_name"])
        if "action" in kwargs:
            if kwargs["action"] in self.VALID_FOR_ACTION:
                self.action = kwargs["action"]
            else:
                logging.warning(f"Action {kwargs['action']} is not a valid action.")
                logging.warning(f"\tValid actions are: {self.VALID_FOR_ACTION}.")
        if "sourceNetworks" in kwargs:
            self.sourceNetworks = {"objects": [], "literals": {}}
            if kwargs["sourceNetworks"].get("objects"):
                self.sourceNetworks["objects"] = kwargs["sourceNetworks"]["objects"]
            if kwargs["sourceNetworks"].get("literals"):
                for literal in kwargs["sourceNetworks"]["literals"]:
                    self.sourceNetworks["literals"][literal["value"]] = literal["type"]
        if "destinationNetworks" in kwargs:
            self.destinationNetworks = {"objects": [], "literals": {}}
            if kwargs["destinationNetworks"].get("objects"):
                self.destinationNetworks["objects"] = kwargs["destinationNetworks"][
                    "objects"
                ]
            if kwargs["destinationNetworks"].get("literals"):
                for literal in kwargs["destinationNetworks"]["literals"]:
                    self.destinationNetworks["literals"][literal["value"]] = literal[
                        "type"
                    ]

        # Check if suffix should be added to URL
        # self.url_suffix()

    def acp(self, name="", id=""):
        # either name or id of the ACP should be given
        logging.debug("In acp() for AccessRules class.")
        if id != "":
            self.URL = f"{self.fmc.configuration_url}{self.PREFIX_URL}/{id}/accessrules"
        elif name != "":
            acp1 = AccessPolicies(fmc=self.fmc)
            acp1.get(name=name)
            if "id" in acp1.__dict__:
                self.URL = f"{self.fmc.configuration_url}{self.PREFIX_URL}/{acp1.id}/accessrules"
            else:
                logging.warning(
                    f"Access Control Policy {name} not found.  Cannot set up accessPolicy for AccessRules."
                )
        else:
            logging.error("No accessPolicy name or ID was provided.")
<commit_msg>Set up getter/setter for enabled, logBegin, logEnd, and sendEventsToFMC variables.<commit_after>from fmcapi.api_objects.apiclasstemplate import APIClassTemplate
from fmcapi.api_objects.policy_services.accesspolicies import AccessPolicies
from fmcapi.api_objects.policy_services.intrusionpolicies import IntrusionPolicies
from fmcapi.api_objects.object_services.variablesets import VariableSets
from fmcapi.api_objects.object_services.securityzones import SecurityZones
from fmcapi.api_objects.object_services.vlantags import VlanTags
from fmcapi.api_objects.object_services.portobjectgroups import PortObjectGroups
from fmcapi.api_objects.object_services.protocolportobjects import ProtocolPortObjects
from fmcapi.api_objects.object_services.fqdns import FQDNS
from fmcapi.api_objects.object_services.networkgroups import NetworkGroups
from fmcapi.api_objects.object_services.networkaddresses import NetworkAddresses
from fmcapi.api_objects.policy_services.filepolicies import FilePolicies
from fmcapi.api_objects.object_services.isesecuritygrouptags import ISESecurityGroupTags
from fmcapi.api_objects.helper_functions import get_networkaddress_type, true_false_checker
import logging
import sys
import warnings


class AccessRules(APIClassTemplate):
    """
    The AccessRules Object in the FMC.
    """

    VALID_JSON_DATA = [
        "id",
        "name",
        "type",
        "action",
        "enabled",
        "sendEventsToFMC",
        "logFiles",
        "logBegin",
        "logEnd",
        "variableSet",
        "originalSourceNetworks",
        "vlanTags",
        "sourceNetworks",
        "destinationNetworks",
        "sourcePorts",
        "destinationPorts",
        "ipsPolicy",
        "urls",
        "sourceZones",
        "destinationZones",
        "applications",
        "filePolicy",
        "sourceSecurityGroupTags",
        "destinationSecurityGroupTags",
    ]
    VALID_FOR_KWARGS = VALID_JSON_DATA + [
        "acp_id",
        "acp_name",
        "insertBefore",
        "insertAfter",
        "section",
    ]
    PREFIX_URL = "/policy/accesspolicies"
    REQUIRED_FOR_POST = ["name", "acp_id"]
    REQUIRED_FOR_GET = ["acp_id"]
    VALID_FOR_ACTION = [
        "ALLOW",
        "TRUST",
        "BLOCK",
        "MONITOR",
        "BLOCK_RESET",
        "BLOCK_INTERACTIVE",
        "BLOCK_RESET_INTERACTIVE",
    ]
    VALID_CHARACTERS_FOR_NAME = """[.\w\d_\- ]"""

    @property
    def URL_SUFFIX(self):
        """
        Add the URL suffixes for categories, insertBefore and insertAfter
        NOTE: You must specify these at the time the object is initialized (created) for this feature
        to work correctly. Example:
            This works:
                new_rule = AccessRules(fmc=fmc, acp_name='acp1', insertBefore=2)

            This does not:
                new_rule = AccessRules(fmc=fmc, acp_name='acp1')
                new_rule.insertBefore = 2
        """
        url = "?"

        if "category" in self.__dict__:
            url = f"{url}category={self.category}&"
        if "insertBefore" in self.__dict__:
            url = f"{url}insertBefore={self.insertBefore}&"
        if "insertAfter" in self.__dict__:
            url = f"{url}insertAfter={self.insertAfter}&"
        if "insertBefore" in self.__dict__ and "insertAfter" in self.__dict__:
            logging.warning("ACP rule has both insertBefore and insertAfter params")
        if "section" in self.__dict__:
            url = f"{url}section={self.section}&"

        return url[:-1]

    @property
    def enabled(self):
        return self._enabled

    @enabled.setter
    def enabled(self, value=False):
        self._enabled = true_false_checker(value)

    @property
    def logBegin(self):
        return self._logBegin

    @logBegin.setter
    def logBegin(self, value=False):
        self._logBegin = true_false_checker(value)

    @property
    def logEnd(self):
        return self._logEnd

    @logEnd.setter
    def logEnd(self, value=False):
        self._logEnd = true_false_checker(value)

    @property
    def sendEventsToFMC(self):
        return self._sendEventsToFMC

    @sendEventsToFMC.setter
    def sendEventsToFMC(self, value=False):
        self._sendEventsToFMC = true_false_checker(value)

    def __init__(self, fmc, **kwargs):
        super().__init__(fmc, **kwargs)
        logging.debug("In __init__() for AccessRules class.")
        self.type = "AccessRule"
        self.enabled = False
        self.logBegin = False
        self.logEnd = False
        self.sendEventsToFMC = False
        self.parse_kwargs(**kwargs)
        self.URL = f"{self.URL}{self.URL_SUFFIX}"

    def format_data(self, filter_query=""):
        json_data = super().format_data(filter_query=filter_query)
        logging.debug("In format_data() for AccessRules class.")
        if "sourceNetworks" in self.__dict__:
            json_data["sourceNetworks"] = {"objects": self.sourceNetworks["objects"]}
            json_data["sourceNetworks"]["literals"] = [
                {"type": v, "value": k}
                for k, v in self.sourceNetworks["literals"].items()
            ]
        if "destinationNetworks" in self.__dict__:
            json_data["destinationNetworks"] = {
                "objects": self.destinationNetworks["objects"]
            }
            json_data["destinationNetworks"]["literals"] = [
                {"type": v, "value": k}
                for k, v in self.destinationNetworks["literals"].items()
            ]
        if "action" in self.__dict__:
            if self.action not in self.VALID_FOR_ACTION:
                logging.warning(f"Action {self.action} is not a valid action.")
                logging.warning(f"\tValid actions are: {self.VALID_FOR_ACTION}.")
        return json_data

    def parse_kwargs(self, **kwargs):
        super().parse_kwargs(**kwargs)
        logging.debug("In parse_kwargs() for AccessRules class.")
        if "acp_id" in kwargs:
            self.acp(id=kwargs["acp_id"])
        if "acp_name" in kwargs:
            self.acp(name=kwargs["acp_name"])
        if "action" in kwargs:
            if kwargs["action"] in self.VALID_FOR_ACTION:
                self.action = kwargs["action"]
            else:
                logging.warning(f"Action {kwargs['action']} is not a valid action.")
                logging.warning(f"\tValid actions are: {self.VALID_FOR_ACTION}.")
        if "sourceNetworks" in kwargs:
            self.sourceNetworks = {"objects": [], "literals": {}}
            if kwargs["sourceNetworks"].get("objects"):
                self.sourceNetworks["objects"] = kwargs["sourceNetworks"]["objects"]
            if kwargs["sourceNetworks"].get("literals"):
                for literal in kwargs["sourceNetworks"]["literals"]:
                    self.sourceNetworks["literals"][literal["value"]] = literal["type"]
        if "destinationNetworks" in kwargs:
            self.destinationNetworks = {"objects": [], "literals": {}}
            if kwargs["destinationNetworks"].get("objects"):
                self.destinationNetworks["objects"] = kwargs["destinationNetworks"][
                    "objects"
                ]
            if kwargs["destinationNetworks"].get("literals"):
                for literal in kwargs["destinationNetworks"]["literals"]:
                    self.destinationNetworks["literals"][literal["value"]] = literal[
                        "type"
                    ]
        # Check if suffix should be added to URL
        # self.url_suffix()

    def acp(self, name="", id=""):
        # either name or id of the ACP should be given
        logging.debug("In acp() for AccessRules class.")
        if id != "":
            self.URL = f"{self.fmc.configuration_url}{self.PREFIX_URL}/{id}/accessrules"
        elif name != "":
            acp1 = AccessPolicies(fmc=self.fmc)
            acp1.get(name=name)
            if "id" in acp1.__dict__:
                self.URL = f"{self.fmc.configuration_url}{self.PREFIX_URL}/{acp1.id}/accessrules"
            else:
                logging.warning(
                    f"Access Control Policy {name} not found.  Cannot set up accessPolicy for AccessRules."
                )
        else:
            logging.error("No accessPolicy name or ID was provided.")

{'fraction_non_alphanumeric': 0.11217948717948718, 'fraction_numerical': 0.001153846153846154, 'mean_word_length': 2.433318661971831, 'pattern_counts': {'":': 24, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4434443', 'n_tokens_mistral': 4495, 'n_tokens_neox': 4463, 'n_words': 936}