Java Code Examples for org.apache.jena.query.QueryExecutionFactory#create()

The following examples show how to use org.apache.jena.query.QueryExecutionFactory#create() . 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: CombineManifest.java    From incubator-taverna-language with Apache License 2.0 6 votes vote down vote up
private static List<RDFNode> creatingAgentsFor(Resource r) {
	logger.fine("Finding creator of " + r);
	String queryStr = sparqlPrefixes + "SELECT ?agent WHERE { \n" + " { \n"
			+ "  ?r dct:creator [ \n" + "	    rdfs:member ?agent \n"
			+ "  ] \n" + " } UNION { \n" + "   ?r dct:creator ?agent .\n "
			+ "   FILTER NOT EXISTS { ?agent rdfs:member ?member } \n"
			+ " } \n" + "} \n";
	logger.finer(QueryFactory.create(queryStr).toString());
	QueryExecution qexec = QueryExecutionFactory.create(queryStr,
			r.getModel());
	QuerySolutionMap binding = new QuerySolutionMap();
	binding.add("r", r);
	qexec.setInitialBinding(binding);
	ResultSet select = qexec.execSelect();
	List<RDFNode> agents = new ArrayList<>();

	while (select.hasNext()) {
		RDFNode agent = select.next().get("agent");
		logger.fine("Found: " + agent);
		agents.add(agent);
	}
	return agents;
}
 
Example 2
Source File: JenaQuery.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Collection<TPatternMatch> evaluate() throws IOException {
	final List<TPatternMatch> matches = new ArrayList<>();

	try (QueryExecution queryExecution = QueryExecutionFactory.create(jenaQuery, driver.getModel())) {
		final ResultSet resultSet = queryExecution.execSelect();

		while (resultSet.hasNext()) {
			final QuerySolution qs = resultSet.next();
			final JenaMatch match = JenaMatch.createMatch(query, qs);
			matches.add((TPatternMatch) match);
		}
	}

	return matches;
}
 
Example 3
Source File: Validator.java    From Processor with Apache License 2.0 6 votes vote down vote up
public OntModel fixOntModel(OntModel ontModel)
    {
        if (ontModel == null) throw new IllegalArgumentException("Model cannot be null");
        
        OntModel fixedModel = ModelFactory.createOntologyModel(ontModel.getSpecification());
        Query fix = QueryFactory.create("CONSTRUCT\n" +
"{\n" +
"  ?s ?p ?o\n" +
"}\n" +
"WHERE\n" +
"{\n" +
"  ?s ?p ?o\n" +
"  FILTER (!(?p = <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> && ?o = <https://www.w3.org/ns/ldt#Constraint>))\n" +
"}");
        
        try (QueryExecution qex = QueryExecutionFactory.create(fix, ontModel))
        {
            fixedModel.add(qex.execConstruct());
        }
        
        return fixedModel;
    }
 
Example 4
Source File: ExTDB5.java    From xcurator with Apache License 2.0 6 votes vote down vote up
public static void main(String... argv)
{
    // Direct way: Make a TDB-back Jena model in the named directory.
    String directory = "MyDatabases/DB1" ;
    Dataset dataset = TDBFactory.createDataset(directory) ;
    
    // Potentially expensive query.
    String sparqlQueryString = "SELECT (count(*) AS ?count) { ?s ?p ?o }" ;
    // See http://incubator.apache.org/jena/documentation/query/app_api.html
    
    Query query = QueryFactory.create(sparqlQueryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, dataset) ;
    try {
      ResultSet results = qexec.execSelect() ;
      for ( ; results.hasNext() ; )
      {
          QuerySolution soln = results.nextSolution() ;
          int count = soln.getLiteral("count").getInt() ;
          System.out.println("count = "+count) ;
      }
    } finally { qexec.close() ; }

    // Close the dataset.
    dataset.close();
    
}
 
