Example #1
0
def ro_root_reference(cmdname, ro_config, rodir, roref=None):
    """
    Find research object root directory.  If the supplied rodir is not a local file
    reference, it is returned as-is, otherwise ro_root_directory is used to locate
    the RO root directory containing the indicated file.

    cmdname     name of ro command, used in diagnostic messages
    ro_config   RO configuration details, used when resolving supplied directory
    rodir       RO directory supplied via -d option.  Must be in configured work area.
    roref       RO reference, supplied by other means, or None.  May be any URI reference,
                resolved against base of file URI for current directory.

    Returns directory path string, or None if not found, in which
    case an error message is displayed.
    """
    if not roref:
        # Process supplied directory option
        roref = ro_uriutils.resolveFileAsUri(rodir)
        if ro_uriutils.isFileUri(roref):
            roref = ro_root_directory(cmdname, ro_config, rodir, restricted=False)
    else:
        if rodir:
            print ("%s: specify either RO directory or URI, not both" % (cmdname))
            return 1
        roref = ro_uriutils.resolveFileAsUri(roref)
    return roref
Example #2
0
def annotations(progname, configbase, options, args):
    """
    Display annotations

    ro annotations [ file | -d dir ]
    """
    log.debug("annotations: progname %s, configbase %s, args %s" % 
              (progname, configbase, repr(args)))
    ro_config = ro_utils.readconfig(configbase)
    ro_file = (args[2] if len(args) >= 3 else "")
    ro_options = {
        "rofile":       ro_file,
        "rodir":        options.rodir or os.path.dirname(ro_file)
        }
    log.debug("ro_options: " + repr(ro_options))
    if options.verbose:
        print "ro annotations -d \"%(rodir)s\" %(rofile)s " % ro_options
    ro_dir = ro_root_directory(progname + " annotations", ro_config, ro_options['rodir'])
    if not ro_dir: return 1
    # Enumerate and display annotations
    rometa = ro_metadata(ro_config, ro_dir)
    if ro_options['rofile']:
        rofile = ro_uriutils.resolveFileAsUri(ro_options['rofile'])  # Relative to CWD
        log.debug("Annotations for %s" % str(rofile))
        annotations = rometa.getFileAnnotations(rofile)
    else:
        annotations = rometa.getAllAnnotations()
    if options.debug:
        log.debug("---- Annotations:")
        for a in annotations:
            log.debug("  %s" % repr(a))
        log.debug("----")
    rometa.showAnnotations(annotations, sys.stdout)
    return 0
    def __init__(self, roconfig, roref, dummysetupfortest=False):
        """
        Initialize: read manifest from object at given directory into local RDF graph

        roconfig    is the research object manager configuration, supplied as a dictionary
        roref       a URI reference that refers to the Research Object to be accessed, or
                    relative path name (see ro_uriutils.resolveFileAsUri for interpretation)
        dummysetupfortest is an optional parameter that, if True, suppresses some aspects of
                    the setup (does not attempt to read a RO manifest) for isolated testing.
        """
        self.roconfig = roconfig
        self.roref    = roref
        self.dummyfortest  = dummysetupfortest
        self.manifestgraph = None
        self.roannotations = None
        self.registries = None
        uri = resolveFileAsUri(roref)
        if not uri.endswith("/"): uri += "/"
        self.rouri    = rdflib.URIRef(uri)
        if self._isLocal():
            self.rosrs = None
        else:
            self.rosrs = ROSRS_Session(
                self.roconfig["rosrs_uri"], 
                self.roconfig["rosrs_access_token"]
                )
        self._loadManifest()
        # Get RO URI from manifest
        # May be different from computed value if manifest has absolute URI
        self.rouri = self.manifestgraph.value(None, RDF.type, RO.ResearchObject)
        # Check that the manifest contained at least one RO URI
        assert self.rouri is not None
        return
Example #4
0
def getResourceNameString(ro_config, rname, base=None):
    """
    Returns a string value corresoponding to a URI indicated by the supplied parameter.
    Relative references are assumed to be paths relative to the supplied base URI or,
    if no rbase is supplied, relative to the current directory.
    """
    rsplit = rname.split(":")
    if len(rsplit) == 2:
        # Try to interpret name as CURIE
        for rpref in ro_config["annotationPrefixes"]:
            if rsplit[0] == rpref:
                rname = ro_config["annotationPrefixes"][rpref]+rsplit[1]
    if urlparse.urlsplit(rname).scheme == "":
        if base:
            rname = resolveUri(rname, base)
        else:
            rname = resolveFileAsUri(rname)
    return rname
