Ejemplo n.º 1
0
  /* @see org.mindswap.common.Parser#parse(java.lang.Object) */
  public ABoxQuery<Variable> parse(final String queryString) throws ParseException {
    if (queryString == null) throw new ParseException(queryString, "Query string null.");

    final Query query;
    try {
      switch (lang) {
        case RDQL:
          query = QueryFactory.create(queryString, Syntax.syntaxRDQL);
          break;
        case SPARQL_DL:
        case SPARQL:
        default:
          query = QueryFactory.create(queryString, Syntax.syntaxSPARQL);
          break;
      }
    } catch (final QueryException e) {
      throw new ParseException(queryString, e);
    }

    final ISWRLFactory swrlFactory = SWRLFactory.createFactory(model);
    final Map<String, Variable> vars = new HashMap<String, Variable>();
    final Element elmnt = query.getQueryPattern();
    final ElementVisitor v = new ElementVisitor(model, swrlFactory, vars);
    elmnt.visit(v);
    final OWLList<Atom> atomList = v.getAtomList();

    final List<Variable> resultVars = new ArrayList<Variable>();
    for (final String var : query.getResultVars()) {
      resultVars.add(vars.get("?" + var));
    }

    return new ABoxQuery<Variable>(atomList, resultVars);
  }
Ejemplo n.º 2
0
 @Test
 public void testDetectSelectStar() {
   Query selectStar = QueryFactory.create("SELECT * { ?s ?p ?o }");
   assertTrue(selectStar.isQueryResultStar());
   Query selectVars = QueryFactory.create("SELECT ?s ?p ?o { ?s ?p ?o }");
   assertFalse(selectVars.isQueryResultStar());
 }
Ejemplo n.º 3
0
  /**
   * Returns a collection of RDFStatements that match the described subject
   *
   * @param subject Subject
   * @return collection of RDFStatements
   */
  public Collection<RDFStatement> getStatements(String subject) {

    if (subject == null || subject.isEmpty()) {
      return null;
    }
    List<RDFStatement> statement = null;

    try {
      // define a describe query
      String query = String.format("DESCRIBE %s FROM < %s >", subject, this.graphName);

      logger.debug("Query: \n{}", query);
      Query sparqlQuery = QueryFactory.create(query);
      VirtuosoQueryExecution vqe = VirtuosoQueryExecutionFactory.create(sparqlQuery, this.graph);
      // execute the query and get the graph
      Model model = vqe.execDescribe();
      Graph queriedGraph = model.getGraph();
      // itreate over the retrieved triples, and place them inside a list
      ExtendedIterator<Triple> iter = queriedGraph.find(Node.ANY, Node.ANY, Node.ANY);
      statement = new ArrayList<>();
      while (iter.hasNext()) {
        Triple t = (Triple) iter.next();
        RDFStatement stmt =
            new RDFStatement(
                t.getSubject().toString(), t.getPredicate().toString(), t.getObject().toString());
        statement.add(stmt);
      }
    } catch (Exception ex) {
      logger.error("Exception occured while querying for statements", ex);
    }
    return statement;
  }
Ejemplo n.º 4
0
  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;
  }
Ejemplo n.º 5
0
  private ResultSet executeQuery(String queryText, Model dataset) {

    QueryExecution queryExecution = null;
    Query query = QueryFactory.create(queryText, SYNTAX);
    queryExecution = QueryExecutionFactory.create(query, dataset);
    return queryExecution.execSelect();
  }
  // NEED -> SUPERCLASSE
  private ArrayList<java.net.URI> getSuperClassFromUri(String uri) {
    String queryBegin =
        "PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
            + "PREFIX mstr: <http://methodo-stat-tutor.com#>\n"
            + "PREFIX rdfs:     <http://www.w3.org/2000/01/rdf-schema#>\n"
            + "PREFIX owl:      <http://www.w3.org/2002/07/owl#> \n"
            + "PREFIX sparqldl: <http://pellet.owldl.com/ns/sdle#>\n "
            + "SELECT DISTINCT ?SUPERCLASS ?LAB ?COM \n"
            + "WHERE {";
    String queryEnd = "}";

    String queryStr2 =
        queryBegin
            +
            // "?titi  owl:Class ?CLASS ." +
            // "?NOTION a ?CLASS ." +
            "?CLASS sparqldl:directSubClassOf ?SUPERCLASS ."
            + "OPTIONAL {?SUPERCLASS rdfs:label ?LAB} ."
            + "OPTIONAL {?SUPERCLASS rdfs:comment ?COM} ."
            + "FILTER (?CLASS = <"
            + uri
            + ">)"
            + queryEnd;
    log.error(queryStr2);
    Query query2 = QueryFactory.create(queryStr2);
    ResultSet results = SparqlDLExecutionFactory.create(query2, ontModel).execSelect();
    ArrayList<java.net.URI> aru = new ArrayList<java.net.URI>();
    while (results.hasNext()) {
      aru.add(java.net.URI.create(results.next().get("?SUPERCLASS").toString()));
    }
    return aru;
  }
  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;
  }
 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;
 }
