Example #1
0
    def post(self):
        valid_params = PAGING_PARAMS

        with safe_params(valid_params):

            try:
                raw_body_params = json.loads(self.request.body)
            except ValueError:
                error_message = _("JSON malformed. Received: {0}.")
                raise HTTPError(400,
                                log_message=error_message.format(
                                    self.request.body))

            body_params = normalize_all_uris_recursively(raw_body_params)
            if '@context' in body_params:
                del body_params['@context']

            validate_json_schema(body_params, SUGGEST_PARAM_SCHEMA)

            self.query_params = ParamDict(self, **valid_params)

        response = do_suggest(self.query_params, body_params)
        if self.query_params['expand_uri'] == "0":
            response = normalize_all_uris_recursively(response, mode=SHORTEN)
        self.finalize(response)
Example #2
0
    def get(self, context_name, class_name, instance_id):
        optional_params = INSTANCE_PARAMS
        with safe_params(optional_params):
            self.query_params = ParamDict(self,
                                          context_name=context_name,
                                          class_name=class_name,
                                          instance_id=instance_id,
                                          **optional_params)

        response = memoize(self.query_params,
                           get_instance,
                           key=build_instance_key(self.query_params),
                           function_arguments=self.query_params)

        if response is None:
            error_message = u"Instance ({0}) of class ({1}) in graph ({2}) was not found.".format(
                self.query_params['instance_uri'],
                self.query_params['class_uri'],
                self.query_params['graph_uri'])
            raise HTTPError(404, log_message=error_message)

        response_meta = response['meta']
        response = response['body']

        if self.query_params["expand_uri"] == "0":
            response = normalize_all_uris_recursively(response, mode=SHORTEN)

        self.add_cache_headers(response_meta)
        self.finalize(response)
Example #3
0
    def get(self, context_name, class_name, instance_id):
        optional_params = INSTANCE_PARAMS
        with safe_params(optional_params):
            self.query_params = ParamDict(self,
                                          context_name=context_name,
                                          class_name=class_name,
                                          instance_id=instance_id,
                                          **optional_params)

        response = memoize(self.query_params,
                           get_instance,
                           key=build_instance_key(self.query_params),
                           function_arguments=self.query_params)

        if response is None:
            error_message = u"Instance ({0}) of class ({1}) in graph ({2}) was not found.".format(
                self.query_params['instance_uri'],
                self.query_params['class_uri'],
                self.query_params['graph_uri'])
            raise HTTPError(404, log_message=error_message)

        response_meta = response['meta']
        response = response['body']

        if self.query_params["expand_uri"] == "0":
            response = normalize_all_uris_recursively(response, mode=SHORTEN)

        self.add_cache_headers(response_meta)
        self.finalize(response)
Example #4
0
    def post(self):
        valid_params = PAGING_PARAMS

        with safe_params(valid_params):
            self.query_params = ParamDict(self, **valid_params)

            raw_body_params = get_json_request_as_dict(self.request.body)
            body_params = normalize_all_uris_recursively(raw_body_params)
            if '@context' in body_params:
                del body_params['@context']

            validate_json_schema(body_params, SUGGEST_PARAM_SCHEMA)

        response = do_suggest(self.query_params, body_params)
        if self.query_params['expand_uri'] == "0":
            response = normalize_all_uris_recursively(response, mode=SHORTEN)
        self.finalize(response)
 def test_real_resource(self):
     input_data = {'rdfs:comment': u'Some kind of monster.'}
     expected_output = {
         'http://www.w3.org/2000/01/rdf-schema#comment':
         u'Some kind of monster.'
     }
     self.assertDictEqual(normalize_all_uris_recursively(input_data),
                          expected_output)
