Пример #1
0
    def _send_request(self,
                      suffix,
                      data=None,
                      content_type=None,
                      category_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 CategoryException("No such Category: {}".\
                        format(category_id))

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

        except BaseException as err:
            print(err)
            raise CategoryException(err)

        return result.text
Пример #2
0
def do_list_category(args, config):
    """
    Lists out all the state associating with the UUIDs in the
    Transaction Family : Category
    
    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:
        CategoryException:
            * If failed to retrieve the list
            
    """
    b_url = config.get("DEFAULT", "url")
    client = CategoryBatch(base_url=b_url)
    category_list = client.list_category()

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

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

        print(output)
    else:
        raise CategoryException("Could not retrieve category 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_category(args, config)
    elif args.command == 'init':
        do_init(args, config)
    elif args.command == 'list-category':
        do_list_category(args, config)
    elif args.command == 'retrieve':
        do_retrieve_category(args, config)
    else:
        raise CategoryException("invalid command: {}".format(args.command))
Пример #4
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:
        CategoryException:
            * 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:
            raise CategoryException("CategoryException : No change.")

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

            elif cmd == "amend":
                raise CategoryException(
                    "CategoryException : UUID does not exist.")

            raise CategoryException("Exception raised.")
        elif "batch_statuses?id" in response:
            print(ret_msg("success", "OK", "CategoryRecord", "{}"))
            return ret_msg("success", "OK", "CategoryRecord", "{}")
        else:
            raise CategoryException("Exception raised.")
    except BaseException as err:
        output = ret_msg("failed", str(err), "CategoryRecord", "{}")
        print(output)
        return output
Пример #5
0
def main_wrapper():
    try:
        main()
    except CategoryException as err:
        errmsg = str(err)
        if '404' in errmsg:
            exp = ret_msg("failed", "404 Not Found", "EmptyRecord", "{}")
            print(CategoryException(exp))

        else:
            exp = ret_msg("failed", errmsg, "EmptyRecord", "{}")
            print(CategoryException())
        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)
Пример #6
0
def do_retrieve_category(args, config):
    category_id = args.category_id
    url = config.get('DEFAULT', 'url')
    client = CategoryBatch(base_url=url)

    data = client.retreive_category(category_id)

    if data is not None:
        result = filter_output(str(data))
        output = ret_msg("success", "OK", "CategoryRecord", result)
        print(output)
    else:
        raise CategoryException("Category not found: {}".format(category_id))
Пример #7
0
def do_list_category(args, config):
    url = config.get('DEFAULT', 'url')
    key_file = config.get('DEFAULT', 'key_file')
    auth_user, auth_password = _get_auth_info(args)

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

    category_list = client.list_category(auth_user=auth_user,
                                         auth_password=auth_password)

    if category_list is not None:
        output = refine_output(str(category_list))
        print(output)
    else:
        raise CategoryException("Could not retrieve category listing.")
Пример #8
0
def do_list_category(args, config):
    b_url = config.get('DEFAULT', 'url')
  
    client = CategoryBatch(base_url=b_url)

    category_list = client.list_category()

    if category_list is not None:
        
        if str(category_list) != "[]":
            result = refine_output(str(category_list))
            output = ret_msg("success","OK","ListOf:CategoryRecord",result)
        else:
            output = ret_msg("success","OK","ListOf:CategoryRecord",str(category_list))
        print (output)
    else:
        raise CategoryException("Could not retrieve category listing.")
Пример #9
0
def do_retrieve_category(args, config):
    category_id = args.category_id

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

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

    data = client.retreive_category(category_id,
                                    auth_user=auth_user,
                                    auth_password=auth_password)

    if data is not None:
        output = filter_output(str(data))
        print(output)
    else:
        raise CategoryException("Category not found: {}".format(category_id))
Пример #10
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 CategoryException("IOError: {}".format(str(ioe)))
Пример #11
0
def do_retrieve_category(args, config):
    """
    Retrieves the state associating with the UUID in the
    Transaction Family : Category
    
    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:
        CategoryException:
            * If failed to retrieve the uuid
    
    """
    all_flag = args.all
    range_flag = args.range

    category_id = args.category_id

    if range_flag != None:
        all_flag = True

    b_url = config.get("DEFAULT", "url")
    client = CategoryBatch(base_url=b_url)
    data = client.retreive_category(category_id, all_flag, range_flag)

    if data is not None:

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

        print(output)
    else:
        raise CategoryException("Category not found: {}".format(category_id))
Пример #12
0
def do_retrieve_category(args, config):
    all_flag = args.all
    range_flag = args.range
    
    category_id = args.category_id
    
    if range_flag != None:
        all_flag = True
    
    b_url = config.get("DEFAULT", "url")
    client = CategoryBatch(base_url=b_url)
    data = client.retreive_category(category_id, all_flag, range_flag)
    
    if data is not None:
        
        if all_flag == False:
            output = ret_msg("success", "OK", "CategoryRecord", data.decode())
        else:
            output = ret_msg("success", "OK", "CategoryRecord", json.loads(data))
            
        print(output)
    else:
        raise CategoryException("Category not found: {}".format(category_id))
Пример #13
0
def do_list_category(args, config):
    b_url = config.get("DEFAULT", "url")
  
    client = CategoryBatch(base_url=b_url)

    category_list = client.list_category()

    if category_list is not None:
        
        if str(category_list) != "[]":
            result = ("[" + str(category_list)[3:-2] + "]").replace("b'", "")\
                        .replace("'", "")
            result = json.loads(result)
            result.sort(key=lambda x:x["timestamp"], reverse=True)
            result = json.dumps(result)
            
            output = ret_msg("success", "OK", "ListOf:CategoryRecord", result)
        else:
            output = ret_msg("success", "OK", "ListOf:CategoryRecord", 
                        str(category_list))
        print (output)
    else:
        raise CategoryException("Could not retrieve category listing.")
Пример #14
0
    def _send_request(self,
                      suffix,
                      data=None,
                      content_type=None,
                      category_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)
            category_id (str): The uuid of the category (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:
            CategoryException:
                * 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 CategoryException("No such Category: {}".\
                        format(category_id))

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

        except BaseException as err:
            print(err)
            return None

        # Returning the data as string
        return result.text