Example #5
0
def annotations(progname, configbase, options, args):
    """
    Display annotations

    ro annotations [ file | -d dir ]
    """
    # @@TODO: although a URI is accepted on the command line, the actual display logic assumes
    #         a local file when displaying annotations.
    log.debug("annotations: progname %s, configbase %s, args %s" % 
              (progname, configbase, repr(args)))
    ro_config = getroconfig(configbase, options)
    ro_file = (args[2] if len(args) >= 3 else "")
    ro_options = {
        "rofile":       ro_file,
        "rodir":        options.rodir or os.path.dirname(ro_file)
        }
    log.debug("ro_options: " + repr(ro_options))
    cmdname = progname + " annotations"
    rouri = ro_root_reference(cmdname, ro_config, ro_options['rodir'])
    if not rouri: return 1
    if options.verbose:
        print cmdname + " -d \"%(rodir)s\" %(rofile)s " % ro_options
    # Enumerate and display annotations
    log.debug("- displaying annotations for %s"%(rouri))
    rometa = ro_metadata(ro_config, rouri)
    if ro_options['rofile']:
        rofile = ro_uriutils.resolveFileAsUri(ro_options['rofile'])  # Relative to CWD
        log.debug("Annotations for %s" % str(rofile))
        annotations = rometa.getFileAnnotations(rofile)
    else:
        annotations = rometa.getAllAnnotations()
    if options.debug:
        log.debug("---- Annotations:")
        for a in annotations:
            log.debug("  %s" % repr(a))
        log.debug("----")
    rometa.showAnnotations(annotations, sys.stdout)
    return 0
Example #6
0
    def __init__(self, roconfig, roref, dummysetupfortest=False):
        """
        Initialize: read manifest from object at given directory into local RDF graph

        roconfig    is the research object manager configuration, supplied as a dictionary
        roref       a URI reference that refers to the Research Object to be accessed, or
                    relative path name (see ro_uriutils.resolveFileAsUri for interpretation)
        dummysetupfortest is an optional parameter that, if True, suppresses some aspects of
                    the setup (does not attempt to read a RO manifest) for isolated testing.
        """
        self.roconfig = roconfig
        self.roref = roref
        self.dummyfortest = dummysetupfortest
        self.manifestgraph = None
        self.roannotations = None
        self.registries = None
        uri = resolveFileAsUri(roref)
        if not uri.endswith("/"): uri += "/"
        self.rouri = rdflib.URIRef(uri)
        if self._isLocal():
            self.rosrs = None
        else:
            self.rosrs = ROSRS_Session(self.roconfig["rosrs_uri"],
                                       self.roconfig["rosrs_access_token"])
        self._loadManifest()
        # Get RO URI from manifest
        # May be different from computed value if manifest has absolute URI
        # Nested URIs may be present; ours is the one described by the manifest URI,
        # which is determined by the _loadManifest() method.
        for s in self.manifestgraph.subjects(RDF.type, RO.ResearchObject):
            if self.manifestgraph.value(s,
                                        ORE.isDescribedBy) == self.manifesturi:
                self.rouri = s
        # Check that the manifest contained at least one RO URI
        assert self.rouri is not None
        return
Example #7
0
def annotate(progname, configbase, options, args):
    """
    Annotate a specified research object component

    ro annotate file attribute-name [ attribute-value ]
    ro link file attribute-name [ attribute-value ]
    """
    ro_config = ro_utils.readconfig(configbase)
    rodir = options.rodir or (not options.wildcard and os.path.dirname(args[2]))
    if len(args) == 3:
        # Using graph form
        ro_options = {
            # Usding graph annotation form
            "rofile":       args[2],
            "rodir":        rodir,
            "wildcard":     options.wildcard,
            "wild":         "-w " if options.wildcard else "",
            "graph":        options.graph or None,
            "defaultType":  "resource" if args[1] == "link" else "string",
            "rocmd":        progname,
            "anncmd":       args[1]
            }
    else:
        ro_options = {
            # Usding explicit annotation form
            "rofile":       args[2],
            "rodir":        rodir,
            "wildcard":     options.wildcard,
            "wild":         "-w " if options.wildcard else "",
            "roattribute":  args[3],
            "rovalue":      args[4] if len(args) == 5 else None,
            "defaultType":  "resource" if args[1] == "link" else "string",
            "rocmd":        progname,
            "anncmd":       args[1]
            }
    log.debug("ro_options: " + repr(ro_options))
    # Find RO root directory
    ro_dir = ro_root_directory("%s %s" % (progname, args[1]), ro_config, ro_options['rodir'])
    if not ro_dir: return 1
    if options.verbose:
        if len(args) == 3:
            print "%(rocmd)s %(anncmd)s -d %(rodir)s %(wild)s%(rofile)s -g %(graph)s " % (ro_options)
        else:
            print "%(rocmd)s %(anncmd)s -d %(rodir)s %(wild)s%(rofile)s %(roattribute)s \"%(rovalue)s\"" % ro_options
    # Read and update manifest and annotations
    # ---- local function to annotate a single entry ----
    def annotate_single(rofile):
        if len(args) == 3:
            # Add existing graph as annotation
            rometa.addGraphAnnotation(rofile, ro_options['graph'])
        else:
            # Create new annotation graph
            rometa.addSimpleAnnotation(rofile,
                ro_options['roattribute'], ro_options['rovalue'],
                ro_options['defaultType'])
    # ----
    rometa = ro_metadata(ro_config, ro_dir)
    if options.wildcard:
        try:
            rofilepattern = re.compile(ro_options['rofile'])
        except re.error as e:
            ro_options["err"] = str(e)
            print '''%(rocmd)s %(anncmd)s -w "%(rofile)s" <...> : %(err)s''' % ro_options
            return 1
        for rofile in [ str(r) for r in rometa.getAggregatedResources() if rofilepattern.search(str(r)) ]:
            annotate_single(rofile)
    else:
        rofile = ro_uriutils.resolveFileAsUri(ro_options['rofile'])  # Relative to CWD
        annotate_single(rofile)
    return 0