Java Code Examples for com.hp.hpl.jena.query.QueryExecutionFactory.create()

The following are Jave code examples for showing how to use create() of the com.hp.hpl.jena.query.QueryExecutionFactory class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: DocIT   File: Containment.java   Source Code and License Vote up 6 votes
public static boolean checkContainment(CompanyModel c){
	String queryString = 
		"ASK" +
			// check whether any manager is an employee in any other department
			"{?dept1"        + " <" + c.MANAGER   + "> " + "?manager"         + ". " +
			" ?dept2"		 + " <" + c.EMPLOYEES + "> " + "?employees1"      + ". " +
			" ?employees1"   + " <" + RDFS.member + "> " + "?employee1"       + ". " +
			" FILTER (?manager = ?employee1) " +
			
			// check whether any employee occurs more than once
			" ?dept3 "		 + " <" + c.EMPLOYEES + "> " + "?employees2"      + ". " +
			" ?employees2"   + " <" + RDFS.member + "> " + "?employee2"       + ". " +
			" FILTER (?employee1 = ?employee2)" +
			
			// check whether any department occurs more than once
			" ?upperDept1"   + " <" + c.DEPTS     + "> " + "?dept4"           + ". " +
			" ?upperDept2"   + " <" + c.DEPTS     + "> " + "?dept5"           + ". " +
			" FILTER (?dept4 = ?dept5) " +
			"}";
	
	Query query = QueryFactory.create(queryString);
	QueryExecution qe = QueryExecutionFactory.create(query, c.getModel());
	boolean out = qe.execAsk();
	qe.close();
	return !out;
}
 
Example 2
Project: ontonethub   File: IndexingJob.java   Source Code and License Vote up 6 votes
private List<Statement> expandSubClasses(Model model){
	List<Statement> stmts = new ArrayList<Statement>();
	
	
	String sparql = "PREFIX rdfs: <" + RDFS.getURI() + ">"
			+ "SELECT DISTINCT ?class ?synonym "
			+ "WHERE { "
			+ "?class rdfs:subClassOf+ ?subClass . "
			+ "?subClass <" + synonym + "> ?synonym"
			+ "}";
	
	Query query = QueryFactory.create(sparql, Syntax.syntaxARQ);
	QueryExecution queryExecution = QueryExecutionFactory.create(query, model);
	ResultSet resultSet = queryExecution.execSelect();
	resultSet.forEachRemaining(querySolution -> {
		stmts.add(new StatementImpl(querySolution.getResource("class"), synonym, querySolution.getLiteral("synonym")));
	});
	return stmts;
}
 
Example 3
Project: ontonethub   File: IndexingJob.java   Source Code and License Vote up 6 votes
private List<Statement> expandSubProperties(Model model){
	List<Statement> stmts = new ArrayList<Statement>();
	
	String sparql = "PREFIX rdfs: <" + RDFS.getURI() + ">"
			+ "SELECT DISTINCT ?property ?synonym "
			+ "WHERE { "
			+ "?property rdfs:subPropertyOf+ ?subProperty . "
			+ "?subProperty <" + synonym + "> ?synonym"
			+ "}";
	
	Query query = QueryFactory.create(sparql, Syntax.syntaxARQ);
	QueryExecution queryExecution = QueryExecutionFactory.create(query, model);
	ResultSet resultSet = queryExecution.execSelect();
	resultSet.forEachRemaining(querySolution -> {
		stmts.add(new StatementImpl(querySolution.getResource("property"), synonym, querySolution.getLiteral("synonym")));
	});
	return stmts;
}
 
Example 4
Project: r2rml-kit   File: ProcessorTestBase.java   Source Code and License Vote up 6 votes
public static Collection<Object[]> getTestListFromManifest(String manifestFileURL) {
		// We'd like to use FileManager.loadModel() but it doesn't work on jar: URLs
//		Model m = FileManager.get().loadModel(manifestFileURL);
		Model m = ModelFactory.createDefaultModel();
		m.read(manifestFileURL, "TURTLE");

		IRI baseIRI = D2RQTestUtil.createIRI(m.getNsPrefixURI("base"));
		ResultSet rs = QueryExecutionFactory.create(TEST_CASE_LIST, m).execSelect();
		List<Object[]> result = new ArrayList<Object[]>();
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			Resource mapping = qs.getResource("mapping");
			Resource schema = qs.getResource("schema");
//			if (!mapping.getLocalName().equals("constant-object.ttl")) continue;
			QueryExecution qe = QueryExecutionFactory.create(TEST_CASE_TRIPLES, m);
			qe.setInitialBinding(qs);
			Model expectedTriples = qe.execConstruct();
			result.add(new Object[]{baseIRI.relativize(mapping.getURI()).toString(), mapping.getURI(), 
					schema.getURI(), expectedTriples});
		}
		return result;
	}
 
Example 5
Project: r2rml-kit   File: MappingGeneratorTest.java   Source Code and License Vote up 6 votes
@Parameters(name="{index}: {0}")
	public static Collection<Object[]> getTestLists() {
		Model m = D2RQTestUtil.loadTurtle(MANIFEST_FILE);
		IRI baseIRI = D2RQTestUtil.createIRI(m.getNsPrefixURI("base"));
		ResultSet rs = QueryExecutionFactory.create(TEST_CASE_LIST, m).execSelect();
		List<Object[]> result = new ArrayList<Object[]>();
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			Resource testCase = qs.getResource("case");
//			if (!case.getLocalName().equals("expression")) continue;
			QueryExecution qe = QueryExecutionFactory.create(TEST_CASE_TRIPLES, m);
			qe.setInitialBinding(qs);
			Model expectedTriples = qe.execConstruct();
			result.add(new Object[]{
					baseIRI.relativize(testCase.getURI()).toString(), 
					qs.getLiteral("sql").getLexicalForm(), 
					expectedTriples});
		}
		return result;
	}
 
Example 6
Project: DoSeR   File: CreateDBpediaIndexV2.java   Source Code and License Vote up 6 votes
public String getDbPediaLongDescription(final String uri) throws QueryException, QueryParseException {
	String labellist = "";
	try {
		final String query = "SELECT ?comment WHERE{ <" + uri
				+ "> <http://dbpedia.org/ontology/abstract> ?comment. }";
		ResultSet results = null;
		QueryExecution qexec = null;

		final com.hp.hpl.jena.query.Query cquery = QueryFactory.create(query);
		qexec = QueryExecutionFactory.create(cquery, this.longdescmodel);
		results = qexec.execSelect();

		if (results != null) {
			while (results.hasNext()) {
				final QuerySolution sol = results.nextSolution();
				final String desc = sol.getLiteral("comment").getLexicalForm();
				labellist = desc;
			}
			qexec.close();
		}
	} catch (QueryParseException e) {
		Logger.getRootLogger().info("Query parse Exception");
	}
	return labellist;
}
 
Example 7
Project: sdh-vocabulary   File: VocabularyTest.java   Source Code and License Vote up 6 votes
@Test
public void testMetric_TotalExecutions_Global() {
	Query query =
		QueryFactory.
			create(
				loadResource("/metrics/total_executions_global.sparql"));
	QueryExecution queryExecution = null;
	try {
		queryExecution = QueryExecutionFactory.create(query, executionsDataSet());
		ResultSet results = queryExecution.execSelect();
		for(; results.hasNext();) {
			QuerySolution solution = results.nextSolution();
			long total_executions = solution.getLiteral("total_executions").getLong();
			System.out.printf("Total executions: %d%n",total_executions);
		}
	} finally {
		if (queryExecution != null) {
			queryExecution.close();
		}
	}
}
 
Example 8
Project: DoSeR   File: CreateDBpediaIndexV2.java   Source Code and License Vote up 6 votes
public Set<String> getRDFTypesFromEntity(final String entityUri) {
	Set<String> set = new HashSet<String>();
	final String query = "SELECT ?types WHERE{ <" + entityUri
			+ "> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?types. }";
	ResultSet results = null;
	QueryExecution qexec = null;
	try {
		final com.hp.hpl.jena.query.Query cquery = QueryFactory.create(query);
		qexec = QueryExecutionFactory.create(cquery, instancemappingtypes);
		results = qexec.execSelect();
	} catch (final QueryException e) {
		Logger.getRootLogger().error(e.getStackTrace());
	} finally {
		if (results != null) {
			while (results.hasNext()) {
				final QuerySolution sol = results.nextSolution();
				final String type = sol.getResource("types").toString();
				set.add(type);
			}
		}
	}
	return set;
}
 
Example 9
Project: sdh-vocabulary   File: VocabularyTest.java   Source Code and License Vote up 6 votes
@Test
public void testMetric_TotalSuccesfulExecutions_Global_Period() {
	Query query =
		QueryFactory.
			create(
				loadResource("/metrics/total_succesful_executions_global_period.sparql"));
	QueryExecution queryExecution = null;
	try {
		queryExecution = QueryExecutionFactory.create(query, executionsDataSet());
		ResultSet results = queryExecution.execSelect();
		for(; results.hasNext();) {
			QuerySolution solution = results.nextSolution();
			long total_executions = solution.getLiteral("total_executions").getLong();
			String day = solution.getLiteral("day").getString();
			System.out.printf("Total succesful executions [%s]: %d%n",day,total_executions);
		}
	} finally {
		if (queryExecution != null) {
			queryExecution.close();
		}
	}
}
 
