Exemple #1
0
  public static String RenderTemplatePage(Bindings b, String templateName) throws IOException {

    MediaType mt = MediaType.TEXT_HTML;
    Resource config = model.createResource("eh:/root");
    Mode prefixMode = Mode.PreferPrefixes;
    ShortnameService sns = new StandardShortnameService();

    List<Resource> noResults = CollectionUtils.list(root.inModel(model));
    Graph resultGraph = graphModel.getGraph();

    resultGraph.getPrefixMapping().setNsPrefix("api", API.NS);
    resultGraph.add(Triple.create(root.asNode(), API.items.asNode(), RDF.nil.asNode()));

    APIResultSet rs = new APIResultSet(resultGraph, noResults, true, true, "details", View.ALL);
    VelocityRenderer vr = new VelocityRenderer(mt, null, config, prefixMode, sns);

    VelocityRendering vx = new VelocityRendering(b, rs, vr);

    VelocityEngine ve = vx.createVelocityEngine();
    VelocityContext vc = vx.createVelocityContext(b);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    Writer w = new OutputStreamWriter(bos, "UTF-8");
    Template t = ve.getTemplate(templateName);

    t.merge(vc, w);
    w.close();

    return bos.toString();
  }
  /**
   * Query SPARQL endpoint with a SELECT query
   *
   * @param qExec QueryExecution encapsulating the query
   * @return model retrieved by querying the endpoint
   */
  private Model getSelectModel(QueryExecution qExec) {
    Model model = ModelFactory.createDefaultModel();
    Graph graph = model.getGraph();
    ResultSet results = qExec.execSelect();

    while (results.hasNext()) {
      QuerySolution sol = results.next();
      String subject;
      String predicate;
      RDFNode object;

      try {
        subject = sol.getResource("s").toString();
        predicate = sol.getResource("p").toString();
        object = sol.get("o");
      } catch (NoSuchElementException e) {
        logger.error("SELECT query does not return a (?s ?p ?o) Triple");
        continue;
      }

      Node objNode;
      if (object.isLiteral()) {
        Literal obj = object.asLiteral();
        objNode = NodeFactory.createLiteral(obj.getString(), obj.getDatatype());
      } else {
        objNode = NodeFactory.createLiteral(object.toString());
      }

      graph.add(
          new Triple(NodeFactory.createURI(subject), NodeFactory.createURI(predicate), objNode));
    }

    return model;
  }
Exemple #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;
  }
 @Override
 public void add(Triple[] arg0) {
   Graph g = GraphFactory.createPlainGraph();
   for (int i = 0; i < arg0.length; i++) {
     g.add(arg0[i]);
   }
   add(g);
 }
 @Override
 public void add(List<Triple> arg0) {
   Graph g = GraphFactory.createPlainGraph();
   for (Triple t : arg0) {
     g.add(t);
   }
   add(g);
 }
 /**
  * @param mGraph
  * @return
  */
 protected static Graph getHiddenTriples(Model m) {
   Graph mGraph = m.getGraph();
   final Reifier r = mGraph.getReifier();
   return new GraphBase() {
     public ExtendedIterator graphBaseFind(TripleMatch m) {
       return r.findEither(m, true);
     }
   };
 }
 @Override
 public boolean contains(Node g, Node s, Node p, Node o) {
   Graph graph = getGraph(g);
   if (graph != null) {
     return graph.contains(s, p, o);
   } else {
     return false;
   }
 }
 /**
  * Extended find interface used in situations where the implementator may or may not be able to
  * answer the complete query. It will attempt to answer the pattern but if its answers are not
  * known to be complete then it will also pass the request on to the nested Finder to append more
  * results.
  *
  * @param pattern a TriplePattern to be matched against the data
  * @param continuation either a Finder or a normal Graph which will be asked for additional match
  *     results if the implementor may not have completely satisfied the query.
  */
 @Override
 public ExtendedIterator<Triple> findWithContinuation(TriplePattern pattern, Finder continuation) {
   if (graph == null) return new NullIterator<Triple>();
   if (continuation == null) {
     return graph.find(pattern.asTripleMatch());
   } else {
     return graph.find(pattern.asTripleMatch()).andThen(continuation.find(pattern));
   }
 }
 @Override
 public void add(Iterator<Triple> arg0) {
   Graph g = GraphFactory.createPlainGraph();
   while (arg0.hasNext()) {
     Triple t = arg0.next();
     g.add(t);
   }
   add(g);
 }
 @Override
 public void add(Quad quad) {
   Graph graph;
   if (quad.isDefaultGraph()) {
     graph = getDefaultGraph();
   } else {
     graph = getGraph(quad.getGraph());
   }
   if (graph != null) {
     graph.add(quad.asTriple());
   }
 }
 public static void removeAll(Graph g, Node s, Node p, Node o) {
   ExtendedIterator<Triple> it = g.find(s, p, o);
   try {
     while (it.hasNext()) {
       Triple t = it.next();
       g.delete(t);
       it.remove();
     }
   } finally {
     it.close();
   }
 }
 /** Removes the triple t (if possible) from the set belonging to this graph. */
 @Override
 public void performDelete(Triple t) {
   version++;
   if (fdata != null) {
     Graph data = fdata.getGraph();
     if (data != null) {
       data.delete(t);
     }
   }
   if (!this.isPrepared()) {
     fdeductions.getGraph().delete(t);
   }
 }
 /**
  * Adds a set of precomputed triples to the deductions store. These do not, themselves, fire any
  * rules but provide additional axioms that might enable future rule firing when real data is
  * added. Used to implement bindSchema processing in the parent Reasoner.
  *
  * @return return true if the rule set has also been loaded
  */
 protected boolean preloadDeductions(Graph preloadIn) {
   Graph d = fdeductions.getGraph();
   BasicForwardRuleInfGraph preload = (BasicForwardRuleInfGraph) preloadIn;
   // If the rule set is the same we can reuse those as well
   if (preload.rules == rules) {
     // Load raw deductions
     for (Iterator<Triple> i = preload.find(null, null, null); i.hasNext(); ) {
       d.add(i.next());
     }
     engine.setRuleStore(preload.engine.getRuleStore());
     return true;
   } else {
     return false;
   }
 }
