public BedStats findAvailableBedsByClinic(Integer clinicId) {
    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("sparqlQueries/BedsAvailabilityQuery").getFile());
    try {
      queryTemplate = FileUtils.readFileToString(file);
      List<String> params = new ArrayList<String>();
      params.add(clinicId.toString());
      String sparqlQuery = prepareQuery(queryTemplate, params);
      Query query = QueryFactory.create(sparqlQuery);
      QueryExecution qexec = QueryExecutionFactory.sparqlService(endpoint, query);
      System.out.println(sparqlQuery);
      ResultSet results = qexec.execSelect();
      if (results.hasNext()) {
        QuerySolution soln = results.nextSolution();

        Literal l = soln.getLiteral("bedsAvailable"); // Get a result variable - must be a literal
        BedStats bedStats = new BedStats();
        bedStats.setClinicId(clinicId);
        bedStats.setAvailabeBeds(l.getInt());
        return bedStats;
      } else {
        return null;
      }

    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
  }
Ejemplo n.º 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();
    }
  }
Ejemplo n.º 3
0
  /*
   * Originally written as a utility function by Atakan Guney.
   * Modified by Umut Dabager.
   */
  public void createResultTable(ResultSet results, PrintWriter writer, String searchQuery) {
    String table = "<form name=\"ftable\" method=\"post\" action=\"/TestWebProject/umut-dabager\">";
    table +=
        "<table border=\"1\" style=\"width:100%\">\n"
            + "<tr>\n"
            + "<th>Select</th>"
            + "<th>Musician</th>\n"
            + "<th>Genre</th>\n"
            + "</tr>\n";

    while (results.hasNext()) {
      QuerySolution currentSolution = results.nextSolution();
      String musicianName =
          currentSolution.getLiteral("?musicianLabel").toString().replace("@en", "");
      String musicianURI = currentSolution.getResource("?musician").toString();
      String genreName = currentSolution.getLiteral("?genreLabel").toString().replace("@en", "");
      String genreURI = currentSolution.getResource("?genre").toString();
      if (musicianName.toLowerCase().contains(searchQuery.toLowerCase())
          || genreName.toLowerCase().contains(searchQuery.toLowerCase())) {
        table +=
            "<tr>\n"
                + "<td>\n"
                + "<input type=\"checkbox\" name=\"check\" value=\""
                + musicianURI
                + valueSeperatorChar
                + musicianName
                + valueSeperatorChar
                + genreURI
                + valueSeperatorChar
                + genreName
                + "\"/>"
                + "</td>\n"
                + "<td>\n";
        table +=
            "<a href=\""
                + musicianURI
                + "\">"
                + musicianName
                + "</td>\n"
                + "<td>\n"
                + "<a href=\""
                + genreURI
                + "\">"
                + genreName;
      }
    }
    table += "</table>";
    table +=
        "<table><tr><td><input id=\"submit\" name=\"submit\" type=\"submit\" value=\"Save the selected results.\"/></td></tr></table>";
    table += "</form>";
    writer.println(table);
  }