Example 10
Project: DoSeR   File: RDFGraphOperations.java   Source Code and License Vote up 6 votes
private static String queryDbPediaCategoryLabel(final String catUri) {
	String res = null;
	final Model model = DisambiguationMainService.getInstance()
			.getDBPediaCategoryLabels();

	final String query = "SELECT ?label WHERE{ <" + catUri
			+ "> <http://www.w3.org/2000/01/rdf-schema#label> ?label. }";
	try {
		final com.hp.hpl.jena.query.Query cquery = QueryFactory
				.create(query);
		final QueryExecution qexec = QueryExecutionFactory.create(cquery,
				model);
		final ResultSet results = qexec.execSelect(); // NOPMD by quh on
														// 18.02.14 15:05
		while (results.hasNext()) {
			final QuerySolution sol = results.nextSolution();
			final String name = sol.getLiteral("label").getLexicalForm();
			res = name;
		}
	} catch (final QueryException e) {
		Logger.getRootLogger().error(e.getStackTrace());
	}
	return res;
}
 
Example 11
Project: semweb4j   File: ModelSetImplJena.java   Source Code and License Vote up 6 votes
@Override
public ClosableIterable<Statement> sparqlConstruct(String query)
		throws ModelRuntimeException, MalformedQueryException {
	Query jenaQuery = QueryFactory.create(query);
	QueryExecution qexec = QueryExecutionFactory.create(jenaQuery,
			this.dataset);

	if (jenaQuery.isConstructType()) {
		com.hp.hpl.jena.rdf.model.Model m = qexec.execConstruct();
		Model resultModel = new ModelImplJena(null, m, Reasoning.none);
		resultModel.open();
		return resultModel;
	} else {
		throw new RuntimeException(
				"Cannot handle this type of query! Please use CONSTRUCT.");
	}

}
 
Example 12
Project: DoSeR   File: Sampling.java   Source Code and License Vote up 6 votes
private String queryEntitiesFromCategory(final String catUri) {
	String res = null;

	final String query = "SELECT ?entities WHERE{ ?entities <http://purl.org/dc/terms/subject> <"
			+ catUri + ">. }";
	try {
		final com.hp.hpl.jena.query.Query cquery = QueryFactory
				.create(query);
		final QueryExecution qexec = QueryExecutionFactory
				.create(cquery, m);
		final ResultSet results = qexec.execSelect();
		List<String> entities = new LinkedList<String>();
		while (results.hasNext()) {
			final QuerySolution sol = results.nextSolution();
			entities.add(sol.getResource("entities").getURI());
		}
		if (entities.size() != 0) {
			int randomNr = this.random.nextInt(entities.size());
			return entities.get(randomNr);
		}

	} catch (final QueryException e) {
		Logger.getRootLogger().error(e.getStackTrace());
	}
	return res;
}
 
Example 13
Project: Luzzu   File: DAQHelper.java   Source Code and License Vote up 6 votes
public static Map<String, Integer> getNumberOfDimensionsInCategory(){
	Map<String, Integer> dimensionPerCategory = new HashMap<String, Integer>();
	Model m = InternalModelConf.getFlatModel();
	
	String whereClause = "?categoryURI a " + SPARQLHelper.toSPARQL(DAQ.Category) + 
			" . ?categoryURI ?hasDimensionProperty ?dimensionURI . " +
			"?hasMetricProperty " + SPARQLHelper.toSPARQL(RDFS.subPropertyOf) + SPARQLHelper.toSPARQL(DAQ.hasDimension) + " .";
	
	String variables = "?categoryURI COUNT(?dimensionURI) as ?count";
	
	String query = SPARQLHelper.SELECT_STATEMENT.replace("[variables]", variables).replace("[whereClauses]", whereClause);
	Query qry = QueryFactory.create(query);
    QueryExecution qe = QueryExecutionFactory.create(qry, m);
    ResultSet rs = qe.execSelect();
    
    while (rs.hasNext()){
    	QuerySolution qs = rs.next();
    	String cat = qs.get("categoryURI").asResource().getURI();
    	Integer count = qs.get("count").asLiteral().getInt();
    	dimensionPerCategory.put(cat, count);
    }
	
    return dimensionPerCategory;
}
 
Example 14
Project: R2RLint   File: InterlinkingCompleteness.java   Source Code and License Vote up 6 votes
private int getCountResult(String queryStr, SparqlifyDataset dataset) {
	int count = 0;
	Query query = QueryFactory.create(queryStr);
	QueryExecution qe;
	if (dataset.isSparqlService() && dataset.getSparqlServiceUri() != null) {
		qe = QueryExecutionFactory.sparqlService(dataset.getSparqlServiceUri(), query);
	} else {
		qe = QueryExecutionFactory.create(query, dataset);
	}
	ResultSet res = qe.execSelect();
	
	while(res.hasNext())
	{
		QuerySolution solution = res.nextSolution();
		RDFNode solNode = solution.get("count");
		count += solNode.asLiteral().getInt();
	}
	qe.close(); 
	
	return count;
}
 
Example 15
Project: uraptor   File: ChallengeValidator.java   Source Code and License Vote up 6 votes
public boolean askcontainsStatement(Statement st, Model m)
{
	String q = "ASK{?subject ?predicate ?object.";
	if (st.getSubject().isAnon())
		q += " FILTER isBlank(?subject)";
	if (st.getObject().isAnon())
		q += " FILTER isBlank(?object)";
	q += "}";

	QuerySolutionMap args = new QuerySolutionMap();
	if (!st.getSubject().isAnon())
		args.add("subject", st.getSubject());
	if (!st.getObject().isAnon())
		args.add("object", st.getObject());
	// QueryExecution qe = QueryExecutionFactory.create(q, m, args);

	Query query = QueryFactory.create(q);
	QueryExecution qe = QueryExecutionFactory.create(query, m, args);

	return qe.execAsk();
}
 
Example 16
Project: JenaTutorial   File: AnotherInverseOfProperty.java   Source Code and License Vote up 6 votes
public static void main( String[] args )
{
	// load some data that uses RDFS
	Model data = FileManager.get().loadModel("file:data/input/turtle/ex20-data.ttl");
	
	
	Reasoner reasoner = ReasonerRegistry.getOWLReasoner();
	InfModel infmodel = ModelFactory.createInfModel(reasoner, data );
	
	/* Do a SPARQL Query over the data in the model */
	String queryString = "SELECT ?x ?z WHERE { ?x <http://www.w3.org/2000/01/rdf-schema#subclassOf> ?z }";

	/* Now create and execute the query using a Query object */
	Query query = QueryFactory.create(queryString) ;
	QueryExecution qexec = QueryExecutionFactory.create(query, infmodel) ;

	QueryExecUtils.executeQuery(qexec);
	
	System.out.println( "\n---------------\n" );		
}
 
Example 17
Project: JenaTutorial   File: SparqlQueryWithPropertySubclass.java   Source Code and License Vote up 6 votes
public static void main( String[] args )
{
	// load some data that uses RDFS
	Model data = FileManager.get().loadModel("file:data/input/turtle/ex5-data.ttl");

	
	Reasoner reasoner = ReasonerRegistry.getRDFSReasoner();
	reasoner.setParameter(ReasonerVocabulary.PROPsetRDFSLevel, 
               ReasonerVocabulary.RDFS_DEFAULT);
	InfModel infmodel = ModelFactory.createInfModel(reasoner, data );
	
	/* Do a SPARQL Query over the data in the model */
	String queryString = "SELECT ?x  ?z WHERE { ?x <http://www.example.org/example#worksFor> ?z }" ;

	/* Now create and execute the query using a Query object */
	Query query = QueryFactory.create(queryString) ;
	QueryExecution qexec = QueryExecutionFactory.create(query, infmodel) ;

	QueryExecUtils.executeQuery(qexec);
	
	System.out.println( "\n----------\ndone" );
	
}
 
Example 18
Project: JenaTutorial   File: RDFSLabels.java   Source Code and License Vote up 6 votes
public static void main( String[] args )
{
	// load some data that uses RDFS
	Model data = FileManager.get().loadModel("file:data/input/turtle/ex13-data.ttl");
	
	Reasoner reasoner = ReasonerRegistry.getRDFSReasoner();
	reasoner.setParameter(ReasonerVocabulary.PROPsetRDFSLevel, 
               ReasonerVocabulary.RDFS_DEFAULT);
	InfModel infmodel = ModelFactory.createInfModel(reasoner, data );
	
	/* Do a SPARQL Query over the data in the model */
	String queryString = "SELECT ?x ?z WHERE { ?x <http://www.w3.org/2000/01/rdf-schema#label> ?z }";

	/* Now create and execute the query using a Query object */
	Query query = QueryFactory.create(queryString) ;
	QueryExecution qexec = QueryExecutionFactory.create(query, infmodel) ;

	QueryExecUtils.executeQuery(qexec);
		
	
	System.out.println( "done" );		
	
}
 