Ejemplo n.º 9
0
  /**
   * This method constructs numeric {@link OpFilter} instance with given index value and using given
   * substituted {@link OpFilter} instance
   *
   * @param index to add all variables in filter block
   * @param substitutedOp {@link OpFilter} instance whose filter block will be turned into numeric
   *     one.
   * @return numeric {@link OpFilter} instance
   */
  private static Op constructNumericOpFilter(int index, Op substitutedOp) {
    Op numericOpFilter = substitutedOp;

    // check whether op instance is an OpFilter
    if (substitutedOp instanceof OpFilter) {
      // turn OpFilter into query
      Query query = OpAsQuery.asQuery(substitutedOp);

      // System.out.println("Query before: " + query);

      // assign index
      final int finalIndex = index;
      // construct numeric filter block
      List<VariablePair> variablePairs = constructVariablePairs(query, finalIndex);
      // get query as text
      String queryStr = query.toString();
      // split query and get filter including second part of query text
      String[] splittedQuery = queryStr.split(FILTER_KEYWORD);
      // replace variables of given text
      String filterIncludingPart = replaceVariables(variablePairs, splittedQuery[1]);

      // construct final query
      String finalQueryText = splittedQuery[0] + FILTER_KEYWORD + filterIncludingPart;

      // System.out.println("Query after: " + finalQueryText);

      // create plan for query and get OpFilter instance from it
      numericOpFilter =
          QueryExecutionFactory.createPlan(
                  QueryFactory.create(finalQueryText), DatasetGraphFactory.createMem(), null)
              .getOp();
    }
    return numericOpFilter;
  }
  /**
   * Queries the {@link #rdfEndpoint(String)} with each of the {@link #rdfQueries} and harvests the
   * results of the query.
   */
  private void harvestFromEndpoint() {

    Query query;
    QueryExecution qExec;

    for (String rdfQuery : rdfQueries) {
      if (closed) break;

      logger.info(
          "Harvesting with query: [{}] on index [{}] and type [{}]", rdfQuery, indexName, typeName);

      try {
        query = QueryFactory.create(rdfQuery);
      } catch (QueryParseException qpe) {
        logger.error("Could not parse [{}]. Please provide a relevant query. {}", rdfQuery, qpe);
        continue;
      }

      qExec = QueryExecutionFactory.sparqlService(rdfEndpoint, query);

      try {
        harvest(qExec);
      } catch (Exception e) {
        logger.error("Exception [{}] occurred while harvesting", e.getLocalizedMessage());
      } finally {
        qExec.close();
      }
    }
  }
Ejemplo n.º 11
0
  public static QuerySolution evaluationOfSPARQLQueryAgainstModel(String queryString, Model model) {

    // that will be our result
    QuerySolution soln = null;

    // Create a SPARQL query from the given string
    Query query = QueryFactory.create(queryString);

    // Create a QueryExecution to execute over the Model.
    QueryExecution qexec = QueryExecutionFactory.create(query, model);

    try {

      // Results from a query in a table-like manner for SELECT queries. Each row corresponds to a
      // set of bindings which fulfill the conditions of the query. Access to the results is by
      // variable name.
      ResultSet results = qexec.execSelect();

      while (results.hasNext()) {

        // QuerySolution -- A single answer from a SELECT query.
        // results.nextSolution() -- Moves to the next result
        soln = results.nextSolution();
      }
    } finally {
      qexec.close();
    }

    return soln;
  }
