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

The following are top voted examples for showing how to use com.hp.hpl.jena.query.ResultSet. 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: harvesters   File: Queries.java   Source Code and License 7 votes vote down vote up
public Resource getAgentUri(VirtGraph graphOrgs, String vatId) {
	
	Resource agentUri = null;
	
	String queryUri = "PREFIX gr: <http://purl.org/goodrelations/v1#> " +
				"SELECT ?org ?vatId " +
				"FROM <" + QueryConfiguration.queryGraphOrganizations + "> " +
				"WHERE { " +
				"?org gr:vatID ?vatId . " +
				"FILTER ( ?vatId = \"" + vatId + "\"^^<http://www.w3.org/2001/XMLSchema#string> ) " +
				"}";

	VirtuosoQueryExecution vqeUri = VirtuosoQueryExecutionFactory.create(queryUri, graphOrgs);		
	ResultSet resultsUri = vqeUri.execSelect();
	
	if (resultsUri.hasNext()) {
		QuerySolution result = resultsUri.nextSolution();
		agentUri = result.getResource("org");
	}
	
	vqeUri.close();
	
	return agentUri;
}
 
Example 2
Project: r2rml-kit   File: R2RMLTest.java   Source Code and License 7 votes vote down vote up
@Parameters(name="{index}: {0}")
public static Collection<Object[]> getAllTestLists() {
	Collection<Object[]> results = new ArrayList<Object[]>();
	for (File dir: new File(TEST_SUITE_DIR).listFiles()) {
		if (!dir.isDirectory() || !new File(dir.getAbsolutePath() + "/manifest.ttl").exists()) continue;
		String absolutePath = dir.getAbsolutePath();
		Model model = FileManager.get().loadModel(absolutePath + "/manifest.ttl");
		ResultSet resultSet = QueryExecutionFactory.create(QUERY, model).execSelect();
		while (resultSet.hasNext()) {
			QuerySolution solution = resultSet.nextSolution();
			if (Arrays.asList(D2RQTestUtil.SKIPPED_R2RML_TESTS).contains(solution.getResource("s").getLocalName())) continue;
			results.add(new Object[]{
					PrettyPrinter.toString(solution.getResource("s")),
					absolutePath + "/create.sql",
					absolutePath + "/" + solution.getLiteral("rml").getLexicalForm(),
					(solution.get("nquad") == null) ? 
							null : 
							absolutePath + "/" + solution.getLiteral("nquad").getLexicalForm()
			});
		}
	}
	return results;
}
 
Example 3
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 4
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 5
Project: harvesters   File: Queries.java   Source Code and License 6 votes vote down vote up
public Resource getAgentUriNoVat(VirtGraph graphOrgs, String vatId) {
	
	Resource agentUri = null;
	
	String queryUri = "PREFIX gr: <http://purl.org/goodrelations/v1#> " +
				"SELECT DISTINCT ?org " +
				"FROM <" + QueryConfiguration.queryGraphOrganizations + "> " +
				"WHERE { " +
				"?org rdf:type foaf:Organization . " +
				"FILTER (STR(?org) = \"http://linkedeconomy.org/resource/Organization/" + vatId + "\") . " +
				"}";

	VirtuosoQueryExecution vqeUri = VirtuosoQueryExecutionFactory.create(queryUri, graphOrgs);		
	ResultSet resultsUri = vqeUri.execSelect();
	
	if (resultsUri.hasNext()) {
		QuerySolution result = resultsUri.nextSolution();
		agentUri = result.getResource("org");
	}
	
	vqeUri.close();
	
	return agentUri;
}
 
