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; }
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; }
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; }
private String getOrderArg(SortCondition condition) { String orderArg = condition.getExpression().getVarName(); int direction = condition.getDirection(); switch(direction) { case Query.ORDER_ASCENDING: { orderArg += " ASC"; break; } case Query.ORDER_DESCENDING: { orderArg += " DESC"; break; } case Query.ORDER_DEFAULT: { break; } } return orderArg; }
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(); }
private List<Query> loadAllQueries() throws IOException { File queryDir; File[] files; List<Query> queries; queries = new ArrayList<Query>(); queryDir = new File(CURR_DIR + "/" + QUERY_DIR); files = queryDir.listFiles(); Arrays.sort(files); for(int i = 0; i < files.length; i++) { readRecursiveAndCreateQuery(files[i], queries); } return queries; }
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; }
private void runQueryButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_runQueryButtonActionPerformed List<String> lines = null; try { lines = Files.readAllLines(queryPath); } catch (IOException ex) { Logger.getLogger(Ontogui.class.getName()).log(Level.SEVERE, null, ex); } String queryString = ""; for (String line : lines) { queryString += line + System.lineSeparator(); } Query query = QueryFactory.create(queryString, Syntax.syntaxARQ); queryResultArea.setText("Starting query: " + queryPath.toFile().getName() + "\n"); Thread t = new Thread(new QueryProcessor(query, new QueryAreaStream( queryResultArea), dataset, checkbox1.getState())); t.start(); }
private void runSmellAnalysisButtonActionPerformed( java.awt.event.ActionEvent evt) {// GEN-FIRST:event_runSmellAnalysisButtonActionPerformed String filename = smellName; File smellFile = new File(System.getProperty("user.dir") + "/sparql/smells/" + filename.replaceAll(" ", "") + ".sparql"); List<String> lines = null; try { lines = Files.readAllLines(smellFile.toPath()); } catch (IOException ex) { Logger.getLogger(Ontogui.class.getName()).log(Level.SEVERE, null, ex); } String queryString = ""; for (String line : lines) { queryString += line + System.lineSeparator(); } Query query = QueryFactory.create(queryString, Syntax.syntaxARQ); queryResultArea.setText("Starting analysis: " + smellName + "\n"); Thread t = new Thread(new QueryProcessor(query, new QueryAreaStream( queryResultArea), dataset, checkbox1.getState())); t.start(); }
private void runMetricsButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_runMetricsButtonActionPerformed String folder = metricName.split(":")[0].toLowerCase(); String filename = metricName.split(":")[1]; File metricFile = new File(System.getProperty("user.dir") + "/sparql/metrics/" + folder + "/" + filename + ".sparql"); List<String> lines = null; try { lines = Files.readAllLines(metricFile.toPath()); } catch (IOException ex) { Logger.getLogger(Ontogui.class.getName()).log(Level.SEVERE, null, ex); } String queryString = ""; for (String line : lines) { queryString += line + System.lineSeparator(); } Query query = QueryFactory.create(queryString, Syntax.syntaxARQ); queryResultArea.setText("Starting analysis:" + metricName + "\n"); System.err.println(checkbox1.isEnabled()); Thread t = new Thread(new QueryProcessor(query, new QueryAreaStream( queryResultArea), dataset, checkbox1.getState())); t.start(); }
@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(); } } }
@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(); } } }
@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(); } } }
@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(); } } }
@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(); } } }
@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(); } } }
@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(); } } }
@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(); } } }
public String executeQuery() { Query query = QueryFactory.create(this.getQuery(), Syntax.syntaxARQ); Op op = Algebra.compile(query); try { if(new String("internal").equals(this.service)) { this.results = jenaService.runLocalOp(op); } else if (new String("external").equals(this.service)) { this.results = jenaService.runExternalOp(op); } } catch (Exception e) { e.printStackTrace(); } finally { } return ("success"); }
/** * Run SPARQL query * @param uri uri resource * @param p property * @return results map: uri-s (if uri is a subject), uri-o (if uri is an object) */ private TObjectCharHashMap<String> runQuery(String uri, String p){ TObjectCharHashMap<String> results = new TObjectCharHashMap<String>(); Query query; String q; q = "SELECT * WHERE {{?s " + p + " <" + uri + ">. FILTER isIRI(?s). } UNION " + "{<" + uri + "> " + p + " ?o ." + " FILTER isIRI(?o). }} "; logger.debug(q); try { query = QueryFactory.create(q); results = executeQuery(query, p); } catch (Exception e) { e.printStackTrace(); } return results; }
/** * Run SPARQL query * @param uri resource uri * @param p property * @return results map: uri-s (if uri is a subject), uri-o (if uri is an object) */ private TObjectByteHashMap<String> runQuery(String uri, String p){ TObjectByteHashMap<String> results = new TObjectByteHashMap<String>(); Query query; String q; q = "SELECT * WHERE {{?s " + p + " <" + uri + ">. FILTER isIRI(?s). } UNION " + "{<" + uri + "> " + p + " ?o ." + " FILTER isIRI(?o). }} "; logger.debug(q); try { query = QueryFactory.create(q); results = executeQuery(query, p); } catch (Exception e) { e.printStackTrace(); } return results; }
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 ""; }
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; }
/** * 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(); }
/** * 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; }
/** * 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; } }
/** * 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; }
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; }
@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."); } }
/** * @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."); } }
@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."); } }
@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."); } }
@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."); } }
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 } } }