Example 5
Source File: DBpediaMappingValidator.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
public List<MappingDomainError> getErrorListFromModel(Model model) {
    List<MappingDomainError> mappingDomainErrors = new ArrayList<>();
    try  ( QueryExecution qe = QueryExecutionFactory.create(SPARQL_QUERY, model))
    {

        qe.execSelect().forEachRemaining( qs -> {

            String mapping = qs.get("mapping").toString();
            String error = qs.get("error").toString();
            String missing = qs.get("missing").toString();
            String predicate = qs.get("predicate").toString();

            mappingDomainErrors.add(new MappingDomainError(mapping, predicate, error, missing));

        } );
    }
    return mappingDomainErrors;
}
 
Example 6
Source File: ExTDB4.java    From xcurator with Apache License 2.0 6 votes vote down vote up
public static void main(String... argv)
{
    // Direct way: Make a TDB-back Jena model in the named directory.
    String directory = "MyDatabases/DB1" ;
    Dataset dataset = TDBFactory.createDataset(directory) ;
    
    // Potentially expensive query.
    String sparqlQueryString = "SELECT (count(*) AS ?count) { ?s ?p ?o }" ;
    // See http://incubator.apache.org/jena/documentation/query/app_api.html
    
    Query query = QueryFactory.create(sparqlQueryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, dataset) ;
    ResultSet results = qexec.execSelect() ;
    ResultSetFormatter.out(results) ;
    qexec.close() ;

    dataset.close();
}
 
