Replaces the subject in RDF files with the datastream's rdf_subject.
 TODO: Deal with what happens when there's no defined datastream.
498792
def replace_subject(content, ds)
      ds.content = content
      if ds.respond_to?(:rdf_subject)
        # Assume the first subject in the metadata is about this object.
        old_subject = self.old_subject || ds.graph.first_subject
        new_repository = RDF::Repository.new
        ds.graph.each_statement do |statement|
          if statement.subject == old_subject
            ds.graph.delete statement
            ds.graph << RDF::Statement.new(ds.rdf_subject, statement.predicate, statement.object)
          end
        end
      end
      ds
    end
1352630
def reload
      @rdf_subject ||= self.class.nr_uri_from_headers(http_head)
      response = get(nil, true)
      self.content_type = response.env.response_headers['content-type']
      self.content = response.env.body
      self
    end
951481
def delete!(headers = {})
      raise "Cannot delete #{rdf_subject}, does not exist." unless exist?
      headers['If-Match'] ||= etag
      response = make_request(:delete, nil, headers)
      @http_headers = nil
      response
    end
748887
def load_rdf(self,
                 uri_or_path=None,
                 data=None,
                 file_obj=None,
                 rdf_format="",
                 verbose=False,
                 hide_base_schemas=True,
                 hide_implicit_types=True,
                 hide_implicit_preds=True):
        """"""
        loader = RDFLoader(verbose=verbose)
        loader.load(uri_or_path, data, file_obj, rdf_format)
        self.rdflib_graph = loader.rdflib_graph
        self.sources = loader.sources_valid
        self.sparqlHelper = SparqlHelper(self.rdflib_graph)
        self.namespaces = sorted(self.rdflib_graph.namespaces())
72829
def _rdf2dot_reduced(g, stream):
    
    import cgi
    import collections

    import rdflib

    from rdflib.tools.rdf2dot import LABEL_PROPERTIES, NODECOLOR

    types = collections.defaultdict(set)
    fields = collections.defaultdict(set)
    nodes = {}

    def node(x):
        """Return a name of the given node."""
        return nodes.setdefault(x, 'node{0}'.format(len(nodes)))

    def label(x, g):
        """Generate a label for the node."""
        for labelProp in LABEL_PROPERTIES:
            label_ = g.value(x, labelProp)
            if label_:
                return label_

        try:
            return g.namespace_manager.compute_qname(x)[2]
        except Exception:
            return x

    def formatliteral(l, g):
        """Format and escape literal."""
        v = cgi.escape(l)
        if l.datatype:
            return '&quot;%s&quot;^^%s' % (v, qname(l.datatype, g))
        elif l.language:
            return '&quot;%s&quot;@%s' % (v, l.language)
        return '&quot;%s&quot;' % v

    def qname(x, g):
        """Compute qname."""
        try:
            q = g.compute_qname(x)
            return q[0] + ':' + q[2]
        except Exception:
            return x

    def color(p):
        """Choose node color."""
        return 'BLACK'

    for s, p, o in g:
        sn = node(s)
        if p == rdflib.RDFS.label:
            continue

        # inject the type predicate into the node itself
        if p == rdflib.RDF.type:
            types[sn].add((qname(p, g), cgi.escape(o)))
            continue
        if p == rdflib.term.URIRef('http://purl.org/dc/terms/isPartOf'):
            fields[sn].add((qname(p, g), cgi.escape(o)))
            continue
        if p == rdflib.term.URIRef('http://www.w3.org/ns/prov#wasInformedBy'):
            continue

        if isinstance(o, (rdflib.URIRef, rdflib.BNode)):
            on = node(o)
            opstr = (
                '\t%s -> %s [ color=%s, label=< <font point-size="12" '
                'color="#336633">%s</font> > ] ;\n'
            )
            stream.write(opstr % (sn, on, color(p), qname(p, g)))
        else:
            fields[sn].add((qname(p, g), formatliteral(o, g)))

    for u, n in nodes.items():
        stream.write(u"# %s %s\n" % (u, n))
        f = [
            '<tr><td align="left"><b>%s</b></td><td align="left">'
            '<b>%s</b></td></tr>' % x for x in sorted(types[n])
        ]
        f += [
            '<tr><td align="left">%s</td><td align="left">%s</td></tr>' % x
            for x in sorted(fields[n])
        ]
        opstr = (
            '%s [ shape=none, color=%s label=< <table color="#666666"'
            ' cellborder="0" cellspacing="0" border="1"><tr>'
            '<td colspan="2" bgcolor="grey"><B>%s</B></td></tr><tr>'
            '<td href="%s" bgcolor="#eeeeee" colspan="2">'
            '<font point-size="12" color="#6666ff">%s</font></td>'
            '</tr>%s</table> > ] \n'
        )
        stream.write(opstr % (n, NODECOLOR, label(u, g), u, u, ''.join(f)))

    stream.write('}\n')
