Ejemplo n.º 1
0
    def update_object(self, repository, patch_uri=None):
        graph = self.graph()
        if not patch_uri:
            patch_uri = self.uri
        prolog = ''
        # TODO: limit this to just the prefixes that are used in the graph
        for (prefix, uri) in graph.namespace_manager.namespaces():
            prolog += "PREFIX {0}: {1}\n".format(prefix, uri.n3())

        triples = []
        for (s, p, o) in graph:
            subject = s.n3(graph.namespace_manager)
            if '#' in subject:
                subject = '<' + subject[subject.index('#'):]
            else:
                subject = '<>'
            triples.append("{0} {1} {2}.".format(
                subject, graph.namespace_manager.normalizeUri(p),
                o.n3(graph.namespace_manager)))

        query = prolog + "INSERT DATA {{{0}}}".format("\n".join(triples))
        data = query.encode('utf-8')
        headers = {'Content-Type': 'application/sparql-update'}
        self.logger.info(f"Updating {self}")
        response = repository.patch(str(patch_uri), data=data, headers=headers)
        if response.status_code == 204:
            self.logger.info(f"Updated {self}")
            self.updated = True
            return response
        else:
            self.logger.error(f"Failed to update {self}")
            self.logger.error(query)
            raise RESTAPIException(response)
Ejemplo n.º 2
0
    def create_object(self, repository, uri=None):
        if not repository.load_binaries:
            self.logger.info(
                f'Skipping loading for binary {self.source.filename}')
            return True
        elif self.created:
            return False
        elif self.exists_in_repo(repository):
            self.created = True
            return False

        self.logger.info(f'Loading {self.source.filename}')

        with self.source.data() as stream:
            headers = {
                'Content-Type':
                self.source.mimetype(),
                'Digest':
                self.source.digest(),
                'Content-Disposition':
                f'attachment; filename="{self.source.filename}"'
            }
            if uri is not None:
                response = repository.put(uri, data=stream, headers=headers)
            else:
                response = repository.post(repository.uri(),
                                           data=stream,
                                           headers=headers)

        if response.status_code == 201:
            self.uri = URIRef(response.headers['Location'])
            self.created = True
            return True
        else:
            raise RESTAPIException(response)
Ejemplo n.º 3
0
 def maintain(self):
     if self.active:
         self.logger.info(f'Maintaining transaction {self}')
         response = self.repository.post(os.path.join(self.uri, 'fcr:tx'))
         if response.status_code == 204:
             self.logger.info(
                 f'Transaction {self} is active until {response.headers["Expires"]}'
             )
         else:
             self.logger.error(f'Failed to maintain transaction {self}')
             raise RESTAPIException(response)
Ejemplo n.º 4
0
 def rollback(self):
     if self.active:
         self.logger.info(f'Rolling back transaction {self}')
         response = self.repository.post(
             os.path.join(self.uri, 'fcr:tx/fcr:rollback'))
         if response.status_code == 204:
             self.logger.info(f'Rolled back transaction {self}')
             self.keep_alive.stop()
             self.active = False
         else:
             self.logger.error(f'Failed to roll back transaction {self}')
             raise RESTAPIException(response)
Ejemplo n.º 5
0
 def commit(self):
     if self.active:
         self.logger.info(f'Committing transaction {self}')
         response = self.repository.post(
             os.path.join(self.uri, 'fcr:tx/fcr:commit'))
         if response.status_code == 204:
             self.logger.info(f'Committed transaction {self}')
             self.keep_alive.stop()
             self.active = False
         else:
             self.logger.error(f'Failed to commit transaction {self}')
             raise RESTAPIException(response)
Ejemplo n.º 6
0
 def get_graph(self, url, include_server_managed=True):
     headers = {'Accept': 'application/n-triples'}
     if not include_server_managed:
         headers['Prefer'] = OMIT_SERVER_MANAGED_TRIPLES
     response = self.get(url, headers=headers, stream=True)
     if response.status_code != 200:
         self.logger.error(
             f"Unable to get {headers['Accept']} representation of {url}")
         raise RESTAPIException(response)
     graph = Graph()
     graph.parse(data=response.text, format='nt')
     return graph
