Java Code Examples for com.hp.hpl.jena.query.Query

The following are top voted examples for showing how to use com.hp.hpl.jena.query.Query. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: DocIT   File: Containment.java   Source Code and License 6 votes vote down vote up
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 6 votes vote down vote up
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 6 votes vote down vote up
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: PigSPARQL   File: PigOrder.java   Source Code and License 6 votes vote down vote up
private String getOrderArg(SortCondition condition) {
    String orderArg = condition.getExpression().getVarName();
    int direction = condition.getDirection();

    switch(direction) {
        case Query.ORDER_ASCENDING: {
            orderArg += " ASC";
            break;
        }
        case Query.ORDER_DESCENDING: {
            orderArg += " DESC";
            break;
        }
        case Query.ORDER_DEFAULT: {
            break;
        }
    }
    
    return orderArg;
}
 
Example 5
Project: r2rml-kit   File: SPARQLExample.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
	ModelD2RQ m = new ModelD2RQ("file:doc/example/mapping-iswc.ttl");
	String sparql = 
		"PREFIX dc: <http://purl.org/dc/elements/1.1/>" +
		"PREFIX foaf: <http://xmlns.com/foaf/0.1/>" +
		"SELECT ?paperTitle ?authorName WHERE {" +
		"    ?paper dc:title ?paperTitle . " +
		"    ?paper dc:creator ?author ." +
		"    ?author foaf:name ?authorName ." +
		"}";
	Query q = QueryFactory.create(sparql); 
	ResultSet rs = QueryExecutionFactory.create(q, m).execSelect();
	while (rs.hasNext()) {
		QuerySolution row = rs.nextSolution();
		System.out.println("Title: " + row.getLiteral("paperTitle").getString());
		System.out.println("Author: " + row.getLiteral("authorName").getString());
	}
	m.close();
}
 
Example 6
Project: c4a_data_repository   File: SPARQLExample.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
	ModelD2RQ m = new ModelD2RQ("file:doc/example/mapping-iswc.ttl");
	String sparql = 
		"PREFIX dc: <http://purl.org/dc/elements/1.1/>" +
		"PREFIX foaf: <http://xmlns.com/foaf/0.1/>" +
		"SELECT ?paperTitle ?authorName WHERE {" +
		"    ?paper dc:title ?paperTitle . " +
		"    ?paper dc:creator ?author ." +
		"    ?author foaf:name ?authorName ." +
		"}";
	Query q = QueryFactory.create(sparql); 
	ResultSet rs = QueryExecutionFactory.create(q, m).execSelect();
	while (rs.hasNext()) {
		QuerySolution row = rs.nextSolution();
		System.out.println("Title: " + row.getLiteral("paperTitle").getString());
		System.out.println("Author: " + row.getLiteral("authorName").getString());
	}
	m.close();
}
 
Example 7
Project: c4a_data_repository   File: SdbSqlEqualityTest.java   Source Code and License 6 votes vote down vote up
private List<Query> loadAllQueries() throws IOException
{
	File queryDir;
	File[] files;
	List<Query> queries;
	
	queries = new ArrayList<Query>();
	
	queryDir = new File(CURR_DIR + "/" + QUERY_DIR);
	files = queryDir.listFiles();
	Arrays.sort(files);
	
	for(int i = 0; i < files.length; i++)
	{
		readRecursiveAndCreateQuery(files[i], queries);
	}
	
	return queries;
}
 
Example 8
Project: freme-ner   File: SPARQLProcessor.java   Source Code and License 6 votes vote down vote up
private Set<String> getTypesFromSPARQL(String sparqlQueryString) {

        Query query = QueryFactory.create(sparqlQueryString);
        QueryExecution qexec = QueryExecutionFactory.sparqlService(this.endpoint, query);
        Set<String> types = new HashSet<>();

        ResultSet results = qexec.execSelect();
        while(results.hasNext()) {
            QuerySolution qs = results.next();
            Resource type = qs.getResource("?type");
            types.add(type.getURI());
        }

        qexec.close();
        return types;
    }
 
Example 9
Project: WikiOnto   File: Ontogui.java   Source Code and License 6 votes vote down vote up
private void runQueryButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_runQueryButtonActionPerformed
	List<String> lines = null;
	try {
		lines = Files.readAllLines(queryPath);
	} catch (IOException ex) {
		Logger.getLogger(Ontogui.class.getName()).log(Level.SEVERE, null,
				ex);
	}
	String queryString = "";
	for (String line : lines) {
		queryString += line + System.lineSeparator();
	}
	Query query = QueryFactory.create(queryString, Syntax.syntaxARQ);
	queryResultArea.setText("Starting query: "
			+ queryPath.toFile().getName() + "\n");
	Thread t = new Thread(new QueryProcessor(query, new QueryAreaStream(
			queryResultArea), dataset, checkbox1.getState()));
	t.start();
}
 
