예제 #1
0
 /**
  * Example the conclusions graph for introduction of restrictions which require a comprehension
  * rewrite and declare new (anon) classes for those restrictions.
  */
 public void comprehensionAxioms(Model premises, Model conclusions) {
   // Comprehend all restriction declarations and note them in a map
   Map<Resource, Resource> comprehension = new HashMap<>();
   StmtIterator ri = conclusions.listStatements(null, RDF.type, OWL.Restriction);
   while (ri.hasNext()) {
     Resource restriction = ri.nextStatement().getSubject();
     StmtIterator pi = restriction.listProperties(OWL.onProperty);
     while (pi.hasNext()) {
       Resource prop = (Resource) pi.nextStatement().getObject();
       StmtIterator vi = restriction.listProperties();
       while (vi.hasNext()) {
         Statement rs = vi.nextStatement();
         if (!rs.getPredicate().equals(OWL.onProperty)) {
           // Have a restriction on(prop) of type rs in the conclusions
           // So assert a premise that such a restriction could exisit
           Resource comp =
               premises
                   .createResource()
                   .addProperty(RDF.type, OWL.Restriction)
                   .addProperty(OWL.onProperty, prop)
                   .addProperty(rs.getPredicate(), rs.getObject());
           comprehension.put(restriction, comp);
         }
       }
     }
   }
   // Comprehend any intersectionOf lists. Introduce anon class which has the form
   // of the intersection expression.
   // Rewrite queries of the form (X intersectionOf Y) to the form
   //   (X equivalentClass ?CC) (?CC intersectionOf Y)
   StmtIterator ii = conclusions.listStatements(null, OWL.intersectionOf, (RDFNode) null);
   List<Statement> intersections = new ArrayList<>();
   while (ii.hasNext()) {
     intersections.add(ii.nextStatement());
   }
   for (Statement is : intersections) {
     // Declare in the premises that such an intersection exists
     Resource comp =
         premises
             .createResource()
             .addProperty(RDF.type, OWL.Class)
             .addProperty(
                 OWL.intersectionOf, mapList(premises, (Resource) is.getObject(), comprehension));
     // Rewrite the conclusions to be a test for equivalence between the class being
     // queried and the comprehended interesection
     conclusions.remove(is);
     conclusions.add(is.getSubject(), OWL.equivalentClass, comp);
   }
   // Comprehend any oneOf lists
   StmtIterator io = conclusions.listStatements(null, OWL.oneOf, (RDFNode) null);
   while (io.hasNext()) {
     Statement s = io.nextStatement();
     Resource comp = premises.createResource().addProperty(OWL.oneOf, s.getObject());
   }
 }
 protected static void addDomainTypes(Model result, Model schema) {
   for (StmtIterator it = schema.listStatements(ANY, RDFS.domain, ANY); it.hasNext(); ) {
     Statement s = it.nextStatement();
     Property property = s.getSubject().as(Property.class);
     RDFNode type = s.getObject();
     for (StmtIterator x = result.listStatements(ANY, property, ANY); x.hasNext(); ) {
       Statement t = x.nextStatement();
       result.add(t.getSubject(), RDF.type, type);
     }
   }
 }
 protected static void addRangeTypes(Model result, Model schema) {
   Model toAdd = ModelFactory.createDefaultModel();
   for (StmtIterator it = schema.listStatements(ANY, RDFS.range, ANY); it.hasNext(); ) {
     Statement s = it.nextStatement();
     RDFNode type = s.getObject();
     Property property = s.getSubject().as(Property.class);
     for (StmtIterator x = result.listStatements(ANY, property, ANY); x.hasNext(); ) {
       RDFNode ob = x.nextStatement().getObject();
       if (ob.isResource()) toAdd.add((Resource) ob, RDF.type, type);
     }
   }
   result.add(toAdd);
 }
 protected static void addSupertypes(Model result) {
   Model temp = ModelFactory.createDefaultModel();
   for (StmtIterator it = result.listStatements(ANY, RDF.type, ANY); it.hasNext(); ) {
     Statement s = it.nextStatement();
     Resource c = AssemblerHelp.getResource(s);
     for (StmtIterator subclasses = result.listStatements(c, RDFS.subClassOf, ANY);
         subclasses.hasNext(); ) {
       RDFNode type = subclasses.nextStatement().getObject();
       // System.err.println( ">> adding super type: subject " + s.getSubject() + ", type " + type
       // );
       temp.add(s.getSubject(), RDF.type, type);
     }
   }
   result.add(temp);
 }