Example 19
Project: com.inova8.remediator   File: Datasets.java   Source Code and License Vote up 6 votes
public void loadPropertyPartitionStatistics(OntModel voidModel) {
	Query query = QueryFactory.create(propertyPartitionStatisticsQuery);
	QueryExecution qexec = QueryExecutionFactory.create(query, voidModel);

	try {
		ResultSet results = qexec.execSelect();
		for (; results.hasNext();) {
			QuerySolution soln = results.nextSolution();
			OntResource dataset = soln.getResource("Dataset").as(
					OntResource.class);
			OntResource property = soln.getResource("Property").as(
					OntResource.class);
			Integer triples = (soln.getLiteral("Triples") != null) ? soln
					.getLiteral("Triples").getInt() : null;	
			Dataset ds = this.getDataset(dataset);		
			if (ds!=null)ds.getPartitions().addPropertyPartition(property, triples);
		}
	} catch (Exception e) {
		Log.debug(
				this,
				"Unable to execute propertyPartitionStatisticsQuery " + query);
	} finally {
		qexec.close();
	}
}
 
Example 20
Project: Luzzu   File: DAQHelper.java   Source Code and License Vote up 6 votes
public static List<String> getDimensionsInCategory(Resource categoryURI){
	Model m = InternalModelConf.getFlatModel();
	
	String whereClause = SPARQLHelper.toSPARQL(categoryURI) + " ?prop ?dimensionURI" +
			"?prop " + SPARQLHelper.toSPARQL(RDFS.subPropertyOf) + SPARQLHelper.toSPARQL(DAQ.hasDimension) + " .";
			
	String query = SPARQLHelper.SELECT_STATEMENT.replace("[variables]", "?dimensionURI").replace("[whereClauses]", whereClause);
	Query qry = QueryFactory.create(query);
    QueryExecution qe = QueryExecutionFactory.create(qry, m);
    ResultSet rs = qe.execSelect();
    
    List<String> dimensions = new ArrayList<String>();
    while (rs.hasNext()){
    	QuerySolution qs = rs.next();
    	dimensions.add(qs.get("dimensionURI").asResource().getURI());
    }
	
    return dimensions;
}
 
Example 21
Project: ontonethub   File: IndexingJob.java   Source Code and License Vote up 5 votes
private List<Statement> getUsage(Property property, Model model){
	
	List<Statement> stmts = new ArrayList<Statement>();
	String sparql = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "
			+ "PREFIX owl: <http://www.w3.org/2002/07/owl#> "
			+ "SELECT DISTINCT ?concept "
			+ "WHERE{"
			+ "  {<" + property.getURI() + "> rdfs:domain ?concept} "
			+ "  UNION "
			+ "  { "
			+ "    ?concept rdfs:subClassOf|owl:equivalentClass ?restriction . "
			+ "    ?restriction a owl:Restriction; "
			+ "      owl:onProperty <" + property.getURI() + "> "
			+ "  } "
			+ "}";
	Query query = QueryFactory.create(sparql, Syntax.syntaxARQ);
	QueryExecution queryExecution = QueryExecutionFactory.create(query, model);
	
	ResultSet resultSet = queryExecution.execSelect();
	while(resultSet.hasNext()){
		QuerySolution querySolution = resultSet.next();
		Resource concept = querySolution.getResource("concept");
		
		stmts.add(new StatementImpl(property, usage, concept));
	}
	
	return stmts;
	
}
 
Example 22
Project: ontonethub   File: IndexingJob.java   Source Code and License Vote up 5 votes
private List<Statement> getUsage(OntClass ontClass, Model model){
	List<Statement> stmts = new ArrayList<Statement>();
	try{
		String sparql = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "
				+ "PREFIX owl: <http://www.w3.org/2002/07/owl#> "
				+ "SELECT DISTINCT ?concept "
				+ "WHERE{"
				+ "  {?prop rdfs:range <" + ontClass.getURI() + ">; "
				+ "    rdfs:domain ?concept"
				+ "  }"
				+ "  UNION "
				+ "  { "
				+ "    ?concept rdfs:subClassOf|owl:equivalentClass ?restriction . "
				+ "    ?restriction a owl:Restriction; "
				+ "      ?p <" + ontClass.getURI() + "> "
				+ "  } "
				+ "}";
		Query query = QueryFactory.create(sparql, Syntax.syntaxARQ);
		QueryExecution queryExecution = QueryExecutionFactory.create(query, model);
		
		ResultSet resultSet = queryExecution.execSelect();
		while(resultSet.hasNext()){
			QuerySolution querySolution = resultSet.next();
			Resource concept = querySolution.getResource("concept");
			
			stmts.add(new StatementImpl(ontClass, usage, concept));
		}
	} catch(Exception e){
		log.error(e.getMessage(), e);
	}
	
	return stmts;
	
}
 
Example 23
Project: BoostSRL   File: GraphDB.java   Source Code and License Vote up 5 votes
void calcTypeCnts()
{
	String qry = "PREFIX nmspc: <http://example.org/> SELECT  ?o  (count(?s) as ?cnt)  WHERE {?s nmspc:type ?o} GROUP BY ?o";
	Query query = QueryFactory.create(qry);
	QueryExecution qexec = QueryExecutionFactory.create(query, m);
	ResultSet results = qexec.execSelect();
	//ResultSetFormatter.out(results);
	while(results.hasNext())
	{
		QuerySolution qs = results.next();
		String type = qs.get("o").asResource().getLocalName();
		int cnt = qs.get("cnt").asLiteral().getInt();
		typeCounts.put(type, cnt);
	}
}
 
Example 24
Project: BimSPARQL   File: Server.java   Source Code and License Vote up 5 votes
public List<String> getResult(InputStream in, String query){
	Model model=ModelFactory.createDefaultModel();
	model.read(in,null,"TTL");
	Query q = QueryFactory.create(query);
	QueryExecution qe = QueryExecutionFactory.create(q, model);
	ResultSet qresults = qe.execSelect();
	List<QuerySolution> solutions=ResultSetFormatter.toList(qresults);
	List<String> results=new ArrayList<String>();
	for(QuerySolution qs:solutions){
		results.add(qs.toString());
	}
	return results;
}
 
Example 25
Project: BimSPARQL   File: IfcSemanticExtractor.java   Source Code and License Vote up 5 votes
public List<Resource> getAllGeometricResources()
		throws FileNotFoundException {
	List<Resource> resources = new ArrayList<Resource>();
	String template = "PREFIX ifc: <"+model.getNsPrefixURI("ifc")+">\n"
			+ "SELECT DISTINCT ?s\n" + "WHERE{\n" + "?s a %s .\n" + "}";
	for (String s : geometryEntities) {
		String q = String.format(template, s);
		Query query = QueryFactory.create(q);
		QueryExecution qexec = QueryExecutionFactory.create(query, model);
		ResultSet results = qexec.execSelect();
		while (results.hasNext()) {
			QuerySolution solution = results.next();
			resources.add(solution.getResource("s"));
		}
		List<String> subclasses = getSubClassShortNames(s);
		for (String subclass : subclasses) {
			String qq = String.format(template, subclass);
			Query qquery = QueryFactory.create(qq);
			QueryExecution qqexec = QueryExecutionFactory.create(qquery,
					model);
			ResultSet qresults = qqexec.execSelect();
			while (qresults.hasNext()) {
				QuerySolution qsolution = qresults.next();
				resources.add(qsolution.getResource("s"));
			}
		}
	}
	return resources;
}
 
Example 26
Project: BimSPARQL   File: QueryFunctionTest.java   Source Code and License Vote up 5 votes
public static void executeQuery(String query){
	System.out.println("Load model...");
	OntModel ontModel=loadDefaultModel();
	System.out.println("Start to query...");
	  long start=System.currentTimeMillis();
	Query q = QueryFactory.create(prefixes+query);
	QueryExecution qe = QueryExecutionFactory.create(q, ontModel);
	ResultSet qresults = qe.execSelect();
	ResultSetFormatter.out(qresults);
	  long end=System.currentTimeMillis();
        System.out.println("Query time: "+((float)(end-start))/1000+ " s");
}
 
Example 27
Project: BimSPARQL   File: FireSeparationDistance.java   Source Code and License Vote up 5 votes
public static void main(String[] args)
	throws ClassNotFoundException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
Model model = ModelFactory.createDefaultModel();
InputStream in = FireSeparationDistance.class.getClassLoader().getResourceAsStream("lifeline_final.ttl");
model.read(in, null, "TTL");
System.out.println(model.size());
Model geometryModel = ModelFactory.createDefaultModel();
InputStream ing = FireSeparationDistance.class.getClassLoader().getResourceAsStream("lifeline_final_geometry.ttl");
geometryModel.read(ing, null, "TTL");
System.out.println(geometryModel.size());
Model schema=loadModel("IFC2X3_TC1.ttl","TTL");
BimSPARQL.init(model, geometryModel);
Model ibcspin = ModelFactory.createDefaultModel();
addMagicProperty(ibcspin, IBC+"hasFireSeparationDistance", prefixes+hasFireSeparationDistance, 1);
addMagicProperty(ibcspin, IBC+"hasProtectedOpeningArea", prefixes+hasProtectedOpeningArea, 1);
addMagicProperty(ibcspin, IBC+"hasUnprotectedOpeningArea", prefixes+hasUnprotectedOpeningArea, 1);
addMagicProperty(ibcspin, IBC+"hasAp", prefixes+hasAp, 1);
addMagicProperty(ibcspin, IBC+"hasAu", prefixes+hasAu, 1);
Model ibc=loadIbcData();
SPINModuleRegistry.get().registerAll(ibc, null);
for (Function f:SPINModuleRegistry.get().getFunctions())
{
	System.out.println(f.getURI());
}
com.hp.hpl.jena.query.Query query = QueryFactory.create(prefixes + mainQuery);

