예제 #1
0
  @Test
  public void testSelectAllType() {
    eval =
        new MockSecurityEvaluator(true, true, true, true, true, true) {

          @Override
          public boolean evaluate(
              final Object principal,
              final Action action,
              final Node graphIRI,
              final Triple triple) {
            if (triple.getSubject().isURI()
                && triple.getSubject().getURI().equals("http://example.com/resource/1")) {
              return false;
            }
            return super.evaluate(principal, action, graphIRI, triple);
          }
        };

    setup();

    try {
      String query = "SELECT ?s ?p ?o WHERE " + " { ?s ?p ?o } ";
      QueryExecution qexec = QueryExecutionFactory.create(query, dataset);
      try {
        final ResultSet results = qexec.execSelect();
        int count = 0;
        for (; results.hasNext(); ) {
          count++;
          results.nextSolution();
        }
        // 2x 3 values + type triple
        Assert.assertEquals(8, count);
      } finally {
        qexec.close();
      }

      query = "SELECT ?g ?s ?p ?o WHERE " + " { GRAPH ?g {?s ?p ?o } }";
      qexec = QueryExecutionFactory.create(query, dataset);
      try {
        final ResultSet results = qexec.execSelect();
        int count = 0;
        for (; results.hasNext(); ) {
          count++;
          results.nextSolution();
        }
        // 2x 3 values + type triple
        // all are in the base graph so no named graphs
        Assert.assertEquals(0, count);
      } finally {
        qexec.close();
      }
    } finally {
      dataset.close();
    }
  }
예제 #2
0
  @Test
  public void testOpenQueryType() {
    eval = new MockSecurityEvaluator(true, true, true, true, true, true);

    setup();

    try {
      final String query =
          "prefix fn: <http://www.w3.org/2005/xpath-functions#>  "
              + " SELECT ?foo ?bar WHERE "
              + " { ?foo a <http://example.com/class> ; "
              + "?bar [] ."
              + "  } ";
      final QueryExecution qexec = QueryExecutionFactory.create(query, dataset);
      try {
        final ResultSet results = qexec.execSelect();
        int count = 0;
        for (; results.hasNext(); ) {
          count++;
          results.nextSolution();
        }
        Assert.assertEquals(8, count);
      } finally {
        qexec.close();
      }
    } finally {
      dataset.close();
    }
  }
