Java Code Examples for org.openrdf.model.ValueFactory

The following examples show how to use org.openrdf.model.ValueFactory. 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
Source Project: tinkerpop3   Source File: BlazeValueFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a datatyped literal from a blueprints property value.
 * <p>
 * Supports: Float, Double, Integer, Long, Boolean, Short, Byte, and String.
 */
default Literal toLiteral(final Object value) {

    final ValueFactory vf = Defaults.VF;
    
    if (value instanceof Float) {
        return vf.createLiteral((Float) value);
    } else if (value instanceof Double) {
        return vf.createLiteral((Double) value);
    } else if (value instanceof Integer) {
        return vf.createLiteral((Integer) value);
    } else if (value instanceof Long) {
        return vf.createLiteral((Long) value);
    } else if (value instanceof Boolean) {
        return vf.createLiteral((Boolean) value);
    } else if (value instanceof Short) {
        return vf.createLiteral((Short) value);
    } else if (value instanceof Byte) {
        return vf.createLiteral((Byte) value);
    } else if (value instanceof String) { 
        return vf.createLiteral((String) value);
    } else {
        throw new IllegalArgumentException(String.format("not supported: %s", value));
    }
    
}
 
Example 2
Source Project: database   Source File: TestTicket632.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final URI serviceUri, final SailRepository repo) throws RepositoryException, MalformedQueryException, QueryEvaluationException, RDFParseException, IOException, RDFHandlerException {
    try {
        repo.initialize();
        final RepositoryConnection conn = repo.getConnection();
        final ValueFactory vf = conn.getValueFactory();
        conn.setAutoCommit(false);
        try {
            final String query = "SELECT ?x { SERVICE <" + serviceUri.stringValue() + "> { ?x <u:1> ?bool1 } }";
            final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
            q.setBinding("bool1", vf.createLiteral(true));
            final TupleQueryResult tqr = q.evaluate();
            try {
                tqr.hasNext();
            } finally {
                tqr.close();
            }
        } finally {
            conn.close();
        }
    } finally {
        repo.shutDown();
    }
}
 
Example 3
@Override
public void activate(final Collection<SesamePosLengthInjectMatch> matches) throws RepositoryException {
	final RepositoryConnection con = driver.getConnection();
	final ValueFactory vf = driver.getValueFactory();

	final URI typeURI = vf.createURI(BASE_PREFIX + ModelConstants.LENGTH);
	final Literal zeroLiteral = vf.createLiteral(0);

	for (final SesamePosLengthInjectMatch match : matches) {
		final URI segment = match.getSegment();

		final RepositoryResult<Statement> statementsToRemove = con.getStatements(segment, typeURI, null, true);
		con.remove(statementsToRemove);

		con.add(segment, typeURI, zeroLiteral);
	}
}
 
Example 4
Source Project: database   Source File: TestTicket4249.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final RepositoryConnection conn, final Literal string, final int start, final int length, final Literal expected)
		throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	final ValueFactory vf = conn.getValueFactory();
	final String query = "select ?substring WHERE { BIND ( SUBSTR(?string, ?start, ?length) as ?substring ) . }";
	final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
	q.setBinding("string", string);
	q.setBinding("start", vf.createLiteral(start));
	q.setBinding("length", vf.createLiteral(length));
	final TupleQueryResult tqr = q.evaluate();
	try {
		while (tqr.hasNext()) {
			final BindingSet bindings = tqr.next();
			// assert expected value
			assertEquals(expected, bindings.getBinding("substring").getValue());
		}
	} finally {
		tqr.close();
	}
}
 
Example 5
Source Project: database   Source File: TestNoExceptions.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final SailRepository repo, final String query)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, IOException,
		RDFHandlerException {
	try {
		repo.initialize();
		final RepositoryConnection conn = repo.getConnection();
		conn.setAutoCommit(false);
		try {
			final ValueFactory vf = conn.getValueFactory();
			conn.commit();
			TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
			TupleQueryResult tqr = tq.evaluate();
			tqr.close();
		} finally {
			conn.close();
		}
	} finally {
		repo.shutDown();
	}
}
 