Example 7
Source File: RdfDataManager.java    From rdf2neo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Uses the underlining TDB and mapping queries to create a new {@link CyNode} instance.
 * 
 * @param nodeRes the RDF/Jena resource correspnding to the Cypher node. This provides the ?iri paramter in the queries below.
 * @param labelsSparql the node labels query, which is usually taken from {@link CyNodeLoadingHandler#getLabelsSparql()}.
 * @param propsSparql the node properties query, which is usually taken from {@link CyNodeLoadingHandler#getNodePropsSparql()}.
 */
public CyNode getCyNode ( Resource nodeRes, String labelsSparql, String propsSparql )
{
	ensureOpen ();
	
	QuerySolutionMap params = new QuerySolutionMap ();
	params.add ( "iri", nodeRes );

	CyNode cyNode = new CyNode ( nodeRes.getURI () );
	
	// The node's labels
	if ( labelsSparql != null )
	{
		// If it's omitted, it will get the default label.
		Query qry = SparqlUtils.getCachedQuery ( labelsSparql );
		Function<String, String> labelIdConverter = this.getCyNodeLabelIdConverter ();
		
		boolean wasInTnx = dataSet.isInTransaction ();
		if ( !wasInTnx ) dataSet.begin ( ReadWrite.READ );
		try {
			QueryExecution qx = QueryExecutionFactory.create ( qry, this.getDataSet(), params );
			qx.execSelect ().forEachRemaining ( row ->
				cyNode.addLabel ( this.getCypherId ( row.get ( "label" ), labelIdConverter ) )
			);
		}
		finally {
			if ( !wasInTnx && dataSet.isInTransaction () ) dataSet.end ();
		}
	}
	
	// and the properties
	this.addCypherProps ( cyNode, propsSparql );
	
	return cyNode;
}
 
Example 8
Source File: JenaDriver.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected boolean ask(final String askQuery) {
	try (QueryExecution queryExecution = QueryExecutionFactory.create(askQuery, model)) {
		final boolean result = queryExecution.execAsk();
		return result;
	}
}
 
Example 9
Source File: ExTDB_Txn1.java    From xcurator with Apache License 2.0 5 votes vote down vote up
public static void execQuery(String sparqlQueryString, Dataset dataset)
{
    Query query = QueryFactory.create(sparqlQueryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, dataset) ;
    try {
        ResultSet results = qexec.execSelect() ;
        for ( ; results.hasNext() ; )
        {
            QuerySolution soln = results.nextSolution() ;
            int count = soln.getLiteral("count").getInt() ;
            System.out.println("count = "+count) ;
        }
      } finally { qexec.close() ; }
}
 
Example 10
Source File: Test.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void updateTest() {
		// Add a new book to the collection
//		String service = "http://219.248.137.7:13030/icbms/update";
//		UpdateRequest ur = UpdateFactory
//				.create(""
//						+ "delete  { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue>  ?value . } "
//						+ "insert  { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue>  \"19\" . } " //<-- 19대신 여기 온도를 넣어주세
//						+ "WHERE   { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue> ?value . }");
//		UpdateProcessor up = UpdateExecutionFactory.createRemote(ur, service);
//		up.execute();

		// Query the collection, dump output
//		String service1 = "http://219.248.137.7:13030/icbms/";
//		QueryExecution qe = QueryExecutionFactory.sparqlService(service1,
//				"SELECT * WHERE {<http://www.pineone.com/campus/Student_S00001> ?r ?y} limit 20 ");
//
//		ResultSet results = qe.execSelect();
//		ResultSetFormatter.out(System.out, results);
//		qe.close();
		Model model = ModelFactory.createDefaultModel();
		Statement s = model.createStatement(model.createResource("ex:e1"),model.createProperty("ex:p1"), ResourceFactory.createTypedLiteral(new String("0.6")));
		model.add(s);
		String query = "select * {?s ?p ?o }";
		QueryExecution qe = QueryExecutionFactory.create(query, model);
		ResultSet results = qe.execSelect();
		ResultSetFormatter.out(System.out, results);
		qe.close();
	}
 
Example 11
Source File: ClassSurfaceForms.java    From NLIWOD with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

		CLASS_SURFACE_FORMS = DIRECTORY + "class_surface_forms.ttl";

		// create an empty model
		Model inputModel = ModelFactory.createDefaultModel();

		// use the FileManager to find the input file
		InputStream in = FileManager.get().open(DBPEDIA_CLASSE_FILE);
		if (in == null) {
			throw new IllegalArgumentException("File: " + DBPEDIA_CLASSE_FILE + " not found");
		}

		// read the RDF/XML file
		inputModel.read(in, null, "N-TRIPLE");

		Model outputModel = ModelFactory.createDefaultModel();
		QueryExecution qExec = QueryExecutionFactory
				.create("SELECT ?s ?label WHERE{?s a <http://www.w3.org/2002/07/owl#Class>."
						+ " ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label. "
						+ "FILTER (lang(?label) = \"en\")}", inputModel);
		ResultSet rs = qExec.execSelect();
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			Resource uri = qs.get("?s").asResource();
			RDFNode label = qs.get("?label");
			StatementImpl s = new StatementImpl(uri, RDFS.label, label);
			outputModel.add(s);

		}

		qExec.close();

		FileOutputStream outputFile = new FileOutputStream(CLASS_SURFACE_FORMS);
		RDFDataMgr.write(outputFile, outputModel, RDFFormat.NTRIPLES);

	}
 
Example 12
Source File: PropertySurfaceForms.java    From NLIWOD with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

		PROPERTY_SURFACE_FORMS = DIRECTORY + "property_surface_forms.ttl";

		// create an empty model
		Model inputModel = ModelFactory.createDefaultModel();

		// use the FileManager to find the input file
		InputStream in = FileManager.get().open(DBPEDIA_PROPERTY_FILE);
		if (in == null) {
			throw new IllegalArgumentException("File: " + DBPEDIA_PROPERTY_FILE + " not found");
		}

		// read the RDF/XML file
		inputModel.read(in, null, "N-TRIPLE");
		inputModel.write(System.out);

		Model outputModel = ModelFactory.createDefaultModel();
		QueryExecution qExec = QueryExecutionFactory
				.create("SELECT ?s  ?label WHERE{?s a <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property>."
						+ " ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label. }", inputModel);
		ResultSet rs = qExec.execSelect();
		System.out.println(qExec);
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			Resource uri = qs.get("?s").asResource();
			RDFNode label = qs.get("?label");
			StatementImpl s = new StatementImpl(uri, RDFS.label, label);
			outputModel.add(s);

		}

		qExec.close();

		FileOutputStream outputFile = new FileOutputStream(PROPERTY_SURFACE_FORMS);
		RDFDataMgr.write(outputFile, outputModel, RDFFormat.NTRIPLES);
	}
 
