org.openrdf.model.Resource Java Examples

The following examples show how to use org.openrdf.model.Resource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testDescribeB()
	throws Exception
{
	loadTestData("/testdata-query/dataset-describe.trig");
	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("DESCRIBE ex:b");

	GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query.toString());

	ValueFactory f = conn.getValueFactory();
	URI b = f.createURI("http://example.org/b");
	URI p = f.createURI("http://example.org/p");
	Model result = QueryResults.asModel(gq.evaluate());
	Set<Resource> subjects = result.filter(null, p, b).subjects();
	assertNotNull(subjects);
	for (Value subject : subjects) {
		if (subject instanceof BNode) {
			assertTrue(result.contains(null, null, subject));
		}
	}
}
 
Example #2
Source File: RDFList.java    From anno4j with Apache License 2.0 6 votes vote down vote up
Resource getRest(Resource list) {
	if (list == null)
		return null;
	try {
		CloseableIteration<Value, RepositoryException> stmts;
		stmts = getValues(list, RDF.REST, null);
		try {
			if (stmts.hasNext())
				return (Resource) stmts.next();
			return null;
		} finally {
			stmts.close();
		}
	} catch (RepositoryException e) {
		throw new ObjectStoreException(e);
	}
}
 
Example #3
Source File: JavaNameResolver.java    From anno4j with Apache License 2.0 6 votes vote down vote up
public void setModel(Model model) {
	this.model = model;
	if (nouns != null) {
		Set<String> localNames = new HashSet<String>();
		for (Resource subj : model.filter(null, RDF.TYPE, null).subjects()) {
			if (subj instanceof URI) {
				localNames.add(((URI) subj).getLocalName());
			}
		}
		for (String name : localNames) {
			if (name.matches("^[a-zA-Z][a-z]+$")) {
				nouns.add(name.toLowerCase());
			}
		}
	}
}
 
Example #4
Source File: RESCALOutput.java    From mustard with MIT License 6 votes vote down vote up
public void loadEntityEmb(String filename, Map<Integer, Resource> invEntityMap) {
	try {
		BufferedReader fr = new BufferedReader(new FileReader(filename));
		String line;

		for (int i = 0; (line = fr.readLine()) != null; i++) {
			int numFacs = line.split(" ").length;
			double[] facs = new double[numFacs];
			entityEmb.put(invEntityMap.get(i), facs);

			int j = 0;
			for (String val : line.split(" ")) {
				facs[j] = Double.parseDouble(val);
				j++;
			}

		}
		fr.close();

	} catch (Exception e) {
		throw new RuntimeException(e);		
	}
}
 
Example #5
Source File: SPARQLUpdateTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testAddFromDefaultToDefault()
	throws Exception
{
	logger.debug("executing testAddFromDefaultToDefault");

	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("ADD DEFAULT TO DEFAULT");

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());

	assertTrue(con.hasStatement(graph1, DC.PUBLISHER, null, false, (Resource)null));
	assertTrue(con.hasStatement(graph2, DC.PUBLISHER, null, false, (Resource)null));
	operation.execute();
	assertTrue(con.hasStatement(graph1, DC.PUBLISHER, null, false, (Resource)null));
	assertTrue(con.hasStatement(graph2, DC.PUBLISHER, null, false, (Resource)null));
}
 
Example #6
Source File: ForwardChainingRDFSInferencerConnection.java    From semweb4j with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private int applyRuleRdfs6()
	throws SailException
{
	int nofInferred = 0;

	Iterator<Statement> iter = this.newThisIteration.match(null, RDF.TYPE, RDF.PROPERTY);

	while (iter.hasNext()) {
		Statement st = iter.next();

		Resource xxx = st.getSubject();
		boolean added = addInferredStatement(xxx, RDFS.SUBPROPERTYOF, xxx);
		if (added) {
			nofInferred++;
		}
	}

	return nofInferred;
}
 
Example #7
Source File: TripleStoreBlazegraph.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void write(DataSource ds, String contextName) {
    RepositoryConnection conn = null;
    try {
        conn = repo.getConnection();
        RepositoryResult<Resource> contexts = conn.getContextIDs();
        while (contexts.hasNext()) {
            Resource context = contexts.next();
            if (context.stringValue().equals(contextName)) {
                write(ds, conn, context);
            }
        }
    } catch (RepositoryException x) {
        throw new TripleStoreException(String.format("Writing on %s", ds), x);
    } finally {
        closeConnection(conn, "Writing on " + ds);
    }
}
 
Example #8
Source File: SampleCode.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Add a statement to a repository.
 * 
 * @param repo
 * @throws Exception
 */