OntModel union = ModelFactory.createOntologyModel();
union.add(schema);
union.add(model);
union.add(geometryModel);
union.add(ibc);
System.out.println(union.size());
QueryExecution qe = QueryExecutionFactory.create(query, union);
com.hp.hpl.jena.query.ResultSet result = qe.execSelect();
      ResultSetFormatter.out(result);

      }
 
Example 28
Project: BimSPARQL   File: JenaTest.java   Source Code and License Vote up 5 votes
public static void main(String[] args) throws FileNotFoundException{
		Model model=ModelFactory.createDefaultModel();
		InputStream in=new FileInputStream("BimSPARQL_example.ttl");
		model.read(in,null,"TTL");
		String query=prefixes+"SELECT ?s\n"+ 
"WHERE{?s ?p ?o .}";
		Query q = QueryFactory.create(query);
		QueryExecution qe = QueryExecutionFactory.create(q, model);
		ResultSet qresults = qe.execSelect();
        ResultSetFormatter.out(qresults);
	}
 
Example 29
Project: semweb4j   File: QueryResultTableImpl.java   Source Code and License Vote up 5 votes
public QueryResultTableImpl(Query query, Model jenaModel) throws ModelRuntimeException {
	
	if(!query.isSelectType()) {
		throw new ModelRuntimeException("The given query is not a SELECT query");
	}
	// else
	this.varnames = new ArrayList<String>();
	for(Object o : query.getResultVars()) {
		this.varnames.add((String)o);
	}
	this.qexec = QueryExecutionFactory.create(query, jenaModel);
}
 
Example 30
Project: WikiOnto   File: SemDistGUI.java   Source Code and License Vote up 5 votes
private void getDistantEntities(){
	File metricFile = new File(
			System.getProperty("user.dir") + "/sparql/smells/SemanticallyDistantEntity.sparql");

	List<String> lines = null;

	try {
		lines = Files.readAllLines(metricFile.toPath());
	} catch (IOException ex) {
		Logger.getLogger(Ontogui.class.getName()).log(Level.SEVERE, null, ex);
	}
	String queryString = "";
	for (String line : lines) {
		queryString += line + System.lineSeparator();
	}
	
	data.begin(ReadWrite.READ);
	List<QuerySolution> rlist = null;
	Query query = QueryFactory.create(queryString, Syntax.syntaxARQ);
	try (QueryExecution qe = QueryExecutionFactory.create(query, data)) {
		ResultSet results = qe.execSelect();
		rlist = ResultSetFormatter.toList(results);
	} catch (Exception e) {
		JOptionPane.showMessageDialog(null, "Writting to textarea failed!");
		e.printStackTrace();
	}
	instances = new String[rlist.size()];
	for(int j = 0; j < rlist.size(); j++){
		instances[j] = rlist.get(j).getLiteral("entityname").getString();
	}
	data.end();
}
 
Example 31
Project: WikiOnto   File: SemDistGUI.java   Source Code and License Vote up 5 votes
private void getDistantTypes(){
	File metricFile = new File(
			System.getProperty("user.dir") + "/sparql/smells/SemanticallyDistantType.sparql");

	List<String> lines = null;

	try {
		lines = Files.readAllLines(metricFile.toPath());
	} catch (IOException ex) {
		Logger.getLogger(Ontogui.class.getName()).log(Level.SEVERE, null, ex);
	}
	String queryString = "";
	for (String line : lines) {
		queryString += line + System.lineSeparator();
	}
	
	data.begin(ReadWrite.READ);
	List<QuerySolution> rlist = null;
	Query query = QueryFactory.create(queryString, Syntax.syntaxARQ);
	try (QueryExecution qe = QueryExecutionFactory.create(query, data)) {
		ResultSet results = qe.execSelect();
		rlist = ResultSetFormatter.toList(results);
	} catch (Exception e) {
		JOptionPane.showMessageDialog(null, "Writting to textarea failed!");
		e.printStackTrace();
	}
	subtypes = new String[rlist.size()];
	for(int j = 0; j < rlist.size(); j++){
		subtypes[j] = rlist.get(j).getLiteral("typename").getString();
	}
	data.end();
}
 
Example 32
Project: semweb4j   File: QueryResultTableImpl.java   Source Code and License Vote up 5 votes
public QueryResultTableImpl(Query query, Dataset jenaDataset) throws ModelRuntimeException {
	
	if(!query.isSelectType()) {
		throw new ModelRuntimeException("The given query is not a SELECT query");
	}
	// else
	this.varnames = new ArrayList<String>();
	for(Object o : query.getResultVars()) {
		this.varnames.add((String)o);
	}
	this.qexec = QueryExecutionFactory.create(query, jenaDataset);
}
 
Example 33
Project: semweb4j   File: ModelSetImplJena.java   Source Code and License Vote up 5 votes
@Override
public boolean sparqlAsk(String query) throws ModelRuntimeException,
		MalformedQueryException {
	Query jenaQuery = QueryFactory.create(query);
	QueryExecution qexec = QueryExecutionFactory.create(jenaQuery,
			this.dataset);

	if (jenaQuery.isAskType()) {
		return qexec.execAsk();
	} else {
		throw new RuntimeException(
				"Cannot handle this type of query! Please use ASK.");
	}
}
 
Example 34
Project: DoSeR   File: CreateDBPediaIndex.java   Source Code and License Vote up 5 votes
public String getDbPediaLongDescription(final String uri)
		throws QueryException, QueryParseException {
	String labellist = "";
	try {
		final String query = "SELECT ?comment WHERE{ <" + uri
				+ "> <http://dbpedia.org/ontology/abstract> ?comment. }";
		ResultSet results = null;
		QueryExecution qexec = null;

		final com.hp.hpl.jena.query.Query cquery = QueryFactory
				.create(query);
		qexec = QueryExecutionFactory.create(cquery, this.longdescmodel);
		results = qexec.execSelect();

		if (results != null) {
			while (results.hasNext()) {
				final QuerySolution sol = results.nextSolution();
				final String desc = sol.getLiteral("comment")
						.getLexicalForm();
				labellist = desc;
			}
			qexec.close();
		}
	} catch (QueryParseException e) {
		Logger.getRootLogger().info("Query parse Exception");
	}
	return labellist;
}
 
Example 35
Project: DoSeR   File: Test1.java   Source Code and License Vote up 5 votes
public HashSet<String> addAdditionalPersonNameOccurrences(String res) {
	HashSet<String> names = new HashSet<String>();
	try {
		final String query = "SELECT ?surname WHERE{ <" + res
				+ "> <http://xmlns.com/foaf/0.1/surname> ?surname. }";
		ResultSet results = null;
		QueryExecution qexec = null;

		final com.hp.hpl.jena.query.Query cquery = QueryFactory
				.create(query);
		qexec = QueryExecutionFactory.create(cquery,
				this.mappingbasedproperties);
		results = qexec.execSelect();

		if (results != null) {
			while (results.hasNext()) {
				final QuerySolution sol = results.nextSolution();
				final String surname = sol.getLiteral("surname")
						.getLexicalForm();
				names.add(surname);
			}
			qexec.close();
		}
	} catch (QueryParseException e) {
		Logger.getRootLogger().info("Query parse Exception");
	}

	return names;
}
 
Example 36
Project: ldp4j   File: QueryHelper.java   Source Code and License Vote up 5 votes
public <T> T select(ResultProcessor<T> collector) {
	try(QueryExecution execution = QueryExecutionFactory.create(build(),this.model)) {
		ResultSet resultSet = execution.execSelect();
		while(resultSet.hasNext()) {
			collector.handle(resultSet.next());
		}
		return collector.getResult();
	}
}
 
Example 37
Project: R2RLint   File: CorrectContainerUse.java   Source Code and License Vote up 5 votes
private void ckeckLeadingZeros(SparqlifyDataset dataset)
		throws NotImplementedException, SQLException {
	// http://www.w3.org/TR/2003/WD-rdf-syntax-grammar-20030123/#rdf-ns-uri
	
	String queryStr =
		"Prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
		"SELECT * { " +
			"?s ?p ?o . " +
			"FILTER(regex(str(?p), \"^http://www.w3.org/1999/02/22-rdf-syntax-ns#_0\")) " +
		"}";
	
	Query query = QueryFactory.create(queryStr);
	
	QueryExecution qe;
	if (dataset.isSparqlService() && dataset.getSparqlServiceUri()!=null) {
		qe = QueryExecutionFactory.createServiceRequest(
				dataset.getSparqlServiceUri(), query);
	} else {
		qe = QueryExecutionFactory.create(query, dataset);
	}
	ResultSet res = qe.execSelect();
	
	List<Triple> leadingZeroTriples = new ArrayList<Triple>();
	while(res.hasNext())
	{
		QuerySolution solution = res.nextSolution();
		Resource subj = solution.getResource("s");
		Resource pred = solution.getResource("p");
		RDFNode obj = solution.get("o");
		Triple leadingzeroTriple = new Triple(subj.asNode(), pred.asNode(), obj.asNode());
		leadingZeroTriples.add(leadingzeroTriple);
	}
	qe.close(); 
	
	for (Triple triple : leadingZeroTriples) {
		Set<ViewQuad<ViewDefinition>> viewQuads = pinpointer.getViewCandidates(triple);
		writeTripleMeasureToSink(leadingZeroVal, triple, viewQuads);
	}
}
 