Example 13
Source File: Test.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void updateTest() {
		// Add a new book to the collection
//		String service = "http://219.248.137.7:13030/icbms/update";
//		UpdateRequest ur = UpdateFactory
//				.create(""
//						+ "delete  { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue>  ?value . } "
//						+ "insert  { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue>  \"19\" . } " //<-- 19대신 여기 온도를 넣어주세
//						+ "WHERE   { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue> ?value . }");
//		UpdateProcessor up = UpdateExecutionFactory.createRemote(ur, service);
//		up.execute();

		// Query the collection, dump output
//		String service1 = "http://219.248.137.7:13030/icbms/";
//		QueryExecution qe = QueryExecutionFactory.sparqlService(service1,
//				"SELECT * WHERE {<http://www.pineone.com/campus/Student_S00001> ?r ?y} limit 20 ");
//
//		ResultSet results = qe.execSelect();
//		ResultSetFormatter.out(System.out, results);
//		qe.close();
		Model model = ModelFactory.createDefaultModel();
		Statement s = model.createStatement(model.createResource("ex:e1"),model.createProperty("ex:p1"), ResourceFactory.createTypedLiteral(new String("0.6")));
		model.add(s);
		String query = "select * {?s ?p ?o }";
		QueryExecution qe = QueryExecutionFactory.create(query, model);
		ResultSet results = qe.execSelect();
		ResultSetFormatter.out(System.out, results);
		qe.close();
	}
 