Ejemplo n.º 4
0
  @Test
  public void testSelectToWurcsSparql() throws SparqlException, UnsupportedEncodingException {
    GlycoSequenceToWurcsSelectSparql s = new GlycoSequenceToWurcsSelectSparql("glycoct");
    SparqlEntity se = new SparqlEntity();
    se.setValue(
        GlycoSequenceToWurcsSelectSparql.FromSequence,
        "RES\n1b:a-dgal-HEX-1:5\n2s:n-acetyl\n3b:b-dgal-HEX-1:5\n4b:b-dglc-HEX-1:5\n5s:n-acetyl\n6b:b-dgal-HEX-1:5\n7b:a-lgal-HEX-1:5|6:d\n8b:b-dglc-HEX-1:5\n9s:n-acetyl\n10b:b-dglc-HEX-1:5\n11s:n-acetyl\n12b:b-dgal-HEX-1:5\n13b:a-lgal-HEX-1:5|6:d\nLIN\n1:1d(2+1)2n\n2:1o(3+1)3d\n3:3o(3+1)4d\n4:4d(2+1)5n\n5:4o(4+1)6d\n6:6o(2+1)7d\n7:3o(6+1)8d\n8:8d(2+1)9n\n9:1o(6+1)10d\n10:10d(2+1)11n\n11:10o(4+1)12d\n12:12o(2+1)13d"
            .replaceAll("\n", "\\\\n"));
    s.setSparqlEntity(se);
    logger.debug(s.getSparql());
    Query query =
        QueryFactory.create(s.getSparql().replaceAll("null", "").replace("?Sequence", ""));
    //        QueryExecution qe =
    // QueryExecutionFactory.sparqlService("http://localhost:3030/glycobase/query",query);
    QueryExecution qe =
        QueryExecutionFactory.sparqlService("http://test.ts.glytoucan.org/sparql", query);
    ResultSet rs = qe.execSelect();

    List<SparqlEntity> results = new ArrayList<SparqlEntity>();

    while (rs.hasNext()) {
      QuerySolution row = rs.next();
      Iterator<String> columns = row.varNames();
      SparqlEntity se2 = new SparqlEntity();
      while (columns.hasNext()) {
        String column = columns.next();
        RDFNode cell = row.get(column);

        if (cell.isResource()) {
          Resource resource = cell.asResource();
          // do something maybe with the OntModel???
          if (resource.isLiteral()) se.setValue(column, resource.asLiteral().getString());
          else se.setValue(column, resource.toString());
        } else if (cell.isLiteral()) {
          se.setValue(column, cell.asLiteral().getString());
        } else if (cell.isAnon()) {
          se.setValue(column, "anon");
        } else {
          se.setValue(column, cell.toString());
        }
      }
      results.add(se);
    }

    for (SparqlEntity entity : results) {
      System.out.println("results: " + entity.getValue("PrimaryId"));
    }
  }
  public BedStats findHospitalAvailableBedsAllClinics(String hospital) {
    ApplicationContext appContext = new ClassPathXmlApplicationContext();
    org.springframework.core.io.Resource resource =
        appContext.getResource("classpath:sparqlQueries/BedsAvailabilityQuery");
    try {
      InputStream is = resource.getInputStream();
      BufferedReader br = new BufferedReader(new InputStreamReader(is));

      String line;
      queryTemplate = "";
      while ((line = br.readLine()) != null) {
        queryTemplate += line + "\n";
      }
      br.close();
    } catch (IOException e1) {
      e1.printStackTrace();
      return null;
    }

    List<String> params = new ArrayList<String>();
    params.add(hospital);
    params.add(hospital);
    String sparqlQuery = prepareQuery(queryTemplate, params);
    System.out.println(sparqlQuery);
    Query query = QueryFactory.create(sparqlQuery);
    QueryExecution qexec = QueryExecutionFactory.sparqlService(endpoint, query);
    ResultSet results = qexec.execSelect();
    if (results.hasNext()) {
      QuerySolution soln = results.next();

      Literal available = soln.getLiteral("available"); // Get a result variable - must be a literal
      Literal deployed = soln.getLiteral("deployed");
      Literal supplementary = soln.getLiteral("supplementary");
      // Literal lastDate = soln.getLiteral("maxDate");
      BedStats bedStats = new BedStats();
      bedStats.setHospitalName(params.get(0));
      bedStats.setAvailabeBeds(available.getInt());
      bedStats.setDeployedBeds(deployed.getInt());
      bedStats.setSupplementaryBeds(supplementary.getInt());
      // bedStats.setLastDate(lastDate.getShort());
      return bedStats;
    } else {
      return null;
    }
  }