public void loadSomeData(Repository repo) throws Exception {
    RepositoryConnection cxn = repo.getConnection();
    
    cxn.setAutoCommit(false);
    try {
        Resource s = new URIImpl("http://www.bigdata.com/rdf#Mike");
        URI p = new URIImpl("http://www.bigdata.com/rdf#loves");
        Value o = new URIImpl("http://www.bigdata.com/rdf#RDF");
        Statement stmt = new StatementImpl(s, p, o);
        cxn.add(stmt);
        cxn.commit();
    } catch (Exception ex) {
        cxn.rollback();
        throw ex;
    } finally {
        // close the repository connection
        cxn.close();
    }
}
 
Example #9
Source File: TestSparqlUpdate.java    From database with GNU General Public License v2.0 6 votes vote down vote up
public void testCopyFromDefault()
        throws Exception
    {
//        log.debug("executing testCopyFromDefault");

        final StringBuilder update = new StringBuilder();
        update.append(getNamespaceDeclarations());
        update.append("COPY DEFAULT TO ex:graph3");

//        Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());

        assertTrue(hasStatement(graph1, DC.PUBLISHER, null, false, (Resource)null));
        assertTrue(hasStatement(graph2, DC.PUBLISHER, null, false, (Resource)null));
    
//        operation.execute();
        m_repo.prepareUpdate(update.toString()).evaluate();

        assertTrue(hasStatement(graph1, DC.PUBLISHER, null, false, (Resource)null));
        assertTrue(hasStatement(graph2, DC.PUBLISHER, null, false, (Resource)null));
        assertTrue(hasStatement(graph1, DC.PUBLISHER, null, false, f.createURI(EX_NS, "graph3")));
        assertTrue(hasStatement(graph2, DC.PUBLISHER, null, false, f.createURI(EX_NS, "graph3")));

    }
 
Example #10
Source File: CreationProvenanceTest.java    From anno4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testRights() throws RepositoryException, IllegalAccessException, InstantiationException {
    Annotation annotation = this.anno4j.createObject(Annotation.class);

    TextualBody body = this.anno4j.createObject(TextualBody.class);
    body.addRight(this.anno4j.createObject(ResourceObject.class, (Resource) RIGHT));

    SpecificResource target = this.anno4j.createObject(SpecificResource.class);
    HashSet<ResourceObject> rights = new HashSet<>();
    rights.add(this.anno4j.createObject(ResourceObject.class, (Resource) RIGHT2));
    rights.add(this.anno4j.createObject(ResourceObject.class, (Resource) RIGHT3));
    target.setRights(rights);

    annotation.addBody(body);
    annotation.addTarget(target);

    Annotation result = this.anno4j.findByID(Annotation.class, annotation.getResourceAsString());

    assertEquals(0, result.getRights().size());
    assertEquals(1, result.getBodies().iterator().next().getRights().size());
    assertEquals(2, ((SpecificResource) result.getTargets().toArray()[0]).getRights().size());
}
 
Example #11
Source File: ValidatedTransactionTest.java    From anno4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testIndirectModification() throws Exception {
    Anno4j anno4j = new Anno4j();

    URI resource1URI = new URIImpl("http://example.de/r1");
    TestResource resource1 = anno4j.createObject(TestResource.class, (Resource) resource1URI);
    TestResource resource2 = anno4j.createObject(TestResource.class);
    resource1.setTransitive(Sets.newHashSet(resource2));

    ValidatedTransaction transaction = anno4j.createValidatedTransaction();
    transaction.begin();
    TestResource foundResource = transaction.findByID(TestResource.class, resource1URI);
    foundResource.getTransitive().iterator().next().setCardinality(Sets.newHashSet(1, 2, 3, 4, 5));

    boolean exceptionThrown = false;
    try {
        transaction.commit();
    } catch (ValidatedTransaction.ValidationFailedException e) {
        exceptionThrown = true;
    }
    assertTrue(exceptionThrown);
}
 
Example #12
Source File: TestSparqlUpdate.java    From database with GNU General Public License v2.0 6 votes vote down vote up
public void testDropDefault()
        throws Exception
    {
//        log.debug("executing testDropDefault");

        String update = "DROP DEFAULT";

//        Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update);

        // Verify statements exist in the named graphs.
        assertTrue(hasStatement(null, null, null, false, graph1));
        assertTrue(hasStatement(null, null, null, false, graph2));
        // Verify statements exist in the default graph.
        assertTrue(hasStatement(null, null, null, false, new Resource[]{null}));

//        operation.execute();
        
        m_repo.prepareUpdate(update.toString()).evaluate();

        assertTrue(hasStatement(null, null, null, false, graph1));
        assertTrue(hasStatement(null, null, null, false, graph2));
        // Verify that no statements remain in the 'default' graph.
        assertFalse(hasStatement(null, null, null, false, new Resource[]{null}));

    }
 