Example 6
Source Project: database   Source File: TestGPO.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checks for reverse linkset referential integrity when property replaced
 */
public void testLinkSetConsistency2() {
	doLoadData();
	
	final ValueFactory vf = om.getValueFactory();

    final URI workeruri = vf.createURI("gpo:#123");
    IGPO workergpo = om.getGPO(workeruri);
    final URI worksFor = vf.createURI("attr:/employee#worksFor");
    final ILinkSet ls = workergpo.getLinksOut(worksFor);
    
    assertTrue(ls.size() > 0);
    
    final IGPO employer = ls.iterator().next();
    
    final ILinkSet employees = employer.getLinksIn(worksFor);
    assertTrue(employees.contains(workergpo));
    
    // set property to new URI
    final URI newuri = vf.createURI("gpo:#999");
    workergpo.setValue(worksFor, newuri);
    
    assertFalse(employees.contains(workergpo));
    assertTrue(om.getGPO(newuri).getLinksIn(worksFor).contains(workergpo));
}
 
Example 7
Source Project: attic-polygene-java   Source File: EntityTypeSerializer.java    License: Apache License 2.0 6 votes vote down vote up
public Iterable<Statement> serialize( final EntityDescriptor entityDescriptor )
{
    Graph graph = new GraphImpl();
    ValueFactory values = graph.getValueFactory();
    URI entityTypeUri = values.createURI( Classes.toURI( entityDescriptor.types().findFirst().orElse( null ) ) );

    graph.add( entityTypeUri, Rdfs.TYPE, Rdfs.CLASS );
    graph.add( entityTypeUri, Rdfs.TYPE, OWL.CLASS );

    graph.add( entityTypeUri,
               PolygeneEntityType.TYPE,
               values.createLiteral( entityDescriptor.types().findFirst().get().toString() )
    );
    graph.add( entityTypeUri, PolygeneEntityType.QUERYABLE, values.createLiteral( entityDescriptor.queryable() ) );

    serializeMixinTypes( entityDescriptor, graph, entityTypeUri );

    serializePropertyTypes( entityDescriptor, graph, entityTypeUri );
    serializeAssociationTypes( entityDescriptor, graph, entityTypeUri );
    serializeManyAssociationTypes( entityDescriptor, graph, entityTypeUri );

    return graph;
}
 
Example 8
Source Project: cumulusrdf   Source File: GraphHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Delete data from the graph.
 * 
 * @param repository the Repository object
 * @param request the HttpServletRequest object
 * @param response the HttpServletResponse object
 * @return the EmptySuccessView if successes
 * @throws ClientHTTPException throws when there are errors in getting the name of the Graph
 * @throws ServerHTTPException throws when errors happens update the data
 */
private ModelAndView getDeleteDataResult(final Repository repository,
		final HttpServletRequest request, final HttpServletResponse response)
		throws ClientHTTPException, ServerHTTPException {
	ProtocolUtil.logRequestParameters(request);

	ValueFactory vf = repository.getValueFactory();

	URI graph = getGraphName(request, vf);

	try {
		RepositoryConnection repositoryCon = repository.getConnection();
		synchronized (repositoryCon) {
			repositoryCon.clear(graph);
		}
		repositoryCon.close();
		return new ModelAndView(EmptySuccessView.getInstance());
	} catch (RepositoryException e) {
		throw new ServerHTTPException("Repository update error: " + e.getMessage(), e);
	}
}
 
Example 9
Source Project: database   Source File: TestGPO.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void testLinkSetsIn() {
	doLoadData();
	
	final ValueFactory vf = om.getValueFactory();

    final URI clssuri = vf.createURI("gpo:#1");
    IGPO clssgpo = om.getGPO(clssuri);
	
    final URI linkURI = vf.createURI("attr:/type");
    ILinkSet ls = clssgpo.getLinksIn(linkURI);
    
    assertTrue(ls.getOwner() == clssgpo);
    assertTrue(ls.isLinkSetIn());
    assertTrue(ls.getLinkProperty().equals(linkURI));
    
    checkLinkSet(ls, 2);
}
 