Example 38
Project: R2RLint   File: CoverageScope.java   Source Code and License Vote up 5 votes
@Override
public void assessDataset(SparqlifyDataset dataset)
		throws NotImplementedException, SQLException {
	
	long numTriples = dataset.size();
	long numInstances = 0;
	
	Query query = QueryFactory.create(
			"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> "
			+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>"
			+ "PREFIX owl: <http://www.w3.org/2002/07/owl#>"
			
			+ "SELECT (count(*) AS ?count) { "
				+ "SELECT distinct ?s {"
					+ " { ?s a ?o . ?o a rdfs:Class }"
					+ " UNION { ?s a ?o . ?o a owl:Class }"
				+ "}"
			+ "}");
		
	QueryExecution qe;
	if (dataset.isSparqlService() && dataset.getSparqlServiceUri() != null) {
		qe = QueryExecutionFactory.sparqlService(dataset.getSparqlServiceUri(), query);
	} else {
		qe = QueryExecutionFactory.create(query, dataset);
	}
	
	ResultSet res = qe.execSelect();
	while(res.hasNext())
	{
		QuerySolution resNode = res.nextSolution();
		numInstances = resNode.getLiteral("count").asLiteral().getLong();
	}
	qe.close(); 
	
	float val;
	if (numTriples == 0) val = 0;
	else val = numInstances / (float) numTriples;

	writeDatasetMeasureToSink(val);
}
 
Example 39
Project: dhus-core   File: Sparql.java   Source Code and License Vote up 4 votes
@Override
public Object execute(Map<String, EdmLiteral> parameters) throws ODataException
{
   EdmLiteral query_lit = parameters.remove("query");
   // Olingo2 checks for presence of non-nullable parameters for us!
   String query_s = query_lit.getLiteral();
   Query query = QueryFactory.create(query_s);
   if (!(query.isSelectType() || query.isDescribeType()))
   {
      throw new InvalidOperationException(query.getQueryType());
   }

   DrbCortexModel cortexmodel;
   try
   {
      cortexmodel = DrbCortexModel.getDefaultModel();
   }
   catch (IOException ex)
   {
      throw new RuntimeException(ex);
   }

   Model model = cortexmodel.getCortexModel().getOntModel();

   QueryExecution qexec = null;
   // FIXME: QueryExecution in newer versions of Jena (post apache incubation) implement AutoClosable.
   try
   {
      qexec = QueryExecutionFactory.create(query, model);
      if (query.isSelectType())
      {
         ResultSet results = qexec.execSelect();
         return ResultSetFormatter.asXMLString(results);
      }
      else
      {
         Model description = qexec.execDescribe();
         // newer version of Jena have the RIOT package for I/O
         StringWriter strwrt = new StringWriter();
         Abbreviated abb = new Abbreviated();
         abb.write(description, strwrt, null);
         return strwrt.toString();
      }
   }
   finally
   {
      if (qexec != null)
      {
         qexec.close();
      }
   }
}
 
Example 40
Project: ScholarLens   File: ProfBuilder.java   Source Code and License Vote up 4 votes
/** Returns the representation of competences in the given model.
 * 
 * @param SPARQLTemplate the query to select competences with a placeholder for a username
 * @param model the dataset model containing the competence triples
 * @return Either a LaTeX table source or a LimeSurvey template
 */
private final static String listCompetencies(final String SPARQLTemplate,final Model model) {
	List<Competency> competenceList = new ArrayList<Competency>();
	//int counter = 0;
	StringBuffer sb = new StringBuffer();
	String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX um: <http://intelleo.eu/ontologies/user-model/ns/> PREFIX c: <http://www.intelleo.eu/ontologies/competences/ns/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX pubo: <http://lod.semanticsoftware.info/pubo/pubo#> SELECT DISTINCT ?uri WHERE {?document pubo:hasAnnotation ?author. ?author rdf:type um:User. ?author rdfs:isDefinedBy ?uri.}";
	Query query = QueryFactory.create(queryString);
	QueryExecution qexec = QueryExecutionFactory.create(query, model);

	try {
		ResultSet results = qexec.execSelect();

		for (; results.hasNext();) {
			QuerySolution soln = results.nextSolution();
			RDFNode user = soln.get("?uri");
			userName = user.toString();

			System.out.println("\nGenerating a semantic profile for  " + userName);
			System.out.println("=============================================================================================");

			RDFNode ne = null;

			// REPLACE THE PLACEHOLDER WITH USERNAME
			String SPARQL = SPARQLTemplate.replaceAll("DUMBO", userName);
			Query neQuery = QueryFactory.create(SPARQL);
			QueryExecution neQexec = QueryExecutionFactory.create(neQuery,model);
			ResultSet neResults = neQexec.execSelect();
			int rankCounter = 1;
			for (; neResults.hasNext();) {
				QuerySolution neSoln = neResults.nextSolution();
				ne = neSoln.get("?uri");
				if (ne != null) {
					Competency cmpt = getInfo(ne.toString(), rankCounter++);
					competenceList.add(cmpt);
				} else {
					System.out.println("No competencies found!");
				}
			}
			if(mode.equalsIgnoreCase("survey")){
				System.out.println("Generating LimeSurvey templates....");
				generateRandomizedSurvey(competenceList);
			}else{
				System.out.println("Generating LaTeX templates....");
				//generateLaTeXProfile(competenceList);
			}
		}
	} finally {
		qexec.close();
	}
	System.out.println("All done.");
	return sb.toString();
}
 
Example 41
Project: r2rml-kit   File: ValidatorTest.java   Source Code and License Vote up 4 votes
@Parameters(name="{index}: {0}")
	public static Collection<Object[]> getTestList() {
		Model m = D2RQTestUtil.loadTurtle(MANIFEST_FILE);
		IRI baseIRI = D2RQTestUtil.createIRI(m.getNsPrefixURI("base"));
		String schema = D2RQTestUtil.getResourceURL(SCHEMA);
		ResultSet rs = QueryExecutionFactory.create(TEST_CASE_LIST, m).execSelect();
		List<Object[]> result = new ArrayList<Object[]>();
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			Resource file = qs.getResource("r2rml");
//			if (!file.getLocalName().equals("duplicate-subject-map.ttl")) continue;
			List<MessageExpectation> expectations = new ArrayList<MessageExpectation>();
			QueryExecution qe = QueryExecutionFactory.create(TEST_CASE_DETAILS, m);
			qe.setInitialBinding(qs);
			ResultSet rs2 = qe.execSelect();
			while (rs2.hasNext()) {
				QuerySolution solution = rs2.next();

				// Work around a SPARQL/ARQ weirdness where MAX() on an empty
				// solution sequence creates a new all-empty solution
				if (!solution.varNames().hasNext()) continue;
				
				MessageExpectation expectation = new MessageExpectation( 
						Problem.valueOf(solution.getResource("problem").getLocalName()));
				if (solution.contains("level")) {
					expectation.expectLevel(Level.valueOf(solution.getResource("level").getLocalName()));
				}
				if (solution.contains("details") && 
						solution.get("details").isLiteral() && 
						solution.getLiteral("details").getBoolean()) {
					expectation.expectDetails();
				}
				if (solution.contains("detailcode")) {
					expectation.expectDetailCode(solution.getResource("detailcode").getLocalName());
				}
				if (solution.contains("subject")) {
					expectation.expectSubject(solution.getResource("subject"));
				}
				if (solution.contains("predicate")) {
					expectation.expectPredicate(solution.getResource("predicate").as(Property.class));
				}
				if (solution.contains("object")) {
					expectation.expectObject(solution.get("object"));
				}
				expectations.add(expectation);
			}
			result.add(new Object[]{baseIRI.relativize(file.getURI()).toString(), file.getURI(), schema, expectations});
		}
		return result;
	}
 
