private String getTemplate(Individual ind, OntModel displayOntModel) { if (ind == null) return "defaultBody"; // check vitroDisplay:requiresBodyTemplate displayOntModel.enterCriticalSection(Model.READ); StmtIterator it = displayOntModel.listStatements( ind, DisplayVocabulary.REQUIRES_BODY_TEMPLATE, (RDFNode) null); // NodeIterator it = ind.listPropertyValues(DisplayVocabulary.REQUIRES_BODY_TEMPLATE); try { while (it.hasNext()) { Statement stmt = it.nextStatement(); if (stmt.getObject().isLiteral()) { String template = ((Literal) stmt.getObject().as(Literal.class)).getLexicalForm(); if (template != null && template.length() > 0) { return template; } } } } finally { it.close(); displayOntModel.leaveCriticalSection(); } return "defaultBody"; }
@Test public void testUpdate() throws Exception { Resource rhmRes = model.getResource(FakeRDFModel.rhm); Property name = model.getProperty(foaf + "name"); Statement nameSt = rhmRes.listProperties(name).nextStatement(); String originalName = nameSt.getLiteral().getString(); // assume update is always first remove and then add model.remove(nameSt); model.add(rhmRes, name, "TESTNAME"); assert changes.size() == 2; assert rhmRes.listProperties(name).toList().size() == 1; assert rhmRes.listProperties(name).nextStatement().getLiteral().getString().equals("TESTNAME"); changes.undo(); assert changes.size() == 2; assert rhmRes.listProperties(name).toList().size() == 1; assert rhmRes .listProperties(name) .nextStatement() .getLiteral() .getString() .equals(originalName); changes.redo(); assert changes.size() == 2; assert rhmRes.listProperties(name).toList().size() == 1; assert rhmRes.listProperties(name).nextStatement().getLiteral().getString().equals("TESTNAME"); }
@Test public void testChildren() throws RepositoryException { when(mockRes1.getPath()).thenReturn(RDF_PATH + "/res1"); when(mockRes2.getPath()).thenReturn(RDF_PATH + "/res2"); when(mockRes3.getPath()).thenReturn(RDF_PATH + "/res3"); when(mockResourceNode.hasNodes()).thenReturn(true); final Stream<FedoraResource> first = of(mockRes1, mockRes2, mockRes3); final Stream<FedoraResource> second = of(mockRes1, mockRes2, mockRes3); when(mockResource.getChildren()).thenReturn(first).thenReturn(second); try (final ChildrenRdfContext context = new ChildrenRdfContext(mockResource, idTranslator)) { final Model results = context.collect(toModel()); final Resource subject = idTranslator.reverse().convert(mockResource); final StmtIterator stmts = results.listStatements(subject, RdfLexicon.HAS_CHILD_COUNT, (RDFNode) null); assertTrue("There should have been a statement!", stmts.hasNext()); final Statement stmt = stmts.nextStatement(); assertTrue("Object should be a literal! " + stmt.getObject(), stmt.getObject().isLiteral()); assertEquals(3, stmt.getInt()); assertFalse("There should not have been a second statement!", stmts.hasNext()); } }
/** * Deletes the given process element from the rnrm:isFlowingTo linked list without breaking the * path. The element is also removed from the process. * * @param processElement */ public void deleteFromPath(Resource processElement) { Model model = process.getModel(); List<Statement> incoming = process.getIncomingEdges(processElement); List<Statement> outgoing = process.getOutgoingEdges(processElement); if (incoming.size() > 1 || outgoing.size() > 1) { throw new IllegalArgumentException( "Error deleting element. Elements with more than 1 outgoing or incoming links cannot be deleted."); } Resource before = null; Resource after = null; Statement stmt = null; if (incoming.size() > 0) { stmt = incoming.get(0); before = stmt.getSubject(); model.remove(stmt); } if (outgoing.size() > 0) { stmt = outgoing.get(0); after = stmt.getResource(); model.remove(stmt); } if (null != before && null != after) { model.add(before, RNRM.isFlowingTo, after); } // now disassociate this element from the process removeFromProcess(processElement); }
@Override public void processInput(Resource input, Resource output) { final Model model = ModelFactory.createDefaultModel(); final List<Statement> tipURIs = input.listProperties(Vocab.has).toList(); final SublistIterator<Statement> tipsIterator = new SublistIterator<Statement>(tipURIs, QUERY_CHUNK_SIZE); while (tipsIterator.hasNext()) { final List<String> ancestorQueryBlocks = new ArrayList<String>(); final List<String> parentQueryBlocks = new ArrayList<String>(); final List<Statement> tips = tipsIterator.next(); for (Statement statement : tips) { final String tipURI = statement.getResource().getProperty(DC.subject).getResource().getURI(); ancestorQueryBlocks.add(String.format(ancestorQueryBody, tipURI)); parentQueryBlocks.add(String.format(parentQueryBody, tipURI)); } final String ancestorQuery = String.format(ancestorQueryHead, StringUtils.join(ancestorQueryBlocks, " UNION ")); final String parentQuery = String.format(parentQueryHead, StringUtils.join(parentQueryBlocks, ", ")); QueryEngineHTTP ancestorQE = new QueryEngineHTTP(endpoint, ancestorQuery); QueryEngineHTTP parentQE = new QueryEngineHTTP(endpoint, parentQuery); ancestorQE.execConstruct(model); ancestorQE.close(); parentQE.execConstruct(model); parentQE.close(); } this.processNode(Vocab.TaxonomyRoot, model, output.getModel(), null, output); output.getModel().setNsPrefix("cdao", "http://www.evolutionaryontology.org/cdao/1.0/cdao.owl#"); }
Map<String, Object> getValues( Individual ind, OntModel displayOntModel, OntModel assertionModel, Map<String, Object> baseValues) { if (ind == null) return Collections.emptyMap(); /* Figure out what ValueFactories are specified in the display ontology for this individual. */ Set<ValueFactory> valueFactories = new HashSet<ValueFactory>(); displayOntModel.enterCriticalSection(Model.READ); StmtIterator stmts = ind.listProperties(DisplayVocabulary.REQUIRES_VALUES); try { while (stmts.hasNext()) { Statement stmt = stmts.nextStatement(); RDFNode obj = stmt.getObject(); valueFactories.addAll(getValueFactory(obj, displayOntModel)); } } finally { stmts.close(); displayOntModel.leaveCriticalSection(); } /* Get values from the ValueFactories. */ HashMap<String, Object> values = new HashMap<String, Object>(); values.putAll(baseValues); for (ValueFactory vf : valueFactories) { values.putAll(vf.getValues(assertionModel, values)); } return values; }
public static Triple createTriple(Statement statement) throws OREException { try { URI subject = new URI(statement.getSubject().getURI()); Property property = statement.getPredicate(); Predicate pred = new Predicate(); pred.setURI(new URI(property.getURI())); TripleJena triple = new TripleJena(); triple.initialise(new URI(statement.getSubject().getURI())); RDFNode node = statement.getObject(); if (node instanceof Resource) { String uris = ((Resource) node).getURI(); // if the object is not a blank node, we include it if (uris != null) { URI object = new URI(uris); triple.relate(pred, object); } } else { String object = ((Literal) statement.getObject()).getLexicalForm(); triple.relate(pred, object); } return triple; } catch (URISyntaxException e) { throw new OREException(e); } }
private static boolean hasPermission( String userPrefix, String username, String uri, Property[] permissions) { Set<Property> permissionSet = new HashSet<Property>(); Resource resource = configModel.createResource(uri); Resource user; if (username == null) user = PERM.Public; else user = configModel.createResource(userPrefix + username); for (Property permission : permissions) { if (configModel.contains(user, permission, resource)) return true; permissionSet.add(permission); } StmtIterator stmts = user.listProperties(); while (stmts.hasNext()) { Statement stmt = stmts.next(); if (!permissionSet.contains(stmt.getPredicate())) continue; RDFNode resourceMatch = stmt.getObject(); if (!(resourceMatch.isResource() && configModel.contains((Resource) resourceMatch, RDF.type, PERM.ResourceMatch))) continue; RDFNode matchRegex = ((Resource) resourceMatch).getProperty(PERM.matchExpression).getObject(); if (matchRegex == null || !matchRegex.isLiteral()) continue; try { if (uri.matches(((Literal) matchRegex).getString())) return true; } catch (PatternSyntaxException e) { } } if (username != null) return hasPermission(userPrefix, null, uri, permissions); else return false; }
public List<ReMSerialisation> getReMSerialisations() throws OREException { try { List<ReMSerialisation> serialisations = new ArrayList<ReMSerialisation>(); StmtIterator itr = res.listProperties(ORE.isDescribedBy); while (itr.hasNext()) { Statement statement = itr.nextStatement(); Resource resource = (Resource) statement.getObject(); StmtIterator itr2 = resource.listProperties(DC.format); StmtIterator itr3 = resource.listProperties(OREX.isAuthoritativeFor); String mime = "application/octet-stream"; if (itr2.hasNext()) { Statement stmt = itr2.nextStatement(); mime = ((Literal) stmt.getObject()).getLexicalForm(); } boolean authoritative = false; if (itr3.hasNext()) { authoritative = true; } ReMSerialisation serialisation = new ReMSerialisation(mime, new URI(resource.getURI())); serialisation.setAuthoritative(authoritative); serialisations.add(serialisation); } return serialisations; } catch (URISyntaxException e) { throw new OREException(e); } }
public List<DataPropertyStatement> getDataPropertyStatements( DataProperty dp, int startIndex, int endIndex) { getOntModel().enterCriticalSection(Lock.READ); List<DataPropertyStatement> dpss = new ArrayList<DataPropertyStatement>(); try { Property prop = ResourceFactory.createProperty(dp.getURI()); ClosableIterator dpsIt = getOntModel().listStatements(null, prop, (Literal) null); try { int count = 0; while ((dpsIt.hasNext()) && ((endIndex < 0) || (count < endIndex))) { ++count; Statement stmt = (Statement) dpsIt.next(); if (startIndex < 0 || startIndex <= count) { Literal lit = (Literal) stmt.getObject(); DataPropertyStatement dps = new DataPropertyStatementImpl(); dps.setDatapropURI(dp.getURI()); dps.setIndividualURI(stmt.getSubject().getURI()); fillDataPropertyStatementWithJenaLiteral(dps, lit); dpss.add(dps); } } } finally { dpsIt.close(); } } finally { getOntModel().leaveCriticalSection(); } return dpss; }
/** * Returns the identifier of an LSRN-typed Resource * * @param lsrnNode * @return the identifier */ public static String getID(Resource lsrnNode) { Set<String> namespaces = new HashSet<String>(); for (Iterator<Resource> types = RdfUtils.getTypes(lsrnNode); types.hasNext(); ) { Resource type = types.next(); if (type.isURIResource()) { String ns = getNamespaceFromLSRNTypeURI(type.getURI()); if (ns != null) namespaces.add(ns); } } Iterator<Resource> ids = RdfUtils.getPropertyValues(lsrnNode, SIO.has_identifier, null) .andThen(RdfUtils.getPropertyValues(lsrnNode, SIO.has_attribute, null)); while (ids.hasNext()) { Resource identifier = ids.next(); for (Iterator<Resource> types = RdfUtils.getTypes(identifier); types.hasNext(); ) { Resource type = types.next(); if (type.isURIResource()) { String ns = getNamespaceFromLSRNIdentifierTypeURI(type.getURI()); if (ns != null && namespaces.contains(ns)) { Statement s = identifier.getProperty(SIO.has_value); if (s != null) { return s.getString(); } } } } } return null; }
private void fillMap( Resource s, Model model, Map<Resource, SortedSet<Statement>> resource2Statements) { // get all statements with subject s ExtendedIterator<Statement> it = model.listStatements(s, null, (RDFNode) null); // filter statement if necessary if (!dropFilters.isEmpty()) { Iterator<Filter<Statement>> iter = dropFilters.iterator(); Filter<Statement> keepFilter = iter.next(); it = it.filterKeep(keepFilter); while (iter.hasNext()) { it = it.filterKeep(iter.next()); // keepFilter = keepFilter.and(iter.next()); } // it = it.filterKeep(keepFilter); } SortedSet<Statement> statements = resource2Statements.get(s); if (statements == null) { statements = new TreeSet<Statement>(comparator); resource2Statements.put(s, statements); } while (it.hasNext()) { Statement st = it.next(); statements.add(st); if ((st.getObject().isResource()) && !resource2Statements.containsKey(st.getObject())) { fillMap(st.getObject().asResource(), model, resource2Statements); } } }
@Override public int compare(Statement s1, Statement s2) { return ComparisonChain.start() .compare(s1.getPredicate().asNode(), s2.getPredicate().asNode(), nodeComparator) .compare(s1.getObject().asNode(), s2.getObject().asNode(), nodeComparator) .result(); }
private void updateAddRemoveDataGetterStatements( OntModel displayModel, Model removeStatements, Model addStatements, Resource oldType, Resource newType) { log.debug("Old type: " + oldType.getURI() + " - newType: " + newType.getURI()); removeStatements.add(displayModel.listStatements(null, RDF.type, oldType)); StmtIterator oldStatements = displayModel.listStatements(null, RDF.type, oldType); while (oldStatements.hasNext()) { Statement stmt = oldStatements.nextStatement(); addStatements.add(stmt.getSubject(), RDF.type, newType); } // Print out remove and add statements here StringWriter sw = new StringWriter(); try { log.debug( "Adding statements with old data getter types to remove statements, remove statements is now"); removeStatements.write(sw, "N3"); log.debug(sw.toString()); sw.close(); sw = new StringWriter(); log.debug( "Adding statements with new data getter types to add statements, add statements is now"); addStatements.write(sw, "N3"); log.debug(sw.toString()); sw.close(); } catch (Exception ex) { log.error("Error occurred in writing out remove and statements for data getter types", ex); } }
/** * Leo Bard spotted a problem whereby removing a reified statement from a model with style * Standard didn't leave the model empty. Here's a test for it. */ public void testLeosBug() { Model A = getModel(); Statement st = statement(A, "pigs fly south"); ReifiedStatement rst = st.createReifiedStatement("eh:pointer"); A.removeReification(rst); assertIsoModels(ModelFactory.createDefaultModel(), A); }
private void writeTriple(Statement stmt) throws IOException { write(" <triple>\n"); writeNode(stmt.getSubject()); writeNode(stmt.getPredicate()); writeNode(stmt.getObject()); write(" </triple>\n"); }
@Override public Edge getEdge(final Object id) { final String[] keys = id.toString().split("->"); final StmtIterator statements = model.listStatements( new SimpleSelector() { @Override public boolean selects(final Statement s) { if (s.getObject().isResource() && s.getSubject().isResource() && s.getSubject().asResource().getURI().equals(keys[0]) && s.getPredicate().asResource().getURI().equals(keys[1]) && s.getObject().asResource().getURI().equals(keys[2])) { return true; } return false; } }); JenaEdge edge = null; if (statements.hasNext()) { final Statement statement = statements.next(); final Property predicate = statement.getPredicate(); edge = new JenaEdge(model, predicate, statement.getSubject(), statement.getObject()); } return edge; }
public void testRemoveReificationWorks() { Statement st = SPO; Model m = model; m.createReifiedStatement(aURI, st); assertTrue("st is now reified", st.isReified()); m.removeAllReifications(st); assertFalse("st is no longer reified", st.isReified()); }
/** * Index all the resources in a Jena Model to ES * * @param model the model to index * @param bulkRequest a BulkRequestBuilder * @param getPropLabel if set to true all URI property values will be indexed as their label. The * label is taken as the value of one of the properties set in {@link #uriDescriptionList}. */ private void addModelToES(Model model, BulkRequestBuilder bulkRequest, boolean getPropLabel) { long startTime = System.currentTimeMillis(); long bulkLength = 0; HashSet<Property> properties = new HashSet<Property>(); StmtIterator it = model.listStatements(); while (it.hasNext()) { Statement st = it.nextStatement(); Property prop = st.getPredicate(); String property = prop.toString(); if (rdfPropList.isEmpty() || (isWhitePropList && rdfPropList.contains(property)) || (!isWhitePropList && !rdfPropList.contains(property)) || (normalizeProp.containsKey(property))) { properties.add(prop); } } ResIterator resIt = model.listSubjects(); while (resIt.hasNext()) { Resource rs = resIt.nextResource(); Map<String, ArrayList<String>> jsonMap = getJsonMap(rs, properties, model, getPropLabel); bulkRequest.add( client.prepareIndex(indexName, typeName, rs.toString()).setSource(mapToString(jsonMap))); bulkLength++; // We want to execute the bulk for every DEFAULT_BULK_SIZE requests if (bulkLength % EEASettings.DEFAULT_BULK_SIZE == 0) { BulkResponse bulkResponse = bulkRequest.execute().actionGet(); // After executing, flush the BulkRequestBuilder. bulkRequest = client.prepareBulk(); if (bulkResponse.hasFailures()) { processBulkResponseFailure(bulkResponse); } } } // Execute remaining requests if (bulkRequest.numberOfActions() > 0) { BulkResponse response = bulkRequest.execute().actionGet(); // Handle failure by iterating through each bulk response item if (response.hasFailures()) { processBulkResponseFailure(response); } } // Show time taken to index the documents logger.info( "Indexed {} documents on {}/{} in {} seconds", bulkLength, indexName, typeName, (System.currentTimeMillis() - startTime) / 1000.0); }
@Test public void test() { PropertyFilter filter = new PropertyFilter(TestData.foaf_firstname); log.info("Testing the {} class", filter.getClass()); Set<Statement> output = TestData.alexdma.getModel().listStatements().filterKeep(filter).toSet(); for (Statement statement : output) { assertTrue(statement.getPredicate().equals(TestData.foaf_firstname)); } }
private static void doStatement(StringBuffer json, Statement statement) { json.append("{\n \"s\": "); doNode(json, statement.getSubject()); json.append(",\n \"p\": "); doNode(json, statement.getPredicate()); json.append(",\n \"o\": "); doNode(json, statement.getObject()); json.append("}"); }
public DataPropertyStatement(OWLObject<?> subject, Statement s) { super(subject, s); property = getOntology().getDataProperty(s.getPredicate().getURI()); if (s.getObject() instanceof Literal) { literal = (Literal) s.getObject(); } else { logger.warning("DataPropertyStatement: object is not a Literal !"); } }
public Alignment buildAlignment( Statement stmt, AlignmentType alignmentType, ThesaurusConcept concept) { logger.debug("Building alignment " + stmt.getObject().toString()); Alignment alignment = new Alignment(); alignment.setIdentifier(generatorService.generate(Alignment.class)); alignment.setAlignmentType(alignmentType); alignment.setAndRelation(false); alignment.setCreated(concept.getCreated()); alignment.setModified(concept.getModified()); alignment.setSourceConcept(concept); if (alignmentType.isResource()) { Set<AlignmentResource> targetResources = new HashSet<AlignmentResource>(); AlignmentResource targetResource = new AlignmentResource(); String externalTargetResource = stmt.getObject().toString(); targetResource.setAlignment(alignment); targetResource.setExternalTargetResource(externalTargetResource); targetResources.add(targetResource); alignment.setTargetResources(targetResources); } else { Set<AlignmentConcept> targetConcepts = new HashSet<AlignmentConcept>(); AlignmentConcept targetConcept = new AlignmentConcept(); targetConcept.setAlignment(alignment); String targetConceptId = stmt.getObject().toString(); ThesaurusConcept internalTargetConcept = thesaurusConceptService.getThesaurusConceptById(targetConceptId); if (internalTargetConcept != null) { targetConcept.setInternalTargetConcept(internalTargetConcept); alignment.setInternalTargetThesaurus(internalTargetConcept.getThesaurus()); } else { // Check if the concept has an ark indentifier. Matcher arkMt = arkPt.matcher(targetConceptId); Matcher urlMt = urlPt.matcher(targetConceptId); if (arkMt.find()) { setExternalThesaurus(alignment, arkMt.group()); } else if (urlMt.find()) { setExternalThesaurus(alignment, urlMt.group()); } targetConcept.setExternalTargetConcept(targetConceptId); } targetConcepts.add(targetConcept); alignment.setTargetConcepts(targetConcepts); } return alignment; }
public void testStatementListReifiedStatements() { Statement st = SPO; Model m = model; assertEquals( "it's not there yet", empty, GraphTestBase.iteratorToSet(st.listReifiedStatements())); ReifiedStatement rs = m.createReifiedStatement(aURI, st); Set justRS = arrayToSet(new Object[] {rs}); m.add(rs, P, O); assertEquals("it's here now", justRS, GraphTestBase.iteratorToSet(st.listReifiedStatements())); }
/** Converts all object occurances of rdfs:Resource with owl:Thing */ private void convertRDFSResource() { for (StmtIterator it = model.listStatements(null, null, RDFS.Resource); it.hasNext(); ) { Statement s = it.nextStatement(); s.getModel().add(s.getSubject(), s.getPredicate(), OWL.Thing); if (log.isLoggable(Level.FINE)) { log.fine("Replaced triple " + s + " with (x, x, owl:Thing)"); } it.remove(); } }
public List<String> getTitles() { List<String> titles = new ArrayList<String>(); StmtIterator itr = res.listProperties(DC.title); while (itr.hasNext()) { Statement statement = itr.nextStatement(); String title = ((Literal) statement.getObject()).getLexicalForm(); titles.add(title); } return titles; }
public void testFindObject() { StmtIterator iter = model.listStatements(new SimpleSelector(null, null, RDFS.Resource)); int i = 0; while (iter.hasNext()) { i++; Statement stmt = iter.nextStatement(); assertEquals(RDFS.Resource, stmt.getObject()); } assertEquals(2, i); }
public void testFindProperty() { StmtIterator iter = model.listStatements(new SimpleSelector(null, RDFS.label, (RDFNode) null)); int i = 0; while (iter.hasNext()) { i++; Statement stmt = iter.nextStatement(); assertEquals(RDFS.label, stmt.getPredicate()); } assertEquals(2, i); }
/** For all inverse relations, ensure that the relationship is defined in both directions. */ private void applyInverseOfReasoning() { List<Statement> list = model.listStatements(null, OWL.inverseOf, (RDFNode) null).toList(); for (Statement s : list) { Resource subject = s.getSubject(); Resource object = s.getObject().asResource(); Statement newStatement = model.createStatement(object, OWL.inverseOf, subject); model.add(newStatement); } }
public Configuration(Model configurationModel) { model = configurationModel; StmtIterator it = model.listStatements(null, RDF.type, CONF.Configuration); if (!it.hasNext()) { throw new IllegalArgumentException("No conf:Configuration found in configuration model"); } config = it.nextStatement().getSubject(); datasets = new ArrayList(); it = model.listStatements(config, CONF.dataset, (RDFNode) null); while (it.hasNext()) { datasets.add(new Dataset(it.nextStatement().getResource())); } labelProperties = new ArrayList(); it = model.listStatements(config, CONF.labelProperty, (RDFNode) null); while (it.hasNext()) { labelProperties.add(it.nextStatement().getObject().as(Property.class)); } if (labelProperties.isEmpty()) { labelProperties.add(RDFS.label); labelProperties.add(DC.title); labelProperties.add(model.createProperty("http://xmlns.com/foaf/0.1/name")); } commentProperties = new ArrayList(); it = model.listStatements(config, CONF.commentProperty, (RDFNode) null); while (it.hasNext()) { commentProperties.add(it.nextStatement().getObject().as(Property.class)); } if (commentProperties.isEmpty()) { commentProperties.add(RDFS.comment); commentProperties.add(DC.description); } imageProperties = new ArrayList(); it = model.listStatements(config, CONF.imageProperty, (RDFNode) null); while (it.hasNext()) { imageProperties.add(it.nextStatement().getObject().as(Property.class)); } if (imageProperties.isEmpty()) { imageProperties.add(model.createProperty("http://xmlns.com/foaf/0.1/depiction")); } prefixes = new PrefixMappingImpl(); if (config.hasProperty(CONF.usePrefixesFrom)) { it = config.listProperties(CONF.usePrefixesFrom); while (it.hasNext()) { Statement stmt = it.nextStatement(); prefixes.setNsPrefixes(FileManager.get().loadModel(stmt.getResource().getURI())); } } else { prefixes.setNsPrefixes(model); } if (prefixes.getNsURIPrefix(CONF.NS) != null) { prefixes.removeNsPrefix(prefixes.getNsURIPrefix(CONF.NS)); } }