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

The following are top voted examples for showing how to use com.hp.hpl.jena.query.QueryExecution. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: DocIT   File: Containment.java   Source Code and License 6 votes vote down vote up
public static boolean checkContainment(CompanyModel c){
	String queryString = 
		"ASK" +
			// check whether any manager is an employee in any other department
			"{?dept1"        + " <" + c.MANAGER   + "> " + "?manager"         + ". " +
			" ?dept2"		 + " <" + c.EMPLOYEES + "> " + "?employees1"      + ". " +
			" ?employees1"   + " <" + RDFS.member + "> " + "?employee1"       + ". " +
			" FILTER (?manager = ?employee1) " +
			
			// check whether any employee occurs more than once
			" ?dept3 "		 + " <" + c.EMPLOYEES + "> " + "?employees2"      + ". " +
			" ?employees2"   + " <" + RDFS.member + "> " + "?employee2"       + ". " +
			" FILTER (?employee1 = ?employee2)" +
			
			// check whether any department occurs more than once
			" ?upperDept1"   + " <" + c.DEPTS     + "> " + "?dept4"           + ". " +
			" ?upperDept2"   + " <" + c.DEPTS     + "> " + "?dept5"           + ". " +
			" FILTER (?dept4 = ?dept5) " +
			"}";
	
	Query query = QueryFactory.create(queryString);
	QueryExecution qe = QueryExecutionFactory.create(query, c.getModel());
	boolean out = qe.execAsk();
	qe.close();
	return !out;
}
 
Example 2
Project: ontonethub   File: IndexingJob.java   Source Code and License 6 votes vote down vote up
private List<Statement> expandSubClasses(Model model){
	List<Statement> stmts = new ArrayList<Statement>();
	
	
	String sparql = "PREFIX rdfs: <" + RDFS.getURI() + ">"
			+ "SELECT DISTINCT ?class ?synonym "
			+ "WHERE { "
			+ "?class rdfs:subClassOf+ ?subClass . "
			+ "?subClass <" + synonym + "> ?synonym"
			+ "}";
	
	Query query = QueryFactory.create(sparql, Syntax.syntaxARQ);
	QueryExecution queryExecution = QueryExecutionFactory.create(query, model);
	ResultSet resultSet = queryExecution.execSelect();
	resultSet.forEachRemaining(querySolution -> {
		stmts.add(new StatementImpl(querySolution.getResource("class"), synonym, querySolution.getLiteral("synonym")));
	});
	return stmts;
}
 
Example 3
Project: ontonethub   File: IndexingJob.java   Source Code and License 6 votes vote down vote up
private List<Statement> expandSubProperties(Model model){
	List<Statement> stmts = new ArrayList<Statement>();
	
	String sparql = "PREFIX rdfs: <" + RDFS.getURI() + ">"
			+ "SELECT DISTINCT ?property ?synonym "
			+ "WHERE { "
			+ "?property rdfs:subPropertyOf+ ?subProperty . "
			+ "?subProperty <" + synonym + "> ?synonym"
			+ "}";
	
	Query query = QueryFactory.create(sparql, Syntax.syntaxARQ);
	QueryExecution queryExecution = QueryExecutionFactory.create(query, model);
	ResultSet resultSet = queryExecution.execSelect();
	resultSet.forEachRemaining(querySolution -> {
		stmts.add(new StatementImpl(querySolution.getResource("property"), synonym, querySolution.getLiteral("synonym")));
	});
	return stmts;
}
 
Example 4
Project: 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 5
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 6
Project: BimSPARQL   File: SPINInferencesWithoutConstructor.java   Source Code and License 6 votes vote down vote up
/**
 * Runs a given Jena Query on a given instance and adds the inferred triples
 * to a given Model.
 * @param queryWrapper  the wrapper of the CONSTRUCT query to execute
 * @param queryModel  the query Model
 * @param newTriples  the Model to write the triples to
 * @param instance  the instance to run the inferences on
 * @param checkContains  true to only call add if a Triple wasn't there yet
 * @return true if changes were done (only meaningful if checkContains == true)
 */
public static boolean runQueryOnInstance(QueryWrapper queryWrapper, Model queryModel, Model newTriples, Resource instance, boolean checkContains) {
	boolean changed = false;
	QueryExecution qexec = ARQFactory.get().createQueryExecution(queryWrapper.getQuery(), queryModel);
	QuerySolutionMap bindings = new QuerySolutionMap();
	bindings.add(SPIN.THIS_VAR_NAME, instance);
	Map<String,RDFNode> initialBindings = queryWrapper.getTemplateBinding();
	if(initialBindings != null) {
		for(String varName : initialBindings.keySet()) {
			RDFNode value = initialBindings.get(varName);
			bindings.add(varName, value);
		}
	}
	qexec.setInitialBinding(bindings);
	Model cm = qexec.execConstruct();
	StmtIterator cit = cm.listStatements();
	while(cit.hasNext()) {
		Statement s = cit.nextStatement();
		if(!checkContains || !queryModel.contains(s)) {
			changed = true;
			newTriples.add(s);
		}
	}
	return changed;
}
 