Example 42
Project: c4a_data_repository   File: ResourceDescriptionServlet.java   Source Code and License Vote up 4 votes
protected void doGet(HttpServletRequest request,
		HttpServletResponse response) throws IOException, ServletException {
	D2RServer server = D2RServer.fromServletContext(getServletContext());
	server.checkMappingFileChanged();
	String relativeResourceURI = request.getRequestURI().substring(
			request.getContextPath().length()
					+ request.getServletPath().length());
	// Some servlet containers keep the leading slash, some don't
	if (!"".equals(relativeResourceURI)
			&& "/".equals(relativeResourceURI.substring(0, 1))) {
		relativeResourceURI = relativeResourceURI.substring(1);
	}
	if (request.getQueryString() != null) {
		relativeResourceURI = relativeResourceURI + "?"
				+ request.getQueryString();
	}

	/* Determine service stem, i.e. vocab/ in /[vocab/]data */
	int servicePos;
	if (-1 == (servicePos = request.getServletPath().indexOf(
			"/" + D2RServer.getDataServiceName())))
		throw new ServletException("Expected to find service path /"
				+ D2RServer.getDataServiceName());
	String serviceStem = request.getServletPath().substring(1,
			servicePos + 1);

	String resourceURI = RequestParamHandler
			.removeOutputRequestParam(server.resourceBaseURI(serviceStem)
					+ relativeResourceURI);
	String documentURL = server.dataURL(serviceStem, relativeResourceURI);

	String pageURL = server.pageURL(serviceStem, relativeResourceURI);

	String sparqlQuery = "DESCRIBE <" + resourceURI + ">";
	QueryExecution qe = QueryExecutionFactory.create(sparqlQuery,
			server.dataset());
	if (server.getConfig().getPageTimeout() > 0) {
		qe.setTimeout(Math.round(server.getConfig().getPageTimeout() * 1000));
	}
	Model description = qe.execDescribe();
	qe.close();
	
	if (description.size() == 0) {
		response.sendError(404);
	}
	if (description.qnameFor(FOAF.primaryTopic.getURI()) == null
			&& description.getNsPrefixURI("foaf") == null) {
		description.setNsPrefix("foaf", FOAF.NS);
	}
	Resource resource = description.getResource(resourceURI);

	Resource document = description.getResource(documentURL);
	document.addProperty(FOAF.primaryTopic, resource);

	Statement label = resource.getProperty(RDFS.label);
	if (label != null) {
		document.addProperty(RDFS.label,
				"RDF Description of " + label.getString());
	}
	server.addDocumentMetadata(description, document);
	if (server.getConfig().serveMetadata()) {
		// add document metadata from template
		Model resourceMetadataTemplate = server.getConfig().getResourceMetadataTemplate(
				server, getServletContext());
		MetadataCreator resourceMetadataCreator = new MetadataCreator(
				server, resourceMetadataTemplate);
		description.add(resourceMetadataCreator.addMetadataFromTemplate(
				resourceURI, documentURL, pageURL));
		
		Map<String, String> descPrefixes = description.getNsPrefixMap();
		descPrefixes.putAll(resourceMetadataTemplate.getNsPrefixMap());
		description.setNsPrefixes(descPrefixes);
	}
	// TODO: Add a Content-Location header
	new ModelResponse(description, request, response).serve();
}
 
Example 43
Project: lodreclib   File: MultiPropQueryExecutor.java   Source Code and License Vote up 4 votes
/**
 * Execute SPARQL query 
 * @param     query  sparql query
 * @param     p  property
 * @return    results map: prop[uri-s] (if uri is a subject), prop[uri-o] (if uri is an object)
 */
private THashMap<String, TObjectCharHashMap<String>> executeQuery(Query query) {
	
	THashMap<String, TObjectCharHashMap<String>> results = new THashMap<String, TObjectCharHashMap<String>>();
	QueryExecution qexec = null;
	
	if(model==null){
		if(graphURI == null)
			qexec = QueryExecutionFactory.sparqlService(endpoint, query); // remote query
		else
			qexec = QueryExecutionFactory.sparqlService(endpoint, query, graphURI); // remote query
	}	
	else
		qexec = QueryExecutionFactory.create(query, model); // local query
		
	try{
	
		ResultSet res = ResultSetFactory.copyResults(qexec.execSelect()) ;
		
		QuerySolution qs;
		String n;
		String p;
		
		while (res.hasNext()) {
			
			qs = res.next();
			p = qs.get("p").toString();
			results.putIfAbsent(p, new TObjectCharHashMap<String>());
			
			if (qs.get("o") == null) 
			{
				// get subject
				n = qs.get("s").toString();
				
				// consider only the type "yago"
				if (!p.contains("type"))
					results.get(p).put(n, 's'); // target as subject
				else 
				{
					if (n.contains("yago"))
						results.get(p).put(n, 's'); // target as subject
				}
				
			}
			else
			{
				// get object
				n = qs.get("o").toString();
				
				// consider only the type "yago"
				if (!p.contains("type"))
					results.get(p).put(n, 'o'); // target as object
				else 
				{
					if (n.contains("yago"))
						results.get(p).put(n, 'o'); // target as object
				}
			}
			
		}
		
	}
	
	catch(Exception e){
		e.printStackTrace();
	}
	finally{
		qexec.close();
	}
	
	return results;
	
}
 
Example 44
Project: semanticoctopus   File: JenaQueryEngine.java   Source Code and License Vote up 4 votes
@Override
public ResultSet execQuery(final String query) throws QueryParseException {
	System.out.println("Unsing model "+model);
	final QueryExecution execution = QueryExecutionFactory.create(QueryFactory.create(query), model);
	return execution.execSelect();
}
 
Example 45
Project: spring-usc   File: WebServiceLoader.java   Source Code and License Vote up 4 votes
private String getServiceUriByServiceAddress(String address) {

		Model model = Repository.Instance().getModel();
		
		// Create a new query
		String queryString =
			"PREFIX " + Prefixes.KARMA + ": <" + Namespaces.KARMA + "> \n" +
			"PREFIX " + Prefixes.HRESTS + ": <" + Namespaces.HRESTS + "> \n" +
			"SELECT ?s \n" +
			"WHERE { \n" +
			"      ?s a " + Prefixes.KARMA + ":Service . \n" +
			"      ?s " + Prefixes.HRESTS + ":hasAddress \"" + address + "\"^^hrests:URITemplate . \n" +
			"      } \n";
		
		logger.debug(queryString);
		
		Query query = QueryFactory.create(queryString);
		// Execute the query and obtain results
		QueryExecution qexec = QueryExecutionFactory.create(query, model);

		try {
			ResultSet results = qexec.execSelect() ;
			
			if (!results.hasNext())
				logger.info("query does not return any answer.");

//			ResultSetFormatter.out(System.out, results, query) ;
			 
			String serviceURI = "";
			for ( ; results.hasNext() ; )
			{
				QuerySolution soln = results.nextSolution() ;
				RDFNode x = soln.get("s") ;       // Get a result variable by name.
				serviceURI = x.toString();
				logger.info("Service with id " + x.toString() + " has been found with the address " + address);
				break;
			}
			
			return serviceURI;
		} catch (Exception e) {
			logger.info("Exception in finding a service with the address " + address + " in service repository.");
			return null;
		} finally { 
			qexec.close() ; 
		}

	}
 
Example 46
Project: Jena-Based-Semantic-Web-Tutorial   File: SelectQueryUsingModel.java   Source Code and License Vote up 4 votes
@Test
public void queryWithMultipleVariable() {

	// populate SPARQL SELECT Query string
	StringBuilder sb = new StringBuilder();
	sb.append("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>").append(NEWLINE);
	sb.append("PREFIX owl: <http://www.w3.org/2002/07/owl#>").append(NEWLINE);
	sb.append("PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>").append(NEWLINE);
	sb.append("PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>").append(NEWLINE);
	sb.append("PREFIX foaf: <http://xmlns.com/foaf/0.1/>").append(NEWLINE);
	sb.append("PREFIX myfoaf: <http://blog.sina.com.cn/zhoujiagenontology/helloworld.owl#>").append(NEWLINE);
	sb.append("PREFIX people: <http://www.people.com#>").append(NEWLINE);
	sb.append("SELECT DISTINCT ?prop ?obj").append(NEWLINE);
	sb.append("WHERE { myfoaf:me ?prop ?obj}").append(NEWLINE);

	// generate Query
	Query query = QueryFactory.create(sb.toString());

	// the binding variable
	String prop = "?prop";
	String obj = "?obj";

	int result = 0;

	// execute Query
	QueryExecution qexec = QueryExecutionFactory.create(query, model);
	System.out.println("Plan to run SPARQL query: ");
	System.out.println(BOUNDARY);
	System.out.println(query);
	System.out.println(BOUNDARY);
	ResultSet rs = qexec.execSelect();
	while (rs.hasNext()) {
		QuerySolution qs = rs.nextSolution();
		RDFNode propRDFNode = qs.get(prop);
		RDFNode objRDFNode = qs.get(obj);

		System.out.println(propRDFNode + Constants.TAB + objRDFNode);
		result++;
	}
	qexec.close();

	// assertion
	assertTrue(result > 0);
}
 
Example 47
Project: p3-osm-transformer   File: OsmRdfTransformer.java   Source Code and License Vote up 4 votes
/**
 * Search for an address (a node in OSM).
 * @param graph The input graph contains a schema:streetAddress with the name of the street, the locality and the country code .
 * @return Returns the geocoordinates of the street that has been found. 
 */