Ejemplo n.º 12
0
  public static void main(String[] args) {
    // String sA = "Select * { ?s ?p ?o . Filter((?s || ?p) && ?o) . }";
    // String sA = "Select * { ?s ?p ?o . Filter((?s || ?p) && !(?o || ?g)) . }";

    String sA =
        "Select * { ?s ?p ?o . Filter(?o != <http://Person>). Optional { { ?x ?y ?z . Filter(?x != <http://x> && ?x = ?y) . } Union { ?x a ?y . Filter(?x = <http://x>) . } } . }";

    // String sA = "Select * { ?s ?p ?o . Filter(!(?s = ?p || ?p = ?o && ?s = ?o || ?o = ?s)) . }";
    // String sA = "Select * { ?s ?p ?o . Filter(!(?s = ?p || ?j = <http://x>)) . }";
    Query qA = QueryFactory.create(sA);

    Op opA = Algebra.compile(qA);
    opA = Algebra.toQuadForm(opA);

    System.out.println(opA);

    // How to deal with union? variables appearing in them

    // System.out.println(opA.getClass());
    ExprList exprs = FilterUtils.collectExprs(opA, new ExprList());

    ExprList proc = eval(exprs);
    System.out.println(proc);

    List<ExprList> clauses = dnfToClauses(proc);

    System.out.println("Mentioned vars:" + proc.getVarsMentioned());

    System.out.println("Clauses: " + clauses);
  }
Ejemplo n.º 13
0
  @Test
  public void testQueryAddValuesInQueryPattern() {
    List<Var> header = vars("a", "b");
    Binding b1 = binding(header, "1", "2");
    Binding b2 = binding(header, "3", "4");

    Query q = QueryFactory.create("SELECT * {}");
    ElementGroup group = new ElementGroup();
    ElementData table = new ElementData();
    table.add(Var.alloc("a"));
    table.add(Var.alloc("b"));
    table.add(b1);
    table.add(b2);
    group.addElement(q.getQueryPattern());
    group.addElement(table);
    q.setQueryPattern(group);
    ResultSet rs = QueryExecutionFactory.create(q, ModelFactory.createDefaultModel()).execSelect();

    assertEquals(Arrays.asList(new String[] {"a", "b"}), rs.getResultVars());
    assertTrue(rs.hasNext());
    assertEquals(b1, rs.nextBinding());
    assertTrue(rs.hasNext());
    assertEquals(b2, rs.nextBinding());
    assertFalse(rs.hasNext());
  }
Ejemplo n.º 14
0
  @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;
  }
Ejemplo n.º 15
0
 @Test
 public void testSPARQLFilterIsAppliedToValues() {
   Query q = QueryFactory.create("SELECT * { FILTER(?a=1) VALUES (?a) { (1) (2) } }");
   ResultSet rs = QueryExecutionFactory.create(q, ModelFactory.createDefaultModel()).execSelect();
   assertTrue(rs.hasNext());
   assertEquals(binding(vars("a"), "1"), rs.nextBinding());
   assertFalse(rs.hasNext());
 }