Example 10
Project: WikiOnto   File: Ontogui.java   Source Code and License 6 votes vote down vote up
private void runSmellAnalysisButtonActionPerformed(
		java.awt.event.ActionEvent evt) {// GEN-FIRST:event_runSmellAnalysisButtonActionPerformed
	String filename = smellName;
	File smellFile = new File(System.getProperty("user.dir")
			+ "/sparql/smells/" + filename.replaceAll(" ", "") + ".sparql");

	List<String> lines = null;

	try {
		lines = Files.readAllLines(smellFile.toPath());
	} catch (IOException ex) {
		Logger.getLogger(Ontogui.class.getName()).log(Level.SEVERE, null,
				ex);
	}
	String queryString = "";
	for (String line : lines) {
		queryString += line + System.lineSeparator();
	}
	Query query = QueryFactory.create(queryString, Syntax.syntaxARQ);
	queryResultArea.setText("Starting analysis: " + smellName + "\n");
	Thread t = new Thread(new QueryProcessor(query, new QueryAreaStream(
			queryResultArea), dataset, checkbox1.getState()));
	t.start();
}
 
Example 11
Project: WikiOnto   File: Ontogui.java   Source Code and License 6 votes vote down vote up
private void runMetricsButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_runMetricsButtonActionPerformed
	String folder = metricName.split(":")[0].toLowerCase();
	String filename = metricName.split(":")[1];
	File metricFile = new File(System.getProperty("user.dir")
			+ "/sparql/metrics/" + folder + "/" + filename + ".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();
	}
	Query query = QueryFactory.create(queryString, Syntax.syntaxARQ);
	queryResultArea.setText("Starting analysis:" + metricName + "\n");
	System.err.println(checkbox1.isEnabled());
	Thread t = new Thread(new QueryProcessor(query, new QueryAreaStream(
			queryResultArea), dataset, checkbox1.getState()));
	t.start();
}
 
Example 12
Project: sdh-vocabulary   File: VocabularyTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testMetric_TotalBuilds() {
	Query query =
		QueryFactory.
			create(
				loadResource("/metrics/total_builds.sparql"));
	QueryExecution queryExecution = null;
	try {
		queryExecution = QueryExecutionFactory.create(query, buildsDataSet());
		ResultSet results = queryExecution.execSelect();
		for(; results.hasNext();) {
			QuerySolution solution = results.nextSolution();
			long buildId = solution.getLiteral("total_builds").getLong();
			System.out.printf("Total builds: %d%n",buildId);
		}
	} finally {
		if (queryExecution != null) {
			queryExecution.close();
		}
	}
}
 
Example 13
Project: sdh-vocabulary   File: VocabularyTest.java   Source Code and License 6 votes vote down vote up
@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 14
Project: sdh-vocabulary   File: VocabularyTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testMetric_TotalExecutions_PerBuild() {
	Query query =
		QueryFactory.
			create(
				loadResource("/metrics/total_executions_per_build.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 buildId = shorten(solution.getResource("build").getURI());
			System.out.printf("Total executions of build %s: %d%n",buildId,total_executions);
		}
	} finally {
		if (queryExecution != null) {
			queryExecution.close();
		}
	}
}
 
Example 15
Project: sdh-vocabulary   File: VocabularyTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testMetric_TotalSuccesfulExecutions_Global() {
	Query query =
		QueryFactory.
			create(
				loadResource("/metrics/total_succesful_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 succesful executions: %d%n",total_executions);
		}
	} finally {
		if (queryExecution != null) {
			queryExecution.close();
		}
	}
}
 
Example 16
Project: sdh-vocabulary   File: VocabularyTest.java   Source Code and License 6 votes vote down vote up
@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 17
Project: sdh-vocabulary   File: VocabularyTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testMetric_TotalSuccesfulExecutions_PerBuild() {
	Query query =
		QueryFactory.
			create(
				loadResource("/metrics/total_succesful_executions_per_build.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 buildId = shorten(solution.getResource("build").getURI());
			System.out.printf("Total succesful executions of build %s: %d%n",buildId,total_executions);
		}
	} finally {
		if (queryExecution != null) {
			queryExecution.close();
		}
	}
}
 
Example 18
Project: sdh-vocabulary   File: VocabularyTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testMetric_TotalBrokenExecutions_Global() {
	Query query =
		QueryFactory.
			create(
				loadResource("/metrics/total_broken_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 broken executions: %d%n",total_executions);
		}
	} finally {
		if (queryExecution != null) {
			queryExecution.close();
		}
	}
}
 
Example 19
Project: sdh-vocabulary   File: VocabularyTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testMetric_TotalBrokenExecutions_PerBuild() {
	Query query =
		QueryFactory.
			create(
				loadResource("/metrics/total_broken_executions_per_build.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 buildId = shorten(solution.getResource("build").getURI());
			System.out.printf("Total broken executions of build %s: %d%n",buildId,total_executions);
		}
	} finally {
		if (queryExecution != null) {
			queryExecution.close();
		}
	}
}
 
