Пример #1
0
    def _send_request(self,
                      suffix,
                      data=None,
                      content_type=None,
                      artifact_id=None):
        if self._base_url.startswith("http://"):
            url = "{}/{}".format(self._base_url, suffix)
        else:
            url = "http://{}/{}".format(self._base_url, suffix)

        headers = {}

        if content_type is not None:
            headers['Content-Type'] = content_type

        try:
            if data is not None:
                result = requests.post(url, headers=headers, data=data)
            else:
                result = requests.get(url, headers=headers)

            if result.status_code == 404:
                raise ArtifactException(
                    "No such artifact as {}".format(artifact_id))

            elif not result.ok:
                raise ArtifactException("Error {} {}".format(
                    result.status_code, result.reason))

        except BaseException as err:
            raise ArtifactException(err)

        return result.text
Пример #2
0
def do_list_artifact(args, config):
    """
    Lists out all the state associating with the UUIDs in the
    Transaction Family : Artifact
    
    Args:
        config (ConfigParser): ConfigParser which contains the default url
    
    Returns:
        type: str
        String representing JSON object which allows the client to know that
        the call was either a success or a failure.
    
    Raises:
        ArtifactException:
            * If failed to retrieve the list
            
    """
    b_url = config.get("DEFAULT", "url")
    client = ArtifactBatch(base_url=b_url)
    result = client.list_artifact()

    if result is not None:
        result.sort(key=lambda x: x["timestamp"], reverse=True)
        result = json.dumps(result)

        output = ret_msg("success", "OK", "ListOf:ArtifactRecord", result)

        print(output)
    else:
        raise ArtifactException("Could not retrieve artifact listing.")
Пример #3
0
def main(prog_name=os.path.basename(sys.argv[0]), args=None):
    if args is None:
        args = sys.argv[1:]
    parser = create_parser(prog_name)
    args = parser.parse_args(args)

    if args.verbose is None:
        verbose_level = 0
    else:
        verbose_level = args.verbose

    setup_loggers(verbose_level=verbose_level)

    config = load_config()

    if args.command == "create":
        do_create_artifact(args, config)
    elif args.command == "list-artifact":
        do_list_artifact(args, config)
    elif args.command == "retrieve":
        do_retrieve_artifact(args, config)
    elif args.command == "amend":
        do_amend_artifact(args, config)
    elif args.command == "AddArtifact":
        do_add_sub_artifact(args, config)
    elif args.command == "AddURI":
        do_add_uri_to_artifact(args, config)
    else:
        raise ArtifactException("invalid command {}".format(args.command))
Пример #4
0
def main_wrapper():
    try:
        main()
    except ArtifactException as err:
        errmsg = str(err)
        if "404" in errmsg:
            exp = ret_msg("failed", "404 Not Found", "EmptyRecord", "{}")
            print(ArtifactException(exp))

        else:
            exp = ret_msg("failed", errmsg, "EmptyRecord", "{}")
            print(ArtifactException())
        sys.exit(1)
    except KeyboardInterrupt:
        pass
    except SystemExit as err:
        raise err
    except BaseException as err:
        traceback.print_exc(file=sys.stderr)
        sys.exit(1)
Пример #5
0
def do_list_artifact(args, config):
    url = config.get('DEFAULT', 'url')

    client = ArtifactBatch(base_url=url)

    result = client.list_artifact()
    
    if (result is not None):
        result = refine_output_artifact(str(result))
        result = amend_artifact_fields(result)
        output = ret_msg("success","OK","ListOf:ArtifactRecord",result)
        print(output)
    else:     
        raise ArtifactException("Could not retrieve artifact listing")
Пример #6
0
def do_retrieve_artifact(args, config):
    artifact_id = args.artifact_id

    url = config.get('DEFAULT', 'url')
  
    client = ArtifactBatch(base_url=url)

    result = client.retrieve_artifact(artifact_id).decode()

    if result is not None:
        output = ''
        result = filter_output(result)
        output = ret_msg("success","OK","ArtifactRecord",result)
        print(output)
    else:
        raise ArtifactException("Artifact not found {}".format(artifact_id))