Example 6
Project: harvesters   File: Queries.java   Source Code and License 6 votes vote down vote up
public Resource getAgentUri(VirtGraph graphOrgs, String vatId) {
	
	Resource agentUri = null;
	
	String queryUri = "PREFIX gr: <http://purl.org/goodrelations/v1#> " +
				"SELECT ?org ?vatId " +
				"FROM <" + QueryConfiguration.queryGraphOrganizations + "> " +
				"WHERE { " +
				"?org gr:vatID ?vatId . " +
				"FILTER ( ?vatId = \"" + vatId + "\"^^<http://www.w3.org/2001/XMLSchema#string> ) " +
				"}";

	VirtuosoQueryExecution vqeUri = VirtuosoQueryExecutionFactory.create(queryUri, graphOrgs);		
	ResultSet resultsUri = vqeUri.execSelect();
	
	if (resultsUri.hasNext()) {
		QuerySolution result = resultsUri.nextSolution();
		agentUri = result.getResource("org");
	}
	
	vqeUri.close();
	
	return agentUri;
}
 
Example 7
Project: harvesters   File: Queries.java   Source Code and License 6 votes vote down vote up
public Resource getAgentUriNoVat(VirtGraph graphOrgs, String vatId) {
	
	Resource agentUri = null;
	
	String queryUri = "PREFIX gr: <http://purl.org/goodrelations/v1#> " +
				"SELECT DISTINCT ?org " +
				"FROM <" + QueryConfiguration.queryGraphOrganizations + "> " +
				"WHERE { " +
				"?org rdf:type foaf:Organization . " +
				"FILTER (STR(?org) = \"http://linkedeconomy.org/resource/Organization/" + vatId + "\") . " +
				"}";

	VirtuosoQueryExecution vqeUri = VirtuosoQueryExecutionFactory.create(queryUri, graphOrgs);		
	ResultSet resultsUri = vqeUri.execSelect();
	
	if (resultsUri.hasNext()) {
		QuerySolution result = resultsUri.nextSolution();
		agentUri = result.getResource("org");
	}
	
	vqeUri.close();
	
	return agentUri;
}
 
Example 8
Project: KBox   File: TDBTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testBulkLoad() throws URISyntaxException, IOException, OperationNotSupportedException {
	URL[] files = new URL[1];
	URL url = TDBTest.class.getResource("/org/aksw/kbox/kibe/dbpedia_3.9.xml");
	files[0] = url;
	java.nio.file.Path f = Files.createTempDirectory("kb");
	String path = f.toFile().getPath();
	TDB.bulkload(f.toFile().getPath(), files);
	Date start = new Date();
	ResultSet rs = TDB.query("Select ?p where {<http://dbpedia.org/ontology/Place> ?p ?o}", path);
	int i = 0;
	Date end = new Date();
	System.out.println(end.getTime() - start.getTime());
	while (rs != null && rs.hasNext()) {
		rs.next();
		i++;
	}
	assertEquals(19, i);
}
 
Example 9
Project: KBox   File: KBoxTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testQueryInstalledKB() throws Exception {
	ResultSet rs = KBox.query("Select ?p where {<http://dbpedia.org/ontology/Place> ?p ?o}",
			new URL("http://dbpedia39"));
	int i = 0;
	while (rs != null && rs.hasNext()) {
		rs.next();
		i++;
	}
	assertEquals(19, i);
	
	rs = KBox.query( 
			"Select ?p where {<http://dbpedia.org/ontology/Place> ?p ?o}",
			new URL("http://dbpedia39"));
	i = 0;
	while (rs != null && rs.hasNext()) {
	rs.next();
	i++;
	}
	assertEquals(19, i);
}
 
Example 10
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 11
Project: r2rml-kit   File: ProcessorTestBase.java   Source Code and License 6 votes vote down vote up
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 12
Project: r2rml-kit   File: MappingGeneratorTest.java   Source Code and License 6 votes vote down vote up
@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 13
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 14
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 15
Project: knowledge   File: MultiQueryEngine.java   Source Code and License 6 votes vote down vote up
@Override
public Result call() throws Exception
{
    QueryEngine engine = pool.getPool().borrowObject();
    try
    {
        ResultSet rs = engine.execSelect(q);

        Result r = new Result();
        r.resultSet = Collections.singletonList(rs);
        r.cursorMap.putAll(engine.getContext().getCursorMap());
        r.metaData.putAll(engine.getContext().getMetadata());

        return r;
    }
    finally
    {
        if (engine != null)
        {
            pool.getPool().returnObject(engine);
        }
    }
}
 
