Пример #1
0
    def get(self):

        client = NanopubClient()

        type_of_search = self.get_argument('type_of_search')

        if type_of_search == 'text':
            search_str = self.get_argument('search_str')
            print('Searching for', search_str)
            results = client.find_nanopubs_with_text(search_str)
        elif type_of_search == 'pattern':
            subj = self.get_argument('subj')
            pred = self.get_argument('pred')
            obj = self.get_argument('obj')
            print('Searching for pattern', subj, pred, obj)
            results = client.find_nanopubs_with_pattern(subj=subj,
                                                        pred=pred,
                                                        obj=obj)
        elif type_of_search == 'things':
            thing_type = self.get_argument('thing_type')
            searchterm = self.get_argument('searchterm')
            print('Searching for "thing"', thing_type, searchterm)
            if not searchterm:
                searchterm = ' '
            results = client.find_things(thing_type=thing_type,
                                         searchterm=searchterm)
        else:
            raise ValueError(f'Unrecognized type_of_search, {type_of_search}')

        ret = json.dumps(list(results))
        self.finish(ret)
Пример #2
0
def main(orcid_id, publish, name, keypair: Union[Tuple[Path, Path], None]):
    """
    Interactive CLI to create a user profile.

    Args:
        orcid_id: the users ORCID iD or other form of universal identifier. Example:
            `https://orcid.org/0000-0000-0000-0000`
        publish: if True, profile will be published to nanopub servers
        name: the name of the user
        keypair: a tuple containing the paths to the public and private RSA key to be used to sign
            nanopubs. If empty, new keys will be generated.
    """
    click.echo('Setting up nanopub profile...')

    if not USER_CONFIG_DIR.exists():
        USER_CONFIG_DIR.mkdir()

    if not keypair:
        if _rsa_keys_exist():
            if _check_erase_existing_keys():
                _delete_keys()
                JavaWrapper.make_keys(path_name=DEFAULT_KEYS_PATH_PREFIX)
                click.echo(f'Your RSA keys are stored in {USER_CONFIG_DIR}')
        else:
            JavaWrapper.make_keys(path_name=DEFAULT_KEYS_PATH_PREFIX)
            click.echo(f'Your RSA keys are stored in {USER_CONFIG_DIR}')
    else:
        public_key_path, private_key = keypair

        # Copy the keypair to the default location
        shutil.copy(public_key_path, USER_CONFIG_DIR / PUBLIC_KEY_FILE)
        shutil.copy(private_key, USER_CONFIG_DIR / PRIVATE_KEY_FILE)

        click.echo(f'Your RSA keys have been copied to {USER_CONFIG_DIR}')

    # Public key can always be found at DEFAULT_PUBLIC_KEY_PATH.
    # Either new keys have been generated there or
    # existing keys have been copy to that location.
    public_key = DEFAULT_PUBLIC_KEY_PATH.read_text()

    profile = Profile(orcid_id, name, DEFAULT_PUBLIC_KEY_PATH,
                      DEFAULT_PRIVATE_KEY_PATH)
    store_profile(profile)

    # Declare the user to nanopub
    if publish:
        assertion, concept = _create_this_is_me_rdf(orcid_id, public_key, name)
        np = Publication.from_assertion(assertion,
                                        introduces_concept=concept,
                                        assertion_attributed_to=orcid_id)

        client = NanopubClient()
        result = client.publish(np)

        profile.nanopub_uri = result['concept_uri']

        # Store profile nanopub uri
        store_profile(profile)
Пример #3
0
 def test_find_nanopubs_with_text_prod(self):
     """
     Check that Nanopub text search is returning results for a few common search terms on the
     production nanopub server
     """
     prod_client = NanopubClient()
     searches = ['test', 'US']
     for search in searches:
         results = prod_client.find_nanopubs_with_text(search)
         assert len(results) > 0
Пример #4
0
    def __init__(
        self,
        db_nano_pub: Nanopublication,
        settings: dict = None,
        np_client: NanopubClient = None,
        from_db_rdf: bool = False,
    ):
        self.dbnanopub = db_nano_pub
        # fetch Publication for published nanopub
        nanopub = None
        if np_client != None and self.dbnanopub.publication_info != None:
            nanopub = np_client.fetch(uri=db_nano_pub.publication_info.nanopub_uri)
        elif from_db_rdf and self.dbnanopub.rdf_raw != None:
            nanopub_rdf = rdflib.ConjunctiveGraph()
            nanopub_rdf.parse(data=self.dbnanopub.rdf_raw, format="trig")
            nanopub = Publication(rdf=nanopub_rdf)

        if nanopub != None and self.dbnanopub.publication_info != None:
            nanopub.rdf.bind(
                "", rdflib.Namespace(self.dbnanopub.publication_info.nanopub_uri + "#")
            )

        super().__init__(
            url=self.dbnanopub.protocol.uri,
            author=self.dbnanopub.author,
            derived_from=self.derived_from,
            settings=settings,
            nanopub=nanopub,
        )