Example 10
Source Project: attic-polygene-java   Source File: EntityTypeSerializer.java    License: Apache License 2.0 6 votes vote down vote up
private void serializePropertyTypes( final EntityDescriptor entityDescriptor,
                                     final Graph graph,
                                     final URI entityTypeUri
)
{
    ValueFactory values = graph.getValueFactory();

    // Properties
    entityDescriptor.state().properties().forEach( persistentProperty -> {
        URI propertyURI = values.createURI( persistentProperty.qualifiedName().toURI() );
        graph.add( propertyURI, Rdfs.DOMAIN, entityTypeUri );
        graph.add( propertyURI, Rdfs.TYPE, Rdfs.PROPERTY );

        // TODO Support more types
        URI type = dataTypes.get( persistentProperty.valueType().primaryType().getName() );
        if( type != null )
        {
            graph.add( propertyURI, Rdfs.RANGE, type );
        }
    } );
}
 
Example 11
static public org.openrdf.model.Statement castJenaOpenRdf(com.hp.hpl.jena.rdf.model.Statement jenaStatement, String modelName) {
    org.openrdf.model.Statement statement = null;
    try {
        ValueFactory valueFactory = ValueFactoryImpl.getInstance();
        URI modelURI = valueFactory.createURI(modelName);
        URI subject = valueFactory.createURI(jenaStatement.getSubject().getURI());
        URI sem = valueFactory.createURI(jenaStatement.getPredicate().getURI());
        if (jenaStatement.getObject().isLiteral()) {
            Literal objectLiteral = valueFactory.createLiteral(jenaStatement.getObject().toString());
             statement = valueFactory.createStatement(subject, sem, objectLiteral, modelURI);
        }

        else {
            URI objectUri = valueFactory.createURI(jenaStatement.getObject().asResource().getURI());
             statement = valueFactory.createStatement(subject, sem, objectUri, modelURI);
        }
    } catch (Exception e) {
        System.out.println("jenaStatement.toString() = " + jenaStatement.toString());
        e.printStackTrace();
    }
    return statement;
}
 
Example 12
Source Project: database   Source File: TestTicket4249.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final RepositoryConnection conn, final Literal string, final int start, final Literal expected)
		throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	final ValueFactory vf = conn.getValueFactory();
	final String query = "select ?substring WHERE { BIND ( SUBSTR(?string, ?start) as ?substring ) . }";
	final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
	q.setBinding("string", string);
	q.setBinding("start", vf.createLiteral(start));
	final TupleQueryResult tqr = q.evaluate();
	try {
		while (tqr.hasNext()) {
			final BindingSet bindings = tqr.next();
			// assert expected value
			assertEquals(expected, bindings.getBinding("substring").getValue());
		}
	} finally {
		tqr.close();
	}
}
 
Example 13
Source Project: attic-polygene-java   Source File: EntityTypeSerializer.java    License: Apache License 2.0 6 votes vote down vote up
private void serializeAssociationTypes( final EntityDescriptor entityDescriptor,
                                        final Graph graph,
                                        final URI entityTypeUri
)
{
    ValueFactory values = graph.getValueFactory();
    // Associations
    entityDescriptor.state().associations().forEach( associationType -> {
        URI associationURI = values.createURI( associationType.qualifiedName().toURI() );
        graph.add( associationURI, Rdfs.DOMAIN, entityTypeUri );
        graph.add( associationURI, Rdfs.TYPE, Rdfs.PROPERTY );

        URI associatedURI = values.createURI( Classes.toURI( Classes.RAW_CLASS.apply( associationType.type() ) ) );
        graph.add( associationURI, Rdfs.RANGE, associatedURI );
        graph.add( associationURI, Rdfs.RANGE, XMLSchema.ANYURI );
    } );
}
 
Example 14
Source Project: anno4j   Source File: SparqlParameters.java    License: Apache License 2.0 6 votes vote down vote up
private Object getDefaultValue(String value, Type type, ObjectConnection con) {
	Class<?> ctype = asClass(type);
	if (Set.class.equals(ctype)) {
		Object v = getDefaultValue(value, getComponentType(ctype, type), con);
		if (v == null)
			return null;
		return Collections.singleton(v);
	}
	ValueFactory vf = con.getValueFactory();
	ObjectFactory of = con.getObjectFactory();
	if (of.isDatatype(ctype)) {
		URIImpl datatype = new URIImpl("java:" + ctype.getName());
		return of.createValue(of.createObject(new LiteralImpl(value, datatype)));
	}
	return vf.createURI(value);
}
 