Example 16
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 17
Project: StreamEventCoreference   File: OwlReader.java   Source Code and License 6 votes vote down vote up
static void readOwlFile (String pathToOwlFile) {
        OntModel ontologyModel =
                ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, null);
        ontologyModel.read(pathToOwlFile, "RDF/XML-ABBREV");
       // OntClass myClass = ontologyModel.getOntClass("namespace+className");

        OntClass myClass = ontologyModel.getOntClass(ResourcesUri.nwr+"domain-ontology#Motion");
        System.out.println("myClass.toString() = " + myClass.toString());
        System.out.println("myClass.getSuperClass().toString() = " + myClass.getSuperClass().toString());

        //List list =
              //  namedHierarchyRoots(ontologyModel);


       Iterator i = ontologyModel.listHierarchyRootClasses()
                .filterDrop( new Filter() {
                    public boolean accept( Object o ) {
                        return ((Resource) o).isAnon();
                    }} ); ///get all top nodes and excludes anonymous classes

       // Iterator i = ontologyModel.listHierarchyRootClasses();
        while (i.hasNext()) {
            System.out.println(i.next().toString());
/*            OntClass ontClass = ontologyModel.getOntClass(i.next().toString());
            if (ontClass.hasSubClass()) {

            }*/
        }

        String q = createSparql("event", "<http://www.newsreader-project.eu/domain-ontology#Motion>");
        System.out.println("q = " + q);
        QueryExecution qe = QueryExecutionFactory.create(q,
                ontologyModel);
        for (ResultSet rs = qe.execSelect() ; rs.hasNext() ; ) {
            QuerySolution binding = rs.nextSolution();
            System.out.println("binding = " + binding.toString());
            System.out.println("Event: " + binding.get("event"));
        }

        ontologyModel.close();
    }
 
Example 18
Project: GPML2RDF   File: SPARQLHelper.java   Source Code and License 6 votes vote down vote up
public static StringMatrix sparql(String endpoint, String queryString)
		throws Exception {
	StringMatrix table = null;

	// use Apache for doing the SPARQL query
	DefaultHttpClient httpclient = new DefaultHttpClient();
	List<NameValuePair> formparams = new ArrayList<NameValuePair>();
	formparams.add(new BasicNameValuePair("query", queryString));
	UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
	HttpPost httppost = new HttpPost(endpoint);
	httppost.setEntity(entity);
	HttpResponse response = httpclient.execute(httppost);
	HttpEntity responseEntity = response.getEntity();
	InputStream in = responseEntity.getContent();

	// now the Jena part
	ResultSet results = ResultSetFactory.fromXML(in);
	// also use Jena for getting the prefixes...
	// Query query = QueryFactory.create(queryString);
	// PrefixMapping prefixMap = query.getPrefixMapping();
	table = convertIntoTable(null, results);

	in.close();
	return table;
}
 
Example 19
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 20
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 21
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 22
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 23
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 24
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 25
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 26
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 27
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 28
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 29
Project: DoSeR   File: FullyEvaluateCategories.java   Source Code and License 6 votes vote down vote up
private Set<String> queryEntitiesFromCategory(final String catUri) {
	Set<String> set = new HashSet<String>();
	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();
		while (results.hasNext()) {
			final QuerySolution sol = results.nextSolution();
			set.add(sol.getResource("entities").getURI()
					.replaceAll("http://dbpedia.org/resource/", ""));
		}

	} catch (final QueryException e) {
		Logger.getRootLogger().error(e.getStackTrace());
	}
	return set;
}
 
