public Map<String, Double> getRelationshipCounts(Model model) { QueryExecution execution = QueryExecutionFactory.create("select ?c ?t where { ?s <" + RDF.type + "> ?c . ?o <" + RDF.type + "> ?t. ?s ?p ?o. }", model); ResultSet result = execution.execSelect(); Map<String, Double> stats = new HashMap<String, Double>(); while (result.hasNext()) { QuerySolution solution = result.next(); String rel = getRelationshipPair(solution.getResource("c").getURI(), solution.getResource("t").getURI()); if (stats.containsKey(rel)) { stats.put(rel, stats.get(rel) + 1); } else { stats.put(rel, 1d); } } return stats; }
private List<String> getUniprotMappings(Model aUpModel) { QueryExecution ex = QueryExecutionFactory .create("SELECT ?x WHERE{?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://purl.uniprot.org/core/Protein>}", aUpModel); ResultSet rs = ex.execSelect(); List<String> returnMe = new ArrayList<String>(); while (rs.hasNext()) { QuerySolution sol = rs.next(); Resource r = sol.getResource("x"); String lPattern = "http:\\/\\/purl.uniprot.org\\/uniprot\\/(\\w+)"; Pattern p = Pattern.compile(lPattern); Matcher m = p.matcher(r.getURI()); if (m.matches()) { returnMe.add(m.group(1).trim()); } } return returnMe; }
public Map<String, Double> getClassCounts(Model model) { QueryExecution execution = QueryExecutionFactory .create("select ?c ?i where { ?i <" + RDF.type + "> ?c }", model); ResultSet result = execution.execSelect(); Map<String, Double> stats = new HashMap<String, Double>(); while (result.hasNext()) { QuerySolution solution = result.next(); String className = solution.getResource("c").getURI(); if (stats.containsKey(className)) { stats.put(className, stats.get(className) + 1); } else { stats.put(className, 1d); } } return stats; }
public Set<DatatypeProperty> getAllDataProperties() { Set<DatatypeProperty> properties = new TreeSet<DatatypeProperty>(); String query = "PREFIX owl: <http://www.w3.org/2002/07/owl#> SELECT ?p WHERE {?p a owl:DatatypeProperty}"; ResultSet q = queryable.query(query); while (q.hasNext()) { QuerySolution qs = q.next(); properties.add(new DatatypeProperty(qs.getResource("p").getURI())); } return properties; }
/** * Get the mappings to GO given a Uniprot RDF model * * @param aUpModel * a Model populated with an RDF representation of a Uniprot * record * @return a list of Strings to GO ids */ private List<String> getGoMappings(Model aUpModel) { List<String> returnMe = new ArrayList(); QueryExecution ex = QueryExecutionFactory.create( "SELECT ?z WHERE{_:x <http://purl.uniprot.org/core/classifiedWith> ?z}", aUpModel); ResultSet rs = ex.execSelect(); while (rs.hasNext()) { QuerySolution sol = rs.next(); Resource r = sol.getResource("z"); // Check if the url is from go String lPattern = "http:\\/\\/purl.uniprot.org\\/go\\/(\\w+)"; Pattern p = Pattern.compile(lPattern); Matcher m = p.matcher(r.getURI()); if (m.matches()) { returnMe.add(m.group(1).trim()); } } return returnMe; }
public Set<ObjectProperty> getAllObjectProperties() { Set<ObjectProperty> properties = new TreeSet<ObjectProperty>(); String query = "PREFIX owl: <http://www.w3.org/2002/07/owl#> SELECT ?p WHERE {?p a owl:ObjectProperty}"; ResultSet q = queryable.query(query); while (q.hasNext()) { QuerySolution qs = q.next(); properties.add(new ObjectProperty(qs.getResource("p").getURI())); } return properties; }
public Set<NamedClass> getAllClasses() { Set<NamedClass> classes = new TreeSet<NamedClass>(); String query = "PREFIX owl: <http://www.w3.org/2002/07/owl#> SELECT ?c WHERE {?c a owl:Class} LIMIT 1000"; ResultSet q = queryable.query(query); while (q.hasNext()) { QuerySolution qs = q.next(); if(qs.getResource("c").isURIResource()){ classes.add(new NamedClass(qs.getResource("c").getURI())); } } //remove trivial classes classes.remove(new NamedClass(OWL.Nothing.toStringID())); classes.remove(new NamedClass(OWL.Thing.toStringID())); return classes; }
/** * Given a query result from a SPARQL query, obtain the number value at the * given variable * * @param resultRow the result from a SPARQL query * @param variableName the name of the variable to obtain * @return the Integer value, or null otherwise */ public static Integer getIntegerValue(QuerySolution resultRow, String variableName) { if (resultRow != null) { Resource res = resultRow.getResource(variableName); if (res != null && res.isLiteral()) { Literal val = res.asLiteral(); if (val != null) { return Integer.valueOf(val.getInt()); } } } return null; }
/** * Given a query result from a SPARQL query, obtain the given variable value * as a String * * @param resultRow the result from a SPARQL query * @param variableName the name of the variable to obtain * @return the value or null if it could not be found */ private static String getStringValueFromRow(QuerySolution resultRow, String variableName) { // Check the input and exit immediately if null if (resultRow == null) { return null; } String result = null; Resource res = resultRow.getResource(variableName); if (res != null && res.isLiteral()) { result = res.asLiteral().getString(); } return result; }
public Map<ObjectProperty, Integer> getMostFrequentProperties(NamedClass cls1, NamedClass cls2){ Map<ObjectProperty, Integer> prop2Cnt = new HashMap<ObjectProperty, Integer>(); String query = String.format("SELECT ?p (COUNT(*) AS ?cnt) WHERE {?x1 a <%s>. ?x2 a <%s>. ?x1 ?p ?x2} GROUP BY ?p", cls1, cls2); ResultSet rs = SparqlQuery.convertJSONtoResultSet(cache.executeSelectQuery(endpoint, query)); QuerySolution qs; while(rs.hasNext()){ qs = rs.next(); ObjectProperty p = new ObjectProperty(qs.getResource("p").getURI()); int cnt = qs.getLiteral("cnt").getInt(); prop2Cnt.put(p, cnt); } return prop2Cnt; }
@Override public void consume(ResultSet rs) { try { int countBnodes = 0; while (rs.hasNext()) { Resource item = rs.next().getResource(SELECT_VAR.name()); if (item == null) { EldaException.BadSpecification("<br>Oops. No binding for " + SELECT_VAR.name() + " in successful SELECT.\n" + "<br>Perhaps ?item was mis-spelled in an explicit api:where clause.\n" + "<br>It's not your fault; contact the API provider."); } if (item.isAnon()) { countBnodes += 1; } else { results.add(withoutModel(item)); } } if (countBnodes > 0 && log.isDebugEnabled()) { log.debug("{} selected bnode items discarded", countBnodes); } } catch (APIException e) { throw e; } catch (Throwable t) { throw new APIException("Query execution problem on query: " + t, t); } }
public void toInteractions(ResultSet results) throws StudyImporterException { final InteractionListener listener = new InteractionListenerImpl(nodeFactory, getGeoNamesService(), getLogger()); while (results.hasNext()) { QuerySolution next = results.next(); Iterator<String> nameIter = next.varNames(); Map<String, String> props = new TreeMap<>(); while (nameIter.hasNext()) { String key = nameIter.next(); RDFNode rdfNode = next.get(key); if (rdfNode.isURIResource()) { props.put(key, next.getResource(key).getURI()); } else { props.put(key, next.getLiteral(key).getString()); } } props.put(StudyImporterForTSV.STUDY_SOURCE_CITATION, getDataset().getCitation()); listener.newLink(props); } }
@Deprecated private static int getNumberOfMetricsInDataSet(Model m, String extraSPARQLstmt){ Integer total = 0; Model internal = InternalModelConf.getFlatModel(); Dataset _temp = new DatasetImpl(internal); String _tempGraph = Commons.generateURI().toString(); _temp.addNamedModel(_tempGraph, m); String whereDefaultGraphClause = "?metricTypeURI " + SPARQLHelper.toSPARQL(RDFS.subClassOf) + " " + SPARQLHelper.toSPARQL(DAQ.Metric) + " ."; whereDefaultGraphClause = whereDefaultGraphClause + extraSPARQLstmt; String graphClause = "GRAPH <"+_tempGraph+"> { [where] }"; String whereNamedGraphClause = "?typeURI " + SPARQLHelper.toSPARQL(RDF.type) + " ?metricTypeURI . "; graphClause = graphClause.replace("[where]", whereNamedGraphClause); String whereClause = whereDefaultGraphClause + graphClause; String query = SPARQLHelper.SELECT_STATEMENT.replace("[variables]", "(count(?typeURI) as ?count)").replace("[whereClauses]", whereClause); Query qry = QueryFactory.create(query); QueryExecution qe = QueryExecutionFactory.create(qry, _temp); ResultSet rs = qe.execSelect(); while (rs.hasNext()){ QuerySolution soln = rs.next(); total = new Integer(soln.getResource("count").toString()); } return total.intValue(); } }
private DataEntry getDataEntryFromRS(ResultSet rs) { DataEntry dataEntry = new DataEntry(); QuerySolution soln = rs.nextSolution(); String colName, value; boolean useColumnNumbers = this.isUsingColumnNumbers(); /* for each column get the colName and colValue and add to the data entry */ for (int i = 0; i < rs.getResultVars().size(); i++) { colName = rs.getResultVars().get(i); RDFNode node = soln.get(colName) ; if (node.isLiteral()) { value = convertRSToString(soln, colName); } else { value = soln.getResource(colName).getURI(); } dataEntry.addValue(useColumnNumbers ? Integer.toString(i + 1) : colName, new ParamValue(value)); } return dataEntry; }
public DataEntry getDataEntryFromRS(ResultSet rs) { DataEntry dataEntry = new DataEntry(); QuerySolution soln = rs.nextSolution(); String colName, value; boolean useColumnNumbers = this.isUsingColumnNumbers(); /* for each column get the colName and colValue and add to the data entry */ for (int i = 0; i < rs.getResultVars().size(); i++) { colName = rs.getResultVars().get(i); RDFNode node = soln.get(colName) ; if (node.isLiteral()) { value = convertRSToString(soln, colName); } else { value = soln.getResource(colName).getURI(); } dataEntry.addValue(useColumnNumbers ? Integer.toString(i + 1) : colName, new ParamValue(value)); } return dataEntry; }
public String getComputedOn(){ String selectQuery = "SELECT ?cOn { graph <"+currentGraphURI+"> { ?s <"+DAQ.computedOn.getURI()+"> ?cOn } }"; QueryExecution exec = QueryExecutionFactory.create(QueryFactory.create(selectQuery), dsLoader.getInternalDataset()); ResultSet set = exec.execSelect(); while(set.hasNext()){ QuerySolution qs = set.next(); Resource computedOn = qs.getResource("cOn"); return computedOn.getURI(); } return null; }
@SuppressWarnings("static-access") public void testGetLayer() { System.out.println("--------GetLayer-------\n"); String uri = "http://geni-orca.renci.org/owl/ben-dtn.rdf#Duke/Infinera/DTN/fB/1/ocgB/1"; System.out.println(ontProcessor.getOntModel().getResource(uri).getLocalName()); ResultSet results = ontProcessor.getLayer(ontProcessor.getOntModel(), uri); String layerName = null; String varName = (String) results.getResultVars().get(0); while (results.hasNext()) { layerName = results.nextSolution().getResource(varName).getLocalName(); System.out.println(layerName); } assertTrue(layerName != null); }
public void describe(Resource r) { // Default model. DB2Closure.closure(otherModel(r, dataset.getDefaultModel()), false, acc, resources); String query = "SELECT ?g { GRAPH ?g { <" + r.getURI() + "> ?p ?o } }"; QueryExecution qExec = RdfStoreQueryExecutionFactory.create(query, dataset); ResultSet rs = qExec.execSelect(); for (; rs.hasNext();) { QuerySolution qs = rs.next(); String gName = qs.getResource("g").getURI(); // mdb for DB2 Model model = dataset.getNamedModel(gName); Resource r2 = otherModel(r, model); DB2Closure.closure(r2, false, acc, resources); } qExec.close(); DB2Closure.closure(r, false, acc, resources); }
private static List<Pair<String, String>> storesByQuery(String fn) { Model model = FileManager.get().loadModel(fn) ; List<Pair<String, String>> data = new ArrayList<Pair<String, String>>(); Query query = QueryFactory.create(queryString) ; QueryExecution qExec = QueryExecutionFactory.create(query, model) ; try { ResultSet rs = qExec.execSelect() ; for ( ; rs.hasNext() ; ) { QuerySolution qs = rs.nextSolution() ; String label = qs.getLiteral("label").getLexicalForm() ; String desc = qs.getResource("desc").getURI() ; data.add(new Pair<String, String>(label, desc)) ; } } finally { qExec.close() ; } return data ; } }
/** Test that looking for items with fake type Item using exists-backwards={existsSetting} will produce the single answer {expect}. */ public void testNotExistsXY( String existsSetting, String expect ) { Shorts sns = new Shorts( "backwards", "type" ); // System.err.println( ">> info: " + sns.asContext().getPropertyByName("type" ).getType() ) ; APIQuery q = QueryTestUtils.queryFromSNS(sns); ContextQueryUpdater x = new ContextQueryUpdater( ContextQueryUpdater.ListEndpoint, (Bindings) null, NamedViews.oneNamedView, sns, q ); Param ptype = Param.make( sns, "type" ); x.addFilterFromQuery( ptype, "Item" ); x.addFilterFromQuery( Param.make( sns, "exists-backwards" ), existsSetting ); // String query = q.assembleSelectQuery( PrefixMapping.Factory.create() ); QueryExecution qx = QueryExecutionFactory.create( query, model ); ResultSet rs = qx.execSelect(); // Set<Resource> solutions = new HashSet<Resource>(); while (rs.hasNext()) solutions.add( rs.next().getResource( "item" ) ); assertEquals( CollectionUtils.a( resource( expect ) ), solutions ); }