Example #13
Source File: DavidsTestBOps.java    From database with GNU General Public License v2.0 6 votes vote down vote up
public void testExplicitDefaultAndNamedGraphNoGraphKeyword ()
    throws Exception
{
    final BigdataSail sail = getTheSail () ;
    final ValueFactory vf = sail.getValueFactory();
    final RepositoryConnection cxn = getRepositoryConnection ( sail ) ;
    try {
    String ns = "http://xyz.com/test#" ;
    String kb = String.format ( "<%ss> <%sp> <%so> .", ns, ns, ns ) ;
    String qs = String.format ( "select ?s from <%sg1> from named <%sg2> where { ?s ?p ?o .}", ns, ns ) ;

    Resource graphs [] = new Resource [] { vf.createURI ( String.format ( "%sg1", ns ) ), vf.createURI ( String.format ( "%sg2", ns ) ) } ;

    Collection<BindingSet> expected = getExpected ( createBindingSet ( new BindingImpl ( "s", new URIImpl ( String.format ( "%ss", ns ) ) ) ) ) ;

    run ( sail, cxn, kb, graphs, qs, expected ) ;
    } finally {
        cxn.close();
    }
}
 
Example #14
Source File: TestTicket348.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private void addDuringQueryExec(final RepositoryConnection conn,
	final Resource subj, final URI pred, final Value obj,
	final Resource... ctx) throws RepositoryException,
	MalformedQueryException, QueryEvaluationException {
final TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL,
      		"select distinct ?s ?p ?o where{?s ?p ?t . ?t <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?o }"
      		);
      tq.setBinding("s", subj);
      tq.setBinding("p", pred);
      tq.setBinding("o", obj);
      final TupleQueryResult tqr = tq.evaluate();
      try {
          if (!tqr.hasNext()) {
              conn.add(subj, pred, obj, ctx);
          }
      } finally {
          tqr.close();
      }
  }
 
Example #15
Source File: DavidsTestBOps.java    From database with GNU General Public License v2.0 6 votes vote down vote up
public void testNamedGraphNoGraphKeyword2 ()
    throws Exception
{
    final BigdataSail sail = getTheSail () ;
    final ValueFactory vf = sail.getValueFactory();
    final RepositoryConnection cxn = getRepositoryConnection ( sail ) ;
    try {
    String ns = "http://xyz.com/test#" ;
    String kb = String.format ( "<%ss> <%sp> <%so> .", ns, ns, ns ) ;
    String qs = String.format ( "select ?s from named <%sg1> from named <%sg2> where { ?s ?p ?o .}", ns, ns ) ;

    Resource graphs [] = new Resource [] { vf.createURI ( String.format ( "%sg1", ns ) ), vf.createURI ( String.format ( "%sg2", ns ) ) } ;

    Collection<BindingSet> expected = getExpected () ;

    run ( sail, cxn, kb, graphs, qs, expected ) ;
    } finally {
        cxn.close();
    }
}
 
Example #16
Source File: LiteralTest.java    From anno4j with Apache License 2.0 6 votes vote down vote up
public void testDay() throws Exception {
	TestConcept tester = manager.addDesignation(manager.getObjectFactory().createObject(), TestConcept.class);
	Resource bNode = (Resource) manager.addObject(tester);
	Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
	cal.set(1970, 0, 1, 0, 0, 0);
	cal.set(Calendar.MILLISECOND, 0);
	Date date = cal.getTime();
	try {
		manager.add(bNode, dateURI, getValueFactory().createLiteral(
				"1970-01-01Z", XMLSchema.DATE));
	} catch (RepositoryException e) {
		throw new ObjectPersistException(e);
	}
	cal.setTime(tester.getADate());
	assertEquals(date, cal.getTime());
}
 
Example #17
Source File: OwlNormalizer.java    From anno4j with Apache License 2.0 6 votes vote down vote up
private void checkPropertyDomains() {
	loop: for (Statement st : ds.match(null, RDF.TYPE, RDF.PROPERTY)) {
		Resource p = st.getSubject();
		if (!ds.contains(p, RDFS.DOMAIN, null)) {
			for (Value sup : ds.match(p, RDFS.SUBPROPERTYOF, null).objects()) {
				for (Value obj : ds.match(sup, RDFS.DOMAIN, null).objects()) {
					ds.add(p, RDFS.DOMAIN, obj);
					continue loop;
				}
			}
			ds.add(p, RDFS.DOMAIN, RDFS.RESOURCE);
			if (!ds.contains(RDFS.RESOURCE, RDF.TYPE, OWL.CLASS)) {
				ds.add(RDFS.RESOURCE, RDF.TYPE, OWL.CLASS);
			}
		}
	}
}
 