예제 #5
0
 /** Return a list of all tests of the given type, according to the current filters */
 public List<Resource> findTestsOfType(Resource testType) {
   ArrayList<Resource> result = new ArrayList<>();
   StmtIterator si = testDefinitions.listStatements(null, RDF.type, testType);
   while (si.hasNext()) {
     Resource test = si.nextStatement().getSubject();
     boolean accept = true;
     // Check test status
     Literal status = (Literal) test.getProperty(RDFTest.status).getObject();
     if (approvedOnly) {
       accept = status.getString().equals(STATUS_FLAGS[0]);
     } else {
       accept = false;
       for (String STATUS_FLAG : STATUS_FLAGS) {
         if (status.getString().equals(STATUS_FLAG)) {
           accept = true;
           break;
         }
       }
     }
     // Check for blocked tests
     for (String BLOCKED_TEST : BLOCKED_TESTS) {
       if (BLOCKED_TEST.equals(test.toString())) {
         accept = false;
       }
     }
     // End of filter tests
     if (accept) {
       result.add(test);
     }
   }
   return result;
 }
  /**
   * Index all the resources in a Jena Model to ES
   *
   * @param model the model to index
   * @param bulkRequest a BulkRequestBuilder
   * @param getPropLabel if set to true all URI property values will be indexed as their label. The
   *     label is taken as the value of one of the properties set in {@link #uriDescriptionList}.
   */
  private void addModelToES(Model model, BulkRequestBuilder bulkRequest, boolean getPropLabel) {
    long startTime = System.currentTimeMillis();
    long bulkLength = 0;
    HashSet<Property> properties = new HashSet<Property>();

    StmtIterator it = model.listStatements();
    while (it.hasNext()) {
      Statement st = it.nextStatement();
      Property prop = st.getPredicate();
      String property = prop.toString();

      if (rdfPropList.isEmpty()
          || (isWhitePropList && rdfPropList.contains(property))
          || (!isWhitePropList && !rdfPropList.contains(property))
          || (normalizeProp.containsKey(property))) {
        properties.add(prop);
      }
    }

    ResIterator resIt = model.listSubjects();

    while (resIt.hasNext()) {
      Resource rs = resIt.nextResource();
      Map<String, ArrayList<String>> jsonMap = getJsonMap(rs, properties, model, getPropLabel);

      bulkRequest.add(
          client.prepareIndex(indexName, typeName, rs.toString()).setSource(mapToString(jsonMap)));
      bulkLength++;

      // We want to execute the bulk for every  DEFAULT_BULK_SIZE requests
      if (bulkLength % EEASettings.DEFAULT_BULK_SIZE == 0) {
        BulkResponse bulkResponse = bulkRequest.execute().actionGet();
        // After executing, flush the BulkRequestBuilder.
        bulkRequest = client.prepareBulk();

        if (bulkResponse.hasFailures()) {
          processBulkResponseFailure(bulkResponse);
        }
      }
    }

    // Execute remaining requests
    if (bulkRequest.numberOfActions() > 0) {
      BulkResponse response = bulkRequest.execute().actionGet();
      // Handle failure by iterating through each bulk response item
      if (response.hasFailures()) {
        processBulkResponseFailure(response);
      }
    }

    // Show time taken to index the documents
    logger.info(
        "Indexed {} documents on {}/{} in {} seconds",
        bulkLength,
        indexName,
        typeName,
        (System.currentTimeMillis() - startTime) / 1000.0);
  }
 /**
  * Add to <code>toAdd</code> all the superclass statements needed to note that any indirect
  * subclass of <code>X = parents.item</code> has as superclass all the classes between it and X
  * and all the remaining elements of <code>parents</code>.
  */
 private static void addSuperClasses(Model m, LinkedSeq parents, Model toAdd) {
   Resource type = parents.item;
   for (StmtIterator it = m.listStatements(null, RDFS.subClassOf, type); it.hasNext(); ) {
     Resource t = it.nextStatement().getSubject();
     for (LinkedSeq scan = parents.rest; scan != null; scan = scan.rest)
       toAdd.add(t, RDFS.subClassOf, scan.item);
     addSuperClasses(m, parents.push(t), toAdd);
   }
 }
 public void testQuintetOfQuadlets() {
   Resource rs = model.createResource();
   rs.addProperty(RDF.type, RDF.Statement);
   model.createResource().addProperty(RDF.value, rs);
   rs.addProperty(RDF.subject, model.createResource());
   rs.addProperty(RDF.predicate, model.createProperty("http://example.org/foo"));
   rs.addProperty(RDF.object, model.createResource());
   rs.addProperty(RDF.object, model.createResource());
   StmtIterator it = model.listStatements();
   while (it.hasNext()) {
     Statement s = it.nextStatement();
     assertFalse(s.getObject().equals(s.getSubject()));
   }
 }