Example #6
0
    def put(self, context_name, class_name, instance_id):
        valid_params = INSTANCE_PARAMS
        with safe_params(valid_params):
            self.query_params = ParamDict(self,
                                          context_name=context_name,
                                          class_name=class_name,
                                          instance_id=instance_id,
                                          **valid_params)
        del context_name
        del class_name
        del instance_id

        instance_data = get_json_request_as_dict(self.request.body)
        instance_data = normalize_all_uris_recursively(instance_data)

        rdf_type_error = is_rdf_type_invalid(self.query_params, instance_data)
        if rdf_type_error:
            raise HTTPError(400, log_message=rdf_type_error)

        try:
            if not instance_exists(self.query_params):
                try:
                    schema = schema_resource.get_cached_schema(
                        self.query_params)
                except SchemaNotFound:
                    schema = None
                if schema is None:
                    msg = _(u"Class {0} doesn't exist in graph {1}.")
                    raise HTTPError(404,
                                    log_message=msg.format(
                                        self.query_params["class_uri"],
                                        self.query_params["graph_uri"]))
                instance_uri, instance_id = create_instance(
                    self.query_params, instance_data,
                    self.query_params["instance_uri"])
                resource_url = self.request.full_url()
                status = 201
                self.set_header("location", resource_url)
                self.set_header("X-Brainiak-Resource-URI", instance_uri)
            else:
                edit_instance(self.query_params, instance_data)
                status = 200
        except InstanceError as ex:
            raise HTTPError(400, log_message=str(ex))
        except SchemaNotFound as ex:
            raise HTTPError(404, log_message=str(ex))

        cache.purge_an_instance(self.query_params['instance_uri'])

        self.query_params["expand_object_properties"] = "1"
        instance_data = get_instance(self.query_params)

        if instance_data and settings.NOTIFY_BUS:
            self.query_params["instance_uri"] = instance_data["@id"]
            self._notify_bus(action="PUT", instance_data=instance_data)

        self.finalize(status)
Example #7
0
    def patch(self, context_name, class_name, instance_id):
        valid_params = INSTANCE_PARAMS
        with safe_params(valid_params):
            self.query_params = ParamDict(self,
                                          context_name=context_name,
                                          class_name=class_name,
                                          instance_id=instance_id,
                                          **valid_params)
        del context_name
        del class_name
        del instance_id

        patch_list = get_json_request_as_dict(self.request.body)

        # Retrieve original data
        instance_data = memoize(self.query_params,
                                get_instance,
                                key=build_instance_key(self.query_params),
                                function_arguments=self.query_params)

        if instance_data is not None:
            # Editing an instance
            instance_data = instance_data['body']
            instance_data.pop(
                'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', None)

            # compute patch
            changed_data = apply_patch(instance_data, patch_list)

            # Try to put
            edit_instance(self.query_params, changed_data)
            status = 200

            # Clear cache
            cache.purge_an_instance(self.query_params['instance_uri'])

            self.finalize(status)
        else:
            # Creating a new instance from patch list
            instance_data = get_instance_data_from_patch_list(patch_list)
            instance_data = normalize_all_uris_recursively(instance_data)

            rdf_type_error = is_rdf_type_invalid(self.query_params,
                                                 instance_data)
            if rdf_type_error:
                raise HTTPError(400, log_message=rdf_type_error)

            instance_uri, instance_id = create_instance(
                self.query_params, instance_data,
                self.query_params["instance_uri"])
            resource_url = self.request.full_url()
            status = 201
            self.set_header("location", resource_url)
            self.set_header("X-Brainiak-Resource-URI", instance_uri)

            self.finalize(status)
Example #8
0
def are_there_label_properties_in(instance_data):
    """
        Validate there are label properties in instance data when creating/modifying an instance
        LABEL_PROPERTIES is a list like [u'http://www.w3.org/2000/01/rdf-schema#label']
    """
    instance_data = normalize_all_uris_recursively(instance_data)
    for label_property in LABEL_PROPERTIES:
        if label_property in instance_data:
            return True
    return False
Example #9
0
def are_there_label_properties_in(instance_data):
    """
        Validate there are label properties in instance data when creating/modifying an instance
        LABEL_PROPERTIES is a list like [u'http://www.w3.org/2000/01/rdf-schema#label']
    """
    instance_data = normalize_all_uris_recursively(instance_data)
    for label_property in LABEL_PROPERTIES:
        if label_property in instance_data:
            return True
    return False