Example 15
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 16
Source Project: anno4j   Source File: SmokeTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testCreateDocument() throws Exception {
	// create a Document
	Document doc = new Document();
	doc.setTitle("Getting Started");

	// add a Document to the repository
	ValueFactory vf = con.getValueFactory();
	URI id = vf
			.createURI("http://meta.leighnet.ca/data/2009/getting-started");
	con.addObject(id, doc);

	// retrieve a Document by id
	doc = con.getObject(Document.class, id);
	assertEquals("Getting Started", doc.getTitle());

}
 
Example 17
Source Project: anno4j   Source File: FieldPredicateTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testReadAccess() throws Exception {
	ValueFactory vf = con.getValueFactory();
	URI graph = vf.createURI("urn:test:graph");
	con.setAddContexts(graph);
	Company c = new Company();
	c = (Company) con.getObject(con.addObject(c));
	c.setName("My Company");
	assertEquals("My Company", c.getName());
	TupleQuery query = con.prepareTupleQuery("SELECT ?g WHERE {GRAPH ?g {?o <urn:test:name> ?name}}");
	query.setBinding("name", vf.createLiteral("My Company"));
	TupleQueryResult results = query.evaluate();
	Value g = results.next().getValue("g");
	results.close();
	assertEquals(graph, g);
	con.setAddContexts();
	assertEquals("My Company", c.getName());
	query = con.prepareTupleQuery("SELECT ?g WHERE {GRAPH ?g {?o <urn:test:name> ?name}}");
	query.setBinding("name", vf.createLiteral("My Company"));
	results = query.evaluate();
	g = results.next().getValue("g");
	results.close();
	assertEquals(graph, g);
}
 
Example 18
Source Project: cumulusrdf   Source File: StatementHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Delete data from the repository.
 * 
 * @param repository the Repository object
 * @param request the HttpServletRequest object
 * @param response the HttpServletResponse object
 * @return EmptySuccessView if success
 * @throws HTTPException throws when there are repository update errors
 */
private ModelAndView getDeleteDataResult(final Repository repository, final HttpServletRequest request,
		final HttpServletResponse response)
		throws HTTPException {
	ProtocolUtil.logRequestParameters(request);

	ValueFactory vf = repository.getValueFactory();

	Resource subj = ProtocolUtil.parseResourceParam(request, SUBJECT_PARAM_NAME, vf);
	URI pred = ProtocolUtil.parseURIParam(request, PREDICATE_PARAM_NAME, vf);
	Value obj = ProtocolUtil.parseValueParam(request, OBJECT_PARAM_NAME, vf);
	Resource[] contexts = ProtocolUtil.parseContextParam(request, CONTEXT_PARAM_NAME, vf);

	try {
		RepositoryConnection repositoryCon = repository.getConnection();
		synchronized (repositoryCon) {
			repositoryCon.remove(subj, pred, obj, contexts);
		}
		repositoryCon.close();
		return new ModelAndView(EmptySuccessView.getInstance());
	} catch (RepositoryException e) {
		if (e.getCause() != null && e.getCause() instanceof HTTPException) {
			// custom signal from the backend, throw as HTTPException directly
			// (see SES-1016).
			throw (HTTPException) e.getCause();
		} else {
			throw new ServerHTTPException("Repository update error: " + e.getMessage(), e);
		}
	}
}
 
Example 19
Source Project: cumulusrdf   Source File: StatementHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get all statements and export them as RDF.
 * 
 * @param repository the Repository object
 * @param request the HttpServletRequest object
 * @param response the HttpServletResponse object
 * @return a model and view for exporting the statements.
 * @throws ClientHTTPException throws when there errors in parsing the request
 */