private TripleCollection geocodeAddress(Dataset ds, Address address){
    TripleCollection geoCodeRdf = new SimpleMGraph();
    
    String pre = StrUtils.strjoinNL( 
        "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>" ,
        "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>" ,
        "PREFIX schema: <http://schema.org/>" ,
        "PREFIX text: <http://jena.apache.org/text#>" ,
        "PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>" ,
        "PREFIX ogc: <http://www.opengis.net/ont/geosparql#>") ;
    
    String qs = StrUtils.strjoinNL( "SELECT ?s ?street ?lat ?lon" ,
                                " { ?s text:query (schema:streetAddress '" + address.getStreetAddress() + "') ;" ,
                                "      schema:streetAddress ?street ;" ,
                                "      schema:addressLocality \"" + address.getLocality() + "\" ;" ,
                                "      schema:addressCountry \"" + address.getCountryCode() + "\" ;" ,
                                "      geo:lat ?lat ;" ,
                                "      geo:long ?lon ." ,                                                                       
                                " }") ;
    
    log.info(pre + "\n" + qs);
    
    ds.begin(ReadWrite.READ) ;
    try {
        Query q = QueryFactory.create(pre + "\n" + qs) ;
        QueryExecution qexec = QueryExecutionFactory.create(q , ds) ;
        //QueryExecUtils.executeQuery(q, qexec) ;
        ResultSet results = qexec.execSelect();   
        int numberOfAddresses = 0;
        for( ; results.hasNext(); ){
            QuerySolution sol = results.nextSolution();
            String streetUriName = sol.getResource("s").getURI();
            String streetName = sol.getLiteral("?street").getString();  
            String latitude = sol.getLiteral("?lat").getLexicalForm();
            String longitude = sol.getLiteral("?lon").getLexicalForm();
            UriRef addressRef = new UriRef(streetUriName);                
            geoCodeRdf.add(new TripleImpl(addressRef, schema_streetAddress, new PlainLiteralImpl(streetName)));
            geoCodeRdf.add(new TripleImpl(addressRef, schema_addressLocality, new PlainLiteralImpl( address.getLocality())) );
            geoCodeRdf.add(new TripleImpl(addressRef, schema_addressCountry, new PlainLiteralImpl( address.getCountryCode())) );
            geoCodeRdf.add(new TripleImpl(addressRef, geo_lat, new PlainLiteralImpl( latitude )) );
            geoCodeRdf.add(new TripleImpl(addressRef, geo_lon, new PlainLiteralImpl( longitude )) );
            numberOfAddresses++;
        }
        log.info("Number of addresses like " + address.getStreetAddress() + " found: " + numberOfAddresses);
    } 
    finally { 
        ds.end() ; 
    }
    
    return geoCodeRdf;
}
 
Example 48
Project: p3-osm-transformer   File: OsmRdfTransformer.java   Source Code and License Vote up 4 votes
/**
 * Search for a street (way in OSM) 
 * @param graph The input graph contain a schema:streetAddress with the name of the street.
 * @return Returns the geometry of the street that has been found with the coordinates serialized as WKT. 
 */
private TripleCollection geocodeStreet(Dataset ds, Address address){
    TripleCollection geoCodeRdf = new SimpleMGraph();
    
    String pre = StrUtils.strjoinNL( 
        "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>" ,
        "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>" ,
        "PREFIX schema: <http://schema.org/>" ,
        "PREFIX text: <http://jena.apache.org/text#>" ,
        "PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>" ,
        "PREFIX ogc: <http://www.opengis.net/ont/geosparql#>") ;
    
    String qs = StrUtils.strjoinNL( "SELECT ?s ?street ?geometry ?wkt " ,
                                " { ?s text:query (schema:streetAddress '" + address.getStreetAddress() + "') ;" ,
                                "      schema:streetAddress ?street ;" ,
                                "      schema:addressLocality " + address.getLocality() + " ;" ,
                                "      schema:addressCountry " + address.getCountryCode() + " ;" ,
                                "      ogc:geometry ?geometry ." ,
                                "   ?geo ogc:asWKT ?wkt ." ,
                                " }") ;
    
    System.out.println(pre + "\n" + qs);
    
    ds.begin(ReadWrite.READ) ;
    try {
        Query q = QueryFactory.create(pre + "\n" + qs) ;
        QueryExecution qexec = QueryExecutionFactory.create(q , ds) ;
        //QueryExecUtils.executeQuery(q, qexec) ;
        ResultSet results = qexec.execSelect();   
        int numberOfToponyms = 0;
        for( ; results.hasNext(); ){
            QuerySolution sol = results.nextSolution();
            String streetUriName = sol.getResource("s").getURI();
            String streetName = sol.getLiteral("?street").getString();
            Resource geo = sol.getResource("?geo");
            String geoUri = geo.getURI();
            String wkt = sol.getLiteral("?wkt").getString();
            UriRef streetRef = new UriRef(streetUriName);
            UriRef geometryRef = new UriRef(geoUri);
            geoCodeRdf.add(new TripleImpl(streetRef, schema_streetAddress, new PlainLiteralImpl(streetName) ));
            geoCodeRdf.add(new TripleImpl(streetRef, schema_addressLocality, new PlainLiteralImpl( address.getLocality())) );
            geoCodeRdf.add(new TripleImpl(streetRef, schema_addressCountry, new PlainLiteralImpl( address.getCountryCode())) );
            geoCodeRdf.add(new TripleImpl(streetRef, new UriRef("http://www.opengis.net/ont/geosparql#geometry"), geometryRef));
            geoCodeRdf.add(new TripleImpl(geometryRef, new UriRef("http://www.opengis.net/ont/geosparql#asWKT"), new PlainLiteralImpl(wkt)));
            numberOfToponyms++;
        }
        log.info("Number of toponymis like " + address.getStreetAddress() + " found: " + numberOfToponyms);
    } 
    finally { 
        ds.end() ; 
    }
    
    return geoCodeRdf;
}
 
Example 49
Project: p3-geo-enriching-transformer   File: SpatialDataEnhancer.java   Source Code and License Vote up 4 votes
/**
 * Searches for points of interest within a circle of a given radius. 
 * The data used is stored in a named graph.
 * @param point
 * @param uri
 * @param radius
 * @return
 */
public TripleCollection queryNearby(WGS84Point point, String graphName, double radius){
    TripleCollection resultGraph = new SimpleMGraph();
    log.info("queryNearby()");
    long startTime = System.nanoTime();
    String pre = StrUtils.strjoinNL("PREFIX spatial: <http://jena.apache.org/spatial#>",
            "PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>",
            "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>",
            "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>");
    
    String qs = StrUtils.strjoinNL("SELECT * ",
            "FROM NAMED <" + graphName + ">",
            "WHERE { ",
            "GRAPH <" + graphName + "> ",
            " { ?s spatial:nearby (" + point.getLat() + " " + point.getLong() + " " + radius + " 'm') ;",
            "      rdf:type ?type ; ",
            "      geo:lat ?lat ;" ,
            "      geo:long ?lon ; ",
            "      rdfs:label ?label .", " }",
            "}");

    log.info(pre + "\n" + qs);
    spatialDataset.begin(ReadWrite.READ);
    int poiCounter = 0;
    try {
        Query q = QueryFactory.create(pre + "\n" + qs);
        QueryExecution qexec = QueryExecutionFactory.create(q, spatialDataset);
        ResultSet results = qexec.execSelect() ;
        for ( ; results.hasNext() ; ) {
            QuerySolution solution = results.nextSolution() ;
            String poiUri = solution.getResource("s").getURI();
            String poiName = checkUriName(poiUri);
            String poiType = checkUriName(solution.getResource("type").getURI());
            String poiLabel = solution.getLiteral("label").getString();
            String poiLatitude = solution.getLiteral("lat").getString();
            String poiLongitude = solution.getLiteral("lon").getString();
            log.info("poi name: " + poiName + " label = " + poiLabel);
            UriRef poiRef = new UriRef(poiName);
            String positionUri = checkUriName(point.getUriName());
            resultGraph.add( new TripleImpl(poiRef, schema_containedIn, new UriRef(positionUri)) );               
            resultGraph.add( new TripleImpl(poiRef, RDFS.label, new PlainLiteralImpl(poiLabel)) );
            resultGraph.add( new TripleImpl(poiRef, RDF.type, new UriRef(poiType)));
            resultGraph.add( new TripleImpl(poiRef, geo_lat, new TypedLiteralImpl(poiLatitude, XSD.float_)) );
            resultGraph.add( new TripleImpl(poiRef, geo_long, new TypedLiteralImpl(poiLongitude, XSD.float_)) );  
            poiCounter++;
            
        }
      
    } 
    finally {
        spatialDataset.end();
    }
    long finishTime = System.nanoTime();
    double time = (finishTime - startTime) / 1.0e6;
    log.info(String.format("FINISH - %.2fms", time));
    log.info(String.format("Found " + poiCounter + " points of interest."));
    return resultGraph;

}
 
Example 50
Project: SolRDF   File: PagedResultSetTestCase.java   Source Code and License Vote up 4 votes
/**
 * Executes a "SELECT ALL" query.
 * 
 * @return the {@link ResultSet} as result of the query execution.
 */
ResultSet executeQuery() {
	final Query query = QueryFactory.create("SELECT * WHERE {?s ?p ?o}");
	final QueryExecution execution = QueryExecutionFactory.create(query, model);
	return execution.execSelect();		
}
 
Example 51
Project: JenaTutorial   File: SparqlQueryForAllTriples.java   Source Code and License Vote up 4 votes
public static void main( String[] args )
{
	// load some data that uses RDFS
	Model data = FileManager.get().loadModel("file:data/input/turtle/ex5-data.ttl");

	
	Reasoner reasoner = ReasonerRegistry.getRDFSReasoner();
	reasoner.setParameter(ReasonerVocabulary.PROPsetRDFSLevel, 
               ReasonerVocabulary.RDFS_DEFAULT);
	InfModel infmodel = ModelFactory.createInfModel(reasoner, data );
	
	/* Do a SPARQL Query over the data in the model */
	String queryString = "SELECT ?x ?y ?z WHERE { ?x ?y ?z }" ;

	/* Now create and execute the query using a Query object */
	Query query = QueryFactory.create(queryString) ;
	QueryExecution qexec = QueryExecutionFactory.create(query, infmodel) ;

	
	QueryExecUtils.executeQuery(qexec);
	
	
	System.out.println( "\n----------\ndone" );
	
}
 