987232
def rdf_iterator(graph, lang, add_vtype=False):
    
    # Return the header row
    hdr = ('subject', 'predicate', 'object')
    yield hdr if not add_vtype else ((h, 'type') for h in hdr)
    # Now the data rows
    for row in graph:
        if lang and not lang_match_rdf(row, lang):
            continue
        yield ((unicode(c), gtype(c)) for c in row)
370812
def update_field(field_name, *obj)
      # Should be an Array of RDF::Term objects
      return unless obj

      if fields[field_name] && fields[field_name].localized?
        trans = {}

        obj.each do |item|
          lang = item.is_a?(RDF::Literal) && item.has_language? ? item.language.to_s : I18n.locale.to_s
          value = item.is_a?(RDF::URI) ? item.to_s : item.object # TODO: tidy this up
          trans[lang] = trans[lang] ? [*trans[lang]] << value : value
        end

        send("#{field_name}_translations=", trans) unless trans.empty?
      else
        objects = obj.map { |item| item.is_a?(RDF::URI) ? item.to_s : item.object } # TODO: tidy this up
        send("#{field_name}=", objects.size > 1 ? objects : objects.first)
      end
    end
1162739
def rdf_source(self, format="turtle"):
        
        s = self.rdflib_graph.serialize(format=format)
        if isinstance(s, bytes):
            s = s.decode('utf-8')
        return s
738727
def transform_concepts(rdf, typemap):
    """"""

    # find out all the types used in the model
    types = set()
    for s, o in rdf.subject_objects(RDF.type):
        if o not in typemap and in_general_ns(o):
            continue
        types.add(o)

    for t in types:
        if mapping_match(t, typemap):
            newval = mapping_get(t, typemap)
            newuris = [v[0] for v in newval]
            logging.debug("transform class %s -> %s", t, str(newuris))
            if newuris[0] is None:  # delete all instances
                for inst in rdf.subjects(RDF.type, t):
                    delete_uri(rdf, inst)
                delete_uri(rdf, t)
            else:
                replace_object(rdf, t, newuris, predicate=RDF.type)
        else:
            logging.info("Don't know what to do with type %s", t)
445731
def _build_rdf(self, data=None):

		'''
		
		'''

		# recreate rdf data
		self.rdf = SimpleNamespace()
		self.rdf.data = data
		self.rdf.prefixes = SimpleNamespace()
		self.rdf.uris = SimpleNamespace()
		# populate prefixes
		for prefix,uri in self.repo.context.items():
			setattr(self.rdf.prefixes, prefix, rdflib.Namespace(uri))
		# graph
		self._parse_graph()
861083
def merge_rdf_list(rdf_list):
    
    # pdb.set_trace()
    if isinstance(rdf_list, list):
        rdf_list = rdf_list[0]
    rtn_list = []
    # for item in rdf_list:
    item = rdf_list
    if item.get('rdf_rest') and item.get('rdf_rest',[1])[0] != 'rdf_nil':
        rtn_list += merge_rdf_list(item['rdf_rest'][0])
    if item.get('rdf_first'):
        rtn_list += item['rdf_first']
    rtn_list.reverse()
    return rtn_list
374823
def set_subject(self, value: Union[Literal, Identifier, str], lang: str= None):
        
        return self.metadata.add(key=DC.subject, value=value, lang=lang)