Example 30
Project: DoSeR   File: EvaluatePureDbpediaCategories.java   Source Code and License 6 votes vote down vote up
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 31
Project: DoSeR   File: DbpediaGraphModification.java   Source Code and License 6 votes vote down vote up
private boolean hasSubCategory(String uri) {
	final String query = "SELECT ?entities WHERE{ ?types <http://www.w3.org/2004/02/skos/core#broader> <"
			+ uri + ">. }";
	boolean hasSubtype = false;
	try {
		final com.hp.hpl.jena.query.Query cquery = QueryFactory
				.create(query);
		final QueryExecution qexec = QueryExecutionFactory
				.create(cquery, skosModel);
		final ResultSet results = qexec.execSelect();
		while (results.hasNext()) {
			hasSubtype = true;
			break;
		}

	} catch (final QueryException e) {
		Logger.getRootLogger().error(e.getStackTrace());
	}
	return hasSubtype;
}
 
Example 32
Project: DoSeR   File: DbpediaGraphModification.java   Source Code and License 6 votes vote down vote up
private Set<String> queryEntitiesFromCategory(final String catUri) {
	Set<String> set = new HashSet<String>();
	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();
		while (results.hasNext()) {
			final QuerySolution sol = results.nextSolution();
			set.add(sol.getResource("entities").getURI()
					.replaceAll("http://dbpedia.org/resource/", ""));
		}

	} catch (final QueryException e) {
		Logger.getRootLogger().error(e.getStackTrace());
	}
	return set;
}
 
Example 33
Project: DoSeR   File: Sampling.java   Source Code and License 6 votes vote down vote up
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 34
Project: DoSeR   File: TimeNumberDisambiguation.java   Source Code and License 6 votes vote down vote up
private String getRedirect(String uri) {
	final Model model = DisambiguationMainService.getInstance().getDBpediaRedirects();
	final String query = "SELECT ?label WHERE{ <" + uri
			+ "> <http://dbpedia.org/ontology/wikiPageRedirects> ?label. }";
	ResultSet results = null;
	QueryExecution qexec = null;
	String redirect = null;
	try {
		final com.hp.hpl.jena.query.Query cquery = QueryFactory.create(query);
		qexec = QueryExecutionFactory.create(cquery, model);
		results = qexec.execSelect();
	} catch (final QueryException e) {
		Logger.getRootLogger().error(e.getStackTrace());
	} finally {
		if (results.hasNext()) {
			final QuerySolution sol = results.nextSolution();
			redirect = sol.getResource("label").getURI();
		}
	}
	return redirect;
}
 
Example 35
Project: DoSeR   File: RDFGraphOperations.java   Source Code and License 6 votes vote down vote up
public static Set<Type> getRDFTypesFromEntity(final String entityUri) {
	Set<Type> set = new HashSet<Type>();
	final Model model = DisambiguationMainService.getInstance().getDBPediaInstanceTypes();
	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, model);
		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(new Type("", type, true, 0));
			}
		}
	}
	return set;
}
 
Example 36
Project: DoSeR   File: RDFGraphOperations.java   Source Code and License 6 votes vote down vote up
public static String getDbPediaDescription(final String uri)
		throws QueryException {
	String res = null;
	final Model model = DisambiguationMainService.getInstance()
			.getDBPediaDescription();
	final String query = "SELECT ?description WHERE{ <" + uri
			+ "> <http://dbpedia.org/ontology/abstract> ?description. }";
	ResultSet results = null; // NOPMD by quh on 14.02.14 10:04
	QueryExecution qexec = null;
	try {
		final com.hp.hpl.jena.query.Query cquery = QueryFactory
				.create(query);
		qexec = QueryExecutionFactory.create(cquery, model);
		results = qexec.execSelect();
	} finally {
		if ((results != null) && results.hasNext()) {
			res = results.nextSolution().getLiteral("description")
					.getString();
		}
		if (qexec != null) {
			qexec.close();
		}
	}
	return res;
}
 
