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

The following are top voted examples for showing how to use com.hp.hpl.jena.query.QueryExecutionFactory. 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: 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 2
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 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: 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: 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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
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 16
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 17
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 18
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 19
Project: DoSeR   File: MainEvaluation.java   Source Code and License 6 votes vote down vote up
public String getRedirect(final String entityUri) {
	final String query = "SELECT ?types WHERE{ <" + entityUri
			+ "> <http://dbpedia.org/ontology/wikiPageRedirects> ?types. }";
	ResultSet results = null;
	QueryExecution qexec = null;
	try {
		final com.hp.hpl.jena.query.Query cquery = QueryFactory
				.create(query);
		qexec = QueryExecutionFactory.create(cquery, redirects);
		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();
				return type;
			}
		}
	}
	return null;
}
 
Example 20
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 21
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 22
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 23
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 24
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 25
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 26
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 27
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 28
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 29
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 30
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 31
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 32
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 33
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 34
Project: DoSeR   File: RDFGraphOperations.java   Source Code and License 6 votes vote down vote up
private static String queryDbPediaCategoryLabel(final String catUri) {
	String res = null;
	final Model model = DisambiguationMainService.getInstance()
			.getDBPediaCategoryLabels();

	final String query = "SELECT ?label WHERE{ <" + catUri
			+ "> <http://www.w3.org/2000/01/rdf-schema#label> ?label. }";
	try {
		final com.hp.hpl.jena.query.Query cquery = QueryFactory
				.create(query);
		final QueryExecution qexec = QueryExecutionFactory.create(cquery,
				model);
		final ResultSet results = qexec.execSelect(); // NOPMD by quh on
														// 18.02.14 15:05
		while (results.hasNext()) {
			final QuerySolution sol = results.nextSolution();
			final String name = sol.getLiteral("label").getLexicalForm();
			res = name;
		}
	} catch (final QueryException e) {
		Logger.getRootLogger().error(e.getStackTrace());
	}
	return res;
}
 
Example 35
Project: DoSeR   File: RDFGraphOperations.java   Source Code and License 6 votes vote down vote up
private static String queryDbPediaCategoryLabel_GER(final String catUri) {
	String res = null;
	final Model model = DisambiguationMainService.getInstance()
			.getDBPediaCategoryLabels_GER();

	final String query = "SELECT ?label WHERE{ <" + catUri
			+ "> <http://www.w3.org/2000/01/rdf-schema#label> ?label. }";
	try {
		final com.hp.hpl.jena.query.Query cquery = QueryFactory
				.create(query);
		final QueryExecution qexec = QueryExecutionFactory.create(cquery,
				model);
		final ResultSet results = qexec.execSelect(); // NOPMD by quh on
														// 18.02.14 15:05
		while (results.hasNext()) {
			final QuerySolution sol = results.nextSolution();
			final String name = sol.getLiteral("label").getLexicalForm();
			// RDFHack ToDo: Inform how to resolve the dbpedia tql files correctly
			 
			res = name;
		}
	} catch (final QueryException e) {
		Logger.getRootLogger().error(e.getStackTrace());
	}
	return res;
}
 
Example 36
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 37
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 38
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 39
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 40
Project: DoSeR   File: CreateDBpediaIndexV2.java   Source Code and License 6 votes vote down vote up
public String getDbPediaLongDescription(final String uri) throws QueryException, QueryParseException {
	String labellist = "";
	try {
		final String query = "SELECT ?comment WHERE{ <" + uri
				+ "> <http://dbpedia.org/ontology/abstract> ?comment. }";
		ResultSet results = null;
		QueryExecution qexec = null;

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

		if (results != null) {
			while (results.hasNext()) {
				final QuerySolution sol = results.nextSolution();
				final String desc = sol.getLiteral("comment").getLexicalForm();
				labellist = desc;
			}
			qexec.close();
		}
	} catch (QueryParseException e) {
		Logger.getRootLogger().info("Query parse Exception");
	}
	return labellist;
}
 