Ejemplo n.º 7
0
    def create(self, url=None, **kwargs):
        if url is not None:
            response = self.put(url, **kwargs)
        else:
            response = self.post(self.uri(), **kwargs)

        if response.status_code == 201:
            created_url = response.headers[
                'Location'] if 'Location' in response.headers else url
            return URIRef(self._remove_transaction_uri(created_url))
        else:
            raise RESTAPIException(response)
Ejemplo n.º 8
0
 def begin(self):
     self.logger.info('Creating transaction')
     response = self.repository.post(
         self.repository.get_transaction_endpoint())
     if response.status_code == 201:
         self.uri = response.headers['Location']
         self.repository.transaction = self
         self.logger.info(f'Created transaction {self}')
         self.keep_alive.start()
         self.active = True
     else:
         self.logger.error('Failed to create transaction')
         raise RESTAPIException(response)
Ejemplo n.º 9
0
 def patch(self, repository, sparql_update):
     headers = {'Content-Type': 'application/sparql-update'}
     self.logger.info(f"Updating {self}")
     response = repository.patch(self.resource.description_uri, data=sparql_update, headers=headers)
     if response.status_code == 204:
         self.logger.info(f"Updated {self}")
         self.updated = True
         return response
     else:
         self.logger.error(f"Failed to update {self}")
         self.logger.error(sparql_update)
         self.logger.error(response.text)
         raise RESTAPIException(response)
Ejemplo n.º 10
0
    def __init__(self, repo, file_uri):
        file_uri = URIRef(file_uri)
        response = repo.head(file_uri)

        if response.status_code == 404:
            raise BinarySourceNotFoundError(
                f'{response.status_code} {response.reason}: {file_uri}')
        if response.status_code != 200:
            raise RESTAPIException(response)

        self._mimetype = response.headers['Content-Type']

        self.repo = repo
        self.file_uri = file_uri
Ejemplo n.º 11
0
 def delete_item(self, resource, graph):
     if resource.uri in self.resources.completed:
         logger.info(
             f'Resource {resource.uri} has already been deleted; skipping')
         return
     title = get_title_string(graph)
     if self.dry_run:
         logger.info(f'Would delete resource {resource} {title}')
     else:
         response = self.repository.delete(resource.uri)
         if response.status_code == 204:
             logger.info(f'Deleted resource {resource} {title}')
             timestamp = parsedate_to_datetime(
                 response.headers['date']).isoformat('T')
             self.resources.log_completed(resource.uri, title, timestamp)
         else:
             raise RESTAPIException(response)
Ejemplo n.º 12
0
 def update_item(self, resource, graph):
     if resource.uri in self.resources.completed:
         logger.info(
             f'Resource {resource.uri} has already been updated; skipping')
         return
     headers = {'Content-Type': 'application/sparql-update'}
     title = get_title_string(graph)
     if self.dry_run:
         logger.info(f'Would update resource {resource} {title}')
     else:
         response = self.repository.patch(resource.description_uri,
                                          data=self.sparql_update,
                                          headers=headers)
         if response.status_code == 204:
             logger.info(f'Updated resource {resource} {title}')
             timestamp = parsedate_to_datetime(
                 response.headers['date']).isoformat('T')
             self.resources.log_completed(resource.uri, title, timestamp)
         else:
             raise RESTAPIException(response)
Ejemplo n.º 13
0
    def create(self, path=None, url=None, container_path=None, **kwargs):
        if url is not None:
            response = self.put(url, **kwargs)
        elif path is not None:
            response = self.put(self.endpoint + path, **kwargs)
        else:
            container_uri = self.endpoint + (container_path or self.relpath)
            response = self.post(container_uri, **kwargs)

        if response.status_code == 201:
            created_uri = self._remove_transaction_uri(
                response.headers['Location'] if 'Location' in
                response.headers else url)
            created_uri = self.handle_forward(created_uri)
            description_uri = self.process_description_uri(
                created_uri, response)

            return ResourceURI(created_uri, description_uri)
        else:
            raise RESTAPIException(response)
Ejemplo n.º 14
0
 def get_description_uri(self, uri, **kwargs):
     response = self.head(uri, **kwargs)
     if response.status_code != 200:
         raise RESTAPIException(response)
     return self.process_description_uri(uri, response)