Java Code Examples for org.openrdf.model.Resource

The following examples show how to use org.openrdf.model.Resource. These examples are extracted from open source projects. 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
@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 2
Source Project: database   Source File: SPARQLUpdateTest.java    License: 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 3
Source Project: anno4j   Source File: JavaNameResolver.java    License: 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 Project: anno4j   Source File: RDFList.java    License: 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 5
Source Project: database   Source File: SampleCode.java    License: 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 6
Source Project: database   Source File: TestSparqlUpdate.java    License: 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 7
Source Project: mustard   Source File: AIFBDataSet.java    License: 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 8
Source Project: database   Source File: UpdateServlet.java    License: 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 9
Source Project: database   Source File: DavidsTestBOps.java    License: 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 10
@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 11
Source Project: database   Source File: TestTicket348.java    License: 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 12
Source Project: anno4j   Source File: LiteralTest.java    License: 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 13
Source Project: anno4j   Source File: OwlNormalizer.java    License: 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 14
Source Project: anno4j   Source File: OwlNormalizer.java    License: 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 15
Source Project: database   Source File: SPARQLUpdateTest.java    License: 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 16
Source Project: anno4j   Source File: ValidatedTransactionTest.java    License: 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 17
Source Project: anno4j   Source File: CreationProvenanceTest.java    License: 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 18
Source Project: database   Source File: TestSparqlUpdate.java    License: 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 19
Source Project: mustard   Source File: RESCALOutput.java    License: 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 20
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 21
Source Project: database   Source File: DavidsTestBOps.java    License: 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 22
/**
 * TODO support baseURI
 */
   @Override
   public void add(final InputStream input, final String baseURI,
           final RDFFormat format, final Resource... c) throws IOException,
           RDFParseException, RepositoryException {
	
	final AddOp op = new AddOp(input, format);
	
	add(op, c);

}
 
Example 23
Source Project: anno4j   Source File: RDFList.java    License: 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 24
private void write(DataSource ds, RepositoryConnection conn, Resource context) throws RepositoryException {
    LOG.info("Writing context {}", context);

    RepositoryResult<Statement> statements = conn.getStatements(null, null, null, true, context);
    Model model = new LinkedHashModel();
    QueryResults.addAll(statements, model);
    copyNamespacesToModel(conn, model);

    String outname = context.toString();
    write(model, outputStream(ds, outname));
}
 
Example 25
/**
	 * aaa xxx bbb 
	 * xxx nrl:inverseProperty yyy
	 * -->
	 * bbb yyy aaa
	 * @return
	 * @throws SailException
	 */
	private int applyRuleN1b()
	throws SailException
{
	int nofInferred = 0;
	
	Iterator<Statement> ntIter = this.newThisIteration.match(null, null, null);

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

		Resource xxx = nt.getPredicate();

		CloseableIteration<? extends Statement, SailException> t1Iter;
		t1Iter = getWrappedConnection().getStatements(xxx,NRL_InverseProperty, null, true);

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

			Value yyy = t1.getObject();
			if (yyy instanceof URI) {
				Resource aaa = 	nt.getSubject();
				Value bbb = nt.getObject();
				boolean added = addInferredStatement((Resource)bbb, (URI) yyy, aaa);
				if (added) {
					nofInferred++;
				}
			}
		}
		t1Iter.close();
	}

	return nofInferred;
}
 
Example 26
Source Project: database   Source File: Example1.java    License: GNU General Public License v2.0 5 votes vote down vote up
public Void call() throws Exception {

        final ICloseableIterator<Statement> itr = om
                .evaluateGraph(
                        "PREFIX foaf: <http://xmlns.com/foaf/0.1/> \n" + //
                        "CONSTRUCT { \n"+//
                        " ?u a foaf:Person . \n" + //
                        " ?u foaf:knows ?v . \n"+
                        " ?u rdfs:label ?name . \n"+
                        "} \n"+//
                        "WHERE {\n"+//
                        " ?u a foaf:Person . \n" + //
                        " ?u foaf:knows ?v . \n"+
                        " OPTIONAL { ?u rdfs:label ?name } . \n"+
                        "} LIMIT 100"//
                        );
        
        final Map<Resource, IGPO> vertices = om.initGPOs(itr);

        System.out.println("Found " + vertices.size() + " instances.");

        for(IGPO gpo : vertices.values()) {
            
            System.out.println(gpo.pp());
            
        }
        
        return null;
        
    }
 