예제 #9
0
  /**
   * Check that a predicate for which no shortnames are defined in name map still gets a term
   * binding in the metadata.
   */
  @Test
  public void testTermBindingsCoverAllPredicates() throws URISyntaxException {
    Resource thisPage = ResourceFactory.createResource("elda:thisPage");
    String pageNumber = "1";
    Bindings cc = new Bindings();
    URI reqURI = new URI("");
    //
    EndpointDetails spec =
        new EndpointDetails() {

          @Override
          public boolean isListEndpoint() {
            return true;
          }

          @Override
          public boolean hasParameterBasedContentNegotiation() {
            return false;
          }
        };
    EndpointMetadata em = new EndpointMetadata(spec, thisPage, pageNumber, cc, reqURI);
    //
    PrefixMapping pm =
        PrefixMapping.Factory.create().setNsPrefix("this", "http://example.com/root#");
    Model toScan = ModelIOUtils.modelFromTurtle(":a <http://example.com/root#predicate> :b.");
    toScan.setNsPrefixes(pm);
    Resource predicate = toScan.createProperty("http://example.com/root#predicate");
    Model meta = ModelFactory.createDefaultModel();
    Resource exec = meta.createResource("fake:exec");
    ShortnameService sns = new StandardShortnameService();
    //		APIEndpoint.Request r = new APIEndpoint.Request( new Controls(), reqURI, cc );

    CompleteContext c =
        new CompleteContext(CompleteContext.Mode.PreferPrefixes, sns.asContext(), pm)
            .include(toScan);

    em.addTermBindings(toScan, meta, exec, c);

    @SuppressWarnings("unused")
    Map<String, String> termBindings = c.Do();
    Resource tb = meta.listStatements(null, API.termBinding, Any).nextStatement().getResource();
    assertTrue(meta.contains(tb, API.label, "this_predicate"));
    assertTrue(meta.contains(tb, API.property, predicate));
  }
예제 #10
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String path = request.getPathInfo();
    boolean htmlOutput = true;
    String language = null;
    String contentType = "text/html; charset='utf-8'";

    if (path != null) {
      if (path.endsWith(".rdf")) {
        contentType = "application/rdf+xml; charset='utf-8'";
        htmlOutput = false;
        language = "RDF/XML";
      } else if (path.endsWith(".xml")) {
        contentType = "application/xml; charset='utf-8'";
        htmlOutput = false;
        language = "RDF/XML";
      } else if (path.endsWith(".n3")) {
        contentType = "text/n3; charset='utf-8'";
        htmlOutput = false;
        language = "N3";
      }
    }

    response.setContentType(contentType);
    response.setStatus(HttpServletResponse.SC_OK);

    Writer writer = response.getWriter();

    synchronized (board) {
      if (htmlOutput) {
        writer.write(
            "<!DOCTYPE html>\n"
                + "<html lang='en'>"
                + "<head><meta charset='utf-8'/><title>MATe model</title></head>"
                + "<body><ul>");
        StmtIterator it = model.listStatements();
        /* TODO: well, this could be prettier */
        while (it.hasNext()) writer.write("<li>" + it.nextStatement() + "</li>");
        writer.write("<ul></body></html>");
      } else model.write(writer, language);
    }
  }