Ejemplo n.º 16
0
 private Set<String> extractVars(String query) {
   log.debug(" {}", query);
   Query q = QueryFactory.create(query);
   Element element = q.getQueryPattern();
   ElementWalker.walk(element, collector);
   Set<String> vars = collector.getVariables();
   log.debug(" > {}", vars);
   return vars;
 }
 static {
   try {
     dataPropertyValueQuery = QueryFactory.create(DATA_PROPERTY_VALUE_QUERY_STRING);
   } catch (Throwable th) {
     log.error(
         "could not create SPARQL query for DATA_PROPERTY_VALUE_QUERY_STRING " + th.getMessage());
     log.error(DATA_PROPERTY_VALUE_QUERY_STRING);
   }
 }
  @Override
  public void processResults() {
    String queryBegin =
        "PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>"
            + "PREFIX mstr: <http://methodo-stat-tutor.com#>"
            + "SELECT ?NOTION "
            + "WHERE {";
    String queryEnd = "}";

    // create a query that asks for the color of the wine that
    // would go with each meal course

    String queryStr2 =
        queryBegin
            + " ?EXO mstr:traiteNotion ?NOTION ."
            + "FILTER (?EXO = mstr:"
            + this.exercise
            + ")\n"
            + queryEnd;
    log.error(queryStr2);
    Query query2 = QueryFactory.create(queryStr2);
    ResultSet results = SparqlDLExecutionFactory.create(query2, ontModel).execSelect();
    ArrayList<java.net.URI> needNotion = new ArrayList<java.net.URI>();
    ArrayList<java.net.URI> giveNotion = new ArrayList<java.net.URI>();

    while (results.hasNext()) {
      RDFNode a = results.next().get("?NOTION");
      giveNotion.add(java.net.URI.create(a.asLiteral().getString()));
      needNotion.addAll(getSuperClassFromUri(a.asLiteral().getString()));
    }
    // remove duplicates from neednotion
    Set<java.net.URI> hs = new HashSet<>();
    hs.addAll(needNotion);
    needNotion.clear();
    needNotion.addAll(hs);
    // end remove duplicate

    this.needNotion = needNotion;
    this.giveNotion = giveNotion;

    // ajout des notions au modele
    int i = 0;
    while (i < needNotion.size()) {
      log.error(needNotion.get(i).toString());
      addStatementToOntModel("needNotion", needNotion.get(i).toString());
      i++;
    }
    i = 0;
    while (i < giveNotion.size()) {
      log.error(giveNotion.get(i).toString());
      addStatementToOntModel("giveNotion", giveNotion.get(i).toString());
      i++;
    }
  }
  public String getQcmNotion() {
    String queryBegin =
        "PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
            + "PREFIX mstr: <http://methodo-stat-tutor.com#>\n"
            + "PREFIX rdfs:     <http://www.w3.org/2000/01/rdf-schema#>\n"
            + "PREFIX owl:      <http://www.w3.org/2002/07/owl#> \n"
            + "PREFIX sparqldl: <http://pellet.owldl.com/ns/sdle#>\n "
            + "SELECT ?NOTION ?NOTIONLAB ?NOTIONCOMM ?TYP  \n"
            + "WHERE {";
    String queryEnd = "}";

    // create a query that asks for the color of the wine that
    // would go with each meal course
    String queryStr2 =
        queryBegin
            + "{?EXO a mstr:Qcm .\n"
            + " ?EXO mstr:traiteNotion ?NOTION .\n"
            + " BIND(IRI(str(?NOTION)) as ?NOTION_IRI) .\n"
            + "OPTIONAL { ?NOTION_IRI rdfs:label ?NOTIONLAB } .\n"
            + "OPTIONAL { ?NOTION_IRI rdfs:comment ?NOTIONCOMM } \n"
            + "values ?TYP { 'traite' }\n"
            + "FILTER (?EXO = mstr:"
            + this.exercise
            + ")\n"
            + "}\n"
            + "UNION \n"
            + "{?EXO a mstr:Qcm .\n"
            + " ?EXO mstr:needNotion ?NOTION .\n"
            + " BIND(IRI(str(?NOTION)) as ?NOTION_IRI) .\n"
            + "OPTIONAL { ?NOTION_IRI rdfs:label ?NOTIONLAB } .\n"
            + "OPTIONAL { ?NOTION_IRI rdfs:comment ?NOTIONCOMM } \n"
            + "values ?TYP { 'need' }\n"
            + "FILTER (?EXO = mstr:"
            + this.exercise
            + ")"
            + "}"
            + "UNION \n"
            + "{?EXO a mstr:Qcm .\n"
            + " ?EXO mstr:giveNotion ?NOTION .\n"
            + " BIND(IRI(str(?NOTION)) as ?NOTION_IRI) .\n"
            + "OPTIONAL { ?NOTION_IRI rdfs:label ?NOTIONLAB } .\n"
            + "OPTIONAL { ?NOTION_IRI rdfs:comment ?NOTIONCOMM } \n"
            + "values ?TYP { 'give' }\n"
            + "FILTER (?EXO = mstr:"
            + this.exercise
            + ")"
            + " }"
            + queryEnd;
    log.error(queryStr2);
    Query query2 = QueryFactory.create(queryStr2);
    ResultSet results = SparqlDLExecutionFactory.create(query2, ontModel).execSelect();
    String str = MstrUtils.getSparqlResultsetAsJson(results);
    return str;
  }
Ejemplo n.º 20
0
  @Override
  public QueryExecution apply(final Dataset dataset) {

    try {
      final Model model = unifyDatasetModel(dataset);
      final Query sparqlQuery = QueryFactory.create(IOUtils.toString(query));

      return QueryExecutionFactory.create(sparqlQuery, model);
    } catch (final IOException e) {
      throw new IllegalStateException(e);
    }
  }
 /**
  * Execute an ASK query
  *
  * @param query
  * @return
  */
 public boolean executeAskQuery(String query) {
   Query query1 = QueryFactory.create(query);
   QueryExecution qexec = QueryExecutionFactory.create(query1, ontologie);
   try {
     if (query.toLowerCase().contains("ask")) {
       return (qexec.execAsk());
     }
   } finally {
     qexec.close();
   }
   return 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]);
      //						 }

    }
  }
