def _send_request(
            self, suffix, data=None,
            content_type=None, pt_id=None, auth_user=None, auth_password=None):
        if self._base_url.startswith("http://"):
            url = "{}/{}".format(self._base_url, suffix)
        else:
            url = "http://{}/{}".format(self._base_url, suffix)

        headers = {}
        if auth_user is not None:
            auth_string = "{}:{}".format(auth_user, auth_password)
            b64_string = b64encode(auth_string.encode()).decode()
            auth_header = 'Basic {}'.format(b64_string)
            headers['Authorization'] = auth_header

        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 PartException("No part found: {}".format(pt_id))

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

        except BaseException as err:
            raise PartException(err)

        return result.text
Esempio n. 2
0
    def _send_request(self, suffix, data=None, content_type=None, pt_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 PartException("No part found: {}".format(pt_id))

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

        except BaseException as err:
            raise PartException(err)

        return result.text
Esempio n. 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_part(args, config)
    elif args.command == "list-part":
        do_list_part(config)
    elif args.command == "retrieve":
        do_retrieve_part(args, config)
    elif args.command == "amend":
        do_amend_part(args, config)
    elif args.command == "AddArtifact":
        do_add_artifact(args, config)     
    elif args.command == "AddOrganization":
        do_add_organization(args, config)     
    elif args.command == "AddCategory":
        do_add_category(args, config)          
    else:
        raise PartException("invalid command: {}".format(args.command))
Esempio n. 4
0
def do_list_part(config):
    """
    Lists out all the state associating with the UUIDs in the
    Transaction Family : Part
    
    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:
        PartException:
            * If failed to retrieve the list
            
    """
    b_url = config.get("DEFAULT", "url")
    client = PartBatch(base_url=b_url)
    result = client.list_part()

    if result is not None:
        result.sort(key=lambda x:x["timestamp"], reverse=True)
        result = json.dumps(result)
        
        output = ret_msg("success", "OK", "ListOf:PartRecord", result)
        
        print(output)
    else:
        raise PartException("Could not retrieve part listing.")
Esempio n. 5
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(args, config)

    elif args.command == 'list-part':
        do_list_part(args, config)
    elif args.command == 'retrieve':
        do_retrieve(args, config)
    elif args.command == 'AddArtifact':
        do_add_artifact(args, config)
    elif args.command == 'AddSupplier':
        add_Supplier(args, config)
    elif args.command == 'AddCategory':
        add_Category(args, config)
    else:
        raise PartException("invalid command: {}".format(args.command))
Esempio n. 6
0
def main_wrapper():
    try:
        main()
    except PartException as err:
        errmsg = str(err)
        if "404" in errmsg:
            exp = ret_msg("failed","404 Not Found","EmptyRecord","{}")
            print(PartException(exp))
           
        else:
            exp = ret_msg("failed",errmsg,"EmptyRecord","{}")
            print(PartException()) 
        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)
Esempio n. 7
0
def do_list_part(args, config):
    url = config.get('DEFAULT', 'url')

    client = PartBatch(base_url=url)
    result = client.list_part()

    if result is not None:
        result = refine_output(str(result))
        output = ret_msg("success", "OK", "ListOf:PartRecord", result)
        print(output)
    else:
        raise PartException("Could not retrieve part listing.")
Esempio n. 8
0
def do_list_part(args, config):
    url = config.get('DEFAULT', 'url')
    key_file = config.get('DEFAULT', 'key_file')
    auth_user, auth_password = _get_auth_info(args)

    client = PartBatch(base_url=url, keyfile=key_file)

    result = client.list_part(auth_user=auth_user, auth_password=auth_password)

    if result is not None:
        output = refine_output(str(result))
        print(output)
    else:
        raise PartException("Could not retrieve part listing.")