Example 52
Project: R2RLint   File: VocabularyPropertyCompleteness.java   Source Code and License Vote up 4 votes
/**
 * @param dataset
 * @return
 */
private Set<Node> getProperties(Model dataset) {
	
	if (dataset instanceof SparqlifyDataset) {
		dataset = (SparqlifyDataset) dataset;
	}
	
	Set<Node> properties = new HashSet<Node>();
	
	// ont model approach
	OntModel ontDataset = 
			ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM_TRANS_INF, dataset);
	ExtendedIterator<OntProperty> ontPropIt = ontDataset.listAllOntProperties();
	
	while (ontPropIt.hasNext()) {
		OntProperty prop = ontPropIt.next();
		properties.add(prop.asNode());
	}
	
	// explicit query approach
	String queryStr =
			"SELECT distinct ?p  {" +
				"?s ?p ?o " +
			"}";
	Query query = QueryFactory.create(queryStr);
	
	QueryExecution qe;
	if (dataset instanceof SparqlifyDataset
			&& ((SparqlifyDataset) dataset).isSparqlService()
			&& ((SparqlifyDataset) dataset).getSparqlServiceUri() != null) {
		String serviceUri = ((SparqlifyDataset) dataset).getSparqlServiceUri();
		qe = QueryExecutionFactory.sparqlService(serviceUri, query);
	} else {
		qe = QueryExecutionFactory.create(query, dataset);
	}
	
	ResultSet res = qe.execSelect();
	
	while(res.hasNext()) {
		QuerySolution solution = res.nextSolution();
		RDFNode solNode = solution.get("p");
		properties.add(solNode.asNode());
	}
	qe.close();
	
	return properties;
}
 
Example 53
Project: JenaTutorial   File: AnotherSubclassExample.java   Source Code and License Vote up 4 votes
public static void main( String[] args )
{
	// load some data that uses RDFS
	Model data = FileManager.get().loadModel("file:data/input/turtle/ex10-data.ttl");
	
	Reasoner reasoner = ReasonerRegistry.getRDFSReasoner();
	reasoner.setParameter(ReasonerVocabulary.PROPsetRDFSLevel, 
               ReasonerVocabulary.RDFS_DEFAULT);
	InfModel infmodel = ModelFactory.createInfModel(reasoner, data );
	
	/* Do a SPARQL Query over the data in the model */
	String 	queryString = "SELECT ?x WHERE { ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.example.org/example#AllStarCandidate> }";



	/* Now create and execute the query using a Query object */
	Query query = QueryFactory.create(queryString) ;
	QueryExecution qexec = QueryExecutionFactory.create(query, infmodel) ;


	QueryExecUtils.executeQuery(qexec);
	
	System.out.println( "done" );
	
}
 
Example 54
Project: JenaTutorial   File: AnotherSubpropertyExample.java   Source Code and License Vote up 4 votes
public static void main( String[] args )
{
	// load some data that uses RDFS
	Model data = FileManager.get().loadModel("file:data/input/turtle/ex11-data.ttl");
	
	
	Reasoner reasoner = ReasonerRegistry.getRDFSReasoner();
	reasoner.setParameter(ReasonerVocabulary.PROPsetRDFSLevel, 
               ReasonerVocabulary.RDFS_DEFAULT);
	InfModel infmodel = ModelFactory.createInfModel(reasoner, data );
			
	
	String queryString = "SELECT ?x ?z WHERE { ?x <http://www.example.org/example#hasPossession> ?z }";

	/* Now create and execute the query using a Query object */
	Query query = QueryFactory.create(queryString) ;
	QueryExecution qexec = QueryExecutionFactory.create(query, infmodel) ;

	QueryExecUtils.executeQuery(qexec);
	
	System.out.println( "\n---------------\n" );		
	
}
 
Example 55
Project: lodreclib   File: QueryExecutor.java   Source Code and License Vote up 4 votes
/**
 * Execute SPARQL query 
 * @param     query  sparql query
 * @param     p  property
 * @return    results map: uri-s (if uri is a subject), uri-o (if uri is an object)
 */
private TObjectByteHashMap<String> executeQuery(Query query, String p) {
	
	TObjectByteHashMap<String> results = new TObjectByteHashMap<String>();
	QueryExecution qexec = null;
	
	if(model==null){
		if(graphURI == null)
			qexec = QueryExecutionFactory.sparqlService(endpoint, query); // remote query
		else
			qexec = QueryExecutionFactory.sparqlService(endpoint, query, graphURI); // remote query
	} 
	else
		qexec = QueryExecutionFactory.create(query, model); // local query
		
	try{
	
		//ResultSet res = qexec.execSelect();
		ResultSet res = ResultSetFactory.copyResults(qexec.execSelect()) ;
		
		QuerySolution qs;
		String n;
		
		while (res.hasNext()) {
			
			qs = res.next();
			
			if (qs.get("o") == null) {
				// get subject
				n = qs.get("s").toString();
				
				// consider only the type "yago"
				if (!p.contains("type"))
					results.put(n, (byte) 1); // target as subject
				else {
					if (n.contains("yago"))
						results.put(n, (byte) 1); // target as subject
				}
				
			}
			else {
				// get object
				n = qs.get("o").toString();
				
				// consider only the type "yago"
				if (!p.contains("type"))
					results.put(n, (byte) 0); // target as object
				else {
					if (n.contains("yago"))
						results.put(n, (byte) 0); // target as object
				}
			}
		}
	}
	
	catch(Exception e){
		e.printStackTrace();
	}
	finally{
		//qexec.close();
	}
	
	return results;
	
}
 
Example 56
Project: JenaTutorial   File: MoreComplicatedPropertiesExample.java   Source Code and License Vote up 3 votes
public static void main( String[] args )
{
	// load some data that uses RDFS
	Model data = FileManager.get().loadModel("file:data/input/turtle/ex24-data.ttl");
	
	
	Reasoner reasoner = ReasonerRegistry.getOWLReasoner();
	InfModel infmodel = ModelFactory.createInfModel(reasoner, data );
	
	/* Do a SPARQL Query over the data in the model */
	String queryString = "SELECT ?z WHERE { <http://www.example.org/example#GraduallyMix> <http://www.example.org/example#dependsOn> ?z }";

	/* Now create and execute the query using a Query object */
	Query query = QueryFactory.create(queryString) ;
	QueryExecution qexec = QueryExecutionFactory.create(query, infmodel) ;

	QueryExecUtils.executeQuery(qexec);
	
	System.out.println( "\n---------------\n" );		
	
	queryString = "SELECT ?z WHERE { <http://www.example.org/example#GraduallyMix> <http://www.example.org/example#hasPrerequisite> ?z }";

	/* Now create and execute the query using a Query object */
	query = QueryFactory.create(queryString) ;
	qexec = QueryExecutionFactory.create(query, infmodel) ;

	QueryExecUtils.executeQuery(qexec);
	
	System.out.println( "\n---------------\n" );		
}
 
Example 57
Project: JenaTutorial   File: JenaTextMain1.java   Source Code and License Vote up 2 votes
public static void main(String[] args) 
{
	
	TextQuery.init();
	
	Dataset dataset = DatasetFactory.createMem();
	
	EntityDefinition entDef = new EntityDefinition("uri", "text", RDFS.label.asNode()) ;

	// Lucene, in memory.
	Directory dir =  new RAMDirectory();

	// Join together into a dataset
	Dataset ds = TextDatasetFactory.createLucene(dataset, dir, entDef);
	
	
	Model m = ds.getDefaultModel();

	Resource rSubject = m.createResource( "http://ontology.fogbeam.com/example/TestResource1" );
	Resource rSubject2 = m.createResource( "http://ontology.fogbeam.com/example/TestResource2" );
	
	try
	{
	
		Statement s = m.createStatement(rSubject, RDFS.label, "This is a Test Resource" );
	
		m.add( s );
	
		Statement s2 = m.createStatement(rSubject2, RDFS.label, "Bratwurst Test" );
		
		m.add( s2 );
		
		String baseQueryString =
				"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " +
				"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> " +
				"PREFIX dc: <http://purl.org/dc/elements/1.1/> " +
				"PREFIX dcterm: <http://purl.org/dc/terms/> " +
				"PREFIX owl: <http://www.w3.org/2002/07/owl#> " +
				"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
				"PREFIX text: <http://jena.apache.org/text#>";
					
				
		/* Do a SPARQL query using Jena-Text here... */
		String queryString = baseQueryString + " SELECT * { ?s  text:query( 'Test') ; . ?s rdfs:label ?label . }";
			
			
		Query query = QueryFactory.create(queryString) ;
			
			
		QueryExecution qexec = QueryExecutionFactory.create(query, ds );
		QueryExecUtils.executeQuery(qexec);
		
		m.close();
		
		
	}
	catch( Exception e )
	{
		e.printStackTrace();
	}
	
	System.out.println( "done" );
}