Exemple #14
0
 public OntModel applyRenamings() {
   OntModel result = ModelFactory.createMem();
   Graph graph = result.getGraph();
   Iterator it = model.getGraph().find(Triple.ANY);
   while (it.hasNext()) {
     Triple t = (Triple) it.next();
     Node s = t.getSubject().isURI() ? rename(t.getSubject()) : null;
     Node o = t.getObject().isURI() ? rename(t.getObject()) : null;
     if (s != null || o != null)
       t =
           Triple.create(
               s != null ? s : t.getSubject(), t.getPredicate(), o != null ? o : t.getObject());
     graph.add(t);
   }
   return result;
 }
 private void addStages(ArrayList<Stage> stages, NamedGraphMap arguments, Mapping map) {
   Iterator<Map.Entry<String, Cons>> it2 = triples.entrySetIterator();
   while (it2.hasNext()) {
     Map.Entry<String, Cons> e = it2.next();
     String name = e.getKey();
     Cons nodeTriples = e.getValue();
     Graph g = arguments.get(name);
     int nBlocks = Cons.size(nodeTriples), i = nBlocks;
     Triple[] nodes = new Triple[nBlocks];
     while (nodeTriples != null) {
       nodes[--i] = nodeTriples.head;
       nodeTriples = nodeTriples.tail;
     }
     nodes = sortTriples(nodes);
     Stage next = g.queryHandler().patternStage(map, constraint, nodes);
     stages.add(next);
   }
 }
 @Override
 public void addGraph(Node gn, Graph g) {
   // Convert to quads.
   // super.addGraph(gn, g) ;
   ExtendedIterator<Triple> iter = g.find(Node.ANY, Node.ANY, Node.ANY);
   for (; iter.hasNext(); ) {
     Triple t = iter.next();
     add(gn, t.getSubject(), t.getPredicate(), t.getObject());
   }
 }
  public static boolean isContainer(Graph graph, Node container, Node containerType) {
    //        if ( container.isLiteral() )
    //            return false ;

    if (containerType == null)
      return isContainer(graph, container, BAG)
          || isContainer(graph, container, ALT)
          || isContainer(graph, container, SEQ);

    return graph.contains(container, RDFtype, containerType);
  }
 /**
  * Create the graph used to hold the deductions. Can be overridden by subclasses that need special
  * purpose graph implementations here. Assumes the graph underlying fdeductions and associated
  * SafeGraph wrapper can be reused if present thus enabling preservation of listeners.
  */
 protected Graph createDeductionsGraph() {
   if (fdeductions != null) {
     Graph dg = fdeductions.getGraph();
     if (dg != null) {
       // Reuse the old graph in order to preserve any listeners
       safeDeductions.getBulkUpdateHandler().removeAll();
       return dg;
     }
   }
   Graph dg = Factory.createGraphMem(style);
   safeDeductions = new SafeGraph(dg);
   return dg;
 }
 /**
  * Create the graph used to hold the deductions. Can be overridden by subclasses that need special
  * purpose graph implementations here. Assumes the graph underlying fdeductions and associated
  * SafeGraph wrapper can be reused if present thus enabling preservation of listeners.
  */
 protected Graph createDeductionsGraph() {
   if (fdeductions != null) {
     Graph dg = fdeductions.getGraph();
     if (dg != null) {
       // Reuse the old graph in order to preserve any listeners
       safeDeductions.clear();
       return dg;
     }
   }
   Graph dg = Factory.createGraphMem();
   safeDeductions = new SafeGraph(dg);
   return dg;
 }
