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 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; }
@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 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 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; }
@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 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()); }
@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)); } }
@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()); }
@Override public List<String> executeSparql(String query) throws QueryParseException, QueryException { ResultSet rs = endpointConnector.executeQuery(query); List<String> results = new ArrayList<String>(); while (rs.hasNext()) { QuerySolution qs = rs.next(); if (qs.get("variable") != null) results.add(qs.get("variable").toString()); } return results; }
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; }
public void deleteProperty(String yourInstance, String yourProperty) { // 查找属性URI String sparqlProperty = "SELECT ?property WHERE{?property <http://www.w3.org/2000/01/rdf-schema#label> '" + yourProperty + "'@zh.}"; ResultSet resultsProperty = Result(sparqlProperty); QuerySolution solutionProperty = null; while (resultsProperty.hasNext()) solutionProperty = resultsProperty.next(); // System.out.println(sparqlProperty); // System.out.println(solutionProperty.get("?property")); // 查找属性值 String sparqlPropertyValue = "SELECT ?propertyValue WHERE{<http://www.semanticweb.org/administrator/ontologies/2015/6/untitled-ontology-31#'" + yourInstance + "'@zh> <" + solutionProperty.get("?property") + "> " + "?propertyValue}"; ResultSet resultsPropertyValue = Result(sparqlPropertyValue); QuerySolution solutionPropertyValue = null; while (resultsPropertyValue.hasNext()) solutionPropertyValue = resultsPropertyValue.next(); // System.out.println(sparqlPropertyValue); // System.out.println(solutionPropertyValue.get("?propertyValue")); String string1 = solutionPropertyValue.toString(); int i = string1.length(); i = i - 2; String string2 = (String) string1.subSequence(19, i); System.out.println(string2); // 删除实例属性 String sparqlDeleteProperty = "delete data{<http://www.semanticweb.org/administrator/ontologies/2015/6/untitled-ontology-31#'" + yourInstance + "'@zh> <" + solutionProperty.get("?property") + "> " + string2 + "}"; // System.out.println(sparqlDeleteProperty); UpdateRequest updateProperty = UpdateFactory.create(sparqlDeleteProperty); UpdateProcessor qexecProperty = UpdateExecutionFactory.createRemote(updateProperty, UPDATE_SERVER); qexecProperty.execute(); }
public static ELearner getELearner(QuerySolution qs, Model model) { ELearner el = new ELearner(); String uri = qs.get("?elearner").toString().trim(); String id = model.getResource(uri).getLocalName(); String name = qs.get("?el_name").toString().trim(); String grade = qs.get("?el_grade").toString().trim(); String email = qs.get("?el_email").toString().trim(); String address = qs.get("?el_address").toString().trim(); el.setId(id); el.setName(StringExchanger.getCommonString(name)); el.setGrade(StringExchanger.getCommonString(grade)); el.setEmail(StringExchanger.getCommonString(email)); el.setAddress(StringExchanger.getCommonString(address)); return el; }
/** * Selects a triple by providing an RDFStatement object collection * * @param stmts * @return Query result */ public List<RDFStatement> selectTriples(Collection<? extends RDFStatement> stmts) { if (stmts == null || stmts.isEmpty()) { return null; } RDFStatement rdfs = stmts.stream().findFirst().get(); String si = rdfs.getSubject(), pi = rdfs.getPredicate(), oi = rdfs.getObject(); // doesnt get value StringBuilder sb = new StringBuilder(); stmts .stream() .forEach( s -> { s.setObject(RDFUtils.escapeString(s.getObject())); sb.append(s.getSubject()) .append(" ") .append(s.getPredicate()) .append(" ") .append(s.getObject()) .append(" .\n"); }); String query = String.format( this.defaultPrefices + "SELECT * FROM <%s> WHERE { %s }", this.graphName, sb.toString()); Query sparqlQuery = QueryFactory.create(query); VirtuosoQueryExecution vqe = VirtuosoQueryExecutionFactory.create(sparqlQuery, this.graph); List<RDFStatement> stmtsList = new ArrayList<>(); ResultSet rs = vqe.execSelect(); while (rs.hasNext()) { QuerySolution qs = rs.nextSolution(); RDFNode s = qs.get(si); RDFNode p = qs.get(pi); RDFNode o = qs.get(oi); RDFStatement stmt = new RDFStatement( s != null ? s.toString() : "null", p != null ? p.toString() : "null", o != null ? RDFUtils.escapeString(o.toString()) : "null"); stmtsList.add(stmt); logger.info("fetched: {}", stmt.toString()); } return stmtsList; }
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; }
/** * 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; }
@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; }
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; }
// This is the inference method for getting data from OWL file public String sparqlInferenceMethod(String qry) { OntModel ont = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_MICRO_RULE_INF, null); try { ont.read( new FileInputStream( // "D:/AI Project/harsh/myNew.owl"), "SmartHospital.owl"), null, "RDF"); } catch (FileNotFoundException e) { e.printStackTrace(); } Reasoner reasoner = ReasonerRegistry.getOWLMicroReasoner(); reasoner = reasoner.bindSchema(ont); Dataset dataset = TDBFactory.createDataset(); Model model = dataset.getDefaultModel(); InfModel infModel = ModelFactory.createInfModel(reasoner, model); String disease = null; String hospital = null; String hospitalCode = null; StringBuilder res = new StringBuilder(); Query query = QueryFactory.create(qry); QueryExecution exec = QueryExecutionFactory.create(query, infModel); try { System.out.println("here"); ResultSet rs = exec.execSelect(); while (rs.hasNext()) { QuerySolution soln = rs.nextSolution(); disease = soln.get("dn").toString(); hospital = soln.get("hn").toString(); hospitalCode = soln.get("hc").toString(); } } finally { exec.close(); } res.append(disease); res.append("::"); res.append(hospital); res.append("::"); res.append(hospitalCode); return res.toString(); }
@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; }
public static Map<String, RDFNode> solutionMap(QuerySolution qs, List<String> vars) { Map<String, RDFNode> result = new HashMap<String, RDFNode>(); for (String var : vars) { RDFNode val = qs.get(var); result.put(var, val.isAnon() ? DUMMY_FOR_BNODE : val); } return result; }
public static JSONObject buildAnswerBoxFeatures(String uri) { JSONObject document = new JSONObject(); document.put("URI", new JsonString(uri)); Set<RDFNode> set = Sets.newHashSet(); try { String query = "select ?thumbnail ?abstract ?comment ?label" + "where {" + "<" + uri + "> <http://dbpedia.org/ontology/thumbnail> ?thumbnail;" + "<http://dbpedia.org/ontology/abstract> ?abstract;" + "<http://www.w3.org/2000/01/rdf-schema#label> ?label;" + "<http://www.w3.org/2000/01/rdf-schema#comment> ?comment." + "FILTER(langMatches(lang(?abstract), \"EN\") &&" + " langMatches(lang(?label), \"EN\") &&" + " langMatches(lang(?comment), \"EN\"))" + "}"; QueryExecution qe = qef.createQueryExecution(query); if (qe != null && query.toString() != null) { ResultSet results = qe.execSelect(); while (results.hasNext()) { QuerySolution next = results.next(); RDFNode thumbnail = next.get("thumbnail"); RDFNode abstractLiteral = next.get("abstract"); RDFNode commentLiteral = next.get("comment"); RDFNode labelLiteral = next.get("label"); if (thumbnail != null) { document.put("thumbnail", new JsonString(thumbnail.asResource().getURI())); } if (abstractLiteral != null) { document.put("abstract", new JsonString(abstractLiteral.asLiteral().getString())); } if (commentLiteral != null) { document.put("comment", new JsonString(commentLiteral.asLiteral().getString())); } if (labelLiteral != null) { document.put("label", new JsonString(labelLiteral.asLiteral().getString())); } } } } catch (Exception e) { log.error("Cannot ask DBpedia for verbose description of " + uri, e); } return document; }
@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 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 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()); }