545255
private String resolveSubjectToDatastream(String subject) throws ServerException{
        String pidURI = PID.toURI(m_obj.getPid());
        if (subject.startsWith(pidURI)) {
            if (subject.length() == pidURI.length()) {
                return "RELS-EXT";
            }
            if (subject.charAt(pidURI.length()) == '/') {
                return "RELS-INT";
            }
        }
        throw new GeneralException("Cannot determine which relationship datastream to update for subject " + subject + ".  Relationship subjects must be the URI of the object or the URI of a datastream within the object.");
    }
183611
private void addDCTriples(Datastream ds,
                              URIReference objURI,
                              Set<Triple> set) throws Exception {
        DCFields dc = new DCFields(ds.getContentStream());
        Map<RDFName, List<DCField>> map = dc.getMap();
        for (RDFName predicate : map.keySet()) {
            for (DCField dcField : map.get(predicate)) {
                String lang = dcField.getLang();
                if (lang == null) {
                    add(objURI, predicate, dcField.getValue(), set);
                } else {
                    add(objURI, predicate, dcField.getValue(), lang, set);
                }
            }
        }
    }
551038
def process(source, target, rdfsonly, base=None, logger=logging):
    '''
    

    '''
    for link in source.match():
        s, p, o = link[:3]
        #SKip docheader statements
        if s == (base or '') + '@docheader': continue
        if p in RESOURCE_MAPPING: p = RESOURCE_MAPPING[p]
        if o in RESOURCE_MAPPING: o = RESOURCE_MAPPING[o]
        if p == VERSA_BASEIRI + 'refines':
            tlinks = list(source.match(s, TYPE_REL))
            if tlinks:
                if tlinks[0][TARGET] == VERSA_BASEIRI + 'Resource':
                    p = I(RDFS_NAMESPACE + 'subClassOf')
                elif tlinks[0][TARGET] == VERSA_BASEIRI + 'Property':
                    p = I(RDFS_NAMESPACE + 'subPropertyOf')
        if p == VERSA_BASEIRI + 'properties':
            suri = I(iri.absolutize(s, base)) if base else s
            target.add((URIRef(o), URIRef(RDFS_NAMESPACE + 'domain'), URIRef(suri)))
            continue
        if p == VERSA_BASEIRI + 'value':
            if o not in ['Literal', 'IRI']:
                ouri = I(iri.absolutize(o, base)) if base else o
                target.add((URIRef(s), URIRef(RDFS_NAMESPACE + 'range'), URIRef(ouri)))
                continue
        s = URIRef(s)
        #Translate v:type to rdf:type
        p = RDF.type if p == TYPE_REL else URIRef(p)
        o = URIRef(o) if isinstance(o, I) else Literal(o)
        if not rdfsonly or p.startswith(RDF_NAMESPACE) or p.startswith(RDFS_NAMESPACE):
            target.add((s, p, o))
    return
1100256
private void validateSubject(final Resource subject) {
        final String subjectURI = subject.getURI();
        // blank nodes are okay
        if (!subject.isAnon()) {
            // hash URIs with the same base as the topic are okay
            final int hashIndex = subjectURI.lastIndexOf("#");
            if (!(hashIndex > 0 && topic.getURI().equals(subjectURI.substring(0, hashIndex)))) {
                // the topic itself is okay
                if (!topic.equals(subject.asNode())) {
                    // it's a bad subject, but it could still be in-domain
                    if (idTranslator.inDomain(subject)) {
                        LOGGER.error("{} is not in the topic of this RDF, which is {}.", subject, topic);
                        throw new IncorrectTripleSubjectException(subject +
                                " is not in the topic of this RDF, which is " + topic);
                    }
                    // it's not even in the right domain!
                    LOGGER.error("subject ({}) is not in repository domain.", subject);
                    throw new OutOfDomainSubjectException(subject.asNode());
                }
            }
        }
    }
15302
def replace_with_text_stream(stream_name):
    
    new_stream = TEXT_STREAMS.get(stream_name)
    if new_stream is not None:
        new_stream = new_stream()
        setattr(sys, stream_name, new_stream)
    return None