Ejemplo n.º 6
0
  @Test
  public void testFullQueryWorks() {
    ReconnectingDatasetGraph toQuery =
        (ReconnectingDatasetGraph)
            ((Dataset) AssemblerUtils.build("basic.ttl", SDBConnect.TYPE)).asDatasetGraph();
    toQuery.getDatasetGraph().getStore().getTableFormatter().format();
    Dataset ds = DatasetImpl.wrap(toQuery);
    // Dataset ds = new DatasetImpl(toQuery);
    QueryExecution qe = QueryExecutionFactory.create("SELECT * { ?s ?p ?o }", ds);
    ResultSet r = qe.execSelect();
    assertTrue("Querying works", !r.hasNext());
    qe.close();

    qe = QueryExecutionFactory.create("SELECT * { graph ?g { ?s ?p ?o } }", ds);
    r = qe.execSelect();
    assertTrue("Querying with named graphs works", !r.hasNext());
    qe.close();
  }
Ejemplo n.º 7
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();
    }
  }
Ejemplo n.º 8
0
  public static void BoxActivite() { // method

    String rol = "";
    String p = "";
    try {
      // OntModel model = OpenOWL.OpenConnectOWL();

      System.out.println("Avoir les activités"); // get the activity from my File OWL

      String queryString;
      queryString =
          "PREFIX saidi:<http://www.owl-ontologies.com/Ontology1364995044.owl#> "
              + "SELECT  (str(?x) as ?xs) "
              + "where { ?y saidi:hasnameactivite ?x."
              + " ?y saidi:avoirrole ?ro. "
              + " ?y saidi:Activitepour ?p. "
              + "?ro saidi:hasnamerole ?nr."
              + " FILTER (?p ='"
              + p
              + "') "
              + "FILTER (?nr ='"
              + rol
              + "') }";

      // call method ExecSparQl from class OpenOWL
      // ExecSparQl return a Resultset
      ResultSet results = OpenOWL.ExecSparQl(queryString);

      while (results.hasNext()) {

        QuerySolution soln = results.nextSolution();
        String nomactiviter = soln.getLiteral("xs").getString();
        // test --
        System.out.println("nomactiviter  " + nomactiviter.toString());
        // public ArrayList<String> ListActivite = new ArrayList<String>();
        // ListActivite.add(nomactiviter.toString());
        System.out.println("ListActivity: " + nomactiviter.toString());
      }
      // Jcombobox   (ac = new javax.swing.JComboBox();)

    } catch (Exception ex) {
      System.err.println(ex);
    }
  } // end first method
Ejemplo n.º 9
0
  /**
   * Textual representation : layout using given separator. Ensure the PrintWriter can handle UTF-8.
   *
   * @param pw PrintWriter
   * @param colSep Column separator
   */
  public void write(
      PrintWriter pw, ResultSet resultSet, String colStart, String colSep, String colEnd) {
    if (resultSet.getResultVars().size() == 0) {
      pw.println("==== No variables ====");
      // return ;
    }

    ResultSetRewindable resultSetRewindable = ResultSetFactory.makeRewindable(resultSet);

    int numCols = resultSetRewindable.getResultVars().size();
    int[] colWidths = colWidths(resultSetRewindable);

    String row[] = new String[numCols];
    int lineWidth = 0;
    for (int col = 0; col < numCols; col++) {
      String rVar = resultSet.getResultVars().get(col);
      row[col] = rVar;
      lineWidth += colWidths[col];
      if (col > 0) lineWidth += colSep.length();
    }
    if (colStart != null) lineWidth += colStart.length();
    if (colEnd != null) lineWidth += colEnd.length();

    for (int i = 0; i < lineWidth; i++) pw.print('-');
    pw.println();

    printRow(pw, row, colWidths, colStart, colSep, colEnd);

    for (int i = 0; i < lineWidth; i++) pw.print('=');
    pw.println();

    for (; resultSetRewindable.hasNext(); ) {
      QuerySolution rBind = resultSetRewindable.nextSolution();
      for (int col = 0; col < numCols; col++) {
        String rVar = resultSet.getResultVars().get(col);
        row[col] = this.getVarValueAsString(rBind, rVar);
      }
      printRow(pw, row, colWidths, colStart, colSep, colEnd);
    }
    for (int i = 0; i < lineWidth; i++) pw.print('-');
    pw.println();
    resultSetRewindable = null;
  }