Ejemplo n.º 23
0
  /** Rigourous Test :-) */
  public void testApp() {
    final List resultvars = QueryFactory.create("select ?x ?y WHERE {?x a ?Y}").getResultVars();
    System.out.println(
        ResultSetFormatter.asXMLString(
            new ResultSet() {

              public Model getResourceModel() {
                // TODO Auto-generated method stub
                return null;
              }

              public List getResultVars() {
                // TODO Auto-generated method stub
                return resultvars;
              }

              public int getRowNumber() {
                // TODO Auto-generated method stub
                return 0;
              }

              public boolean hasNext() {
                // TODO Auto-generated method stub
                return false;
              }

              public boolean isOrdered() {
                // TODO Auto-generated method stub
                return false;
              }

              public Object next() {
                // TODO Auto-generated method stub
                return null;
              }

              public Binding nextBinding() {
                // TODO Auto-generated method stub
                return null;
              }

              public QuerySolution nextSolution() {
                // TODO Auto-generated method stub
                return null;
              }

              public void remove() {
                // TODO Auto-generated method stub

              }
            }));
  }
Ejemplo n.º 24
0
  private void compareQuery(URL htmlURL, URL compareURL) throws SAXException, IOException {
    Query query = QueryFactory.read(compareURL.toExternalForm());

    Map<String, Query> qs =
        QueryUtilities.makeQueries(ParserFactory.Format.XHTML, htmlURL.toExternalForm());

    assertTrue("We have a query", qs.size() != 0);

    Query qFromHTML = qs.get(qs.keySet().toArray()[0]);

    assertEquals(
        "Query matches (" + htmlURL + ")", Algebra.compile(query), Algebra.compile(qFromHTML));
  }
Ejemplo n.º 25
0
  public String executeQuery(String queryString) {
    /*
    //System.out.println(queryString);
    Query query = QueryFactory.create(queryString);

    QueryExecution qe = QueryExecutionFactory.create(query, model);
    ResultSet results = qe.execSelect();

    ByteArrayOutputStream ostream = new ByteArrayOutputStream();

    ResultSetFormatter.out(ostream, results, query);
    //ResultSetFormatter.out(System.out, results, query);
    String r = "";
    try{
        r = new String(ostream.toByteArray(), "UTF-8");
        //System.out.println(r);
    }
    catch(Exception e){
        System.out.println(e.getMessage());
    }
    qe.close();
    return r;
    */

    //// new added for test JSON output
    try {
      Query query = QueryFactory.create(queryString);

      QueryExecution qe = QueryExecutionFactory.create(query, model);
      ResultSet results = qe.execSelect();

      ByteArrayOutputStream ostream = new ByteArrayOutputStream();
      ResultSetFormatter.outputAsJSON(ostream, results);
      // ResultSetFormatter.out(ostream, results, query);
      // ResultSetFormatter.out(System.out, results, query);
      String r = "";
      try {
        r = new String(ostream.toByteArray(), "UTF-8");
        // System.out.println(r);
      } catch (Exception e) {
        System.out.println(e.getMessage());
      }
      qe.close();
      return r;
    } catch (Exception e) {
      System.out.println(e.toString());
      return "";
    }
  }
Ejemplo n.º 26
0
 /**
  * The constructor of the SPARQL list object.
  *
  * @param store The reference to the data store.
  * @param query The string containing the query.
  * @throws PersistanceQueryException
  */
 public JenaSPARQLList(Model store, String queryString) throws PersistanceQueryException {
   try {
     Query query = QueryFactory.create(queryString);
     QueryExecution executioner = QueryExecutionFactory.create(query, store);
     ResultSet resultSet = executioner.execSelect();
     while (resultSet.hasNext()) {
       QuerySolution solution = resultSet.nextSolution();
       JenaPersistanceResultRow row = new JenaPersistanceResultRow(store, solution);
       this.add(row);
     }
   } catch (Exception ex) {
     log.error("Failed to execute the query : " + ex.getMessage(), ex);
     throw new PersistanceQueryException("Failed to execute the query : " + ex.getMessage(), ex);
   }
 }