Example #10
0
    def post(self, context_name, class_name):
        valid_params = CLASS_PARAMS
        with safe_params(valid_params):
            self.query_params = ParamDict(self,
                                          context_name=context_name,
                                          class_name=class_name,
                                          **valid_params)
        del context_name
        del class_name

        try:
            schema = schema_resource.get_cached_schema(self.query_params)
        except SchemaNotFound:
            schema = None
        if schema is None:
            class_uri = self.query_params["class_uri"]
            graph_uri = self.query_params["graph_uri"]
            raise HTTPError(
                404,
                log_message=_(
                    u"Class {0} doesn't exist in context {1}.").format(
                        class_uri, graph_uri))

        try:
            instance_data = json.loads(self.request.body)
        except ValueError:
            raise HTTPError(400,
                            log_message=_(u"No JSON object could be decoded"))

        instance_data = normalize_all_uris_recursively(instance_data)

        try:
            (instance_uri,
             instance_id) = create_instance(self.query_params, instance_data)
        except InstanceError as ex:
            raise HTTPError(500, log_message=unicode(ex))

        instance_url = self.build_resource_url(instance_id)

        self.set_header("location", instance_url)
        self.set_header("X-Brainiak-Resource-URI", instance_uri)

        self.query_params["instance_uri"] = instance_uri
        self.query_params["instance_id"] = instance_id
        self.query_params["expand_object_properties"] = "1"

        instance_data = get_instance(self.query_params)

        if settings.NOTIFY_BUS:
            self._notify_bus(action="POST", instance_data=instance_data)

        self.finalize(201)
Example #11
0
    def post(self):
        valid_params = PAGING_PARAMS

        with safe_params(valid_params):

            try:
                raw_body_params = json.loads(self.request.body)
            except ValueError:
                error_message = _("JSON malformed. Received: {0}.")
                raise HTTPError(400, log_message=error_message.format(self.request.body))

            body_params = normalize_all_uris_recursively(raw_body_params)
            if '@context' in body_params:
                del body_params['@context']

            validate_json_schema(body_params, SUGGEST_PARAM_SCHEMA)

            self.query_params = ParamDict(self, **valid_params)

        response = do_suggest(self.query_params, body_params)
        if self.query_params['expand_uri'] == "0":
            response = normalize_all_uris_recursively(response, mode=SHORTEN)
        self.finalize(response)
Example #12
0
    def get(self, context_name, class_name):
        valid_params = LIST_PARAMS + CLASS_PARAMS + DefaultParamsDict(direct_instances_only='0')
        with safe_params(valid_params):
            self.query_params = ParamDict(self,
                                          context_name=context_name,
                                          class_name=class_name,
                                          **valid_params)
        del context_name
        del class_name

        response = filter_instances(self.query_params)

        if self.query_params['expand_uri'] == "0":
            response = normalize_all_uris_recursively(response, mode=SHORTEN)

        self.finalize(response)
Example #13
0
    def get(self, context_name, class_name):
        valid_params = LIST_PARAMS + CLASS_PARAMS + DefaultParamsDict(direct_instances_only='0')
        with safe_params(valid_params):
            self.query_params = ParamDict(self,
                                          context_name=context_name,
                                          class_name=class_name,
                                          **valid_params)
        del context_name
        del class_name

        response = filter_instances(self.query_params)

        if self.query_params['expand_uri'] == "0":
            response = normalize_all_uris_recursively(response, mode=SHORTEN)

        self.finalize(response)
Example #14
0
    def post(self, context_name, class_name):
        valid_params = CLASS_PARAMS
        with safe_params(valid_params):
            self.query_params = ParamDict(self,
                                          context_name=context_name,
                                          class_name=class_name,
                                          **valid_params)
        del context_name
        del class_name

        try:
            schema = schema_resource.get_cached_schema(self.query_params)
        except SchemaNotFound:
            schema = None
        if schema is None:
            class_uri = self.query_params["class_uri"]
            graph_uri = self.query_params["graph_uri"]
            raise HTTPError(404, log_message=_(u"Class {0} doesn't exist in context {1}.").format(class_uri, graph_uri))

        try:
            instance_data = json.loads(self.request.body)
        except ValueError:
            raise HTTPError(400, log_message=_(u"No JSON object could be decoded"))

        instance_data = normalize_all_uris_recursively(instance_data)

        try:
            (instance_uri, instance_id) = create_instance(self.query_params, instance_data)
        except InstanceError as ex:
            raise HTTPError(500, log_message=unicode(ex))

        instance_url = self.build_resource_url(instance_id)

        self.set_header("location", instance_url)
        self.set_header("X-Brainiak-Resource-URI", instance_uri)

        self.query_params["instance_uri"] = instance_uri
        self.query_params["instance_id"] = instance_id
        self.query_params["expand_object_properties"] = "1"

        instance_data = get_instance(self.query_params)

        if settings.NOTIFY_BUS:
            self._notify_bus(action="POST", instance_data=instance_data)

        self.finalize(201)