Ejemplo n.º 10
0
  /*
   * Inserts raw data into database.
   * @param results Retrieved results from wikiData
   *
   * UPDATE !! Tried to insert all the raw data into db and pulling data from there.
   * Insert is taking too long for big data. ABANDONED!
   */
  private void insertRawDataToDB(ResultSet results) throws ClassNotFoundException {
    Connection conn = null;
    Statement statement = null;
    String sqlInsertQuery = "TRUNCATE TABLE group5db.umut_rawData ";
    try {
      Class.forName("com.mysql.jdbc.Driver");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      statement = conn.createStatement();
      while (results.hasNext()) {
        QuerySolution currentSolution = results.nextSolution();
        String musicianName =
            currentSolution.getLiteral("?musicianLabel").toString().replace("@en", "");
        String musicianURI =
            currentSolution
                .getResource("?musician")
                .toString()
                .replace("http://www.wikidata.org/entity/", "");
        String genreName = currentSolution.getLiteral("?genreLabel").toString().replace("@en", "");
        String genreURI =
            currentSolution
                .getResource("?genre")
                .toString()
                .replace("http://www.wikidata.org/entity/", "");

        sqlInsertQuery +=
            "INSERT INTO group5db.umut_rawData "
                + "(musicianid,musician,genreid,genre) "
                + "VALUES ('"
                + musicianURI
                + "', '"
                + musicianName
                + "', '"
                + genreURI
                + "', '"
                + genreName
                + "') ";
      }
      statement.execute(sqlInsertQuery);

    } catch (SQLException exc) {
      exc.printStackTrace();
    }
  }
Ejemplo n.º 11
0
  /**
   * Perform the {@link QueryExecution} once.
   *
   * @param action
   * @param queryExecution
   * @param query
   * @param queryStringLog Informational string created from the initial query.
   * @return
   */
  protected SPARQLResult executeQuery(
      HttpAction action, QueryExecution queryExecution, Query query, String queryStringLog) {
    setAnyTimeouts(queryExecution, action);

    if (query.isSelectType()) {
      ResultSet rs = queryExecution.execSelect();

      // Force some query execution now.
      // If the timeout-first-row goes off, the output stream has not
      // been started so the HTTP error code is sent.

      rs.hasNext();

      // If we wanted perfect query time cancellation, we could consume
      // the result now to see if the timeout-end-of-query goes off.
      // rs = ResultSetFactory.copyResults(rs) ;

      // action.log.info(format("[%d] exec/select", action.id)) ;
      return new SPARQLResult(rs);
    }

    if (query.isConstructType()) {
      Dataset dataset = queryExecution.execConstructDataset();
      // action.log.info(format("[%d] exec/construct", action.id));
      return new SPARQLResult(dataset);
    }

    if (query.isDescribeType()) {
      Model model = queryExecution.execDescribe();
      // action.log.info(format("[%d] exec/describe", action.id)) ;
      return new SPARQLResult(model);
    }

    if (query.isAskType()) {
      boolean b = queryExecution.execAsk();
      // action.log.info(format("[%d] exec/ask", action.id)) ;
      return new SPARQLResult(b);
    }

    ServletOps.errorBadRequest("Unknown query type - " + queryStringLog);
    return null;
  }
  public static List<String> listThingDescriptions(String query) {
    List<String> tds = new ArrayList<>();

    Dataset dataset = Repository.get().dataset;
    dataset.begin(ReadWrite.READ);

    try {
      String q = "SELECT DISTINCT ?g WHERE { GRAPH ?g { " + query + " }}";
      try (QueryExecution qexec = QueryExecutionFactory.create(q, dataset)) {
        ResultSet result = qexec.execSelect();
        while (result.hasNext()) {
          tds.add(result.next().get("g").asResource().getURI());
        }
      }
    } finally {
      dataset.end();
    }

    return tds;
  }
