Ejemplo n.º 1
0
    def _send_request(self, suffix, data=None, content_type=None, 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 OrganizationException(
                    "No such organization: {}".format(id))

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

        except BaseException as err:
            raise OrganizationException(err)

        return result.text
Ejemplo n.º 2
0
    def _send_request(self, suffix, data=None, content_type=None,
                        org_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)
            org_id (str): The uuid of the organization (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:
            OrganizationException:
                * 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 OrganizationException("No such organization: {}".format(id))

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

        except BaseException as err:
            print(err)
            return None
        
        # Returning the data as string
        return result.text
Ejemplo 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_organization(args, config)
    elif args.command == "list-organization":
        do_list_organization(args, config)
    elif args.command == "retrieve":
        do_retrieve_organization(args, config)
    elif args.command == "AddPart":
        do_addpart(args, config)
    elif args.command == "amend":
        do_amend_organization(args, config)
    else:
        raise OrganizationException("invalid command: {}".format(args.command))
Ejemplo n.º 4
0
def do_list_organization(args, config):
    """
    Lists out all the state associating with the UUIDs in the
    Transaction Family : Organization
    
    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:
        OrganizationException:
            * If failed to retrieve the list
            
    """
    b_url = config.get("DEFAULT", "url")
    client = OrganizationBatch(base_url=b_url)
    result = client.list_organization()

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

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

        print(output)
    else:
        raise OrganizationException("Could not retrieve organization listing.")
Ejemplo n.º 5
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:
        OrganizationException:
            * 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 OrganizationException("OrganizationException : No change.")

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

            elif cmd == "amend" or cmd == "AddPart":
                raise OrganizationException(
                    "OrganizationException : UUID does not exist.")

            raise OrganizationException("Exception raised.")
        elif "batch_statuses?id" in response:
            print(ret_msg("success", "OK", "OrganizationRecord", "{}"))
            return ret_msg("success", "OK", "OrganizationRecord", "{}")
        else:
            raise OrganizationException("Exception raised.")
    except BaseException as err:
        output = ret_msg("failed", str(err), "OrganizationRecord", "{}")
        print(output)
        return output
Ejemplo n.º 6
0
def main_wrapper():
    try:
        main()
    except OrganizationException as err:
        errmsg = str(err)
        if "404" in errmsg:
            exp = ret_msg("failed", "404 Not Found", "EmptyRecord", "{}")
            print(OrganizationException(exp))

        else:
            exp = ret_msg("failed", errmsg, "EmptyRecord", "{}")
            print(OrganizationException())
        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)
Ejemplo n.º 7
0
def do_retrieve(args, config):
    id = args.id

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

    data = client.retrieve_organization(id)
    if data is not None:
        data = filter_output(str(data))
        output = ret_msg("success", "OK", "OrganizationRecord", data)
        print(output)
    else:
        raise OrganizationException("Organization not found: {}".format(id))
Ejemplo n.º 8
0
def do_list_organization(args, config):
    b_url = config.get('DEFAULT', 'url')

    client = OrganizationBatch(base_url=b_url)

    result = client.list_organization()

    if result is not None:
        result = refine_output_organization(str(result))
        result = refine_output(result)
        output = ret_msg("success", "OK", "ListOf:OrganizationRecord", result)

        print(output)
    else:
        raise OrganizationException("Could not retrieve organization listing.")
Ejemplo n.º 9
0
def do_retrieve_organization(args, config):
    """
    Retrieves the state associating with the UUID in the
    Transaction Family : Organization
    
    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:
        OrganizationException:
            * If failed to retrieve the uuid
    
    """
    all_flag = args.all
    range_flag = args.range

    org_id = args.org_id

    if range_flag != None:
        all_flag = True

    b_url = config.get("DEFAULT", "url")
    client = OrganizationBatch(base_url=b_url)
    data = client.retrieve_organization(org_id, all_flag, range_flag)

    if data is not None:

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

        print(output)
    else:
        raise OrganizationException(
            "Organization not found: {}".format(org_id))