public static Method create(QuerySolution qs) throws Exception { Resource id = (Resource) qs.get("x"); Literal fullPath = (Literal) qs.get("fullPath"); Literal name = (Literal) qs.get("name"); Literal accessModifier = (Literal) qs.get("accessModifier"); Literal lineStart = (Literal) qs.get("line_start"); Literal lineEnd = (Literal) qs.get("line_end"); Resource returnType = (Resource) qs.get("returnType"); Resource hasParameter = (Resource) qs.get("hasParameter"); Resource throwsException = (Resource) qs.get("throwsException"); Resource belongsTo = (Resource) qs.get("belongsTo"); Method meth = new Method(id.toString(), name.getValue().toString()); meth.setAccessModifier(accessModifier.getValue().toString()); meth.setFullPath(fullPath.getValue().toString()); meth.setLineStart(lineStart.getInt()); meth.setLineEnd(lineEnd.getInt()); meth.setReturnType(returnType.toString()); if (hasParameter != null) { meth.setHasParameter(hasParameter.toString()); } if (throwsException != null) { meth.setThrowsException(throwsException.toString()); } meth.setBelongsTo(belongsTo.toString()); return meth; }
private int getMaxRank(String objectUri, String subjectUri, VitroRequest vreq) { int maxRank = 0; // default value if (objectUri == null) { // adding new webpage String queryStr = QueryUtils.subUriForQueryVar(MAX_RANK_QUERY, "subject", subjectUri); log.debug("Query string is: " + queryStr); try { ResultSet results = QueryUtils.getQueryResults(queryStr, vreq); if (results != null && results.hasNext()) { // there is at most one result QuerySolution soln = results.next(); RDFNode node = soln.get("rank"); if (node != null && node.isLiteral()) { // node.asLiteral().getInt() won't return an xsd:string that // can be parsed as an int. int rank = Integer.parseInt(node.asLiteral().getLexicalForm()); if (rank > maxRank) { log.debug("setting maxRank to " + rank); maxRank = rank; } } } } catch (NumberFormatException e) { log.error("Invalid rank returned from query: not an integer value."); } catch (Exception e) { log.error(e, e); } } return maxRank; }
public Set<NamingIssue> detectNonExactMatchingDirectChildIssues(Model model) { long start = System.currentTimeMillis(); // get SubClass - SuperClass pairs via SPARQL query QueryExecution qe = QueryExecutionFactory.create( "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> PREFIX owl:<http://www.w3.org/2002/07/owl#> " + "SELECT * WHERE {?sub a owl:Class .?sup a owl:Class .?sub rdfs:subClassOf ?sup}", model); ResultSet rs = qe.execSelect(); Set<Pair<String, String>> subClassSuperClassPairs = new HashSet<Pair<String, String>>(); while (rs.hasNext()) { QuerySolution qs = rs.next(); String subClass = qs.getResource("sub").getURI(); String superClass = qs.getResource("sup").getURI(); subClassSuperClassPairs.add(new Pair<String, String>(subClass, superClass)); } qe.close(); // compute non matching pairs Set<NamingIssue> nonMatchingChildren = computeNonExactMatchingChildren(subClassSuperClassPairs); long end = System.currentTimeMillis(); logger.info("Operation took " + (end - start) + "ms"); return nonMatchingChildren; }
@Override public List<String> executeSparqlSet(List<SparqlCandidate> sparqlCandidates) throws QueryParseException, QueryException { List<String> results = new ArrayList<String>(); for (SparqlCandidate candidate : sparqlCandidates) { logger.info("Start: " + candidate.getSparqlQuery()); ResultSet rs = endpointConnector.executeQuery(candidate.getSparqlQuery()); logger.debug(candidate + " returns results:"); while (rs.hasNext()) { QuerySolution qs = rs.next(); if (qs.get("variable") != null) { String new_variable = qs.get("variable").toString(); logger.debug(new_variable); if (!results.contains(new_variable)) results.add(new_variable); } } } return results; }
public Map<String, String> getProperties(String query) throws AutoSPARQLException { property2LabelMap = new TreeMap<String, String>(); String queryTriples = query.substring(18, query.length() - 1); String newQuery = "SELECT DISTINCT ?p ?label WHERE {" + queryTriples + "?x0 ?p ?o. " + "?p <" + RDFS.label + "> ?label. FILTER(LANGMATCHES(LANG(?label), 'en'))} " + "LIMIT 1000"; ResultSet rs = SparqlQuery.convertJSONtoResultSet(selectCache.executeSelectQuery(endpoint, newQuery)); QuerySolution qs; while (rs.hasNext()) { qs = rs.next(); property2LabelMap.put(qs.getResource("p").getURI(), qs.getLiteral("label").getLexicalForm()); } Iterator<String> it = property2LabelMap.keySet().iterator(); while (it.hasNext()) { String uri = it.next(); if (!uri.startsWith("http://dbpedia.org/ontology")) { it.remove(); } } property2LabelMap.put(RDFS.label.getURI(), "label"); return property2LabelMap; }
private Map<String, Integer> getStats(String sparqlQuery, QueryExecutionFactory qef) { Map<String, Integer> stats = new HashMap<>(); QueryExecution qe = null; try { qe = qef.createQueryExecution(sparqlQuery); ResultSet results = qe.execSelect(); while (results.hasNext()) { QuerySolution qs = results.next(); String s = qs.get("stats").toString(); int c = 0; if (qs.contains("count")) { c = qs.get("count").asLiteral().getInt(); } stats.put(s, c); } } finally { if (qe != null) { qe.close(); } } return stats; }
public static int getDataMatrix(Model model) { String sparqlQuery = String.format( "PREFIX ot:<%s>\n" + "PREFIX isa:<%s>\n" + "PREFIX dcterms:<http://purl.org/dc/terms/>\n" + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" + "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n" + "SELECT ?node ?feature ?title ?value where {\n" + " ?node rdf:type isa:Data." + " ?feature ot:hasSource ?node." + " ?feature dcterms:title ?title." + " ?fv ot:feature ?feature." + " ?fv ot:value ?value." + "} ORDER by ?node ?sample \n", OT.NS, ISA.URI); // Hashtable<String,Hashtable<String,String>> lookup = new Hashtable<String, // Hashtable<String,String>>(); Query query = QueryFactory.create(sparqlQuery); QueryExecution qe = QueryExecutionFactory.create(query, model); ResultSet rs = qe.execSelect(); int row = 0; while (rs.hasNext()) { QuerySolution qs = rs.next(); RDFNode node = qs.get("node"); RDFNode feature = qs.get("feature"); RDFNode title = qs.get("title"); RDFNode value = qs.get("value"); row++; } return row; // lookup; }
/** * Query SPARQL endpoint with a SELECT query * * @param qExec QueryExecution encapsulating the query * @return model retrieved by querying the endpoint */ private Model getSelectModel(QueryExecution qExec) { Model model = ModelFactory.createDefaultModel(); Graph graph = model.getGraph(); ResultSet results = qExec.execSelect(); while (results.hasNext()) { QuerySolution sol = results.next(); String subject; String predicate; RDFNode object; try { subject = sol.getResource("s").toString(); predicate = sol.getResource("p").toString(); object = sol.get("o"); } catch (NoSuchElementException e) { logger.error("SELECT query does not return a (?s ?p ?o) Triple"); continue; } Node objNode; if (object.isLiteral()) { Literal obj = object.asLiteral(); objNode = NodeFactory.createLiteral(obj.getString(), obj.getDatatype()); } else { objNode = NodeFactory.createLiteral(object.toString()); } graph.add( new Triple(NodeFactory.createURI(subject), NodeFactory.createURI(predicate), objNode)); } return model; }
@Test public void testSolutionVars() throws Exception { final QuerySolution solution = testObj.nextSolution(); final List<String> vars = ImmutableList.copyOf(solution.varNames()); assertArrayEquals(columnNames, vars.toArray()); }
public String sparql(String qry) { Model model = ModelFactory.createDefaultModel(); try { model.read(new FileInputStream("D:/AI Project/harsh/myNew.owl"), null, "RDF"); } catch (FileNotFoundException e) { e.printStackTrace(); } String res = null; String res1 = null; Query query = QueryFactory.create(qry); QueryExecution exec = QueryExecutionFactory.create(query, model); try { ResultSet rs = exec.execSelect(); while (rs.hasNext()) { QuerySolution soln = rs.nextSolution(); // res = soln.get("dn").toString(); res = soln.get("dn").toString(); System.out.println(res); System.out.println("HAS"); res1 = soln.get("rn").toString(); System.out.println(res1); } } finally { exec.close(); } return res; }
private static Set<Property> getPermissions(String userPrefix, String username, String uri) { Set<Property> permissions = new HashSet<Property>(); Resource resource = configModel.createResource(uri); Resource user; if (username == null) user = PERM.Public; else user = configModel.createResource(userPrefix + username); StmtIterator stmts = configModel.listStatements(user, null, resource); while (stmts.hasNext()) permissions.add(stmts.next().getPredicate()); String queryString = ""; queryString += "PREFIX perm: <http://vocab.ox.ac.uk/perm#>\n"; queryString += "SELECT ?perm ?regex WHERE {\n"; queryString += " <" + user.getURI() + "> ?perm ?rm ."; queryString += " ?rm a perm:ResourceMatch ;"; queryString += " perm:matchExpression ?regex }"; com.hp.hpl.jena.query.Query query = QueryFactory.create(queryString); QueryExecution qexec = QueryExecutionFactory.create(query, configModel); ResultSet results = qexec.execSelect(); while (results.hasNext()) { QuerySolution sol = results.next(); if (uri.matches(((Literal) sol.get("regex")).getLexicalForm())) permissions.add(configModel.createProperty(((Resource) sol.get("perm")).getURI())); } if (username != null) permissions.addAll(getPermissions(userPrefix, null, uri)); return permissions; }
public Map<String, List<RDFNode>> queryModel( String queryString, List<String> queryVariables, VirtDataset virtDataset) { Map<String, List<RDFNode>> solution = new HashMap<String, List<RDFNode>>(); QueryExecution qexec = null; try { qexec = QueryExecutionFactory.create(queryString, virtDataset); // ResultSet rs = executeQuery(sb.toString(), virtDataset); } catch (com.hp.hpl.jena.query.QueryParseException e) { System.err.println(ExceptionUtils.getStackTrace(e) + "\n Will return an empty map..."); return Collections.EMPTY_MAP; } ResultSet results = qexec.execSelect(); while (results.hasNext()) { QuerySolution sol = results.next(); for (String variable : queryVariables) { RDFNode nodeVar = sol.get(variable); if (nodeVar != null) { if (solution.get(variable) == null) { solution.put(variable, new ArrayList<RDFNode>()); } solution.get(variable).add(nodeVar); } } } return solution; }
@Override public List<Literal> getDataPropertyValuesForIndividualByProperty( String subjectUri, String propertyUri) { log.debug("Data property value query string:\n" + DATA_PROPERTY_VALUE_QUERY_STRING); log.debug("Data property value:\n" + dataPropertyValueQuery); QuerySolutionMap initialBindings = new QuerySolutionMap(); initialBindings.add("subject", ResourceFactory.createResource(subjectUri)); initialBindings.add("property", ResourceFactory.createResource(propertyUri)); // Run the SPARQL query to get the properties List<Literal> values = new ArrayList<Literal>(); DatasetWrapper w = dwf.getDatasetWrapper(); Dataset dataset = w.getDataset(); dataset.getLock().enterCriticalSection(Lock.READ); try { QueryExecution qexec = QueryExecutionFactory.create(dataPropertyValueQuery, dataset, initialBindings); ResultSet results = qexec.execSelect(); while (results.hasNext()) { QuerySolution soln = results.next(); RDFNode node = soln.get("value"); if (!node.isLiteral()) { continue; } Literal value = soln.getLiteral("value"); values.add(value); } } finally { dataset.getLock().leaveCriticalSection(); w.close(); } return values; }
@SuppressWarnings("unchecked") private static List<RDFNode> getURIObjects() { List<RDFNode> objectsURIs = new ArrayList<RDFNode>(); if (demo) { // Deserialize the results if exists (For Demo purpose) if (useCache) { try { List<String> ser = new ArrayList<String>(); File file = new File("URIObjects.ser"); if (file.exists()) { ObjectInputStream in; in = new ObjectInputStream(new FileInputStream(file)); ser = (List<String>) in.readObject(); in.close(); // convert every object back from string for (String n : ser) { objectsURIs.add(ResourceFactory.createResource(n)); } return objectsURIs; } } catch (Exception e) { e.printStackTrace(); } } } // create a query to retrieve URIs objects String queryString = "SELECT * " + "WHERE { ?s ?p ?o . FILTER (isURI(?o)) . " + "FILTER (STRSTARTS(STR(?o), \"" + resourcePrefix + "\"))}"; Query query = QueryFactory.create(queryString); QueryExecution exec = QueryExecutionFactory.create(query, localModel); ResultSet rs = exec.execSelect(); while (rs.hasNext()) { QuerySolution sol = rs.next(); RDFNode object = sol.get("?o"); objectsURIs.add(object); } if (demo) { // serialize the output (for Demo purpose) try { FileOutputStream fileOut = new FileOutputStream("URIObjects.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); // convert to Serializabe Strings List<String> l = new ArrayList<String>(); for (RDFNode n : objectsURIs) { l.add(n.toString()); } out.writeObject(l); out.close(); } catch (Exception e2) { e2.printStackTrace(); } } return objectsURIs; }
@Test public void testNextWithLiteralDouble() throws Exception { when(mockValue.getType()).thenReturn(PropertyType.DOUBLE); when(mockValue.getDouble()).thenReturn(1.0); final QuerySolution solution = testObj.next(); assertEquals(1.0, solution.get("a").asLiteral().getDouble(), 0.1); }
@Test public void testNextWithURI() throws Exception { when(mockValue.getType()).thenReturn(PropertyType.URI); when(mockValue.getString()).thenReturn("info:xyz"); final QuerySolution solution = testObj.next(); assertEquals("info:xyz", solution.get("a").asResource().getURI()); }
@Test public void testNextWithLiteralLong() throws Exception { when(mockValue.getType()).thenReturn(PropertyType.LONG); when(mockValue.getLong()).thenReturn(1L); final QuerySolution solution = testObj.next(); assertEquals(1L, solution.get("a").asLiteral().getLong()); }
@Test public void testNextWithLiteralBoolean() throws Exception { when(mockValue.getType()).thenReturn(PropertyType.BOOLEAN); when(mockValue.getString()).thenReturn("true"); final QuerySolution solution = testObj.next(); assertEquals("true", solution.get("a").asLiteral().getLexicalForm()); }
@Test public void testNextWithLiteral() throws Exception { when(mockValue.getString()).thenReturn("x"); final QuerySolution solution = testObj.next(); assertTrue(solution.contains("a")); assertEquals("x", solution.get("a").asLiteral().getLexicalForm()); assertEquals(solution.get("a"), solution.getLiteral("a")); }
private void resolveChildren(ModelTreeNode modelTreeNode, String oldModelUrl) throws IOException { ZdoModel model = modelTreeNode.getModel(); // If there is also a published version of this doc, find it, remove it and adopt all its // children if (oldModelUrl != null) { // Change its children to be ours String queryString = "SELECT ?subject WHERE {\n" + " ?subject <" + DCTerms.isPartOf.getURI() + "> <" + oldModelUrl + ">.\n" + "}"; QueryExecution queryExecution = QueryExecutionFactory.sparqlService(SPARQL_ENDPOINT, queryString); ResultSet resultSet = queryExecution.execSelect(); while (resultSet.hasNext()) { QuerySolution querySolution = resultSet.next(); RDFNode childNode = querySolution.get("subject"); String childToAdoptUrl = childNode.asResource().getURI(); ZdoModel childModel = store.get(childToAdoptUrl); childModel.replaceValueOfProperty( DCTerms.isPartOf, store.removeTransactionFromUrl(model.getUrl())); // If this children was published if (ZdoGroup.ZDO.name().equals(childModel.get(ZdoTerms.group))) { // Is this children getting replaced by newer version? if (modelTreeNodeKdrIndex.containsKey(childModel.get(ZdoTerms.kdrObject))) { // Yes, unpublish it ZdoModel childKdrObject = store.get(childModel.get(ZdoTerms.kdrObject)); markAsUnpublished(childModel, childKdrObject); store.update(childKdrObject); } else { // No, it should be added to our tree to solr ModelTreeNode childModelTreeNode = new ModelTreeNode(); childModelTreeNode.setModel(childModel); modelTreeNodeKdrIndex.put(childModel.get(ZdoTerms.kdrObject), childModelTreeNode); modelTreeNodeIndex.put( store.removeTransactionFromUrl(childModel.getUrl()), modelTreeNode); modelTreeNode.getChildren().add(childModelTreeNode); } } store.update(childModel); } } // Recurse on children for (ModelTreeNode childNode : modelTreeNode.getChildren()) { // Get kdr version of this doc ZdoModel kdrDoc = store.get(childNode.getModel().get(ZdoTerms.kdrObject)); resolveChildren(childNode, kdrDoc.get(ZdoTerms.newestPublished)); kdrDoc.replaceValueOfProperty( ZdoTerms.newestPublished, store.removeTransactionFromUrl(childNode.getModel().getUrl())); store.update(kdrDoc); } }
private void processPoint(QuerySolution solution, StringBuilder builder) { double lat = solution.get("lat").asLiteral().getDouble(); double longitude = solution.get("long").asLiteral().getDouble(); builder.append(lat).append(" ").append(longitude).append(","); if (this.firstLat == null && this.firstLong == null) { this.firstLat = lat; this.firstLong = longitude; } }
public static EConcept getEConcept(QuerySolution qs, Model model) { EConcept con = new EConcept(); String uri = qs.get("?concept").toString().trim(); String id = model.getResource(uri).getLocalName(); String name = qs.get("?c_name").toString().trim(); con.setCid(id); con.setName(StringExchanger.getCommonString(name)); return con; }
@Test public void testNextWithLiteralDate() throws Exception { when(mockValue.getType()).thenReturn(PropertyType.DATE); final Calendar date = Calendar.getInstance(); when(mockValue.getDate()).thenReturn(date); final QuerySolution solution = testObj.next(); assertNotNull(solution.get("a").asLiteral()); assertEquals(XSDDatatype.XSDdateTime.getURI(), solution.get("a").asLiteral().getDatatypeURI()); }
@Override public Iterator<Quad> find(Node graph, Node subject, Node predicate, Node object) { if (!isVar(subject) && !isVar(predicate) && !isVar(object) && !isVar(graph)) { if (contains(subject, predicate, object, graph)) { return new SingletonIterator(new Triple(subject, predicate, object)); } else { return WrappedIterator.create(Collections.EMPTY_LIST.iterator()); } } StringBuffer findQuery = new StringBuffer("SELECT * WHERE { \n"); String graphURI = !isVar(graph) ? graph.getURI() : null; findQuery.append(" GRAPH "); if (graphURI != null) { findQuery.append(" <" + graphURI + ">"); } else { findQuery.append("?g"); } findQuery.append(" { "); findQuery .append(SparqlGraph.sparqlNode(subject, "?s")) .append(" ") .append(SparqlGraph.sparqlNode(predicate, "?p")) .append(" ") .append(SparqlGraph.sparqlNode(object, "?o")); findQuery.append(" } "); findQuery.append("\n}"); // log.info(findQuery.toString()); ResultSet rs = null; try { rs = JSONInput.fromJSON( rdfService.sparqlSelectQuery(findQuery.toString(), RDFService.ResultFormat.JSON)); } catch (RDFServiceException rdfse) { throw new RuntimeException(rdfse); } List<Quad> quadlist = new ArrayList<Quad>(); while (rs.hasNext()) { QuerySolution soln = rs.nextSolution(); Quad q = new Quad( isVar(graph) ? soln.get("?g").asNode() : graph, isVar(subject) ? soln.get("?s").asNode() : subject, isVar(predicate) ? soln.get("?p").asNode() : predicate, isVar(object) ? soln.get("?o").asNode() : object); // log.info(t); quadlist.add(q); } // log.info(triplist.size() + " results"); return WrappedIterator.create(quadlist.iterator()); }
@Test public void testNextWithReference() throws Exception { when(mockValue.getType()).thenReturn(PropertyType.REFERENCE); when(mockValue.getString()).thenReturn("uuid"); when(mockSession.getNodeByIdentifier("uuid")).thenReturn(mockNode); when(mockGraphSubjects.getSubject(mockNode.getPath())) .thenReturn(ResourceFactory.createResource("http://localhost:8080/xyz")); final QuerySolution solution = testObj.next(); assertEquals("http://localhost:8080/xyz", solution.get("a").asResource().getURI()); }
@Test public void testNextWithResource() throws Exception { when(mockValue.getType()).thenReturn(PropertyType.PATH); when(mockValue.getString()).thenReturn("/x"); when(mockGraphSubjects.getSubject("/x")).thenReturn(ResourceFactory.createResource("info:x")); final QuerySolution solution = testObj.next(); assertTrue(solution.contains("a")); assertEquals("info:x", solution.get("a").asResource().getURI()); assertEquals(solution.get("a"), solution.getResource("a")); }
public Item(String uri, ResultSet set, String s, String p, String o) { this.uri = uri; values = new ArrayList<Prop>(); while (set.hasNext()) { QuerySolution result = set.nextSolution(); String relation = result.get(p).toString(); String value = result.get(o).toString(); values.add(new Prop(relation, value, result.get(o).isLiteral(), false)); } }
// method to get Hospital list given treatment type public static void issueSPARQLTreatment_Hospital( Model m, String treatMent_Name, HashMap hos_treatment) { /** * **************************************Getting test name type by cancer * name******************************************************** */ String causes_val = treatMent_Name; // String drug="HPV"; String defaultNameSpace = "http://www.semanticweb.org/janani/ontologies/2015/3/cancer-treatment#"; String offersNameSpace = "<http://www.semanticweb.org/janani/ontologies/2015/3/cancer-treatment#offers>"; String ntemp1 = "<" + defaultNameSpace + treatMent_Name + ">"; String temp1 = ""; temp1 = temp1 + " ?Hospital " + offersNameSpace + " " + ntemp1 + " ."; String queryStringDrug = "SELECT ?Hospital " + "WHERE {" + temp1 + " }"; System.out.println(queryStringDrug); Query query1 = QueryFactory.create(queryStringDrug); QueryExecution qe1 = QueryExecutionFactory.create(query1, m); ResultSet results1 = qe1.execSelect(); // ResultSetFormatter.out(System.out, results1, query1); RDFNode hospital_name; // System.out.println("Treatment is: "+ treatMent_Name); // System.out.println("Hospitals are: "); while (results1.hasNext()) { String[] Hos_name; QuerySolution querySolution = results1.next(); hospital_name = querySolution.get("Hospital"); String temp_val = String.valueOf(hospital_name); Hos_name = temp_val.split("#"); // System.out.println(Hos_name[1]); hos_treatment.put(treatMent_Name, Hos_name[1]); // if(!Hospital_list.contains(Hos_name[1])) // { // Hospital_list.add(Hos_name[1]); // // System.out.println(Hos_name[1]); // } } }
@Test(enabled = true) public void selectAllNamedGraphs() { List<String> namedGraphs = new ArrayList<String>(); String query = "SELECT DISTINCT(?g) WHERE { GRAPH ?g { ?s ?p ?o } }"; ResultSet results = Util.executeQuery(query, virtDataset); while (results.hasNext()) { QuerySolution sol = results.next(); RDFNode nodeVar = sol.get("g"); namedGraphs.add(nodeVar.toString()); } System.out.println(namedGraphs); }
public static ISCB_Resource getEResource(QuerySolution qs, Model model) { ISCB_Resource res = new ISCB_Resource(); String uri = qs.get("?resource").toString().trim(); String id = model.getResource(uri).getLocalName(); String name = qs.get("?r_name").toString().trim(); String difficulty = qs.get("?r_difficulty").toString().trim(); String fileLocation = qs.get("?r_fileLocation").toString().trim(); res.setRid(id); res.setName(StringExchanger.getCommonString(name)); res.setDifficulty(StringExchanger.getCommonString(difficulty)); res.setFileLocation(StringExchanger.getCommonString(fileLocation)); return res; }