Ejemplo n.º 13
0
 private ResultSet ConvertResults(org.apache.jena.query.ResultSet results) {
   ResultSet rs = new ResultSet();
   while (results.hasNext()) {
     Binding b = results.nextBinding();
     Result result = new Result();
     Iterator<Var> v = b.vars();
     while (v.hasNext()) {
       Var currentV = v.next();
       Node val = b.get(currentV);
       if (currentV.toString().contains("_info_")) {
         String[] parts = val.getLiteral().getLexicalForm().toString().split("=");
         if (parts.length > 1) {
           for (int i = 0; i < parts.length; i++) {
             String[] subParts = parts[i].split("\\.");
             if (subParts.length > 1) {
               if (!Character.isDigit(subParts[1].charAt(0))) result.addTable(subParts[0]);
             }
           }
         }
         result.addWhere(val.getLiteral().getLexicalForm());
       } else {
         if (val.isLiteral()) {
           String value = val.getLiteral().getLexicalForm();
           String datatype = val.getLiteralDatatypeURI();
           if (datatype.equals(S2SML.LITERAL_MAP_IRI)) {
             String[] parts = value.split("\\.");
             if (parts.length > 1) {
               if (!Character.isDigit(parts[1].charAt(0))) result.addTable(parts[0]);
             }
           }
         }
         //					System.out.println(currentV.toString().replace("?", "") +" "+val);
         result.addVarMapping(
             currentV.toString().replace("?", ""), FormatUtil.processNode(val, dialect));
       }
     }
     rs.add(result);
   }
   return rs;
 }
Ejemplo n.º 14
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();
    }
  }
Ejemplo n.º 15
0
  @Test
  public void testKBtoWurcsSparqlTranslation() throws SparqlException {

    List<Translation> translations = Ebean.find(Translation.class).findList();
    HashSet<String> resultList = new HashSet<>();

    String ct = "";

    for (Translation translation : translations) {
      System.out.println("id check " + translation.id + " ct " + translation.ct);
      if (translation.ct == null) continue;

      if (translation.structure.id > 0) {

        ct = translation.ct;

        GlycoSequenceToWurcsSelectSparql s = new GlycoSequenceToWurcsSelectSparql("glycoct");
        SparqlEntity se = new SparqlEntity();
        ct = StringUtils.chomp(ct);
        System.out.println("ct on top: " + ct);
        if (ct != null) {
          se.setValue(
              GlycoSequenceToWurcsSelectSparql.FromSequence,
              ct.replaceAll("\n", "\\\\n")
                  .replaceAll("x\\(", "u\\(")
                  .replaceAll("\\)x", "\\)u")
                  .trim());
          s.setSparqlEntity(se);
          logger.debug(s.getSparql());

          Query query =
              QueryFactory.create(s.getSparql().replaceAll("null", "").replace("?Sequence", ""));
          System.out.println(
              "Id "
                  + translation.structure.id
                  + " Query: "
                  + s.getSparql().replaceAll("null", "").replace("?Sequence", ""));
          QueryExecution qe =
              QueryExecutionFactory.sparqlService("http://test.ts.glytoucan.org/sparql", query);
          ResultSet rs = qe.execSelect();

          List<SparqlEntity> results = new ArrayList<>();
          HashSet<String> resultsList = new HashSet<>();

          while (rs.hasNext()) {
            QuerySolution row = rs.next();
            Iterator<String> columns = row.varNames();
            SparqlEntity se2 = new SparqlEntity();
            while (columns.hasNext()) {
              String column = columns.next();
              RDFNode cell = row.get(column);

              if (cell.isResource()) {
                Resource resource = cell.asResource();
                // do something maybe with the OntModel???
                if (resource.isLiteral()) se.setValue(column, resource.asLiteral().getString());
                else se.setValue(column, resource.toString());
              } else if (cell.isLiteral()) {
                se.setValue(column, cell.asLiteral().getString());
              } else if (cell.isAnon()) {
                se.setValue(column, "anon");
              } else {
                se.setValue(column, cell.toString());
              }
            }
            results.add(se);
          }

          for (SparqlEntity entity : results) {
            // System.out.println("results: " + entity.getValue("PrimaryId"));
            resultList.add(
                translation.structure.id + "\t" + entity.getValue("PrimaryId").toString());
          }
        }
      }
    }

    for (String c : resultList) {
      System.out.println(c);
    }
  }