Ejemplo n.º 27
0
 @Override
 public QueryResult query(String queryString, String language, String baseURI) {
   Model graph = null;
   GraphConnection graphConnection = null;
   QueryResult res = null;
   QueryExecution qe = null;
   try {
     graphConnection = openGraph();
     graph = graphConnection.getGraph();
     graph.enterCriticalSection(Lock.READ);
     log.debug(String.format("Running query %s", queryString));
     // XXX AT: ignore language for now
     if (language != null && !language.equals("sparql")) {
       log.warn(String.format("Unknown language %s for query, using SPARQL", language));
     }
     Query query = QueryFactory.create(queryString);
     query.setBaseURI(baseURI);
     qe = QueryExecutionFactory.create(query, graph);
     res = new QueryResultImpl(0, new ArrayList<String>(), new ArrayList<Map<String, Node>>());
     ResultSet jenaResults = qe.execSelect();
     Integer count = 0;
     List<String> variableNames = jenaResults.getResultVars();
     List<Map<String, Node>> nuxResults = new ArrayList<Map<String, Node>>();
     while (jenaResults.hasNext()) {
       QuerySolution soln = jenaResults.nextSolution();
       Map<String, Node> nuxSol = new HashMap<String, Node>();
       for (String varName : variableNames) {
         RDFNode x = soln.get(varName);
         nuxSol.put(varName, getNXRelationsNode(x.asNode()));
       }
       nuxResults.add(nuxSol);
       count++;
     }
     res = new QueryResultImpl(count, variableNames, nuxResults);
   } finally {
     if (qe != null) {
       // Important - free up resources used running the query
       qe.close();
     }
     if (graph != null) {
       graph.leaveCriticalSection();
     }
     if (graphConnection != null) {
       graphConnection.close();
     }
   }
   return res;
 }
Ejemplo n.º 28
0
 private void cachingForTriples(Table table, String endpoint) {
   Model model = ModelFactory.createDefaultModel();
   List<String> resources = null;
   FileWriter fstream = null;
   try {
     fstream = new FileWriter("/home/mofeed/TrialStart/zicozico.nt");
   } catch (IOException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
   }
   BufferedWriter out = new BufferedWriter(fstream);
   try {
     for (Object id : table.getItemIds()) {
       Item item = table.getItem(id);
       Property sourceURI = item.getItemProperty("sourceURI"); // vaadin property not jena
       Resource resource = model.createResource();
       try {
         String sparqlQuery = "select distinct * where { <" + sourceURI.getValue() + "> ?p  ?o .}";
         Query query = QueryFactory.create(sparqlQuery);
         QueryExecution qexec = QueryExecutionFactory.sparqlService(endpoint, query);
         com.hp.hpl.jena.query.ResultSet results = qexec.execSelect();
         com.hp.hpl.jena.query.QuerySolution binding = null;
         while (results.hasNext()) {
           binding = results.next();
           String property = binding.getResource("?p").toString();
           String value;
           if (binding.get("?o").isResource()) value = binding.getResource("?o").toString();
           else value = binding.getLiteral("?o").toString();
           com.hp.hpl.jena.rdf.model.Property pt = ResourceFactory.createProperty(property);
           // resource.addProperty(pt, value);
           model.add(resource, pt, value);
         }
         qexec.close();
         model.write(out, null, "TURTLE");
       } catch (Exception e) {
         Notification.show(e.toString());
       }
       // model.add(s, p, o);
       // Property destinationURI = item.getItemProperty("destinationURI");
       // out.write(sourceURI.getValue()+"\n");
     }
     /*out.flush();
     fstream.flush();*/
     out.close();
   } catch (Exception e) { // Catch exception if any
     System.err.println("Error: " + e.getMessage());
   }
 }
Ejemplo n.º 29
0
  /**
   * 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 static void query(Dataset dataset) {
    Query q =
        QueryFactory.create(
            "PREFIX pf: <http://jena.hpl.hp.com/ARQ/property#>"
                + "SELECT * WHERE {"
                + "  GRAPH ?g { "
                + "    ?doc ?p ?lit ."
                + "    (?lit ?score ) pf:textMatch '+london' ."
                + "  } "
                + "}");

    QueryExecution qe = QueryExecutionFactory.create(q, dataset);
    ResultSet res = qe.execSelect();
    ResultSetFormatter.out(res);
    qe.close();
  }