예제 #11
0
  /**
   * Answer the shortest path from the <code>start</code> resource to the <code>end</code> RDF node,
   * such that every step on the path is accepted by the given filter. A path is a {@link List} of
   * RDF {@link Statement}s. The subject of the first statement in the list is <code>start</code>,
   * and the object of the last statement in the list is <code>end</code>.
   *
   * <p>The <code>onPath</code> argument is a {@link Filter}, which accepts a statement and returns
   * true if the statement should be considered to be on the path. To search for an unconstrained
   * path, pass {@link Filter#any} as an argument. To search for a path whose predicates match a
   * fixed restricted set of property names, pass an instance of {@link PredicatesFilter}.
   *
   * <p>If there is more than one path of minimal length from <code>start</code> to <code>end</code>
   * , this method returns an arbitrary one. The algorithm is blind breadth-first search, with loop
   * detection.
   *
   * @param m The model in which we are seeking a path
   * @param start The starting resource
   * @param end The end, or goal, node
   * @param onPath A filter which determines whether a given statement can be considered part of the
   *     path
   * @return A path, consisting of a list of statements whose first subject is <code>start</code>,
   *     and whose last object is <code>end</code>, or null if no such path exists.
   */
  public static Path findShortestPath(
      Model m, Resource start, RDFNode end, Filter<Statement> onPath) {
    List<Path> bfs = new LinkedList<Path>();
    Set<Resource> seen = new HashSet<Resource>();

    // initialise the paths
    for (Iterator<Statement> i = m.listStatements(start, null, (RDFNode) null).filterKeep(onPath);
        i.hasNext(); ) {
      bfs.add(new Path().append(i.next()));
    }

    // search
    Path solution = null;
    while (solution == null && !bfs.isEmpty()) {
      Path candidate = bfs.remove(0);

      if (candidate.hasTerminus(end)) {
        solution = candidate;
      } else {
        Resource terminus = candidate.getTerminalResource();
        if (terminus != null) {
          seen.add(terminus);

          // breadth-first expansion
          for (Iterator<Statement> i = terminus.listProperties().filterKeep(onPath);
              i.hasNext(); ) {
            Statement link = i.next();

            // no looping allowed, so we skip this link if it takes us to a node we've seen
            if (!seen.contains(link.getObject())) {
              bfs.add(candidate.append(link));
            }
          }
        }
      }
    }

    return solution;
  }
  public static void main(String[] args) {

    List<String> obj = new ArrayList<String>();

    Scanner input = new Scanner(System.in);

    System.out.print("Enter URI: ");

    String userIn = input.nextLine();

    // create an empty Model
    Model model = ModelFactory.createDefaultModel();

    // read the RDF/XML file
    model.read(userIn);

    // write it to standard out
    // model.write(System.out);

    // list the statements in the Model
    StmtIterator iter = model.listStatements();

    System.out.println();

    // print out the predicate, subject and object of each statement
    while (iter.hasNext()) {
      Statement stmt = iter.nextStatement(); // get next statement
      Resource subject = stmt.getSubject(); // get the subject
      Property predicate = stmt.getPredicate(); // get the predicate
      RDFNode object = stmt.getObject(); // get the object

      System.out.print(subject.toString());
      System.out.print(" -> " + predicate.toString() + " -> ");
      if (object instanceof Resource) {
        System.out.print(object.toString() + "\n");
      } else {
        // object is a literal
        System.out.print(" \"" + object.toString() + "\"\n");
      }
    }

    /* for(int i = 0; i < (obj.size()); i++){

    	String sparqlQueryString1=
    								"SELECT ?s ?o "+
    								"WHERE {"+
    								"?s ?p ?o ."+
    								"?o <bif:contains> \""+obj.get(i)+"\" ."+
    								"}"+
    								"limit 10";

    		      Query query = QueryFactory.create(sparqlQueryString1);
    		      QueryExecution qexec = QueryExecutionFactory.sparqlService("http://pubmed.bio2rdf.org/sparql", query);

    		      ResultSet results = qexec.execSelect();
    		      System.out.println("Query: "+obj.get(i));
    		      ResultSetFormatter.out(System.out, results, query);

    		     qexec.close() ;
    } */

  }
예제 #13
0
 protected static void addSubclassesFrom(Model result, Model schema) {
   for (StmtIterator it = schema.listStatements(ANY, RDFS.subClassOf, ANY); it.hasNext(); ) {
     Statement s = it.nextStatement();
     if (s.getSubject().isURIResource() && s.getObject().isURIResource()) result.add(s);
   }
 }
예제 #14
0
 private static Set<Resource> subjectSet(Model result, Resource S, Property P, RDFNode O) {
   return result.listStatements(S, P, O).mapWith(Statement.Util.getSubject).toSet();
 }
예제 #15
0
 private static void addIntersections(Model result, Model schema) {
   StmtIterator it = schema.listStatements(ANY, OWL.intersectionOf, ANY);
   while (it.hasNext()) addIntersections(result, schema, it.nextStatement());
 }
예제 #16
0
 /**
  * Answer the set of all classes which appear in <code>m</code> as the subject or object of a
  * <code>rdfs:subClassOf</code> statement.
  */
 private static Set<RDFNode> findClassesBySubClassOf(Model m) {
   Set<RDFNode> classes = new HashSet<RDFNode>();
   StmtIterator it = m.listStatements(null, RDFS.subClassOf, (RDFNode) null);
   while (it.hasNext()) addClasses(classes, it.nextStatement());
   return classes;
 }