Example 27
Source Project: anno4j   Source File: OwlNormalizer.java    License: Apache License 2.0 5 votes vote down vote up
private void mergeUnionClasses() {
	for (Resource subj : ds.match(null, RDF.TYPE, OWL.CLASS).subjects()) {
		List<Value> unionOf = new ArrayList<Value>();
		for (Value obj : ds.match(subj, OWL.UNIONOF, null).objects()) {
			if (obj instanceof Resource) {
				List<? extends Value> list = new RDFList(ds,
						(Resource) obj).asList();
				list.removeAll(unionOf);
				unionOf.addAll(list);
			}
		}
		if (!unionOf.isEmpty()) {
			Set<URI> common = findCommonSupers(unionOf);
			if (common.contains(subj)) {
				// if union contains itself then remove it
				ds.remove(subj, OWL.UNIONOF, null);
				continue;
			} else if (findCommon(common, unionOf) != null) {
				// if union includes the common super class then fold
				// together
				URI sup = findCommon(common, unionOf);
				ds.remove(subj, OWL.UNIONOF, null);
				nameClass(subj, sup);
				continue;
			}
			for (URI c : common) {
				ds.add(subj, RDFS.SUBCLASSOF, c);
			}
			for (Value ofValue : unionOf) {
				if (ds.contains(ofValue, RDF.TYPE, RDFS.DATATYPE)
						&& ofValue instanceof URI) {
					// don't use anonymous class for datatypes
					nameClass(subj, (URI) ofValue);
				} else {
					ds.add((Resource) ofValue, RDFS.SUBCLASSOF, subj);
				}
			}
		}
	}
}
 
Example 28
Source Project: anno4j   Source File: OwlNormalizer.java    License: Apache License 2.0 5 votes vote down vote up
private void renameAnonymousClasses() {
	for (Resource res : ds.match(null, RDF.TYPE, OWL.CLASS).subjects()) {
		if (res instanceof URI)
			continue;
		// if not already moved
		nameAnonymous(res);
	}
}
 
Example 29
Source Project: mustard   Source File: AffiliationComputationTimeExperiment.java    License: MIT License 5 votes vote down vote up
private static RDFData createRandomSubset(RDFData data, double fraction, long seed) {
	List<Resource> i = data.getInstances();
	Collections.shuffle(i, new Random(seed));

	i = i.subList(0, (int) Math.round(fraction * i.size()));
	return new RDFData(data.getDataset(), i, data.getBlackList());
}
 
Example 30
Source Project: anno4j   Source File: OWLSchemaPersistingManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMatchingExistingSchema() throws Exception {
    Anno4j anno4j = new Anno4j();

    OWLClazz myPerson = anno4j.createObject(OWLClazz.class, (Resource) new URIImpl("http://example.de/#validly_annotated_person"));
    RDFSProperty bossProperty = anno4j.createObject(RDFSProperty.class, (Resource) new URIImpl("http://example.de/#has_boss"));

    Restriction bossAllValuesFromRestr = anno4j.createObject(Restriction.class);
    bossAllValuesFromRestr.setOnClazz(Sets.newHashSet(myPerson));
    bossAllValuesFromRestr.setOnProperty(Sets.newHashSet(bossProperty));
    bossAllValuesFromRestr.setAllValuesFrom(Sets.<OWLClazz>newHashSet(myPerson));

    Reflections types = new Reflections(
            new ConfigurationBuilder()
                    .setUrls(
                            ClasspathHelper.forClass(Person.class, ClasspathHelper.staticClassLoader()),
                            ClasspathHelper.forClass(PersonSupport.class, ClasspathHelper.staticClassLoader())
                    )
                    .setScanners(new MethodAnnotationsScanner(), new FieldAnnotationsScanner(), new TypeAnnotationsScanner(), new SubTypesScanner())
    );

    Transaction transaction = anno4j.createTransaction();
    transaction.begin();
    SchemaPersistingManager persistingManager = new OWLSchemaPersistingManager(transaction.getConnection());

    boolean exceptionThrown = false;
    try {
        persistingManager.persistSchema(types);
    } catch (SchemaPersistingManager.ContradictorySchemaException e) {
        exceptionThrown = true;
    }
    assertFalse(exceptionThrown);
}