Example 41
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 42
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 43
Project: Jena-Based-Semantic-Web-Tutorial   File: SelectQueryUsingRemoteService.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
	// populate SPARQL SELECT Query string
	StringBuilder sb = new StringBuilder();
	sb.append("PREFIX books:   <http://example.org/book/>").append(NEWLINE);
	sb.append("PREFIX dc:      <http://purl.org/dc/elements/1.1/>").append(NEWLINE);
	sb.append("SELECT ?book ?title").append(NEWLINE);
	sb.append("WHERE {").append(NEWLINE);
	sb.append("		?book dc:title ?title").append(NEWLINE);
	sb.append("}").append(NEWLINE);

	// query from remote service
	QueryExecution qexec = QueryExecutionFactory.sparqlService(SERVICE_URL, sb.toString());

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

	ResultSet rs = qexec.execSelect();

	// use result set formatter
	ResultSetFormatter.out(rs);

	qexec.close();
}
 
Example 44
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 45
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 46
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 47
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 48
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 49
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 50
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 51
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 52
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 53
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 54
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 55
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 56
Project: JenaTutorial   File: TermReconciliation_Subclass.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-data.ttl");
	
	Reasoner reasoner = ReasonerRegistry.getRDFSReasoner();
	reasoner.setParameter(ReasonerVocabulary.PROPsetRDFSLevel, 
               ReasonerVocabulary.RDFS_DEFAULT);
	InfModel infmodel = ModelFactory.createInfModel(reasoner, data );
	
	/* Do a SPARQL Query over the data in the model */
	String 	queryString = "SELECT ?x WHERE { ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.example.org/example#Analyst> }";

	/* 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 57
Project: aliada-tool   File: RDFStoreDAO.java   Source Code and License 6 votes vote down vote up
/**
 * It executes a SELECT SPARQL query on the SPARQL endpoint, 
 * to get the number of resources specified in the query argument.
 *
 * @param query					the query to execute to get the number of resources.  
 * @param sparqlEndpointURI		the SPARQL endpoint URI.  
 * @param user					the user name for the SPARQl endpoint.
 * @param password				the password for the SPARQl endpoint.
 * @return the number of resources.
 * @since 2.0
 */
public int getNumResources(final String query, final String sparqlEndpointURI, final String user, final String password) {
	int numRes = 0;
	try {
        // Execute the query and obtain results
        final QueryExecution qexec = QueryExecutionFactory.sparqlService(
        		sparqlEndpointURI, 
        		QueryFactory.create(query), 
				auth(sparqlEndpointURI, user, password));
        qexec.setTimeout(2000, 5000);
           final ResultSet results = qexec.execSelect() ;
           while (results.hasNext())
           {
           	final QuerySolution soln = results.nextSolution() ;
           	numRes = soln.getLiteral("count").getInt();
           }
        qexec.close() ;
      } catch (Exception exception) {
		LOGGER.error(MessageCatalog._00035_SPARQL_FAILED, exception, query);
	}
	return numRes;
}
 
Example 58
Project: aliada-tool   File: RDFStoreDAO.java   Source Code and License 6 votes vote down vote up
/**
 * It executes a SELECT SPARQL query on the SPARQL endpoint.
 *
 * @param sparqlEndpointURI		the SPARQL endpoint URI.  
 * @param user					the user name for the SPARQl endpoint.
 * @param password				the password for the SPARQl endpoint.
 * @param query					the query to use to look for the resources.
 * @return the {@link com.hp.hpl.jena.query.ResultSet} of the SELECT SPARQL query.
 * @since 2.0
 */
public ResultSet executeSelect(final String sparqlEndpointURI, final String user, final String password, final String query) {
	ResultSet results = null;
 	try {
        // Execute the query and obtain results
        final QueryExecution qexec = QueryExecutionFactory.sparqlService(
        		sparqlEndpointURI, 
        		QueryFactory.create(query), 
				auth(sparqlEndpointURI, user, password));
        qexec.setTimeout(2000, 5000);
           results = qexec.execSelect() ;
        qexec.close() ;
      } catch (Exception exception) {
		LOGGER.error(MessageCatalog._00035_SPARQL_FAILED, exception, query);
	}
 	return results;
}
 
Example 59
Project: JenaTutorial   File: AnotherInverseOfProperty.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/ex20-data.ttl");
	
	
	Reasoner reasoner = ReasonerRegistry.getOWLReasoner();
	InfModel infmodel = ModelFactory.createInfModel(reasoner, data );
	
	/* Do a SPARQL Query over the data in the model */
	String queryString = "SELECT ?x ?z WHERE { ?x <http://www.w3.org/2000/01/rdf-schema#subclassOf> ?z }";

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

	QueryExecUtils.executeQuery(qexec);
	
	System.out.println( "\n---------------\n" );		
}
 
Example 60
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();
	}
}