Example 37
Project: DoSeR   File: RDFGraphOperations.java   Source Code and License 6 votes vote down vote up
public static List<String> getDbPediaLabel(final String uri)
		throws QueryException {
	final List<String> labellist = new LinkedList<String>();

	final Model model = DisambiguationMainService.getInstance()
			.getDBPediaLabels();
	final String query = "SELECT ?label WHERE{ <" + uri
			+ "> <http://www.w3.org/2000/01/rdf-schema#label> ?label. }";
	ResultSet results = null; // NOPMD by quh on 14.02.14 10:04
	QueryExecution qexec = null;

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

	if (results != null) {
		while (results.hasNext()) {
			final QuerySolution sol = results.nextSolution();
			final String label = sol.getLiteral("label").getLexicalForm();
			labellist.add(label);
		}
		qexec.close();
	}
	return labellist;
}
 
Example 38
Project: DoSeR   File: RDFGraphOperations.java   Source Code and License 6 votes vote down vote up
public static List<String> getDbPediaLabel_GER(final String uri)
		throws QueryException {
	final List<String> labellist = new LinkedList<String>();

	final Model model = DisambiguationMainService.getInstance()
			.getDBPediaLabels_GER();
	final String query = "SELECT ?label WHERE{ <" + uri
			+ "> <http://www.w3.org/2000/01/rdf-schema#label> ?label. }";
	ResultSet results = null; // NOPMD by quh on 14.02.14 10:04
	QueryExecution qexec = null;

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

	if (results != null) {
		while (results.hasNext()) {
			final QuerySolution sol = results.nextSolution();
			final String label = sol.getLiteral("label").getLexicalForm();
			labellist.add(label);
		}
		qexec.close();
	}
	return labellist;
}
 
Example 39
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 40
Project: DoSeR   File: RDFGraphOperations.java   Source Code and License 6 votes vote down vote up
public static List<Type> queryYagoCategories(final String uri) {
	final Model model = DisambiguationMainService.getInstance()
			.getYagoTransitiveTypes();

	final List<Type> types = new LinkedList<Type>();
	final String query = "SELECT ?type WHERE{ <"
			+ uri
			+ "> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?type. }";
	try {
		final com.hp.hpl.jena.query.Query que = QueryFactory.create(query);
		final QueryExecution qexec = QueryExecutionFactory.create(que,
				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.getResource("type").toString();
			types.add(new Type("", name, true, 0));
		}
	} catch (final QueryException e) {
		Logger.getRootLogger().error(e.getStackTrace());
	}
	return types;
}
 