Пример #7
0
def do_retrieve_artifact(args, config):
    """
    Retrieves the state associating with the UUID in the
    Transaction Family : Artifact
    
    Args:
        args (ArgumentParser):
            ArgumentParser object containing required parameters
        config (ConfigParser): ConfigParser which contains the default url
        
    Returns:
        type: str
        String representing JSON object which allows the client to know that
        the call was either a success or a failure.
    
    Raises:
        ArtifactException:
            * If failed to retrieve the uuid
    
    """
    all_flag = args.all
    range_flag = args.range

    artifact_id = args.artifact_id

    if range_flag != None:
        all_flag = True

    b_url = config.get("DEFAULT", "url")
    client = ArtifactBatch(base_url=b_url)
    data = client.retrieve_artifact(artifact_id, all_flag, range_flag)

    if data is not None:

        if all_flag == False:
            output = ret_msg("success", "OK", "ArtifactRecord", data.decode())
        else:
            output = ret_msg("success", "OK", "ArtifactRecord", data)

        print(output)
    else:
        raise ArtifactException("Artifact not found {}".format(artifact_id))
Пример #8
0
def print_msg(response, cmd=None):
    """
    Helps create the return message for the terminal or the web-browser.
    
    Args:
        response (None or list containing None and str):
            Contains the data for the function to construct return message
        cmd (None or str): The subcommand which was performed
    
    Returns:
        type: str
        String representing JSON object which allows the client to know that
        the call was either a success or a failure. 
    
    Raises:
        ArtifactException:
            * If response is None
            * If response is unknown
            * If response is a list with None
    
    """
    try:
        if type(response) is list and response[0] == None:
            if len(response) > 1:
                raise ArtifactException("ArtifactException : {}".format(
                    response[1]))
            raise ArtifactException("ArtifactException : No change.")

        if response == None:
            if cmd == "create":
                raise ArtifactException("ArtifactException : Duplicate UUID.")

            elif cmd == "amend" or cmd == "AddArtifact" or cmd == "AddURI":
                raise ArtifactException(
                    "ArtifactException : UUID does not exist.")

            raise ArtifactException("Exception raised.")
        elif "batch_statuses?id" in response:
            print(ret_msg("success", "OK", "ArtifactRecord", "{}"))
            return ret_msg("success", "OK", "ArtifactRecord", "{}")
        else:
            raise ArtifactException("Exception raised.")
    except BaseException as err:
        output = ret_msg("failed", str(err), "ArtifactRecord", "{}")
        print(output)
        return output
Пример #9
0
    def _send_request(self,
                      suffix,
                      data=None,
                      content_type=None,
                      artifact_id=None,
                      creation=False):
        """
        Performs RESTful API call on the given params.
        
        Args:
            suffix (str): The suffix of the url in query
            data (str): The data to be sent in POST request (default None)
            content_type (str): The data type (default None)
            artifact_id (str): The uuid of the artifact (default None)
            creation (bool): The flag for "create" command (default False)
        
        Returns:
            type: str
            Data associated with suffix as a string.
            
                or
                
            type: None
            None object if any exception occurs or "404" was raised during
            "create" command.
            
        Raises:
            ArtifactException:
                * If "404" was raised for the request
                * If status was "sucessful"
            
        """
        # Building the URL
        if self._base_url.startswith("http://"):
            url = "{}/{}".format(self._base_url, suffix)
        else:
            url = "http://{}/{}".format(self._base_url, suffix)

        headers = {}

        if content_type is not None:
            headers["Content-Type"] = content_type

        # Performing appropriate RESTful API
        try:
            if data is not None:
                result = requests.post(url, headers=headers, data=data)
            else:
                result = requests.get(url, headers=headers)

            if result.status_code == 404:
                if creation:
                    return None
                raise ArtifactException(
                    "No such artifact as {}".format(artifact_id))

            elif not result.ok:
                raise ArtifactException("Error {} {}".format(
                    result.status_code, result.reason))

        except BaseException as err:
            print(err)
            return None

        # Returning the data as string
        return result.text