Exemple #1
0
 def get_HTTP(self) -> HydraError:
     """Return the HTTP response for the Exception."""
     if str(self.id_) is None:
         description = "Instance of type {} already exists".format(self.type_)
         return HydraError(code=400, title="Instance already exists.", desc=description)
     else:
         description = "Instance of type {} with ID {} already exists".format(
             self.type_, str(self.id_))
         return HydraError(code=400, title="Instance already exists.", desc=description)
Exemple #2
0
 def get_HTTP(self) -> HydraError:
     """Return the HTTP response for the Exception."""
     if str(self.id_) is None:
         description = f"Instance of type {self.type_} not found"
         return HydraError(code=404,
                           title="Instance not found",
                           desc=description)
     else:
         description = f"Instance of type {self.type_} with ID {str(self.id_)} not found"
         return HydraError(code=404,
                           title="Instance not found",
                           desc=description)
Exemple #3
0
def parse_collection_members(object_: dict) -> dict:
    """Parse the members of a collection to make it easier
    to insert in database.

    :param object_: The body of the request having object members
    :type object_: dict
    :return: Object with parsed members
    :rtype: dict
    """
    members = list()
    for member in object_['members']:
        # example member
        # {
        #     "@id": "/serverapi/LogEntry/aab38f9d-516a-4bb2-ae16-068c0c5345bd",
        #     "@type": "LogEntry"
        # }
        member_id = member['@id'].split('/')[-1]
        member_type = member['@type']
        if crud.item_exists(member_type, member_id, get_session()):
            members.append({
                "id_": member_id,
                "@type": member_type,
            })
        else:
            error = HydraError(code=400, title="Data is not valid")
            return error_response(error)
    object_['members'] = members
    return object_
Exemple #4
0
def get_context(category: str) -> Response:
    """
    Generate the context for a given category.

    :param category: The category of class for which context is required
    :type category: str
    :return: Response with context
    :rtype: Response
    """
    collections, parsed_classes = get_collections_and_parsed_classes()
    # Check for collection
    if category in get_doc().collections:
        # type: Union[Dict[str,Any],Dict[int,str]]
        response = {"@context": collections[category]["context"].generate()}
        return set_response_headers(jsonify(response))
    # Check for non collection class
    elif category in parsed_classes:
        response = {
            "@context":
            get_doc().parsed_classes[category]["context"].generate()
        }
        return set_response_headers(jsonify(response))
    else:
        error = HydraError(code=404,
                           title="NOT FOUND",
                           desc="Context not found")
        return error_response(error)
Exemple #5
0
def items_put_check_support(id_, class_path, path, is_collection):
    """Check if class_type supports PUT operation"""
    object_ = json.loads(request.data.decode('utf-8'))
    collections, parsed_classes = get_collections_and_parsed_classes()
    if path in parsed_classes:
        class_path = path
        obj_type = getType(path, "PUT")
    elif path in collections:
        collection = collections[path]["collection"]
        class_path = collection.path
        obj_type = collection.name
    link_props, link_type_check = get_link_props(class_path, object_)
    # Load new object and type
    if (validate_object(object_, obj_type, class_path) and link_type_check):
        if is_collection:
            object_ = parse_collection_members(object_)
        try:
            # Add the object with given ID
            object_id = crud.insert(object_=object_, id_=id_,
                                    session=get_session(), collection=is_collection)
            headers_ = [{"Location": f"{get_hydrus_server_url()}"
                                     f"{get_api_name()}/{path}/{object_id}"}]
            status_description = f"Object with ID {object_id} successfully added"
            status = HydraStatus(code=201, title="Object successfully added.",
                                 desc=status_description)
            return set_response_headers(
                jsonify(status.generate()), headers=headers_,
                status_code=status.code)
        except (ClassNotFound, InstanceExists, PropertyNotFound) as e:
            error = e.get_HTTP()
            return error_response(error)
    else:
        error = HydraError(code=400, title="Data is not valid")
        return error_response(error)