Example 14
Source File: RdfDataManager.java    From rdf2neo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Take an existing {@link CypherEntity} and adds the properties that can be mapped from the underlining TDB by means 
 * of a property query, like {@link CyNodeLoadingHandler#getNodePropsSparql()}, or 
 * {@link CyRelationLoadingHandler#getRelationPropsSparql()}.
 * 
 * It doesn't do anything if the query is null.
 * 
 */
protected void addCypherProps ( CypherEntity cyEnt, String propsSparql )
{
	ensureOpen ();		
	Dataset dataSet = this.getDataSet ();
	
	QuerySolutionMap params = new QuerySolutionMap ();
	params.add ( "iri", dataSet.getUnionModel().getResource ( cyEnt.getIri () ) );

	// It may be omitted, if you don't have any property except the IRI.
	if ( propsSparql == null ) return;
	
	Query qry = SparqlUtils.getCachedQuery ( propsSparql );
	Function<String, String> propIdConverter = this.getCyPropertyIdConverter ();
	
	boolean wasInTnx = dataSet.isInTransaction ();
	if ( !wasInTnx ) dataSet.begin ( ReadWrite.READ );
	try
	{
		QueryExecution qx = QueryExecutionFactory.create ( qry, dataSet, params );
		qx.execSelect ().forEachRemaining ( row ->
		{
			String propName = this.getCypherId ( row.get ( "name" ), propIdConverter );
			if ( propName == null ) throw new IllegalArgumentException ( 
				"Null property name for " + cyEnt.getIri () 
			);
			
			String propValue = JENAUTILS.literal2Value ( row.getLiteral ( "value" ) ).get ();
			cyEnt.addPropValue ( propName, propValue );
		});
	}
	finally {
		if ( !wasInTnx && dataSet.isInTransaction () ) dataSet.end ();
	}
}
 
Example 15
Source File: JenaGraphSearcher.java    From Stargraph with MIT License 4 votes vote down vote up
private Map<String, List<LabeledEntity>> doSparqlQuery(String sparqlQuery) {
    logger.debug(marker, "Executing: {}", sparqlQuery);

    long startTime = System.currentTimeMillis();

    Map<String, List<LabeledEntity>> result = new LinkedHashMap<>();

    try (QueryExecution qexec = QueryExecutionFactory.create(sparqlQuery, graphModel)) {
        ResultSet results = qexec.execSelect();

        while (results.hasNext()) {
            Binding jBinding = results.nextBinding();
            Iterator<Var> vars = jBinding.vars();
            while (vars.hasNext()) {
                Var jVar = vars.next();

                if (!jBinding.get(jVar).isLiteral()) {
                    String id = jBinding.get(jVar).getURI();
                    List<LabeledEntity> entities = result.computeIfAbsent(jVar.getVarName(), (v) -> new ArrayList<>());
                    LabeledEntity labeledEntity = ns.isFromMainNS(id) ? entitySearcher.getEntity(dbId, id) : ModelUtils.createInstance(id);
                    entities.add(labeledEntity);
                } else {
                    LiteralLabel lit = jBinding.get(jVar).getLiteral();
                    ValueEntity valueEntity = new ValueEntity(lit.getLexicalForm(), lit.getDatatype().getURI(), lit.language());
                    result.computeIfAbsent(jVar.getVarName(), (v) -> new ArrayList<>()).add(valueEntity);
                }
            }
        }

    }
    long millis = System.currentTimeMillis() - startTime;

    if (!result.isEmpty()) {
        logger.info(marker, "SPARQL {} query took {}s", sparqlQuery, millis / 1000.0);
    }
    else {
        logger.warn(marker, "No matches for {}", sparqlQuery);
    }

    return result;
}
 
Example 16
Source File: CombineManifest.java    From incubator-taverna-language with Apache License 2.0 4 votes vote down vote up
private static String nameForAgent(Resource agentResource) {
	logger.fine("Finding name of " + agentResource);
	String queryStr = sparqlPrefixes
			+ "SELECT ?name WHERE { \n"
			+ "		{ ?agent foaf:name ?name } \n"
			+ "	UNION  \n"
			+ "		{ ?agent vcard:fn ?name } \n"
			+ "	UNION  \n"
			+ "		{ ?agent vcard:FN ?name } \n"
			+ // legacy
			"	UNION  \n"
			+ "		{ ?agent rdfs:label ?name } \n"
			+ " UNION  \n"
			+ "     { \n"
			+ "         { ?agent vcard:n ?n } UNION { ?agent vcard:hasName ?n } \n"
			+ "         ?n vcard:family-name ?family ; \n"
			+ "            vcard:given-name ?given . \n"
			+ "          BIND(CONCAT(?given, \" \", ?family) AS ?name) \n"
			+ "     } \n" + " UNION \n" + "     { "
			+ "         ?agent foaf:givenName ?given ; \n"
			+ "                foaf:familyName ?family \n"
			+ "          BIND(CONCAT(?given, \" \", ?family) AS ?name) \n"
			+ "     } \n" + " UNION \n" + "     { "
			+ "         ?agent foaf:firstName ?given ; \n"
			+ "                foaf:surname ?family \n"
			+ "          BIND(CONCAT(?given, \" \", ?family) AS ?name) \n"
			+ "     } \n" + "	}  \n";
	logger.finer(QueryFactory.create(queryStr).toString());
	QueryExecution qexec = QueryExecutionFactory.create(queryStr,
			agentResource.getModel());
	QuerySolutionMap binding = new QuerySolutionMap();
	binding.add("agent", agentResource);
	qexec.setInitialBinding(binding);
	ResultSet select = qexec.execSelect();
	if (select.hasNext()) {
		String name = select.next().getLiteral("name").getString();
		logger.fine(name);
		return name;
	}
	logger.fine("(null)");
	return null;
}
 
Example 17
Source File: JenaTDBBasedRequestProcessorForTPFs.java    From Server.Java with MIT License 4 votes vote down vote up
/**
 *
 * @param subject
 * @param predicate
 * @param object
 * @param offset
 * @param limit
 * @return
 */
@Override
protected ILinkedDataFragment createFragment(
           final ITriplePatternElement<RDFNode,String,String> subject,
           final ITriplePatternElement<RDFNode,String,String> predicate,
           final ITriplePatternElement<RDFNode,String,String> object,
           final long offset,
           final long limit )
{
    // FIXME: The following algorithm is incorrect for cases in which
    //        the requested triple pattern contains a specific variable
    //        multiple times;
    //        e.g., (?x foaf:knows ?x ) or (_:bn foaf:knows _:bn)
    // see https://github.com/LinkedDataFragments/Server.Java/issues/24

    Model model;
    if (defaultGraph == null) {
        model = tdb.getDefaultModel();
    } else {
        model = tdb.getNamedModel(defaultGraph);
    }

    QuerySolutionMap map = new QuerySolutionMap();
    if ( ! subject.isVariable() ) {
        map.add("s", subject.asConstantTerm());
    }
    if ( ! predicate.isVariable() ) {
        map.add("p", predicate.asConstantTerm());
    }
    if ( ! object.isVariable() ) {
        map.add("o", object.asConstantTerm());
    }

    query.setOffset(offset);
    query.setLimit(limit);

    Model triples = ModelFactory.createDefaultModel();

    try (QueryExecution qexec = QueryExecutionFactory.create(query, model, map)) {
        qexec.execConstruct(triples);
    }

    if (triples.isEmpty()) {
        return createEmptyTriplePatternFragment();
    }

    // Try to get an estimate
    long size = triples.size();
    long estimate = -1;

    try (QueryExecution qexec = QueryExecutionFactory.create(countQuery, model, map)) {
        ResultSet results = qexec.execSelect();
        if (results.hasNext()) {
            QuerySolution soln = results.nextSolution() ;
            Literal literal = soln.getLiteral("count");
            estimate = literal.getLong();
        }
    }

    /*GraphStatisticsHandler stats = model.getGraph().getStatisticsHandler();
    if (stats != null) {
        Node s = (subject != null) ? subject.asNode() : null;
        Node p = (predicate != null) ? predicate.asNode() : null;
        Node o = (object != null) ? object.asNode() : null;
        estimate = stats.getStatistic(s, p, o);
    }*/

    // No estimate or incorrect
    if (estimate < offset + size) {
        estimate = (size == limit) ? offset + size + 1 : offset + size;
    }

    // create the fragment
    final boolean isLastPage = ( estimate < offset + limit );
    return createTriplePatternFragment( triples, estimate, isLastPage );
}
 
Example 18
Source File: QueryExecutionFactoryFilter.java    From shacl with Apache License 2.0 4 votes vote down vote up
public QueryExecution create(Query query, Dataset dataset, QuerySolution initialBinding) {
	analyzeRequest(query, dataset, initialBinding);
	return QueryExecutionFactory.create(query, dataset, initialBinding);
}
 
Example 19
Source File: QueryExecutionFactoryFilter.java    From shacl with Apache License 2.0 4 votes vote down vote up
public QueryExecution create(Query query, Dataset dataset) {
	analyzeRequest(query, dataset, null);
	return QueryExecutionFactory.create(query, dataset);
}
 
Example 20
Source File: QueryExecutionFactoryFilter.java    From shacl with Apache License 2.0 4 votes vote down vote up
public QueryExecution create(Query query, Model model) {
	analyzeRequest(query, model, null);
	return QueryExecutionFactory.create(query, model);
}