Example #15
0
class ClassHandler(BrainiakRequestHandler):

    SUPPORTED_METHODS = list(
        BrainiakRequestHandler.SUPPORTED_METHODS) + ["PURGE"]

    def __init__(self, *args, **kwargs):
        super(ClassHandler, self).__init__(*args, **kwargs)

    @greenlet_asynchronous
    def purge(self, context_name, class_name):
        if settings.ENABLE_CACHE:
            with safe_params():
                self.query_params = ParamDict(self,
                                              context_name=context_name,
                                              class_name=class_name)
            path = cache.build_key_for_class(self.query_params)
            cache.purge_by_path(path, False)
        else:
            raise HTTPError(
                405,
                log_message=
                _("Cache is disabled (Brainaik's settings.ENABLE_CACHE is set to False)"
                  ))

    @greenlet_asynchronous
    def get(self, context_name, class_name):
        self.request.query = unquote(self.request.query)

        with safe_params():
            self.query_params = ParamDict(self,
                                          context_name=context_name,
                                          class_name=class_name)
        del context_name
        del class_name

        try:
            response = schema_resource.get_cached_schema(self.query_params,
                                                         include_meta=True)
        except schema_resource.SchemaNotFound, e:
            raise HTTPError(404, log_message=e.message)

        if self.query_params['expand_uri'] == "0":
            response = normalize_all_uris_recursively(response, mode=SHORTEN)
        self.add_cache_headers(response['meta'])
        self.finalize(response['body'])
Example #16
0
    def get(self, context_name, class_name):
        self.request.query = unquote(self.request.query)

        with safe_params():
            self.query_params = ParamDict(self,
                                          context_name=context_name,
                                          class_name=class_name)
        del context_name
        del class_name

        try:
            response = schema_resource.get_cached_schema(self.query_params, include_meta=True)
        except schema_resource.SchemaNotFound as e:
            raise HTTPError(404, log_message=e.message)

        if self.query_params['expand_uri'] == "0":
            response = normalize_all_uris_recursively(response, mode=SHORTEN)
        self.add_cache_headers(response['meta'])
        self.finalize(response['body'])
 def test_normalize_recursively_with_invalid_type(self):
     d = {'invalid': 3}
     self.assertDictEqual(normalize_all_uris_recursively(d), d)
Example #18
0
def load_label_properties():
    global LABEL_PROPERTIES
    LABEL_PROPERTIES += get_subproperties(RDFS_LABEL)
    normalize_all_uris_recursively(LABEL_PROPERTIES)
Example #19
0
def load_label_properties():
    global LABEL_PROPERTIES
    LABEL_PROPERTIES += get_subproperties(RDFS_LABEL)
    normalize_all_uris_recursively(LABEL_PROPERTIES)
 def test_normalize_recusively_with_valid_input(self):
     self.assertDictEqual(
         normalize_all_uris_recursively(VALID_COMPRESSED_INSTANCE_DATA),
         EXPECTED_UNCOMPRESSED_INSTANCE_DATA)
 def test_bug_normalize_recursively_eating_up_context(self):
     expected = {'@context': {'@language': 'pt'}}
     computed = normalize_all_uris_recursively(expected, mode=SHORTEN)
     self.assertEqual(computed, expected)