Exemple #20
0
  /**
   * Create an instance of the SecuredGraph
   *
   * @param securityEvaluator The security evaluator to use
   * @param graphIRI The IRI for the graph.
   * @param graph The graph that we are wrapping.
   * @return the secured graph
   */
  public static SecuredGraph getInstance(
      final SecurityEvaluator securityEvaluator, final String graphIRI, final Graph graph) {

    final ItemHolder<Graph, SecuredGraphImpl> holder =
        new ItemHolder<Graph, SecuredGraphImpl>(graph);
    final SecuredGraphImpl checker = new SecuredGraphImpl(securityEvaluator, graphIRI, holder) {};

    // If we going to create a duplicate proxy return this one.
    if (graph instanceof SecuredGraphImpl) {
      if (checker.isEquivalent((SecuredGraphImpl) graph)) {
        return (SecuredGraph) graph;
      }
    }
    return holder.setSecuredItem(new SecuredItemInvoker(graph.getClass(), checker));
  }
  public static void removeAll(Graph g) {
    ExtendedIterator<Triple> it = GraphUtil.findAll(g);
    try {
      while (it.hasNext()) {
        Triple t = it.next();
        g.delete(t);
        it.remove();
      }
    } finally {
      it.close();
    }

    // get rid of remaining blank nodes using a SPARQL DELETE
    if (g instanceof SparqlGraph) {
      ((SparqlGraph) g).removeAll();
    }
  }
  public static Collection<Node> containerMembers(Graph graph, Node container, Node containerType) {
    if (!isContainer(graph, container, containerType)) return null;

    ExtendedIterator<Triple> iter = graph.find(container, Node.ANY, Node.ANY);

    SortedMap<Integer, Node> triples = new TreeMap<Integer, Node>(order);
    try {
      for (; iter.hasNext(); ) {
        Triple t = iter.next();
        int index = getIndex(t);
        if (index == NOT_FOUND) continue;
        // Insert
        triples.put(new Integer(index), t.getObject());
      }
    } finally {
      iter.close();
    }
    return triples.values();
  }
  @Override
  public void delete(Graph g) {
    Model[] model = separateStatementsWithBlankNodes(g);
    deleteModel(model[1] /*statements without blank nodes*/);
    // replace blank nodes in remaining statements with variables

    StringBuffer patternBuff = new StringBuffer();
    Iterator<Triple> tripIt = g.find(null, null, null);
    while (tripIt.hasNext()) {
      Triple t = tripIt.next();
      patternBuff.append(SparqlGraph.sparqlNodeDelete(t.getSubject(), null));
      patternBuff.append(" ");
      patternBuff.append(SparqlGraph.sparqlNodeDelete(t.getPredicate(), null));
      patternBuff.append(" ");
      patternBuff.append(SparqlGraph.sparqlNodeDelete(t.getObject(), null));
      patternBuff.append(" .\n");
    }

    StringBuffer queryBuff = new StringBuffer();
    String graphURI = graph.getGraphURI();
    queryBuff.append(
        "DELETE { " + ((graphURI != null) ? "GRAPH <" + graphURI + "> { " : "") + " \n");
    queryBuff.append(patternBuff);
    if (graphURI != null) {
      queryBuff.append("    } \n");
    }
    queryBuff.append("} WHERE { \n");
    if (graphURI != null) {
      queryBuff.append("    GRAPH <" + graphURI + "> { \n");
    }
    queryBuff.append(patternBuff);
    if (graphURI != null) {
      queryBuff.append("    } \n");
    }
    queryBuff.append("} \n");

    log.debug(queryBuff.toString());

    graph.executeUpdate(queryBuff.toString());
  }
  private static int countContainerMember(
      Graph graph, Node container, Node containerType, Node member, boolean stopEarly) {
    if (graph == null) {
      Log.warn(GraphContainerUtils.class, "containerMember called with null graph");
      return 0;
    }

    if (container == null) {
      Log.warn(GraphContainerUtils.class, "containerMember called with null list");
      return 0;
    }
    if (member == null) {
      Log.warn(GraphContainerUtils.class, "containerMember called with null member");
      return 0;
    }

    if (!isContainer(graph, container, containerType)) return 0;

    int count = 0;
    ExtendedIterator<Triple> iter = graph.find(container, Node.ANY, member);
    try {
      for (; iter.hasNext(); ) {
        Triple t = iter.next();
        Node p = t.getPredicate();
        String u = p.getURI();

        if (u.matches(membershipPattern)) {
          count++;
          if (stopEarly) return count;
        }
      }
    } finally {
      iter.close();
    }
    return count;
  }
 /**
  * this is a simple-minded implementation of containsNode that uses find up to three times to
  * locate the node. Almost certainly particular graphs will be able to offer better query-handlers
  * ...
  */
 public boolean containsNode(Node n) {
   return graph.contains(n, Node.ANY, Node.ANY)
       || graph.contains(Node.ANY, n, Node.ANY)
       || graph.contains(Node.ANY, Node.ANY, n);
 }
 /** Return true if the given pattern occurs somewhere in the find sequence. */
 @Override
 public boolean contains(TriplePattern pattern) {
   return graph.contains(pattern.getSubject(), pattern.getPredicate(), pattern.getObject());
 }
 /**
  * Basic pattern lookup interface.
  *
  * @param pattern a TriplePattern to be matched against the data
  * @return a ClosableIterator over all Triples in the data set that match the pattern
  */
 @Override
 public ExtendedIterator<Triple> find(TriplePattern pattern) {
   if (graph == null) return new NullIterator<Triple>();
   return graph.find(pattern.asTripleMatch());
 }
        /** Return true iff the node can be converted to an instance of this class (Thing) */
        public boolean canWrap(Node n, EnhGraph eg) {
          Profile profile;
          if (eg instanceof OntModel) profile = ((OntModel) eg).getProfile();
          else return false;

          if (!profile.isSupported(n, eg, Individual.class)) {
            return false;
          }

          Graph graph = eg.asGraph();
          return graph.contains(
                  n,
                  com.hp.hpl.jena.vocabulary.RDF.type.asNode(),
                  eu.lod2.nlp2rdf.schema.tools.Vocabulary.Thing.asNode())
              || graph.contains(
                  n,
                  com.hp.hpl.jena.vocabulary.RDF.type.asNode(),
                  eu.lod2.nlp2rdf.schema.tools.Vocabulary.String.asNode())
              || graph.contains(
                  n,
                  com.hp.hpl.jena.vocabulary.RDF.type.asNode(),
                  eu.lod2.nlp2rdf.schema.tools.Vocabulary.Phrase.asNode())
              || graph.contains(
                  n,
                  com.hp.hpl.jena.vocabulary.RDF.type.asNode(),
                  eu.lod2.nlp2rdf.schema.tools.Vocabulary.Word.asNode())
              || graph.contains(
                  n,
                  com.hp.hpl.jena.vocabulary.RDF.type.asNode(),
                  eu.lod2.nlp2rdf.schema.tools.Vocabulary.StopWord.asNode())
              || graph.contains(
                  n,
                  com.hp.hpl.jena.vocabulary.RDF.type.asNode(),
                  eu.lod2.nlp2rdf.schema.tools.Vocabulary.Sentence.asNode())
              || graph.contains(
                  n,
                  com.hp.hpl.jena.vocabulary.RDF.type.asNode(),
                  eu.lod2.nlp2rdf.schema.tools.Vocabulary.OffsetBasedString.asNode())
              || graph.contains(
                  n,
                  com.hp.hpl.jena.vocabulary.RDF.type.asNode(),
                  eu.lod2.nlp2rdf.schema.tools.Vocabulary.ContextHashBasedString.asNode())
              || graph.contains(
                  n,
                  com.hp.hpl.jena.vocabulary.RDF.type.asNode(),
                  eu.lod2.nlp2rdf.schema.tools.Vocabulary.Document.asNode())
              || graph.contains(
                  n,
                  com.hp.hpl.jena.vocabulary.RDF.type.asNode(),
                  eu.lod2.nlp2rdf.schema.tools.Vocabulary.Topic.asNode())
              || graph.contains(
                  n,
                  com.hp.hpl.jena.vocabulary.RDF.type.asNode(),
                  eu.lod2.nlp2rdf.schema.tools.Vocabulary.Error.asNode());
        }
 public static ExtendedIterator subjectsFor(Graph g, Node p, Node o) {
   Set objects = CollectionFactory.createHashedSet();
   ClosableIterator it = g.find(Node.ANY, p, o);
   while (it.hasNext()) objects.add(((Triple) it.next()).getSubject());
   return WrappedIterator.createNoRemove(objects.iterator());
 }
 public static ExtendedIterator predicatesFor(Graph g, Node s, Node o) {
   Set predicates = CollectionFactory.createHashedSet();
   ClosableIterator it = g.find(s, Node.ANY, o);
   while (it.hasNext()) predicates.add(((Triple) it.next()).getPredicate());
   return WrappedIterator.createNoRemove(predicates.iterator());
 }