Example #18
Source File: UpdateServlet.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 
 * @param namespace
 *           The namespace of the target KB instance.
 * @param timestamp
 *           The timestamp used to obtain a mutable connection.
 * @param baseURI
 *           The base URI for the operation.
 * @param bindings 
 * @param defaultContextDelete
 *           When removing statements, the context(s) for triples without
 *           an explicit named graph when the KB instance is operating in
 *           a quads mode.
 * @param defaultContextInsert
 *           When inserting statements, the context(s) for triples without
 *           an explicit named graph when the KB instance is operating in
 *           a quads mode.
 */
public UpdateWithQueryMaterializedTask(final HttpServletRequest req,
      final HttpServletResponse resp, final String namespace,
      final long timestamp,
      final String queryStr,//
      final String baseURI,
      final boolean suppressTruthMaintenance, //
      final Map<String, Value> bindings,
      final RDFParserFactory parserFactory,
      final Resource[] defaultContextDelete,//
      final Resource[] defaultContextInsert//
) {
   super(req, resp, namespace, timestamp);
   this.queryStr = queryStr;
   this.baseURI = baseURI;
   this.suppressTruthMaintenance = suppressTruthMaintenance;
   this.bindings = bindings;
   this.parserFactory = parserFactory;
   this.defaultContextDelete = defaultContextDelete;
   this.defaultContextInsert = defaultContextInsert;
}
 
Example #19
Source File: AIFBDataSet.java    From mustard with MIT License 6 votes vote down vote up
public void create() {
	List<Statement> stmts = tripleStore.getStatementsFromStrings(null, "http://swrc.ontoware.org/ontology#affiliation", null);

	List<Resource> instances = new ArrayList<Resource>();
	List<Value> labels = new ArrayList<Value>();

	for (Statement stmt : stmts) {
		instances.add(stmt.getSubject());
		labels.add(stmt.getObject());
	}

	List<Statement> blackList = DataSetUtils.createBlacklist(tripleStore, instances, labels);

	if (!smallClass) {
		EvaluationUtils.removeSmallClasses(instances, labels, 5);
	}

	Map<Value, Double> labelMap = new HashMap<Value,Double>();
	target = EvaluationUtils.createTarget(labels, labelMap);

	System.out.println("Label mapping: " + labelMap);

	data = new RDFData(tripleStore, instances, blackList);
}
 
Example #20
Source File: OwlNormalizer.java    From anno4j with Apache License 2.0 6 votes vote down vote up
private Set<URI> findCommonSupers(List<? extends Value> unionOf) {
	Set<? extends Value> common = null;
	for (Value of : unionOf) {
		if (of instanceof Resource) {
			Set<Value> supers = findSuperClasses((Resource) of);
			if (common == null) {
				common = new HashSet<Value>(supers);
			} else {
				common.retainAll(supers);
			}
		}
	}
	if (common == null)
		return Collections.emptySet();
	Iterator<? extends Value> iter = common.iterator();
	while (iter.hasNext()) {
		if (!(iter.next() instanceof URI)) {
			iter.remove();
		}
	}
	return (Set<URI>) common;
}
 
Example #21
Source File: SPARQLUpdateTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testMoveToDefault()
	throws Exception
{
	logger.debug("executing testMoveToDefault");

	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("MOVE GRAPH <" + graph1.stringValue() + "> TO DEFAULT");

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());

	assertTrue(con.hasStatement(graph1, DC.PUBLISHER, null, false, (Resource)null));
	assertTrue(con.hasStatement(graph2, DC.PUBLISHER, null, false, (Resource)null));
	operation.execute();
	assertFalse(con.hasStatement(graph1, DC.PUBLISHER, null, false, (Resource)null));
	assertFalse(con.hasStatement(graph2, DC.PUBLISHER, null, false, (Resource)null));
	assertTrue(con.hasStatement(bob, FOAF.NAME, null, false, (Resource)null));
	assertFalse(con.hasStatement(null, null, null, false, graph1));
}
 
Example #22
Source File: RDFList.java    From anno4j with Apache License 2.0 5 votes vote down vote up
private List<Value> copyTo(Value node, List<Value> list) {
	Value first = triples.match(node, RDF.FIRST, null).objectValue();
	Resource rest = triples.match(node, RDF.REST, null).objectResource();
	if (first == null)
		return list;
	list.add(first);
	return copyTo(rest, list);
}
 