Example #22
0
    def put(self, context_name, class_name, instance_id):
        valid_params = INSTANCE_PARAMS
        with safe_params(valid_params):
            self.query_params = ParamDict(self,
                                          context_name=context_name,
                                          class_name=class_name,
                                          instance_id=instance_id,
                                          **valid_params)
        del context_name
        del class_name
        del instance_id

        try:
            instance_data = json.loads(self.request.body)
        except ValueError:
            raise HTTPError(400,
                            log_message=_("No JSON object could be decoded"))

        instance_data = normalize_all_uris_recursively(instance_data)

        RDFS_TYPE = "http://www.w3.org/2000/01/rdf-schema#type"
        rdfs_type = instance_data.get(RDFS_TYPE)

        if rdfs_type:
            class_uri = self.query_params["class_uri"]
            if (rdfs_type == class_uri):
                instance_data.pop(RDFS_TYPE)
            else:
                msg = u"Incompatible values for rdfs:type <{0}> and class URI <{1}>"
                msg = msg.format(rdfs_type, class_uri)
                raise HTTPError(400, log_message=msg)

        try:
            if not instance_exists(self.query_params):
                try:
                    schema = schema_resource.get_cached_schema(
                        self.query_params)
                except SchemaNotFound:
                    schema = None
                if schema is None:
                    msg = _(u"Class {0} doesn't exist in graph {1}.")
                    raise HTTPError(404,
                                    log_message=msg.format(
                                        self.query_params["class_uri"],
                                        self.query_params["graph_uri"]))
                instance_uri, instance_id = create_instance(
                    self.query_params, instance_data,
                    self.query_params["instance_uri"])
                resource_url = self.request.full_url()
                status = 201
                self.set_header("location", resource_url)
                self.set_header("X-Brainiak-Resource-URI", instance_uri)
            else:
                edit_instance(self.query_params, instance_data)
                status = 200
        except InstanceError as ex:
            raise HTTPError(400, log_message=unicode(ex))
        except SchemaNotFound as ex:
            raise HTTPError(404, log_message=unicode(ex))

        cache.purge_an_instance(self.query_params['instance_uri'])

        self.query_params["expand_object_properties"] = "1"
        instance_data = get_instance(self.query_params)

        if instance_data and settings.NOTIFY_BUS:
            self.query_params["instance_uri"] = instance_data["@id"]
            self._notify_bus(action="PUT", instance_data=instance_data)

        self.finalize(status)
 def test_normalize_recursively_with_lang(self):
     d = {'@context': {'@language': 'pt'}}
     self.assertDictEqual(normalize_all_uris_recursively(d), d)
Example #24
0
    def put(self, context_name, class_name, instance_id):
        valid_params = INSTANCE_PARAMS
        with safe_params(valid_params):
            self.query_params = ParamDict(self,
                                          context_name=context_name,
                                          class_name=class_name,
                                          instance_id=instance_id,
                                          **valid_params)
        del context_name
        del class_name
        del instance_id

        try:
            instance_data = json.loads(self.request.body)
        except ValueError:
            raise HTTPError(400, log_message=_("No JSON object could be decoded"))

        instance_data = normalize_all_uris_recursively(instance_data)

        RDFS_TYPE = "http://www.w3.org/2000/01/rdf-schema#type"
        rdfs_type = instance_data.get(RDFS_TYPE)

        if rdfs_type:
            class_uri = self.query_params["class_uri"]
            if (rdfs_type == class_uri):
                instance_data.pop(RDFS_TYPE)
            else:
                msg = u"Incompatible values for rdfs:type <{0}> and class URI <{1}>"
                msg = msg.format(rdfs_type, class_uri)
                raise HTTPError(400, log_message=msg)

        try:
            if not instance_exists(self.query_params):
                try:
                    schema = schema_resource.get_cached_schema(self.query_params)
                except SchemaNotFound:
                    schema = None
                if schema is None:
                    msg = _(u"Class {0} doesn't exist in graph {1}.")
                    raise HTTPError(404, log_message=msg.format(self.query_params["class_uri"],
                                                                self.query_params["graph_uri"]))
                instance_uri, instance_id = create_instance(self.query_params, instance_data, self.query_params["instance_uri"])
                resource_url = self.request.full_url()
                status = 201
                self.set_header("location", resource_url)
                self.set_header("X-Brainiak-Resource-URI", instance_uri)
            else:
                edit_instance(self.query_params, instance_data)
                status = 200
        except InstanceError as ex:
            raise HTTPError(400, log_message=unicode(ex))
        except SchemaNotFound as ex:
            raise HTTPError(404, log_message=unicode(ex))

        cache.purge_an_instance(self.query_params['instance_uri'])

        self.query_params["expand_object_properties"] = "1"
        instance_data = get_instance(self.query_params)

        if instance_data and settings.NOTIFY_BUS:
            self.query_params["instance_uri"] = instance_data["@id"]
            self._notify_bus(action="PUT", instance_data=instance_data)

        self.finalize(status)
 def test_normalize_recusively_with_invalid_prefix(self, mock):
     expected = compressed = 'invalid_prefix'
     self.assertEqual(normalize_all_uris_recursively(compressed), expected)