private ModelAndView getExportStatementsResult(final Repository repository, final HttpServletRequest request,
		final HttpServletResponse response)
		throws ClientHTTPException {
	ProtocolUtil.logRequestParameters(request);

	ValueFactory vf = repository.getValueFactory();

	Resource subj = ProtocolUtil.parseResourceParam(request, SUBJECT_PARAM_NAME, vf);
	URI pred = ProtocolUtil.parseURIParam(request, PREDICATE_PARAM_NAME, vf);
	Value obj = ProtocolUtil.parseValueParam(request, OBJECT_PARAM_NAME, vf);
	Resource[] contexts = ProtocolUtil.parseContextParam(request, CONTEXT_PARAM_NAME, vf);
	boolean useInferencing = ProtocolUtil.parseBooleanParam(request, INCLUDE_INFERRED_PARAM_NAME, true);

	RDFWriterFactory rdfWriterFactory = ProtocolUtil.getAcceptableService(request, response,
			RDFWriterRegistry.getInstance());

	Map<String, Object> model = new HashMap<String, Object>();
	model.put(ExportStatementsView.SUBJECT_KEY, subj);
	model.put(ExportStatementsView.PREDICATE_KEY, pred);
	model.put(ExportStatementsView.OBJECT_KEY, obj);
	model.put(ExportStatementsView.CONTEXTS_KEY, contexts);
	model.put(ExportStatementsView.USE_INFERENCING_KEY, Boolean.valueOf(useInferencing));
	model.put(ExportStatementsView.FACTORY_KEY, rdfWriterFactory);
	model.put(ExportStatementsView.HEADERS_ONLY, METHOD_HEAD.equals(request.getMethod()));
	model.put(ExportStatementsView.REPO_KEY, repository);
	return new ModelAndView(ExportStatementsView.getInstance(), model);
}
 
Example 20
Source Project: database   Source File: TestSingleTailRule.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testSingleTail() throws Exception {

        final BigdataSail sail = getSail();
        final BigdataSailRepository repo = new BigdataSailRepository(sail);
        repo.initialize();
        final BigdataSailRepositoryConnection cxn = repo.getConnection();
        cxn.setAutoCommit(false);
        
        try {
    
            final ValueFactory vf = sail.getValueFactory();
            
            final String ns = BD.NAMESPACE;
            
            URI mike = vf.createURI(ns+"Mike");
            URI likes = vf.createURI(ns+"likes");
            URI rdf = vf.createURI(ns+"RDF");
/**/
            cxn.setNamespace("ns", ns);
            
            testValueRoundTrip(cxn.getSailConnection(), mike, likes, rdf);
            
            if (log.isInfoEnabled()) {
                log.info(cxn.getTripleStore().dumpStore());
            }
            
        } finally {
            cxn.close();
            if (sail instanceof BigdataSail)
                ((BigdataSail)sail).__tearDownUnitTest();
        }

    }
 
Example 21
Source Project: database   Source File: TestTicket355.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void executeQuery(final SailRepository repo)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, IOException,
		RDFHandlerException {
	try {
		repo.initialize();
		final RepositoryConnection conn = repo.getConnection();
		conn.setAutoCommit(false);
		try {
			final ValueFactory vf = conn.getValueFactory();
			conn.add(vf.createURI("os:subject"), vf.createURI("os:prop"), vf.createLiteral("value"));
			conn.commit();

			String query = "SELECT ?subj WHERE { "
					+ "?subj <os:prop> ?val . "
					+ "FILTER(STR(?val) != ?arg)}";
			TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
			tq.setBinding("arg", vf.createLiteral("notValue"));
			TupleQueryResult tqr = tq.evaluate();
			assertTrue(tqr.hasNext());
			tqr.close();
		} finally {
			conn.close();
		}
	} finally {
		repo.shutDown();
	}
}
 
Example 22
@Override
public void activate(final Collection<SesameRouteSensorInjectMatch> matches) throws RepositoryException {
	final RepositoryConnection connection = driver.getConnection();
	final ValueFactory vf = connection.getValueFactory();

	final List<Statement> statementsToRemove = new ArrayList<>(matches.size());
	final URI requires = vf.createURI(BASE_PREFIX + ModelConstants.REQUIRES);
	for (final SesameRouteSensorInjectMatch match : matches) {
		final Statement statement = vf.createStatement(match.getRoute(), requires, match.getSensor());
		statementsToRemove.add(statement);
	}
	connection.remove(statementsToRemove);
}
 