Example 41
Project: DoSeR   File: RDFGraphOperations.java   Source Code and License 6 votes vote down vote up
private static String queryYagoCategoryLabel(final String catUri) {
	String res = null;
	final Model model = DisambiguationMainService.getInstance()
			.getYagoCategoryLabels();

	final String query = "SELECT ?label WHERE{ <" + catUri
			+ "> <http://www.w3.org/2004/02/skos/core#> ?label. }";
	try {
		final com.hp.hpl.jena.query.Query que = QueryFactory.create(query);
		final QueryExecution qexec = QueryExecutionFactory.create(que,
				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 42
Project: DoSeR   File: CreateDBpediaIndexV2.java   Source Code and License 6 votes vote down vote up
public List<String> getDbPediaLabel(final String uri) throws QueryException, QueryParseException {
	final List<String> labellist = new LinkedList<String>();
	try {
		final String query = "SELECT ?label WHERE{ <" + uri
				+ "> <http://www.w3.org/2000/01/rdf-schema#label> ?label. }";
		ResultSet results = null;
		QueryExecution qexec = null;

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

		if (results != null) {
			while (results.hasNext()) {
				final QuerySolution sol = results.nextSolution();
				final String label = sol.getLiteral("label").getLexicalForm();
				labellist.add(label);
			}
			qexec.close();
		}
	} catch (QueryParseException e) {
		Logger.getRootLogger().info("Query parse Exception");
	}
	return labellist;
}
 
Example 43
Project: DoSeR   File: CreateDBpediaIndexV2.java   Source Code and License 6 votes vote down vote up
public String getDbPediaShortDescription(final String uri) throws QueryException, QueryParseException {
	String labellist = "";
	try {
		final String query = "SELECT ?comment WHERE{ <" + uri
				+ "> <http://www.w3.org/2000/01/rdf-schema#comment> ?comment. }";
		ResultSet results = null;
		QueryExecution qexec = null;

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

		if (results != null) {
			while (results.hasNext()) {
				final QuerySolution sol = results.nextSolution();
				String desc = sol.getLiteral("comment").getLexicalForm();
				labellist = desc;
			}
			qexec.close();
		}
	} catch (QueryParseException e) {
		Logger.getRootLogger().info("Query parse Exception");
	}
	return labellist;
}
 
Example 44
Project: DoSeR   File: CreateDBpediaIndexV2.java   Source Code and License 6 votes vote down vote up
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 45
Project: DoSeR   File: DBpediaCategoryCorrection.java   Source Code and License 6 votes vote down vote up
public Set<String> querySubCategories(final String uri) {
	final Set<String> types = new HashSet<String>();
	final String query = "SELECT ?sub WHERE { <"+uri+"> <http://www.w3.org/2004/02/skos/core#broader> ?sub }";

	try {
		final com.hp.hpl.jena.query.Query que = QueryFactory.create(query);
		final QueryExecution qexec = QueryExecutionFactory.create(que,
				categorySkosModel);
		final ResultSet results = qexec.execSelect();

		while (results.hasNext()) {
			final QuerySolution sol = results.nextSolution();
			final String name = sol.getResource("sub").toString();
			types.add(new String(name));
		}
	} catch (final QueryException e) {
		Logger.getRootLogger().error(e.getStackTrace());
	}
	return types;
}
 
Example 46
Project: Jena-Based-Semantic-Web-Tutorial   File: SPARQLUtils.java   Source Code and License 6 votes vote down vote up
/**
 * RDF Navigation using remote SPARQL Query
 * 
 * @param service
 *            the SAPRQL end point URL
 * @param query
 *            SPARQL Query String
 * @param queryField
 *            the placeholder of filed in parameter query(sample: ?name)
 */
public static void queryRemote(final String service, final String query, String... queryFields) {
	if (queryFields == null || queryFields.length == 0) {
		return;
	}

	QueryExecution qexec = QueryExecutionFactory.sparqlService(service, query);

	System.out.println("Plan to run remote SPARQL query: ");
	System.out.println(BOUNDARY);
	System.out.println(query);
	System.out.println(BOUNDARY);

	ResultSet rs = qexec.execSelect();
	rendererResultSet(rs, queryFields);

	System.out.println(BOUNDARY);

	qexec.close();
}
 
Example 47
Project: Jena-Based-Semantic-Web-Tutorial   File: SPARQLUtils.java   Source Code and License 6 votes vote down vote up
private static void rendererResultSet(ResultSet rs, String... queryFields) {
	System.out.println("Result:");
	int queryFieldSize = queryFields.length;
	for (int i = 0; i < queryFieldSize; i++) {
		System.out.print(queryFields[i] + TAB);
	}
	System.out.println();

	while (rs.hasNext()) {
		QuerySolution qs = rs.nextSolution();
		for (int i = 0; i < queryFieldSize; i++) {
			RDFNode name = qs.get(queryFields[i]);
			if (name != null) {
				System.out.print(name + TAB);
			} else {
				System.out.print("NULL" + TAB);
			}
		}
		System.out.println();
	}
}
 
Example 48
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 49
Project: Tapioca   File: SPARQLEndpointLabelExtractor.java   Source Code and License 6 votes vote down vote up
private Set<String> queryLabels(QueryExecutionFactory qef, String query) throws IOException {
	QueryExecution exec = qef.createQueryExecution(query);
	ResultSet resultSet = null;
	try {
		resultSet = exec.execSelect();
	} catch (Exception e) {
		throw new IOException("Couldn't query labels.", e);
	}
	Set<String> labels = new HashSet<String>();
	QuerySolution result = null;
	RDFNode predicate, object;
	while (resultSet.hasNext()) {
		result = resultSet.next();
		predicate = result.get(PREDICATE);
		if ((predicate != null) && (LABEL_PROPERTIES.contains(predicate.toString()))) {
			object = result.get(OBJECT);
			if (object != null) {
				labels.add(object.toString());
			}
		}
	}
	return labels;
}
 
Example 50
Project: europeana   File: WikidataFetch.java   Source Code and License 6 votes vote down vote up
private Collection<String> getResources(String query, String varName)
{
	Collection<String> ret = new HashSet<String>();
	QueryEngineHTTP endpoint = new QueryEngineHTTP(SPARQL_ENDPOINT, query);
	try {
		ResultSet rs = endpoint.execSelect();
        while (rs.hasNext()) {
            QuerySolution qs = rs.next();
            ret.add(qs.getResource(varName).getURI());
        }
	}
	catch (Throwable t) {
		t.printStackTrace();
	}
	finally {
		endpoint.close();
	}
	return ret;
}
 
Example 51
Project: europeana   File: WikidataCoReferenceResolver.java   Source Code and License 6 votes vote down vote up
private String[] execQuery(String query, Processor processor)
{
	QueryEngineHTTP endpoint = new QueryEngineHTTP(_sparql, query);
	try {
		ResultSet rs = endpoint.execSelect();
		if ( !rs.hasNext() ) { return EMPTY; }

		List<String> l = new ArrayList<String>();
        while (rs.hasNext())
        {
            String uri = processor.process(rs.next().get("x"));
            if ( uri != null ) { l.add(uri); }
        }
        return ( l.size() == 0 ? EMPTY : l.toArray(EMPTY) );
	}
	catch (Throwable t) {
		t.printStackTrace();
	}
	finally {
		endpoint.close();
	}
	return EMPTY;
}
 
Example 52
Project: europeana   File: CoReferenceResolverImpl.java   Source Code and License 6 votes vote down vote up
private String[] execQuery(String query)
{
	QueryEngineHTTP endpoint = new QueryEngineHTTP(_sparql, query);
	try {
		System.err.println(query);
		//endpoint.setSelectContentType(WebContent.contentTypeResultsXML);
		ResultSet rs = endpoint.execSelect();
		if ( !rs.hasNext() ) { return EMPTY; }

		List<String> l = new ArrayList<String>();
        while (rs.hasNext())
        {
            String sameAs = rs.next().getResource("x").getURI();
            if ( !_accept.matcher(sameAs).matches() ) { continue; }
            l.add(sameAs);
        }
        return ( l.size() == 0 ? EMPTY : l.toArray(EMPTY) );
	}
	catch (Throwable t) {
		t.printStackTrace();
	}
	finally {
		endpoint.close();
	}
	return EMPTY;
}
 
Example 53
Project: europeana   File: CoRefCacheHarvester.java   Source Code and License 6 votes vote down vote up
private void harvest(String query, CSVWriter p)
{
    QueryEngineHTTP endpoint = new QueryEngineHTTP(_sparql, query);
    try {
        System.err.println(query);
        ResultSet rs = endpoint.execSelect();
        if ( !rs.hasNext() ) { return; }

        int cursor = 0;
        while (rs.hasNext())
        {
            QuerySolution sol = rs.next();
            String src = sol.getResource("src").getURI();
            String trg = sol.getResource("trg").getURI();
            p.println(src, trg);
            if (++cursor % 1000 == 0) { System.out.println("fetched: " + cursor); }
        }
    }
    catch (Throwable t) {
        t.printStackTrace();
    }
    finally {
        endpoint.close();
    }
}
 
Example 54
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 55
Project: semanticoctopus   File: AggregationTestUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Perform a query about relatives against the ontology obtained by
 * aggregating a set of ontologies and using the specified engine.
 * 
 * @param engine
 * @param expected
 *            pairs expected to be returned as result of the relative query
 * @throws InterruptedException
 */
public void testRelatives(final QueryEngine engine, final List<RelativePair> expected) throws InterruptedException {
	engine.write(System.out, "http://example.org");
	final ResultSet actual = engine.execQuery(RELATIVES_QUERY);
	final Iterator<RelativePair> expectedIt = expected.iterator();
	int n = 0;
	while (expectedIt.hasNext()) {
		n++;
		final RelativePair expectedPair = expectedIt.next();
		assertTrue("Too less pairs returned rows=" + n, actual.hasNext());
		final QuerySolution actualPair = actual.next();
		final String actualx = actualPair.get("x").asResource().getURI();
		final String actualy = actualPair.get("y").asResource().getURI();
		System.out.println("Expected (x=" + expectedPair.x + ",y=" + expectedPair.y + "); Actual (x=" + actualx
				+ ",y=" + actualy + ")");
		assertEquals("row=" + n, expectedPair.x, actualx);
		assertEquals("row=" + n, expectedPair.y, actualy);
	}
	assertFalse("Too much pairs returned. Rows=" + n, actual.hasNext());
}
 
Example 56
Project: ontonethub   File: IndexingJob.java   Source Code and License 5 votes vote down vote up
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 57
Project: ontonethub   File: IndexingJob.java   Source Code and License 5 votes vote down vote up
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 58
Project: CostFed   File: Stats.java   Source Code and License 5 votes vote down vote up
private static Info process(String endpoint, String query, String p) {
		
		long sum = 0, n = 0, sumsq = 0;
		for (int j2 = 0; true; j2++) {
			ResultSet rsPs = query(endpoint,
					query, p, j2 * 10000);
			int i2;
			for (i2 = 0; rsPs.hasNext(); i2++) {
				int f = rsPs.next().getLiteral("x").getInt();
				sum += f;
				sumsq += f * f;
//				System.out.println(sum + "," + sumsq);
			}
			n += i2;
			if (i2 == 0)
				break;
		}
		double mean = ((double) sum / n);
		System.out.println("Mean is " + mean);
//		System.out.println(sumsq + "," + sum + "," + n);
		double stdev = n==1 ? 0 : Math.sqrt(Math.abs(sumsq - (sum * sum) / (double) n)
				* (1.0d / (n - 1)));
		System.out.println("StDev is " + stdev);
		
		return new Info(mean, stdev);

	}
 
Example 59
Project: KBox   File: TDBTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testMultiGraphQuery() throws URISyntaxException, IOException, OperationNotSupportedException {
	URL[] files = new URL[1];
	URL url = TDBTest.class.getResource("/org/aksw/kbox/kibe/foaf.rdf");
	files[0] = url;
	java.nio.file.Path f = Files.createTempDirectory("kb");
	String foafPath = f.toFile().getPath();
	TDB.bulkload(f.toFile().getPath(), files);
	Date start = new Date();
	ResultSet rs = TDB.query("Select ?p where {<http://dbpedia.org/ontology/Place> ?p ?o}", foafPath, graphPath);
	int i = 0;
	Date end = new Date();
	System.out.println(end.getTime() - start.getTime());
	while (rs != null && rs.hasNext()) {
		rs.next();
		i++;
	}
	assertEquals(19, i);
	
	start = new Date();
	rs = TDB.query("Select ?p where {<http://xmlns.com/foaf/0.1/Agent> ?p ?o}", foafPath, graphPath);
	i = 0;
	end = new Date();
	System.out.println(end.getTime() - start.getTime());
	while (rs != null && rs.hasNext()) {
		rs.next();
		i++;
	}
	assertEquals(9, i);
}
 
Example 60
Project: KBox   File: TDBTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testQuery2() throws URISyntaxException, IOException, OperationNotSupportedException {
	ResultSet rs = TDB.query("Select ?p where {<http://dbpedia.org/ontology/Place> ?p ?o}", graphPath);
	int i = 0;
	while (rs != null && rs.hasNext()) {
		rs.next();i++;
	}
	assertEquals(19, i);
}