Example 20
Project: reneviz   File: SparqlController.java   Source Code and License 6 votes vote down vote up
public String executeQuery() {

		Query query = QueryFactory.create(this.getQuery(), Syntax.syntaxARQ);

		Op op = Algebra.compile(query);

		try {
			
			if(new String("internal").equals(this.service)) {
				this.results = jenaService.runLocalOp(op);
			} else if (new String("external").equals(this.service)) {
				this.results = jenaService.runExternalOp(op);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		return ("success");
	}
 
Example 21
Project: lodreclib   File: TreeQueryExecutor.java   Source Code and License 6 votes vote down vote up
/**
 * Run SPARQL query 
 * @param     uri  uri resource
 * @param     p  property
 * @return    results map: uri-s (if uri is a subject), uri-o (if uri is an object)
 */
private TObjectCharHashMap<String> runQuery(String uri, String p){
	
	TObjectCharHashMap<String> results = new TObjectCharHashMap<String>();
	
	Query query;
	String q;
	
	q = "SELECT * WHERE {{?s " + p + " <" + uri + ">. FILTER isIRI(?s). } UNION " +
						"{<" + uri + "> " + p + " ?o ." + " FILTER isIRI(?o). }} ";
	
	logger.debug(q);
	
	try 
	{	
		query = QueryFactory.create(q);
		results = executeQuery(query, p);
	} 
	catch (Exception e) 
	{
		e.printStackTrace();
	}

	return results;
}
 
Example 22
Project: lodreclib   File: QueryExecutor.java   Source Code and License 6 votes vote down vote up
/**
 * Run SPARQL query 
 * @param     uri  resource uri
 * @param     p  property
 * @return    results map: uri-s (if uri is a subject), uri-o (if uri is an object)
 */
private TObjectByteHashMap<String> runQuery(String uri, String p){
	
	TObjectByteHashMap<String> results = new TObjectByteHashMap<String>();
	
	Query query;
	String q;
	
	q = "SELECT * WHERE {{?s " + p + " <" + uri + ">. FILTER isIRI(?s). } UNION " +
						"{<" + uri + "> " + p + " ?o ." + " FILTER isIRI(?o). }} ";
	
	logger.debug(q);
	
	try {	
		query = QueryFactory.create(q);
		results = executeQuery(query, p);
	} 
	catch (Exception e) {
		e.printStackTrace();
	}

	return results;
}
 
Example 23
Project: DoSeR   File: LimayeGroundtruthAnnotationParser.java   Source Code and License 6 votes vote down vote up
private String checkAvailability(String resource) {
	try {
		Query query = QueryFactory
				.create("SELECT ?label WHERE{ <"
						+ resource
						+ "> <http://www.w3.org/2000/01/rdf-schema#label> ?label. }");
		QueryExecution qe = QueryExecutionFactory.create(query, this.m_l);
		ResultSet results = qe.execSelect();
		if (results.hasNext()) {
			return resource;
		}
	} catch (Exception e) {
		return "";
	}
	return "";
}
 
Example 24
Project: DoSeR   File: LimayeGroundtruthAnnotationParser.java   Source Code and License 6 votes vote down vote up
private String checkRedirects(String resource) {
	String result = resource;
	try {

		Query query = QueryFactory
				.create("SELECT ?redirect WHERE{ <"
						+ resource
						+ "> <http://dbpedia.org/ontology/wikiPageRedirects> ?redirect. }");
		QueryExecution qe = QueryExecutionFactory.create(query, this.m);
		ResultSet results = qe.execSelect();
		while (results.hasNext()) {
			QuerySolution sol = results.nextSolution();
			result = sol.getResource("redirect").getURI();
		}
	} catch (Exception e) {
		return resource;
	}
	return result;
}
 
Example 25
Project: DoSeR   File: LimayeAnnotationParserWebTables.java   Source Code and License 6 votes vote down vote up
private String checkAvailability(String resource) {
	try {
		Query query = QueryFactory
				.create("SELECT ?label WHERE{ <"
						+ resource
						+ "> <http://www.w3.org/2000/01/rdf-schema#label> ?label. }");
		QueryExecution qe = QueryExecutionFactory.create(query, this.m_l);
		ResultSet results = qe.execSelect();
		if (results.hasNext()) {
			return resource;
		}
	} catch (Exception e) {
		return "";
	}
	return "";
}
 
Example 26
Project: DoSeR   File: LimayeAnnotationParserWebTables.java   Source Code and License 6 votes vote down vote up
private String checkRedirects(String resource) {
	String result = resource;
	try {

		Query query = QueryFactory
				.create("SELECT ?redirect WHERE{ <"
						+ resource
						+ "> <http://dbpedia.org/ontology/wikiPageRedirects> ?redirect. }");
		QueryExecution qe = QueryExecutionFactory.create(query, this.m);
		ResultSet results = qe.execSelect();
		while (results.hasNext()) {
			QuerySolution sol = results.nextSolution();
			result = sol.getResource("redirect").getURI();
		}
	} catch (Exception e) {
		return resource;
	}
	return result;
}
 
Example 27
Project: Jena-Based-Semantic-Web-Tutorial   File: HelloSemanticWeb.java   Source Code and License 6 votes vote down vote up
/**
 * RDF Navigation using SPARQL Query
 * 
 * @param model
 *            the RDF model
 * @param query
 *            SPARQL Query String
 * @param field
 *            the placeholder of filed in parameter query
 */
private static void sparql(Model model, String query, String field) {
	Query q = QueryFactory.create(query);
	QueryExecution qexec = QueryExecutionFactory.create(q, 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 name = qs.get(field);// using RDFNode currently
		if (name != null) {
			System.out.println("Hello to " + name);
		} else {
			System.out.println("No friends found!");
		}
	}
	qexec.close();
}
 
Example 28
Project: Localizr   File: DBPedia.java   Source Code and License 6 votes vote down vote up
/**
 * Queries DBPedia dataset for info based on the name of the city of the current location
 * @param location
 * @return
 */
public static DBPediaInfoObject poseInfoQuery(Location location) { 
	String sQuery = "";
	try {
        java.net.URL url = Play.class.getResource("/dbpedia_sparql.txt");
        java.nio.file.Path resPath = java.nio.file.Paths.get(url.toURI());
        sQuery= new String(java.nio.file.Files.readAllBytes(resPath), "UTF8");

           sQuery = sQuery.replace("SIMPLE_NAME", location.getSimpleName());

           Query query = QueryFactory.create(sQuery);
           QueryExecution qexec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", query);
           ResultSet results = qexec.execSelect();
           // Put result into a DBPediaInfoObject
           DBPediaInfoObject info = parseResult(results);
           qexec.close();

           return info;
	} catch (Exception e) {
		e.printStackTrace();
	}

       return null;
}
 
Example 29
Project: Localizr   File: GeoNamesRecommendation.java   Source Code and License 6 votes vote down vote up
/**
  * Gets and returns the geolocation of a POI
  * @param resource
  * @return
  */
 private static Literal getGeoLocation(String resource){
 	
 	Literal geoLocation;
 	
 	String sparqlquery= "PREFIX geo:<http://www.w3.org/2003/01/geo/wgs84_pos#> \n"			
				+ "select distinct ?geolocation where {" 
				+ "<"+resource+"> geo:geometry ?geolocation.}\n"
				+ "LIMIT 1 ";
 	Query query = QueryFactory.create(sparqlquery);
  QueryExecution qexec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", query);
  ResultSet results = qexec.execSelect();
  if (results.hasNext() ){ 				
QuerySolution soln = results.nextSolution();
geoLocation = soln.getLiteral("geolocation");
   qexec.close();
   return geoLocation;
  }
  else {
   qexec.close();
  	return null;
  }
 }
 
Example 30
Project: Localizr   File: GeoNamesRecommendation.java   Source Code and License 6 votes vote down vote up
/**
 * Queries for the supertypes of the given resource
 * @param resource
 * @return
 */
private static List<Resource> retrieveHierarchyTwo(String resource){
	
	String sparqlquery= "PREFIX dbpedia-owl:<http://dbpedia.org/ontology/> \n"
+ "PREFIX geo:<http://www.w3.org/2003/01/geo/wgs84_pos#> \n"
+ "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> \n"
+ "PREFIX foaf:<http://xmlns.com/foaf/0.1/> \n"
+ "PREFIX xsd:<http://www.w3.org/2001/XMLSchema#> \n"
+ "select distinct ?super ?subclass where {" 
+ "<"+resource+"> a ?super.\n"
+ "<"+resource+">  a ?subclass.\n"
+ "?subclass rdfs:subClassOf ?super.\n"
+ "FILTER (?subclass!=?super)}";
	
	Query query = QueryFactory.create(sparqlquery);
 QueryExecution qexec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", query);
 ResultSet results = qexec.execSelect();
 
 // Parse the result to avoid transitivity and thus repetition of types
 List<Resource> hierarchy_two = parseResult(results);
 qexec.close();
 
 return hierarchy_two;

}
 
Example 31
Project: openimaj   File: SparqlQueryPager.java   Source Code and License 6 votes vote down vote up
private ArrayList<QuerySolution> fetch(String pageQueryString) {
	ArrayList<QuerySolution> result = new ArrayList<QuerySolution>();
	Query q = QueryFactory.create(pageQueryString);
	QueryExecution qexec =QueryExecutionFactory.sparqlService(endPoint, q);
	ResultSet results;
	try {
		results = qexec.execSelect();		
		for (; results.hasNext();) {
			QuerySolution soln = results.nextSolution();
			result.add(soln);				
		}
	}
	catch(Exception e){
		e.printStackTrace();
		return null;
	}		
	finally {
		qexec.close();
	}		
	return result;
}
 
Example 32
Project: semweb4j   File: ModelImplJena.java   Source Code and License 6 votes vote down vote up
@Override
public ClosableIterable<Statement> sparqlConstruct(String queryString)
        throws ModelRuntimeException {
	assertModel();
	Query query = QueryFactory.create(queryString);
	QueryExecution qexec = QueryExecutionFactory.create(query, this.jenaModel);
	
	if(query.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 queries! Please use CONSTRUCT.");
	}
}
 
Example 33
Project: semweb4j   File: ModelImplJena.java   Source Code and License 6 votes vote down vote up
/**
 * @return opened result Model
 */
@Override
public ClosableIterable<Statement> sparqlDescribe(String queryString)
        throws ModelRuntimeException {
	assertModel();
	Query query = QueryFactory.create(queryString);
	QueryExecution qexec = QueryExecutionFactory.create(query, this.jenaModel);
	
	if(query.isDescribeType()) {
		com.hp.hpl.jena.rdf.model.Model m = qexec.execDescribe();
		Model resultModel = new ModelImplJena(null, m, Reasoning.none);
		resultModel.open();
		return resultModel;
	} else {
		throw new RuntimeException("Cannot handle this type of queries! Please use DESCRIBE.");
	}
	
}
 
Example 34
Project: semweb4j   File: ModelSetImplJena.java   Source Code and License 6 votes vote down vote up
@Override
public ClosableIterable<Statement> queryConstruct(String query,
		String querylanguage) throws QueryLanguageNotSupportedException,
		MalformedQueryException, ModelRuntimeException {

	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 35
Project: semweb4j   File: ModelSetImplJena.java   Source Code and License 6 votes vote down vote up
@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 36
Project: semweb4j   File: ModelSetImplJena.java   Source Code and License 6 votes vote down vote up
@Override
public ClosableIterable<Statement> sparqlDescribe(String query)
		throws ModelRuntimeException {
	Query jenaQuery = QueryFactory.create(query);
	QueryExecution qexec = QueryExecutionFactory.create(jenaQuery,
			this.dataset);

	if (jenaQuery.isDescribeType()) {
		com.hp.hpl.jena.rdf.model.Model m = qexec.execDescribe();
		Model resultModel = new ModelImplJena(null, m, Reasoning.none);
		resultModel.open();
		return resultModel;
	} else {
		throw new RuntimeException(
				"Cannot handle this type of query! Please use DESCRIBE.");
	}
}
 
Example 37
Project: OpenCollegeGraph   File: SPARQLExample.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
	ModelD2RQ m = new ModelD2RQ("file:doc/example/mapping-iswc.ttl");
	String sparql = 
		"PREFIX dc: <http://purl.org/dc/elements/1.1/>" +
		"PREFIX foaf: <http://xmlns.com/foaf/0.1/>" +
		"SELECT ?paperTitle ?authorName WHERE {" +
		"    ?paper dc:title ?paperTitle . " +
		"    ?paper dc:creator ?author ." +
		"    ?author foaf:name ?authorName ." +
		"}";
	Query q = QueryFactory.create(sparql); 
	ResultSet rs = QueryExecutionFactory.create(q, m).execSelect();
	while (rs.hasNext()) {
		QuerySolution row = rs.nextSolution();
		System.out.println("Title: " + row.getLiteral("paperTitle").getString());
		System.out.println("Author: " + row.getLiteral("authorName").getString());
	}
	m.close();
}
 
Example 38
Project: OpenCollegeGraph   File: SdbSqlEqualityTest.java   Source Code and License 6 votes vote down vote up
private List<Query> loadAllQueries() throws IOException
{
	File queryDir;
	File[] files;
	List<Query> queries;
	
	queries = new ArrayList<Query>();
	
	queryDir = new File(CURR_DIR + "/" + QUERY_DIR);
	files = queryDir.listFiles();
	Arrays.sort(files);
	
	for(int i = 0; i < files.length; i++)
	{
		readRecursiveAndCreateQuery(files[i], queries);
	}
	
	return queries;
}
 
Example 39
Project: lodreclib   File: QueryExecutor.java   Source Code and License 6 votes vote down vote up
/**
 * Run SPARQL query 
 * @param     uri  resource uri
 * @param     p  property
 * @return    results map: uri-s (if uri is a subject), uri-o (if uri is an object)
 */
private TObjectByteHashMap<String> runQuery(String uri, String p){
	
	TObjectByteHashMap<String> results = new TObjectByteHashMap<String>();
	
	Query query;
	String q;
	
	q = "SELECT * WHERE {{?s " + p + " <" + uri + ">. FILTER isIRI(?s). } UNION " +
						"{<" + uri + "> " + p + " ?o ." + " FILTER isIRI(?o). }} ";
	
	logger.debug(q);
	
	try {	
		query = QueryFactory.create(q);
		results = executeQuery(query, p);
	} 
	catch (Exception e) {
		e.printStackTrace();
	}

	return results;
}
 
Example 40
Project: aliada-tool   File: AliadaRDFStoreDAO.java   Source Code and License 6 votes vote down vote up
public String crm2AliadaClass(final String crmClass) {
	final Query query = QueryFactory.create(CRM_TO_ALIADA_CLASS_P1 + crmClass + CRM_TO_ALIADA_CLASS_P2);
	ARQ.getContext().setTrue(ARQ.useSAX);
       
	QueryExecution execution = null;
	try {
		execution = QueryExecutionFactory.sparqlService("http://172.25.5.15:8890/sparql", query);
		execution.setTimeout(2000, 5000);
		final ResultSet results = execution.execSelect();
		//Iterating over the SPARQL Query results
		while (results.hasNext()) {
			QuerySolution soln = results.nextSolution();
			//Printing DBpedia entries' abstract.
			System.out.println(soln.get("?abstract"));   
			return soln.get("?abstract").asResource().getURI();
		}
		return "NULL";
       } finally {
       	try {
       		execution.close();
		} catch (Exception exception) {
			// TODO: handle exception
		}
       }

}
 
Example 41
Project: shanks-wsn-module   File: ZigBeeCoordiantorNodeSoftware.java   Source Code and License 6 votes vote down vote up
/**
 * @param rulesFile
 * @param model
 * @throws FileNotFoundException
 */
private void loadSPINRules(String rulesFile, OntModel model) throws FileNotFoundException {

	this.getLogger().fine("---> loadSPINRules(): Starting to load rules from " + rulesFile);
	Scanner scanner = new Scanner(new File(rulesFile)).useDelimiter("\\n---\\n");

	int i = 0;
	while (scanner.hasNext()) {
		i++;
		String uri = scanner.next();
		String rule = scanner.next();
		Query arqQuery = ARQFactory.get().createQuery(model, rule);
		ARQ2SPIN arq2SPIN = new ARQ2SPIN(model);
		org.topbraid.spin.model.Query spinQuery = arq2SPIN.createQuery(arqQuery, null);
		Resource resource = model.getResource(uri);
		resource.addProperty((Property) SPIN.rule, spinQuery);
	}
	this.getLogger().info("<--- loadSPINRules(): " + i + " rules loaded from file: " + rulesFile);
}
 
Example 42
Project: R2RLint   File: SparqlifyDataset.java   Source Code and License 6 votes vote down vote up
@Override
public long size() {
	if (sparqlWrapping) {
		if (size < 0 || !cachingEnabled) {
			Query query = QueryFactory.create(
					"SELECT DISTINCT (count(*) AS ?count) {?s ?p ?o}");
			QueryExecution qe = QueryExecutionFactory.sparqlService(
					((SparqlGraph) getGraph()).getServiceUri(),
					query);
			ResultSet res = qe.execSelect();
			RDFNode count = null;
			while(res.hasNext())
			{
				QuerySolution sol = res.nextSolution();
				count = sol.get("count").asLiteral();
			}
			qe.close();
			
			return count.asLiteral().getLong();
		} else {
			return size;
		}
	} else {
		return super.size();
	}
}
 
Example 43
Project: R2RLint   File: PopulationCompleteness.java   Source Code and License 6 votes vote down vote up
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 44
Project: Luzzu   File: DAQHelper.java   Source Code and License 6 votes vote down vote up
private static Resource getDomainResource(Resource uri){
	String whereClause = "?prop " + " " + SPARQLHelper.toSPARQL(RDFS.range) + SPARQLHelper.toSPARQL(uri) + " . ";
	whereClause = whereClause + " ?prop " + SPARQLHelper.toSPARQL(RDFS.domain) + " ?domain .";
	
	Model m = InternalModelConf.getFlatModel();
	String query = SPARQLHelper.SELECT_STATEMENT.replace("[variables]", "?domain").replace("[whereClauses]", whereClause);
	Resource r = null;
	Query qry = QueryFactory.create(query);
    QueryExecution qe = QueryExecutionFactory.create(qry, m);
    ResultSet rs = qe.execSelect();

    while (rs.hasNext()){
    	r = rs.next().get("domain").asResource();
    }
    
    return r;
}
 
Example 45
Project: R2RLint   File: NoResourceNameClashes.java   Source Code and License 6 votes vote down vote up
/**
 * This method finds all individuals (= instances of owl:Class)
 * 
 * @param dataset
 */
private void initIndividuals(SparqlifyDataset dataset) {
	String indivQueryStr =
			"SELECT distinct ?indiv {" +
				"?indiv a ?cls . ?cls a <" + OWL.Class.getURI() + "> }";
	
	Query indivQuery = QueryFactory.create(indivQueryStr);
	QueryExecution indivQe;
	if (dataset.isSparqlService() && dataset.getSparqlServiceUri()!=null) {
		indivQe = QueryExecutionFactory.createServiceRequest(
				dataset.getSparqlServiceUri(), indivQuery);
	} else {
		indivQe = QueryExecutionFactory.create(indivQuery, dataset);
	}
	
	ResultSet indivRes = indivQe.execSelect();
	while (indivRes.hasNext()) {
		QuerySolution sol = indivRes.next();
		Node indiv = sol.get("indiv").asNode();
		individuals.add(indiv);
	}
}
 
Example 46
Project: VirtualSPARQLer   File: SPARQLExample.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
	ModelD2RQ m = new ModelD2RQ("file:doc/example/mapping-iswc.ttl");
	String sparql = 
		"PREFIX dc: <http://purl.org/dc/elements/1.1/>" +
		"PREFIX foaf: <http://xmlns.com/foaf/0.1/>" +
		"SELECT ?paperTitle ?authorName WHERE {" +
		"    ?paper dc:title ?paperTitle . " +
		"    ?paper dc:creator ?author ." +
		"    ?author foaf:name ?authorName ." +
		"}";
	Query q = QueryFactory.create(sparql); 
	ResultSet rs = QueryExecutionFactory.create(q, m).execSelect();
	while (rs.hasNext()) {
		QuerySolution row = rs.nextSolution();
		System.out.println("Title: " + row.getLiteral("paperTitle").getString());
		System.out.println("Author: " + row.getLiteral("authorName").getString());
	}
	m.close();
}
 
Example 47
Project: neo4jena   File: Course_Test.java   Source Code and License 6 votes vote down vote up
public static void getJob(GraphDatabaseService njgraph)
{
	NeoGraph graph = new NeoGraph(njgraph);
	Model njmodel = ModelFactory.createModelForGraph(graph);
	
	ST descJob = TemplateLoader.getQueriesGroup().getInstanceOf("getGraph");
	String queryASString = Constants.QUERY_PREFIX+ descJob.render();
	
	Query query = QueryFactory.create(queryASString, Syntax.syntaxSPARQL_11);
	QueryExecution qexec = QueryExecutionFactory.create(query, njmodel);
	ResultSet res = qexec.execSelect();
	
	int count=0;
       while(res.hasNext()){
       	//System.out.println("in while"+count);
       	QuerySolution sol = res.next();
       	System.out.println(sol.get("?Z"));
       	count++;
       }
      
      //log.info("Record fetched:"+ count);
      System.out.println("Record fetched:"+ count);
}
 
Example 48
Project: RdfLiteralStats   File: NquadsTest.java   Source Code and License 6 votes vote down vote up
public void doit() {
	Dataset dataset = DatasetFactory.createMem();
	
	Model model = dataset.getDefaultModel();
	model.read("category_labels_en.nq");
	if (model.READ){
		System.out.println("right!!");
	}
	Query q = QueryFactory.create(query);
	QueryExecution qe = QueryExecutionFactory.create(q, model);
	ResultSet rs = qe.execSelect();
	ResultSetFormatter.out(rs);
	
	

}
 
Example 49
Project: Luzzu   File: DAQHelper.java   Source Code and License 6 votes vote down vote up
public static Resource getPropertyResource(Resource uri){
	String whereClause = "?prop " + " " + SPARQLHelper.toSPARQL(RDFS.range) + SPARQLHelper.toSPARQL(uri) + " . ";
	
	Model m = InternalModelConf.getFlatModel();
	String query = SPARQLHelper.SELECT_STATEMENT.replace("[variables]", "?prop").replace("[whereClauses]", whereClause);
	Resource r = null;
	Query qry = QueryFactory.create(query);
    QueryExecution qe = QueryExecutionFactory.create(qry, m);
    ResultSet rs = qe.execSelect();
    
    while (rs.hasNext()){
    	r = rs.next().get("prop").asResource();
    }
    
    return r;
}
 
Example 50
Project: OWL2SPARQL   File: OWLAxiomToSPARQLConverterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testDisjointPropertiesAxiom() {
	OWLAxiom axiom = df.getOWLDisjointObjectPropertiesAxiom(propR, propS, propT);
	
	Query targetQuery = QueryFactory.create("SELECT DISTINCT  ?s\n" + 
			"WHERE\n" + 
			"  {   { ?s <r> ?o\n" + 
			"        FILTER NOT EXISTS {?s <s> ?o }\n" + 
			"        FILTER NOT EXISTS {?s <t> ?o }\n" + 
			"      }\n" + 
			"    UNION\n" + 
			"      { ?s <s> ?o\n" + 
			"        FILTER NOT EXISTS {?s <r> ?o }\n" + 
			"        FILTER NOT EXISTS {?s <t> ?o }\n" + 
			"      }\n" + 
			"    UNION\n" + 
			"      { ?s <t> ?o\n" + 
			"        FILTER NOT EXISTS {?s <r> ?o }\n" + 
			"        FILTER NOT EXISTS {?s <s> ?o }\n" + 
			"      }\n" + 
			"  }");
	Query query = converter.asQuery(axiom);
	
	assertTrue("Conversion of axiom " + axiom + " failed.\n" + query + " does not match " + targetQuery, query.equals(targetQuery));
}
 
Example 51
Project: jena-nosql   File: SparqlSelectIntegrationTestCase.java   Source Code and License 6 votes vote down vote up
@Override
protected void executeTestWithFile(final String filename) throws Exception {
	final Query query = QueryFactory.create(queryString(filename + ".rq"));
	QueryExecution execution = null;
	QueryExecution inMemoryExecution = null;
	
	try {
		assertTrue(
				ResultSetCompare.isomorphic(
						(execution = QueryExecutionFactory.create(query, dataset)).execSelect(),
						(inMemoryExecution = QueryExecutionFactory.create(query, memoryDataset)).execSelect()));
	} finally {
		// CHECKSTYLE:OFF
		if (execution != null) { execution.close(); }
		if (inMemoryExecution != null) { inMemoryExecution.close(); }
		// CHECKSTYLE:ON
	}		
}
 
Example 52
Project: jena-nosql   File: SparqlConstructIntegrationTestCase.java   Source Code and License 6 votes vote down vote up
@Override
protected void executeTestWithFile(final String filename) throws Exception {
	final Query query = QueryFactory.create(queryString(filename + ".rq"));
	QueryExecution execution = null;
	QueryExecution inMemoryExecution = null;
	
	try {
		assertTrue(
				(execution = QueryExecutionFactory.create(query, dataset))
					.execConstruct()
					.isIsomorphicWith(
							(inMemoryExecution = QueryExecutionFactory.create(query, memoryDataset))
							.execConstruct()));
	} finally {
		// CHECKSTYLE:OFF
		if (execution != null) { execution.close(); }
		if (inMemoryExecution != null) { inMemoryExecution.close(); }
		// CHECKSTYLE:ON
	}					
}
 
Example 53
Project: JenaTutorial   File: OWL_WeirdInference.java   Source Code and License 6 votes vote down vote up
public static void main( String[] args )
{
	// load some data that uses RDFS
	Model data = FileManager.get().loadModel("file:data/input/turtle/ex19-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.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( "done" );		
}
 
Example 54
Project: RdfLiteralStats   File: JenaTesting.java   Source Code and License 6 votes vote down vote up
public void queryResultSet() {

		Query q = QueryFactory.create(query);
		QueryExecution qe = QueryExecutionFactory.create(q, model);
		ResultSet rs = qe.execSelect();
		while (rs.hasNext()) {
			QuerySolution soln = rs.nextSolution();
			// RDFNode x = soln.get("?o") ; // Get a result variable by name.
			// Resource r = soln.getResource("?o"); // Get a result variable -
			// must be a resource
			Literal l = soln.getLiteral("?o"); // Get a result variable - must
												// be a literal
			literalsListDuplicates.add(l.getLexicalForm());
			literalsListNODuplicates.add(l.getLexicalForm());
		}
		// NodeIterator itr = model.listObjects();
		// while (itr.hasNext()) {
		// System.out.println(itr.next());
		// }

	}
 
Example 55
Project: com.inova8.remediator   File: Linkset.java   Source Code and License 6 votes vote down vote up
@Override
public void loadVocabularies() {

	QuerySolutionMap binding = new QuerySolutionMap();
	binding.add("linkset", this.dataset);
	Query query = QueryFactory.create(linksetVocabularyQuery);
	QueryExecution qexec = QueryExecutionFactory.create(query, voidInstance.getVoidModel(),
			binding);

	try {
		ResultSet results = qexec.execSelect();
		for (; results.hasNext();) {
			QuerySolution soln = results.nextSolution();
			OntResource vocabulary = soln.getResource("vocabulary").as(
					OntResource.class);
			vocabularies.add(vocabulary);
		}
	} catch (Exception e) {
		Log.debug(Linkset.class, "Failed linksetVocabularyQuery");
		Log.debug(Linkset.class, e.getStackTrace().toString());
	} finally {
		qexec.close();
	}

}
 
Example 56
Project: Luzzu   File: DAQHelper.java   Source Code and License 6 votes vote down vote up
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 57
Project: Luzzu   File: DAQHelper.java   Source Code and License 6 votes vote down vote up
public static String getDimensionForMetric(Resource metricURI){
	Model m = InternalModelConf.getFlatModel();
	
	String whereClause = "?dimension ?prop " + SPARQLHelper.toSPARQL(metricURI) +
			"?prop " + SPARQLHelper.toSPARQL(RDFS.subPropertyOf) + SPARQLHelper.toSPARQL(DAQ.hasMetric) + " .";
			
	String query = SPARQLHelper.SELECT_STATEMENT.replace("[variables]", "?dimension").replace("[whereClauses]", whereClause);
	Query qry = QueryFactory.create(query);
    QueryExecution qe = QueryExecutionFactory.create(qry, m);
    ResultSet rs = qe.execSelect();
    
    String dim = "";
    while (rs.hasNext()){
    	QuerySolution qs = rs.next();
    	dim = qs.get("dimension").asResource().getURI();
    }
	
    return dim;
}
 
Example 58
Project: com.inova8.remediator   File: Datasets.java   Source Code and License 6 votes vote down vote up
public void loadClassPartitionStatistics(OntModel voidModel) {
	Query query = QueryFactory.create(classPartitionStatisticsQuery);
	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 clazz = soln.getResource("Class").as(
					OntResource.class);
			Integer entities = (soln.getLiteral("Entities") != null) ? soln
					.getLiteral("Entities").getInt() : null;	
			Dataset ds = this.getDataset(dataset);		
			if (ds!=null)ds.getPartitions().addClassPartition(clazz, entities);
		}
	} catch (Exception e) {
		Log.debug(
				this,
				"Unable to execute classPartitionStatisticsQuery " + query);
	} finally {
		qexec.close();
	}
}
 
Example 59
Project: JenaTutorial   File: TermReconcilation_UnionPattern.java   Source Code and License 6 votes vote down vote up
public static void main( String[] args )
{
	// load some data that uses RDFS
	Model data = FileManager.get().loadModel("file:data/input/turtle/ex12-data2.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#Investigator> }";

	/* 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 60
Project: com.inova8.remediator   File: Dataset.java   Source Code and License 6 votes vote down vote up
public void loadVocabularies() {

		QuerySolutionMap binding = new QuerySolutionMap();
		binding.add("dataset", dataset);
		Query query = QueryFactory.create(datasetVocabularyQuery);
		QueryExecution qexec = QueryExecutionFactory.create(query, voidInstance.getVoidModel(),
				binding);

		try {
			ResultSet results = qexec.execSelect();
			for (; results.hasNext();) {
				QuerySolution soln = results.nextSolution();
				OntResource vocabulary = soln.getResource("vocabulary").as(
						OntResource.class);
				vocabularies.add(vocabulary);
			}
		} catch (Exception e) {
			Log.debug(Dataset.class, "Failed datasetVocabularyQuery");
			Log.debug(Dataset.class, e.getStackTrace().toString());

		} finally {
			qexec.close();
		}
	}