Esempio n. 9
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:
        PartException:
            * 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 PartException(
                        "PartException : {}".format(response[1])
                    )
            raise PartException(
                        "PartException : No change."
                    )
        
        if response == None:
            if cmd == "create":
                raise PartException("PartException : Duplicate UUID.")
                
            elif (cmd == "amend" or cmd == "AddOrganization" or 
                    cmd == "AddArtifact" or cmd == "AddCategory"):
                raise PartException(
                            "PartException : UUID does not exist."
                        )
                
            raise PartException("Exception raised.")
        elif "batch_statuses?id" in response:
            print(ret_msg("success", "OK", "PartRecord", "{}"))
            return ret_msg("success", "OK", "PartRecord", "{}")
        else:
            raise PartException("Exception raised.")
    except BaseException as err:
        output = ret_msg(
                            "failed",
                            str(err),
                            "PartRecord", "{}"
                        )
        print(output)
        return output
Esempio n. 10
0
def do_retrieve(args, config):

    pt_id = args.pt_id

    url = config.get('DEFAULT', 'url')

    client = PartBatch(base_url=url)

    result = client.retrieve_part(pt_id).decode()

    if result is not None:
        result = filter_output(str(result))
        output = ret_msg("success", "OK", "PartRecord", result)
        print(result)

    else:
        raise PartException("Part not found: {}".format(pt_id))
Esempio n. 11
0
def do_retrieve_part(args, config):
    """
    Retrieves the state associating with the UUID in the
    Transaction Family : Part
    
    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:
        PartException:
            * If failed to retrieve the uuid
    
    """
    all_flag = args.all
    range_flag = args.range
    
    pt_id = args.pt_id
    
    if range_flag != None:
        all_flag = True
    
    b_url = config.get("DEFAULT", "url")
    client = PartBatch(base_url=b_url)
    data = client.retrieve_part(pt_id, all_flag, range_flag)
    
    if data is not None:
        
        if all_flag == False:
            output = ret_msg("success", "OK", "PartRecord", data.decode())
        else:
            output = ret_msg("success", "OK", "PartRecord", data)
            
        print(output)
    else:
        raise PartException("Part not found: {}".format(pt_id))
Esempio n. 12
0
def do_init(args, config):
    username = config.get('DEFAULT', 'username')
    if args.username is not None:
        username = args.username

    url = config.get('DEFAULT', 'url')
    if args.url is not None:
        url = args.url

    config.set('DEFAULT', 'username', username)
    print("set username: {}".format(username))
    config.set('DEFAULT', 'url', url)
    print("set url: {}".format(url))

    save_config(config)

    priv_filename = config.get('DEFAULT', 'key_file')
    if priv_filename.endswith(".priv"):
        addr_filename = priv_filename[0:-len(".priv")] + ".addr"
    else:
        addr_filename = priv_filename + ".addr"

    if not os.path.exists(priv_filename):
        try:
            if not os.path.exists(os.path.dirname(priv_filename)):
                os.makedirs(os.path.dirname(priv_filename))

            privkey = signing.generate_privkey()
            pubkey = signing.generate_pubkey(privkey)
            addr = signing.generate_identifier(pubkey)

            with open(priv_filename, "w") as priv_fd:
                print("writing file: {}".format(priv_filename))
                priv_fd.write(privkey)
                priv_fd.write("\n")

            with open(addr_filename, "w") as addr_fd:
                print("writing file: {}".format(addr_filename))
                addr_fd.write(addr)
                addr_fd.write("\n")
        except IOError as ioe:
            raise PartException("IOError: {}".format(str(ioe)))
Esempio n. 13
0
def do_retrieve(args, config):

    pt_id = args.pt_id

    url = config.get('DEFAULT', 'url')
    key_file = config.get('DEFAULT', 'key_file')
    auth_user, auth_password = _get_auth_info(args)

    client = PartBatch(base_url=url, keyfile=key_file)

    result = client.retrieve_part(pt_id,
                                  auth_user=auth_user,
                                  auth_password=auth_password).decode()

    if result is not None:
        result = filter_output(str(result))
        print(result)

    else:
        raise PartException("Part not found: {}".format(pt_id))
Esempio n. 14
0
    def _send_request(self,
                      suffix,
                      data=None,
                      content_type=None,
                      pt_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)
            pt_id (str): The uuid of the part (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:
            PartException:
                * 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 PartException("No part found: {}".format(pt_id))

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

        except BaseException as err:
            print(err)
            return None

        # Returning the data as string
        return result.text