Example #23
Source File: ObjectMgrModel.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Deprecated // no need for explicit recall.
public IGPO recallAsGPO(final URI key) {
	
    final Value val = recall(key);
	
	if (val instanceof Resource) {
		return getGPO((Resource) val);
	} else {
		return null;
	}
}
 
Example #24
Source File: GPO.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Override
	public void removeValue(final URI property, final Value value) {

		if (property == null)
			throw new IllegalArgumentException();

		if (value == null)
			throw new IllegalArgumentException();

//		final Lock writeLock = m_lock.writeLock();
//		writeLock.lock();
//		try {
			materialize();

			final GPOEntry entry = establishEntry(property);

			if (entry.remove(this, value)) {
				
				if (value instanceof Resource) {
					((GPO) m_om.getGPO((Resource) value)).removeLinkSetMember(property, m_id);
				}

				dirty();

			}
//		} finally {
//			writeLock.unlock();
//		}

	}
 
Example #25
Source File: SchemaSanitizingObjectSupportTest.java    From anno4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveValue() throws Exception {
    SanitizingTestResource resource = anno4j.createObject(SanitizingTestResource.class, (Resource) new URIImpl("urn:anno4j:r"));
    SanitizingTestResource x1 = anno4j.createObject(SanitizingTestResource.class, (Resource) new URIImpl("urn:anno4j:x1"));
    SanitizingTestResource x2 = anno4j.createObject(SanitizingTestResource.class, (Resource) new URIImpl("urn:anno4j:x2"));

    // Setup values:
    resource.setSuperproperty(Sets.newHashSet(1));
    resource.setSubproperty(Sets.newHashSet(2));
    resource.setObjectSuperproperty(Sets.newHashSet(x1));
    resource.setObjectSubproperty(Sets.newHashSet(x2));

    // Actual test happens here:
    resource.testRemoveValue(x2);
}
 
Example #26
Source File: RDFList.java    From anno4j with Apache License 2.0 5 votes vote down vote up
void removeStatements(Resource subj, URI pred, Value obj) {
	try {
		ObjectConnection conn = getObjectConnection();
		conn.remove(subj, pred, obj);
	} catch (RepositoryException e) {
		throw new ObjectPersistException(e);
	}
}
 
Example #27
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
protected void loadTestData(String dataFile, Resource... contexts)
	throws RDFParseException, RepositoryException, IOException
{
	logger.debug("loading dataset {}", dataFile);
	InputStream dataset = ComplexSPARQLQueryTest.class.getResourceAsStream(dataFile);
	try {
		conn.add(dataset, "", RDFFormat.forFileName(dataFile), contexts);
	}
	finally {
		dataset.close();
	}
	logger.debug("dataset loaded.");
}
 
Example #28
Source File: BigdataSail.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Unsupported API.
 */
@Override
public void removeStatement(UpdateContext op, Resource subj, URI pred, Value obj, Resource... contexts)
    throws SailException
{
    
    throw new SailException(ERR_OPENRDF_QUERY_MODEL);

}
 
Example #29
Source File: ForwardChainingRDFSInferencerConnection.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private int applyRuleRdfs3_2()
	throws SailException
{
	int nofInferred = 0;

	Iterator<Statement> ntIter = this.newThisIteration.match(null, RDFS.RANGE, null);

	while (ntIter.hasNext()) {
		Statement nt = ntIter.next();

		Resource aaa = nt.getSubject();
		Value zzz = nt.getObject();

		if (aaa instanceof URI && zzz instanceof Resource) {
			CloseableIteration<? extends Statement, SailException> t1Iter;
			t1Iter = getWrappedConnection().getStatements(null, (URI)aaa, null, true);

			while (t1Iter.hasNext()) {
				Statement t1 = t1Iter.next();

				Value uuu = t1.getObject();
				if (uuu instanceof Resource) {
					boolean added = addInferredStatement((Resource)uuu, RDF.TYPE, zzz);
					if (added) {
						nofInferred++;
					}
				}
			}
			t1Iter.close();
		}
	}

	return nofInferred;

}
 
Example #30
Source File: RDFEntity.java    From anno4j with Apache License 2.0 5 votes vote down vote up
public Set<RDFProperty> getRDFProperties(URI pred) {
	Set<RDFProperty> set = new HashSet<RDFProperty>();
	for (Value value : model.filter(self, pred, null).objects()) {
		if (value instanceof Resource) {
			Resource subj = (Resource) value;
			set.add(new RDFProperty(model, subj));
		}
	}
	return set;
}