Ejemplo n.º 16
0
  @Test
  public void testKBtoWurcsSparql() throws SparqlException {

    List<Structure> structures = Ebean.find(Structure.class).findList();
    HashSet<String> resultList = new HashSet<>();

    String ct = "";

    for (Structure structure : structures) {
      if (structure.id >= 7400) {

        if (structure.glycanst.startsWith("v--")) {
          structure.glycanst = structure.glycanst.replace("v--", "FreeEnd--");
        }

        if (structure.glycanst.startsWith("FreenEnd")) {
          structure.glycanst = structure.glycanst.replace("FreenEnd", "FreeEnd");
        }

        if (structure.glycanst.startsWith("FreeEnd?")) {
          structure.glycanst = structure.glycanst.replace("FreeEnd?", "FreeEnd--?");
        }

        if (structure.glycanst.startsWith("<Gly") || structure.glycanst.contains("0.0000u")) {
          continue;
        }

        System.out.println(structure.getGlycanst());

        BuilderWorkspace workspace = new BuilderWorkspace(new GlycanRendererAWT());
        workspace.setNotation("cfg"); // cfgbw | uoxf | uoxfcol | text
        GlycanRenderer renderer = workspace.getGlycanRenderer();
        org.eurocarbdb.application.glycanbuilder.Glycan glycan =
            org.eurocarbdb.application.glycanbuilder.Glycan.fromString(structure.glycanst.trim());
        if (glycan != null) {
          ct = glycan.toGlycoCTCondensed();
          System.out.println("this was the ct: " + ct);
          GlycoSequenceToWurcsSelectSparql s = new GlycoSequenceToWurcsSelectSparql("glycoct");
          SparqlEntity se = new SparqlEntity();
          ct = StringUtils.chomp(ct);
          se.setValue(
              GlycoSequenceToWurcsSelectSparql.FromSequence,
              ct.replaceAll("\n", "\\\\n")
                  .replaceAll("x\\(", "u\\(")
                  .replaceAll("\\)x", "\\)u")
                  .trim());
          s.setSparqlEntity(se);
          logger.debug(s.getSparql());

          Query query =
              QueryFactory.create(s.getSparql().replaceAll("null", "").replace("?Sequence", ""));
          System.out.println(
              "Id "
                  + structure.id
                  + " Query: "
                  + s.getSparql().replaceAll("null", "").replace("?Sequence", ""));
          QueryExecution qe =
              QueryExecutionFactory.sparqlService("http://test.ts.glytoucan.org/sparql", query);
          ResultSet rs = qe.execSelect();

          List<SparqlEntity> results = new ArrayList<>();
          HashSet<String> resultsList = new HashSet<>();

          while (rs.hasNext()) {
            QuerySolution row = rs.next();
            Iterator<String> columns = row.varNames();
            SparqlEntity se2 = new SparqlEntity();
            while (columns.hasNext()) {
              String column = columns.next();
              RDFNode cell = row.get(column);

              if (cell.isResource()) {
                Resource resource = cell.asResource();
                // do something maybe with the OntModel???
                if (resource.isLiteral()) se.setValue(column, resource.asLiteral().getString());
                else se.setValue(column, resource.toString());
              } else if (cell.isLiteral()) {
                se.setValue(column, cell.asLiteral().getString());
              } else if (cell.isAnon()) {
                se.setValue(column, "anon");
              } else {
                se.setValue(column, cell.toString());
              }
            }
            results.add(se);
          }

          for (SparqlEntity entity : results) {
            // System.out.println("results: " + entity.getValue("PrimaryId"));
            resultList.add(structure.id + "\t" + entity.getValue("PrimaryId").toString());
          }
        }
      }
    }
    PrintWriter writer = null;
    try {
      writer =
          new PrintWriter(
              new OutputStreamWriter(new FileOutputStream("/tmp/HashSet.txt"), "UTF-8"));
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    for (String c : resultList) {
      System.out.println(c);
      writer.println(c);
    }
  }
Ejemplo n.º 17
0
  /** {@inheritDoc} */
  @Override
  protected Collection<TestCaseResult> executeSingleTest(TestSource testSource, TestCase testCase)
      throws TestCaseExecutionException {

    Collection<TestCaseResult> testCaseResults = new ArrayList<>();
    PropertyValuePairSet.PropertyValuePairSetBuilder annotationSetBuilder =
        PropertyValuePairSet.builder();

    try (QueryExecution qe =
        testSource
            .getExecutionFactory()
            .createQueryExecution(queryGenerationFactory.getSparqlQuery(testCase))) {

      ResultSet results = qe.execSelect();

      ExtendedTestCaseResultImpl.Builder resultBuilder = null;
      String prevResource = "";

      while (results.hasNext()) {

        QuerySolution qs = results.next();

        String resource = qs.get("this").toString();
        if (qs.get("this").isLiteral()) {
          resource = StringUtils.getHashFromString(resource);
        }
        String message = testCase.getResultMessage();
        if (qs.contains("message")) {
          message = qs.get("message").toString();
        }
        RLOGLevel logLevel = testCase.getLogLevel();

        // If resource != before
        // we add the previous result in the list
        if (!prevResource.equals(resource)) {
          // The very first time we enter, result = null and we don't add any result
          if (resultBuilder != null) {
            testCaseResults.add(
                resultBuilder
                    .setResultAnnotations(annotationSetBuilder.build().getAnnotations())
                    .build());
          }

          resultBuilder =
              new ExtendedTestCaseResultImpl.Builder(
                  testCase.getTestURI(), logLevel, message, resource);

          annotationSetBuilder = PropertyValuePairSet.builder(); // reset

          // get static annotations for new test
          for (ResultAnnotation resultAnnotation : testCase.getResultAnnotations()) {
            // Get values
            if (resultAnnotation.getAnnotationValue().isPresent()) {
              annotationSetBuilder.annotation(
                  PropertyValuePair.create(
                      resultAnnotation.getAnnotationProperty(),
                      resultAnnotation.getAnnotationValue().get()));
            }
          }
        }

        // result must be initialized by now
        checkNotNull(resultBuilder);

        // get annotations from the SPARQL query
        for (ResultAnnotation resultAnnotation : testCase.getVariableAnnotations()) {
          // Get the variable name
          if (resultAnnotation.getAnnotationVarName().isPresent()) {
            String variable = resultAnnotation.getAnnotationVarName().get().trim();
            // If it exists, add it in the Set
            if (qs.contains(variable)) {
              annotationSetBuilder.annotation(
                  PropertyValuePair.create(
                      resultAnnotation.getAnnotationProperty(), qs.get(variable)));
            }
          }
        }
      }
      // Add last result (if query return any)
      if (resultBuilder != null) {
        testCaseResults.add(
            resultBuilder
                .setResultAnnotations(annotationSetBuilder.build().getAnnotations())
                .build());
      }
    } catch (QueryExceptionHTTP e) {
      checkQueryResultStatus(e);
    }

    return testCaseResults;
  }
Ejemplo n.º 18
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);
  }