Example 23
Source Project: anno4j   Source File: RoleMapper.java    License: Apache License 2.0 5 votes vote down vote up
public RoleMapper(ValueFactory vf) {
	this.vf = vf;
	roleMapper.setURIFactory(vf);
	complementIDs = new ConcurrentHashMap<Class<?>, String>();
	complementClasses = new ConcurrentHashMap<Class<?>, Class<?>>();
	intersections = new ConcurrentHashMap<Class<?>, List<Class<?>>>();
}
 
Example 24
Source Project: database   Source File: TestGPO.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testRemoveValues() {
	doLoadData();
	
	final ValueFactory vf = om.getValueFactory();

    final URI workeruri = vf.createURI("gpo:#123");
    IGPO workergpo = om.getGPO(workeruri);
    final URI worksFor = vf.createURI("attr:/employee#worksFor");
	
    assertFalse(workergpo.getLinksOut(worksFor).isEmpty());
    assertFalse(workergpo.getValues(worksFor).isEmpty());
    workergpo.removeValues(worksFor);
    assertTrue(workergpo.getValues(worksFor).isEmpty());
    assertTrue(workergpo.getLinksOut(worksFor).isEmpty());
}
 
Example 25
Source Project: GeoTriples   Source File: CustomSesameDataset.java    License: Apache License 2.0 5 votes vote down vote up
public void remove(Resource s, URI p, Value o, Resource... context) {
	try {
		RepositoryConnection con = currentRepository.getConnection();
		try {
			ValueFactory myFactory = con.getValueFactory();
			Statement st = myFactory.createStatement((Resource) s, p,
					(Value) o);
			con.remove(st, context);
		} finally {
			con.close();
		}
	} catch (Exception e) {
		// handle exception
	}
}
 
Example 26
@Test
public void testDescribeD()
	throws Exception
{
	loadTestData("/testdata-query/dataset-describe.trig");
	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("DESCRIBE ex:d");

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

	ValueFactory f = conn.getValueFactory();
	URI d = f.createURI("http://example.org/d");
	URI p = f.createURI("http://example.org/p");
	URI e = f.createURI("http://example.org/e");
	Model result = QueryResults.asModel(gq.evaluate());

	assertNotNull(result);
	assertTrue(result.contains(null, p, e));
	assertFalse(result.contains(e, null, null));
	Set<Value> objects = result.filter(d, p, null).objects();
	assertNotNull(objects);
	for (Value object : objects) {
		if (object instanceof BNode) {
			Set<Value> childObjects = result.filter((BNode)object, null, null).objects();
			assertNotNull(childObjects);
			for (Value childObject : childObjects) {
				if (childObject instanceof BNode) {
					assertTrue(result.contains((BNode)childObject, null, null));
				}
			}
		}
	}
}
 
Example 27
Source Project: database   Source File: TestTicket348.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void executeTest(final SailRepository repo)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, RDFHandlerException,
		IOException {
	try {
		repo.initialize();
		final RepositoryConnection conn = repo.getConnection();
		try {
			conn.setAutoCommit(false);
			final ValueFactory vf = conn.getValueFactory();
	        final URI uri = vf.createURI("os:/elem/example");
	        // run a query which looks for a statement and then adds it if it is not found.
	        addDuringQueryExec(conn, uri, RDF.TYPE, vf.createURI("os:class/Clazz"));
	        // now try to export the statements.
        	final RepositoryResult<Statement> stats = conn.getStatements(null, null, null, false);
	        try {
	        	// materialize the newly added statement.
	        	stats.next();
	        } catch (RuntimeException e) {
	        	fail(e.getLocalizedMessage(), e); // With Bigdata this fails
	        } finally {
	        	stats.close();
	        }
	        conn.rollback(); // discard the result (or commit, but do something to avoid a logged warning from Sesame).
		} finally {
			conn.close();
		}
	} finally {
		repo.shutDown();
	}
}
 