Exemple #6
0
def items_put_response(path: str, int_list="") -> Response:
    """
    Handles PUT operation to insert multiple items.

    :param path: Path for Item Collection
    :type path: str
    :param int_list: Optional String containing ',' separated ID's
    :type int_list: List
    :return: Appropriate response for the PUT operation on multiple items.
    :rtype: Response
    """
    object_ = json.loads(request.data.decode('utf-8'))
    object_ = object_["data"]
    _, parsed_classes = get_collections_and_parsed_classes()
    if path in parsed_classes:
        class_path = path
        obj_type = getType(path, "PUT")
        incomplete_objects = []
        for obj in object_:
            if not check_required_props(class_path, obj):
                incomplete_objects.append(obj)
                object_.remove(obj)
        link_props_list, link_type_check = get_link_props_for_multiple_objects(class_path,
                                                                               object_)
        if validObjectList(object_) and link_type_check:
            type_result = type_match(object_, obj_type)
            # If Item in request's JSON is a valid object
            # ie. @type is one of the keys in object_
            if type_result:
                # If the right Item type is being added to the
                # collection
                try:
                    # Insert object and return location in Header
                    object_id = crud.insert_multiple(
                        objects_=object_, session=get_session(), id_=int_list)
                    headers_ = [{"Location": f"{get_hydrus_server_url()}"
                                             f"{get_api_name()}/{path}/{object_id}"}]
                    if len(incomplete_objects) > 0:
                        status = HydraStatus(code=202,
                                             title="Object(s) missing required property")
                        response = status.generate()
                        response["objects"] = incomplete_objects
                        return set_response_headers(
                            jsonify(response), headers=headers_,
                            status_code=status.code)
                    else:
                        status_description = f"Objects with ID {object_id} successfully added"
                        status = HydraStatus(code=201, title="Objects successfully added",
                                             desc=status_description)
                        return set_response_headers(
                            jsonify(status.generate()), headers=headers_,
                            status_code=status.code)
                except (ClassNotFound, InstanceExists, PropertyNotFound) as e:
                    error = e.get_HTTP()
                    return error_response(error)

        error = HydraError(code=400, title="Data is not valid")
        return error_response(error)
Exemple #7
0
 def get_HTTP(self) -> HydraError:
     """Return the HTTP response for the Exception."""
     description = "Following parameters are incompatible with each other: ["
     for i in range(len(self.params)):
         if i == len(self.params) - 1:
             description += "{}]".format(self.params[i])
         else:
             description += "{}, ".format(self.params[i])
     return HydraError(code=400, title="Incompatible parameters.", desc=description)
Exemple #8
0
def error_response(error: HydraError) -> Response:
    """
    Generate the response if there is an error while performing any operation
    :param error: HydraError object which will help in generating response
    :type error: HydraError
    :return: Error response with appropriate status code
    :rtype: Response
    """
    return set_response_headers(jsonify(error.generate()),
                                status_code=error.code)
def items_post_check_support(id_, object_, class_path, path, is_collection):
    """Check if class_type supports POST operation"""
    collections, parsed_classes = get_collections_and_parsed_classes()
    if path in parsed_classes:
        class_path = path
        obj_type = getType(path, "PUT")
    elif path in collections:
        collection = collections[path]["collection"]
        class_path = collection.path
        obj_type = collection.name
    link_props, link_type_check = get_link_props(class_path, object_)
    # Load new object and type
    if (validate_object(object_, obj_type, class_path) and link_type_check):
        if is_collection:
            object_ = parse_collection_members(object_)
        try:
            # Update the right ID if the object is valid and matches
            # type of Item
            object_id = crud.update(object_=object_,
                                    id_=id_,
                                    type_=object_["@type"],
                                    session=get_session(),
                                    api_name=get_api_name(),
                                    collection=is_collection)
            method = "POST"
            resource_url = f"{get_hydrus_server_url()}{get_api_name()}/{path}/{object_id}"
            last_job_id = crud.get_last_modification_job_id(
                session=get_session())
            new_job_id = crud.insert_modification_record(method,
                                                         resource_url,
                                                         session=get_session())
            send_sync_update(socketio=socketio,
                             new_job_id=new_job_id,
                             last_job_id=last_job_id,
                             method=method,
                             resource_url=resource_url)
            headers_ = [{"Location": resource_url}]
            status_description = (f"Object with ID {object_id} successfully "
                                  "updated")
            status = HydraStatus(code=200,
                                 title="Object updated",
                                 desc=status_description)
            return set_response_headers(jsonify(status.generate()),
                                        headers=headers_)

        except (ClassNotFound, InstanceNotFound, InstanceExists,
                PropertyNotFound) as e:
            error = e.get_HTTP()
            return error_response(error)
    else:
        error = HydraError(code=400, title="Data is not valid")
        return error_response(error)