예제 #3
0
  @Test
  public void testRestrictedQueryType() {
    eval =
        new MockSecurityEvaluator(true, true, true, true, true, true) {

          @Override
          public boolean evaluate(
              final Object principal,
              final Action action,
              final Node graphIRI,
              final Triple triple) {
            if (triple.getSubject().isURI()
                && triple.getSubject().getURI().equals("http://example.com/resource/1")) {
              return false;
            }
            return super.evaluate(principal, action, graphIRI, triple);
          }
        };

    setup();

    try {
      final String query =
          "prefix fn: <http://www.w3.org/2005/xpath-functions#>  "
              + " SELECT ?foo ?bar WHERE "
              + " { ?foo a <http://example.com/class> ; "
              + "?bar [] ."
              + "  } ";
      final QueryExecution qexec = QueryExecutionFactory.create(query, dataset);
      try {
        final ResultSet results = qexec.execSelect();
        int count = 0;
        for (; results.hasNext(); ) {
          count++;
          results.nextSolution();
        }
        Assert.assertEquals(4, count);
      } finally {
        qexec.close();
      }
    } finally {
      dataset.close();
    }
  }
  /**
   * Returns the string value of the first of the properties in the uriDescriptionList for the given
   * resource (as an URI). In case the resource does not have any of the properties mentioned, its
   * URI is returned. The value is obtained by querying the endpoint and the endpoint is queried
   * repeatedly until it gives a response (value or the lack of it)
   *
   * <p>It is highly recommended that the list contains properties like labels or titles, with test
   * values.
   *
   * @param uri - the URI for which a label is required
   * @return a String value, either a label for the parameter or its value if no label is obtained
   *     from the endpoint
   */
  private String getLabelForUri(String uri) {
    String result;

    if (uriLabelCache.containsKey(uri)) {
      return uriLabelCache.get(uri);
    }

    for (String prop : uriDescriptionList) {
      String innerQuery = "SELECT ?r WHERE {<" + uri + "> <" + prop + "> ?r } LIMIT 1";

      try {
        Query query = QueryFactory.create(innerQuery);
        QueryExecution qExec = QueryExecutionFactory.sparqlService(rdfEndpoint, query);
        boolean keepTrying = true;
        while (keepTrying) {
          keepTrying = false;
          try {
            ResultSet results = qExec.execSelect();

            if (results.hasNext()) {
              QuerySolution sol = results.nextSolution();
              result = EEASettings.parseForJson(sol.getLiteral("r").getLexicalForm());
              if (!result.isEmpty()) {
                uriLabelCache.put(uri, result);
                return result;
              }
            }
          } catch (Exception e) {
            keepTrying = true;
            logger.warn("Could not get label for uri {}. Retrying.", uri);
          } finally {
            qExec.close();
          }
        }
      } catch (QueryParseException qpe) {
        logger.error("Exception for query {}. The label cannot be obtained", innerQuery);
      }
    }
    return uri;
  }
  /**
   * Get a set of unique queryObjName returned from a select query
   *
   * <p>Used to retrieve sets of modified objects used in sync
   *
   * @param rdfQuery query to execute
   * @param queryObjName name of the object returned
   * @return set of values for queryObjectName in the rdfQuery result
   */
  HashSet<String> executeSyncQuery(String rdfQuery, String queryObjName) {
    HashSet<String> rdfUrls = new HashSet<String>();

    Query query;
    try {
      query = QueryFactory.create(rdfQuery);
    } catch (QueryParseException qpe) {
      logger.warn(
          "Could not parse [{}]. Please provide a relevant query. {}",
          rdfQuery,
          qpe.getLocalizedMessage());
      return null;
    }

    QueryExecution qExec = QueryExecutionFactory.sparqlService(rdfEndpoint, query);
    try {
      ResultSet results = qExec.execSelect();

      while (results.hasNext()) {
        QuerySolution sol = results.nextSolution();
        try {
          String value = sol.getResource(queryObjName).toString();
          rdfUrls.add(value);
        } catch (NoSuchElementException e) {
          logger.error("Encountered a NoSuchElementException: " + e.getLocalizedMessage());
          return null;
        }
      }
    } catch (Exception e) {
      logger.error(
          "Encountered a [{}] while querying the endpoint for sync", e.getLocalizedMessage());
      return null;
    } finally {
      qExec.close();
    }

    return rdfUrls;
  }