Example 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
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 16
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 17
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 18
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 19
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 20
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 21
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 22
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 23
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 24
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 25
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 26
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 27
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 28
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 29
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 30
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 31
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 32
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 33
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 34
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 35
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 36
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 37
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 38
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 39
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 40
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 41
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 42
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 43
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 44
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 45
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 46
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 47
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 48
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 49
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 50
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 51
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 52
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 53
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 54
Project: aliada-tool   File: AliadaRDFStoreDAO.java   Source Code and License 6 votes vote down vote up
public String crm2AliadaClass(final String crmClass) {
	final Query query = QueryFactory.create(CRM_TO_ALIADA_CLASS_P1 + crmClass + CRM_TO_ALIADA_CLASS_P2);
	ARQ.getContext().setTrue(ARQ.useSAX);
       
	QueryExecution execution = null;
	try {
		execution = QueryExecutionFactory.sparqlService("http://172.25.5.15:8890/sparql", query);
		execution.setTimeout(2000, 5000);
		final ResultSet results = execution.execSelect();
		//Iterating over the SPARQL Query results
		while (results.hasNext()) {
			QuerySolution soln = results.nextSolution();
			//Printing DBpedia entries' abstract.
			System.out.println(soln.get("?abstract"));   
			return soln.get("?abstract").asResource().getURI();
		}
		return "NULL";
       } finally {
       	try {
       		execution.close();
		} catch (Exception exception) {
			// TODO: handle exception
		}
       }

}
 
Example 55
Project: JenaTutorial   File: OWLMain30_WithSameAs.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/ex30-data.ttl");
	
	Model sameAsData = FileManager.get().loadModel( "file:data/input/turtle/ex30-sameas.ttl" );
	data.add( sameAsData );
	
	Reasoner reasoner = ReasonerRegistry.getOWLReasoner();
	
	InfModel infmodel = ModelFactory.createInfModel(reasoner, data );
	
	/* Do a SPARQL Query over the data in the model */
	String queryString = "SELECT ?facility ?location WHERE { ?p <http://www.example.org/example#manufactureLocation> ?location . ?p <http://mfg.example.org/mfg#facility> ?facility . }";

	/* 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-------DONE--------\n" );		
}
 
Example 56
Project: cobalt   File: CompatibleResourceFinder.java   Source Code and License 6 votes vote down vote up
private Set<O> findOffers(final T request) {
  final Set<O> offers = new HashSet<>();

  dataset.begin(ReadWrite.READ);

  try {

    final Model model = dataset.getDefaultModel();

    try (QueryExecution qx = QueryExecutionFactory.create(getQuery(request, model), dataset)) {
      final ResultSet rs = qx.execSelect();
      while (rs.hasNext()) {
        offers.add(createOffer(rs.next()));
      }
    }

  } finally {
    dataset.end();
  }

  return offers;
}
 
Example 57
Project: R2RLint   File: SparqlifyDataset.java   Source Code and License 6 votes vote down vote up
@Override
public long size() {
	if (sparqlWrapping) {
		if (size < 0 || !cachingEnabled) {
			Query query = QueryFactory.create(
					"SELECT DISTINCT (count(*) AS ?count) {?s ?p ?o}");
			QueryExecution qe = QueryExecutionFactory.sparqlService(
					((SparqlGraph) getGraph()).getServiceUri(),
					query);
			ResultSet res = qe.execSelect();
			RDFNode count = null;
			while(res.hasNext())
			{
				QuerySolution sol = res.nextSolution();
				count = sol.get("count").asLiteral();
			}
			qe.close();
			
			return count.asLiteral().getLong();
		} else {
			return size;
		}
	} else {
		return super.size();
	}
}
 
Example 58
Project: R2RLint   File: ExternalSameAsLinks.java   Source Code and License 6 votes vote down vote up
private long getWholeCount(SparqlifyDataset dataset) {
	long count = 0;
	Query query = QueryFactory.create("SELECT (count(*) AS ?count) { ?s ?p ?o }");
	QueryExecution qe;
	if (dataset.isSparqlService() && dataset.getSparqlServiceUri() != null) {
		qe = QueryExecutionFactory.sparqlService(dataset.getSparqlServiceUri(), query);
	} else {
		qe = QueryExecutionFactory.create(query, dataset);
	}
	ResultSet res = qe.execSelect();
	
	while(res.hasNext())
	{
		QuerySolution solution = res.nextSolution();
		RDFNode solNode = solution.get("count");
		count += solNode.asLiteral().getLong();
	}
	qe.close(); 
	
	return count;
}
 
Example 59
Project: R2RLint   File: InterlinkingCompleteness.java   Source Code and License 6 votes vote down vote up
private int getCountResult(String queryStr, SparqlifyDataset dataset) {
	int count = 0;
	Query query = QueryFactory.create(queryStr);
	QueryExecution qe;
	if (dataset.isSparqlService() && dataset.getSparqlServiceUri() != null) {
		qe = QueryExecutionFactory.sparqlService(dataset.getSparqlServiceUri(), query);
	} else {
		qe = QueryExecutionFactory.create(query, dataset);
	}
	ResultSet res = qe.execSelect();
	
	while(res.hasNext())
	{
		QuerySolution solution = res.nextSolution();
		RDFNode solNode = solution.get("count");
		count += solNode.asLiteral().getInt();
	}
	qe.close(); 
	
	return count;
}
 
Example 60
Project: R2RLint   File: CorrectCollectionUse.java   Source Code and License 6 votes vote down vote up
private void check_firstStatementHasLiteralObject(SparqlifyDataset dataset)
        throws NotImplementedException, SQLException {
    
    String queryStr =
            "SELECT * {" +
                "?lnode <" + RDF.first.getURI() + "> ?first " +
                "FILTER (isLiteral(?first)) " +
            "}";
    QueryExecution qe = getQueryExecution(queryStr, dataset);
    ResultSet res = qe.execSelect();
    while (res.hasNext()) {
        QuerySolution sol = res.next();
        Node lNode = sol.get("lnode").asNode();
        Node firstVal = sol.get("first").asNode();
        Triple triple = new Triple(lNode, RDF.first.asNode(), firstVal);
        
        Set<ViewQuad<ViewDefinition>> quadViewDefs = pinpointer
                .getViewCandidates(triple);
        writeTripleMeasureToSink(score_firstStatementHasLiteralObject,
                triple, quadViewDefs);
    }
}