Exemple #10
0
def item_collection_put_response(path: str) -> Response:
    """
    Handles PUT operation on item collection classes.

    :param path: Path for Item Collection
    :type path: str
    :return: Appropriate response for the PUT operation.
    :rtype: Response
    """
    object_ = json.loads(request.data.decode('utf-8'))
    collections, parsed_classes = get_collections_and_parsed_classes()
    is_collection = False
    if path in parsed_classes:
        class_path = path
        is_collection = False
        obj_type = getType(path, "PUT")
    elif path in collections:
        collection = collections[path]["collection"]
        class_path = collection.path
        obj_type = collection.name
        is_collection = True
    if validate_object(object_, obj_type, class_path):
        # If Item in request's JSON is a valid object ie. @type is a key in object_
        # and the right Item type is being added to the collection
        if is_collection:
            object_ = parse_collection_members(object_)
        try:
            # Insert object and return location in Header
            object_id = crud.insert(object_=object_,
                                    session=get_session(),
                                    collection=is_collection)
            headers_ = [{
                "Location":
                f"{get_hydrus_server_url()}{get_api_name()}/{path}/{object_id}"
            }]
            status_description = f"Object with ID {object_id} successfully added"
            status = HydraStatus(code=201,
                                 title="Object successfully added",
                                 desc=status_description)
            return set_response_headers(jsonify(status.generate()),
                                        headers=headers_,
                                        status_code=status.code)
        except (ClassNotFound, InstanceExists, PropertyNotFound,
                PropertyNotGiven) as e:
            error = e.get_HTTP()
            return error_response(error)
    else:
        error = HydraError(code=400, title="Data is not valid")
        return error_response(error)
Exemple #11
0
 def get_HTTP(self) -> HydraError:
     """Return the HTTP response for the Exception."""
     description = f"The page with ID {self.page_id} not found"
     return HydraError(code=400, title="Page not found", desc=description)
Exemple #12
0
 def get_HTTP(self) -> HydraError:
     """Return the HTTP response for the Exception."""
     description = f"The user with ID {self.id_} already exists"
     return HydraError(code=400,
                       title="User already exists.",
                       desc=description)
Exemple #13
0
 def get_HTTP(self) -> HydraError:
     """Return the HTTP response for the Exception."""
     description = f"The User with ID {self.id_} is not a valid/defined User"
     return HydraError(code=400, title="User not found", desc=description)
Exemple #14
0
 def get_HTTP(self) -> HydraError:
     """Return the HTTP response for the Exception."""
     description = f"The property {self.type_} is not a valid/defined Property"
     return HydraError(code=400,
                       title="Property not found",
                       desc=description)
Exemple #15
0
 def get_HTTP(self) -> HydraError:
     """Return the HTTP response for the Exception."""
     description = "The property {} is not an Abstract property".format(self.type_)
     return HydraError(code=400, title="Not an Abstract property", desc=description)
Exemple #16
0
 def get_HTTP(self) -> HydraError:
     """Return the HTTP response for the Exception."""
     description = f"Offset {self.offset} is out of range."
     return HydraError(code=400, title="Page not found", desc=description)
Exemple #17
0
 def get_HTTP(self) -> HydraError:
     """Return the HTTP response for the Exception."""
     description = f"Query parameter [{self.param}] is invalid"
     return HydraError(code=400,
                       title="Invalid query parameter",
                       desc=description)
Exemple #18
0
 def get_HTTP(self) -> HydraError:
     """Return the HTTP response for the Exception."""
     description = f"The class {self.type_} is not a valid/defined RDFClass"
     return HydraError(code=400, title="Invalid class", desc=description)