예제 #6
0
  @Test
  public void testDO() {
    String doid = "1485";
    String queryString =
        "prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
            + "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
            + "prefix owl: <http://www.w3.org/2002/07/owl#>\n"
            + "\n"
            + "select ?s ?p ?o \n"
            + "from <http://purl.obolibrary.org/obo/merged/DOID>\n"
            + "\n"
            + "WHERE {\n"
            + "   <http://purl.obolibrary.org/obo/DOID_"
            + doid
            + "> ?p ?o\n"
            + "}";

    Query query = QueryFactory.create(queryString);
    QueryExecution qExe =
        QueryExecutionFactory.sparqlService("http://sparql.hegroup.org/sparql/", query);
    ResultSet results = qExe.execSelect();
    ResultSetFormatter.out(System.out, results, query);

    assertNotNull(results);

    /*Model model = ModelFactory.createDefaultModel();
    Selector selector = new SimpleSelector(null, model.getProperty("<http://www.geneontology.org/formats/oboInOwl#hasDbXref>"), (RDFNode) null);  // you need to cast the last null as otherwise the method is ambigious
    */

    List<String> dbXref = new ArrayList<>();
    List<String> iao = new ArrayList<>();
    List<String> exactSynonym = new ArrayList<>();
    List<String> alternativeId = new ArrayList<>();
    String diseaseLabel;

    while (results.hasNext()) {
      QuerySolution querySolution = results.nextSolution();

      if (querySolution.get("p").toString().matches("rdfs:label ")) {
        diseaseLabel = querySolution.get("o").toString();
      }

      if (querySolution
          .get("p")
          .toString()
          .matches("http://www.geneontology.org/formats/oboInOwl#hasDbXref")) {
        System.out.println(
            querySolution.get("p").toString() + "   " + querySolution.get("o").toString());
        dbXref.add(querySolution.get("o").toString());
      }

      if (querySolution.get("p").toString().matches("http://purl.obolibrary.org/obo/IAO_0000115")) {
        System.out.println(
            querySolution.get("p").toString() + "   " + querySolution.get("o").toString());
        iao.add(querySolution.get("o").toString());
      }

      if (querySolution
          .get("p")
          .toString()
          .matches("http://www.geneontology.org/formats/oboInOwl#hasExactSynonym")) {
        System.out.println(
            querySolution.get("p").toString() + "   " + querySolution.get("o").toString());
        exactSynonym.add(querySolution.get("o").toString());
      }

      if (querySolution
          .get("p")
          .toString()
          .matches("http://www.geneontology.org/formats/oboInOwl#hasAlternativeId")) {
        System.out.println(
            querySolution.get("p").toString() + "   " + querySolution.get("o").toString());
        alternativeId.add(querySolution.get("o").toString());
      }
    }

    assertNotNull(dbXref);
    assertNotNull(iao);
  }
  /**
   * A method to build a collection of collaborator objects representing a network based on an
   * organisation
   *
   * @param id the id of the central organisation
   * @param radius the number of edges required from the central contributor
   * @return the collection of collaborator objects
   */
  @SuppressWarnings("rawtypes")
  public TreeMap<Integer, Collaborator> getRawCollaboratorData_org(String id, int radius) {

    // check the parameters
    if (InputUtils.isValidInt(id) == false) {
      throw new IllegalArgumentException("Error: the id parameter is required");
    }

    if (InputUtils.isValidInt(radius, ExportServlet.MIN_DEGREES, ExportServlet.MAX_DEGREES)
        == false) {
      throw new IllegalArgumentException(
          "Error: the radius parameter must be between "
              + ExportServlet.MIN_DEGREES
              + " and "
              + ExportServlet.MAX_DEGREES);
    }

    // define helper variables
    // collection of collaborators
    java.util.TreeMap<Integer, Collaborator> cId_cObj_map =
        new java.util.TreeMap<Integer, Collaborator>();

    // set of collaborators that we've already processed
    java.util.TreeSet<Integer> foundCollaboratorsSet = new java.util.TreeSet<Integer>();

    // define other helper variables
    String contributor_id = null;
    QuerySolution row = null;
    Collaborator collaborator = null;

    String sql =
        "SELECT DISTINCT b.eventid   "
            + "FROM events a, orgevlink b "
            + "WHERE b.organisationid = ? " // +id
            + "AND a.eventid = b.eventid";

    int[] param = {Integer.parseInt(id)};
    java.sql.ResultSet resultSet = db.exePreparedStatement(sql, param);

    ArrayList<String> eventResults = new ArrayList<String>();

    try {
      //		 	check to see that data was returned
      if (!resultSet.last()) {
        db.tidyup();
        return null;
      } else resultSet.beforeFirst();

      // loop through the resultset
      while (resultSet.next() == true) {
        eventResults.add(resultSet.getString(1));
      }

    } catch (java.sql.SQLException ex) {
      System.out.println("Exception: " + ex.getMessage());
      resultSet = null;
    }

    db.tidyup();

    // helper
    int first = 0;

    // define the query
    String sparqlQuery1 =
        "PREFIX foaf:       <"
            + FOAF.NS
            + "> "
            + "PREFIX ausestage:  <"
            + AuseStage.NS
            + "> "
            + "PREFIX event:      <http://purl.org/NET/c4dm/event.owl#> "
            + "PREFIX dcterms:    <http://purl.org/dc/terms/> "
            + "SELECT DISTINCT ?agent ?givenName ?familyName "
            + "WHERE { ";
    for (String event : eventResults) {
      if (first > 0) {
        sparqlQuery1 += "UNION ";
      }
      first++;

      sparqlQuery1 +=
          "{<ausstage:e:"
              + event
              + "> a                event:Event; "
              + "   event:agent      ?agent. "
              + "	?agent             a                foaf:Person; "
              + "   foaf:givenName   ?givenName; "
              + "   foaf:familyName  ?familyName. "
              + " } ";
    }
    sparqlQuery1 += " } ";

    // execute query
    ResultSet results = rdf.executeSparqlQuery(sparqlQuery1);

    // now we transfer the results to a TreeMap <Integer,
    while (results.hasNext()) {

      row = results.nextSolution();

      contributor_id = AusStageURI.getId(row.get("agent").toString());

      collaborator = new Collaborator(contributor_id);

      cId_cObj_map.put(Integer.parseInt(contributor_id), collaborator);
      foundCollaboratorsSet.add(Integer.parseInt(contributor_id));
    }

    rdf.tidyUp();

    return cId_cObj_map;
  } // end getRawCollaboratorData_org method
  /*
   * add some of the additional required information for collaborator
   */
  public ArrayList<Collaborator> getCollaborators(
      TreeMap<Integer, Collaborator> network, String id) {

    // declare helper variables
    java.util.ArrayList<Collaborator> collaborators = new java.util.ArrayList<Collaborator>();

    // define a SPARQL query to get details about a collaborator
    String sparqlQuery =
        "PREFIX foaf:       <"
            + FOAF.NS
            + ">"
            + "PREFIX ausestage:  <"
            + AuseStage.NS
            + "> "
            + "SELECT ?collabName ?function ?gender ?nationality  "
            + "WHERE {  "
            + "       @ a foaf:Person ; "
            + "           foaf:name ?collabName. "
            + "OPTIONAL {@ ausestage:function ?function} "
            + "OPTIONAL {@ foaf:gender ?gender} "
            + "OPTIONAL {@ ausestage:nationality ?nationality} "
            + "} ";

    String queryToExecute = null;

    ResultSet results = null;
    QuerySolution row = null;
    Collaborator collaborator = null;

    // loop through the list of collaborators and get additional information
    Collection networkKeys = network.keySet();
    Iterator networkKeyIterator = networkKeys.iterator();
    Integer networkKey = null;
    Integer centreId = Integer.parseInt(id);

    // loop through the list of keys
    while (networkKeyIterator.hasNext()) {

      // get the key for this collaborator
      networkKey = (Integer) networkKeyIterator.next();

      // create a new collaborator object
      collaborator = new Collaborator(networkKey.toString());

      // build the query
      queryToExecute =
          sparqlQuery.replaceAll(
              "@", "<" + AusStageURI.getContributorURI(collaborator.getId()) + ">");

      // execute the query
      results = rdf.executeSparqlQuery(queryToExecute);

      // add details to this contributor
      while (results.hasNext()) {
        // loop though the resulset
        // get a new row of data
        row = results.nextSolution();

        // add the data to the collaborator
        collaborator.setName(row.get("collabName").toString());
        if (row.get("function") != null) {
          collaborator.setFunction(row.get("function").toString());
        }

        if (row.get("gender") != null) {
          collaborator.setGender(row.get("gender").toString());
        }

        if (row.get("nationality") != null) {
          collaborator.setNationality(row.get("nationality").toString());
        }

        collaborator.setUrl(AusStageURI.getContributorURL(collaborator.getId()));
      }

      // play nice and tidy
      rdf.tidyUp();
      results = null;

      // add the collaborator to the list
      collaborators.add(collaborator);
    }

    return collaborators;
  }