Пример #5
0
    def __init__(
        self,
        workflow: Workflow,
        settings: dict = None,
        np_client: NanopubClient = None,
    ):
        self.workflow = workflow
        worflow_nanopub = None
        if self.workflow.rdf != None:
            workflow_nanopub_rdf = rdflib.ConjunctiveGraph()
            workflow_nanopub_rdf.parse(data=self.workflow.rdf, format="trig")
            worflow_nanopub = Publication(rdf=workflow_nanopub_rdf)
        elif np_client != None:
            worflow_nanopub = np_client.fetch(
                uri=self.workflow.publication_info["nanopub_uri"])
        else:
            raise "Can't build rdf from workflow passed"

        worflow_nanopub.rdf.bind(
            "",
            rdflib.Namespace(self.workflow.publication_info["nanopub_uri"] +
                             "#"))

        super().__init__(author=self.workflow.author,
                         derived_from=[],
                         nanopub=worflow_nanopub)
Пример #6
0
    def test_nanopub_publish(self):
        test_concept = rdflib.term.BNode('test')
        test_published_uri = 'http://www.example.com/my-nanopub'
        expected_concept_uri = 'http://www.example.com/my-nanopub#test'
        client = NanopubClient()
        client.java_wrapper.publish = mock.MagicMock(
            return_value=test_published_uri)
        assertion_rdf = rdflib.Graph()
        assertion_rdf.add((test_concept, namespaces.HYCL.claims,
                           rdflib.Literal('This is a test')))

        nanopub = Publication.from_assertion(
            assertion_rdf=assertion_rdf,
            introduces_concept=test_concept,
        )
        pubinfo = client.publish(nanopub)
        assert pubinfo['nanopub_uri'] == test_published_uri
        assert pubinfo['concept_uri'] == expected_concept_uri
    def get(self):
        client = NanopubClient()

        np_uri = self.get_argument('np_uri')

        print('Fetching nanopub from', np_uri)

        # Fetch the nanopub at the given URI
        np = client.fetch(np_uri)
        print(np)

        # Look for first step (if exists)
        first_step_URI = self.get_first_step(np.rdf)

        if first_step_URI is not None:
            step_URIs = [first_step_URI]
            step_URIs += self.get_subsequent_steps(np.rdf)

            steps = []
            for step_uri in step_URIs:
                print(step_uri, type(step_uri))
                step_np = client.fetch(step_uri)
                steps.append({
                    'nanopubURI':
                    step_uri,
                    'description':
                    self.get_step_from_nanopub(step_np.rdf, step_uri)
                })

        else:
            # If not a workflow, return the step description in this NP
            print('No first step found - assuming this np describes a step')
            steps = [{
                'nanopubURI': np_uri,
                'description': self.get_step_from_nanopub(np.rdf, np_uri)
            }]

        ret = json.dumps(steps)
        self.finish(ret)
Пример #8
0
    def test_retract_without_force(self, mock_get_public_key):
        test_uri = 'http://www.example.com/my-nanopub'
        test_public_key = 'test key'
        client = NanopubClient()
        client.java_wrapper.publish = mock.MagicMock()

        # Return a mocked to-be-retracted publication object that is signed with public key
        mock_publication = mock.MagicMock()
        mock_publication.pubinfo = rdflib.Graph()
        mock_publication.pubinfo.add(
            (rdflib.URIRef(test_uri + '#sig'), namespaces.NPX.hasPublicKey,
             rdflib.Literal(test_public_key)))
        client.fetch = mock.MagicMock(return_value=mock_publication)

        # Retract should be successful when public keys match
        mock_get_public_key.return_value = test_public_key
        client.retract(test_uri)

        # And fail if they don't match
        mock_get_public_key.return_value = 'Different public key'
        with pytest.raises(AssertionError):
            client.retract(test_uri)
Пример #9
0
 def test_retract_with_force(self):
     client = NanopubClient()
     client.java_wrapper.publish = mock.MagicMock()
     client.retract('http://www.example.com/my-nanopub', force=True)
Пример #10
0
 def test_nanopub_claim(self):
     client = NanopubClient()
     client.java_wrapper.publish = mock.MagicMock()
     client.claim(statement_text='Some controversial statement')
Пример #11
0
from unittest import mock

import pytest
import rdflib

from conftest import skip_if_nanopub_server_unavailable
from nanopub import NanopubClient, namespaces, Publication

client = NanopubClient(use_test_server=True)

TEST_ASSERTION = (namespaces.AUTHOR.DrBob, namespaces.HYCL.claims,
                  rdflib.Literal('This is a test'))


class TestNanopubClient:
    @pytest.mark.flaky(max_runs=10)
    @skip_if_nanopub_server_unavailable
    def test_find_nanopubs_with_text(self):
        """
        Check that Nanopub text search is returning results for a few common search terms
        """
        searches = ['test', 'US']

        for search in searches:
            results = client.find_nanopubs_with_text(search)
            assert len(results) > 0

        assert len(client.find_nanopubs_with_text('')) == 0

    @pytest.mark.flaky(max_runs=10)
    def test_find_nanopubs_with_text_prod(self):