Example 28
Source Project: attic-polygene-java   Source File: EntityStateSerializer.java    License: Apache License 2.0 5 votes vote down vote up
private void serializeAssociations( final EntityState entityState,
                                    final Graph graph, URI entityUri,
                                    final Stream<? extends AssociationDescriptor> associations,
                                    final boolean includeNonQueryable
)
{
    ValueFactory values = graph.getValueFactory();

    // Associations
    associations.filter( type -> includeNonQueryable || type.queryable() ).forEach(
        associationType ->
        {
            EntityReference associatedId
                = entityState
                .associationValueOf(
                    associationType
                        .qualifiedName() );
            if( associatedId != null )
            {
                URI assocURI = values
                    .createURI(
                        associationType
                            .qualifiedName()
                            .toURI() );
                URI assocEntityURI
                    = values.createURI(
                    associatedId
                        .toURI() );
                graph.add( entityUri,
                           assocURI,
                           assocEntityURI );
            }
        } );
}
 
Example 29
Source Project: anno4j   Source File: OwlNormalizer.java    License: Apache License 2.0 5 votes vote down vote up
private void hasValueFromList() {
	ValueFactory vf = getValueFactory();
	for (Statement st : ds.match(null, OWL.HASVALUE, null)) {
		Resource res = st.getSubject();
		Value obj = st.getObject();
		if (obj instanceof Resource) {
			BNode node = vf.createBNode();
			ds.add(res, OWL.ALLVALUESFROM, node);
			ds.add(node, RDF.TYPE, OWL.CLASS);
			BNode list = vf.createBNode();
			ds.add(node, OWL.ONEOF, list);
			ds.add(list, RDF.TYPE, RDF.LIST);
			ds.add(list, RDF.FIRST, obj);
			ds.add(list, RDF.REST, RDF.NIL);
			for (Value type : ds.match(obj, RDF.TYPE, null).objects()) {
				ds.add(node, RDFS.SUBCLASSOF, type);
			}
			for (Value prop : ds.match(res, OWL.ONPROPERTY, null).objects()) {
				for (Value range : ds.match(prop, RDFS.RANGE, null).objects()) {
					ds.add(node, RDFS.SUBCLASSOF, range);
				}
				for (Resource cls : ds.match(null, RDFS.SUBCLASSOF, res).subjects()) {
					for (Value sup : findSuperClasses(cls)) {
						if (!sup.equals(res) && !ds.match(sup, OWL.ONPROPERTY, prop).isEmpty()) {
							for (Value from : ds.match(sup, OWL.ALLVALUESFROM, null).objects()) {
								ds.add(node, RDFS.SUBCLASSOF, from);
							}
						}
					}
				}
			}
		}
	}
}
 
Example 30
Source Project: cumulusrdf   Source File: IntegrationTestSupertypeLayer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an in-memory clone of the incoming collection of statements. 
 * This is needed in order to execute comparisons between statements belonging to different value factories (e.g. InMemory and CumulusRDF).
 * 
 * @param model the set of statements to be cloned.
 * @return an in-memory clone of the incoming collection of statements.
 */
protected Set<Statement> statements(final Collection<? extends Statement> model) {
	final ValueFactory factory = inMemoryRepository.getValueFactory();
	return model
			.stream()
			.map(statement -> {
					Value object = null;
					if (statement.getObject() instanceof Literal) {
						Literal l = (Literal) statement.getObject();
						if (l.getLanguage() != null) {
							object = factory.createLiteral(l.getLabel(), l.getLanguage());								
						} else {
							object = factory.createLiteral(l.getLabel(), l.getDatatype());																
						}
					} else if (statement.getObject() instanceof BNode) {
						object = factory.createBNode(((BNode)statement.getObject()).getID()); 
					} else if (statement.getObject() instanceof URI) {
						object = factory.createURI(((URI)statement.getSubject()).stringValue());
					}
					
					return factory.createStatement(
						statement.getSubject() instanceof BNode 
							? factory.createBNode(((BNode)statement.getSubject()).getID()) 
							: factory.createURI(((URI)statement.getSubject()).stringValue()), 
						factory.createURI(((URI)statement.getPredicate()).stringValue()), 
						object);
			})
			.collect(toSet());
}