public static QueryExecution create(String queryStr, Model model) {
   checkArg(queryStr);
   checkArg(model);
   if (model.getGraph() instanceof VirtGraph) {
     VirtuosoQueryExecution ret =
         new VirtuosoQueryExecution(queryStr, (VirtGraph) model.getGraph());
     return ret;
   } else {
     return create(makeQuery(queryStr), model);
   }
 }
示例#2
0
 /**
  * test that two models are isomorphic and fail if they are not.
  *
  * @param title a String appearing at the beginning of the failure message
  * @param wanted the model value that is expected
  * @param got the model value to check
  * @exception if the models are not isomorphic
  */
 public static void assertIsoModels(String title, Model wanted, Model got) {
   if (wanted.isIsomorphicWith(got) == false) {
     Map<Node, Object> map = CollectionFactory.createHashedMap();
     fail(
         title
             + ": expected "
             + nice(wanted.getGraph(), map)
             + "\n but had "
             + nice(got.getGraph(), map));
   }
 }
  public static QueryExecution create(Query query, Model model) {
    checkArg(query);
    checkArg(model);

    if (model.getGraph() instanceof VirtGraph) {
      VirtuosoQueryExecution ret =
          new VirtuosoQueryExecution(query.toString(), (VirtGraph) model.getGraph());
      return ret;
    } else {
      return make(query, new DatasetImpl(model));
    }
  }
示例#4
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;
  }
示例#6
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;
  }
  public SPDXChecksum(Model spdxModel, Node checksumNode) throws InvalidSPDXAnalysisException {
    this.model = spdxModel;
    this.checksumNode = checksumNode;
    if (checksumNode.isBlank()) {
      checksumResource = model.createResource(checksumNode.getBlankNodeId());
    } else if (checksumNode.isURI()) {
      checksumResource = model.createResource(checksumNode.getURI());
    } else {
      throw (new InvalidSPDXAnalysisException("Checksum node can not be a literal"));
    }
    // Algorithm
    Node p =
        spdxModel
            .getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_CHECKSUM_ALGORITHM)
            .asNode();
    Triple m = Triple.createMatch(checksumNode, p, null);
    ExtendedIterator<Triple> tripleIter = spdxModel.getGraph().find(m);
    while (tripleIter.hasNext()) {
      Triple t = tripleIter.next();
      if (t.getObject().isLiteral()) {
        // The following is for compatibility with rdf generated with older
        // versions of the tool
        this.algorithm = t.getObject().toString(false);
      } else if (t.getObject().isURI()) {
        this.algorithm = URI_TO_ALGORITHM.get(t.getObject().getURI());
        if (this.algorithm == null) {
          this.algorithm = "UNKNOWN";
        }
      } else {
        throw (new InvalidSPDXAnalysisException(
            "Invalid checksum algorithm - must be one of the defined algorithms supported by SPDX."));
      }
    }

    // value
    p =
        spdxModel
            .getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_CHECKSUM_VALUE)
            .asNode();
    m = Triple.createMatch(checksumNode, p, null);
    tripleIter = spdxModel.getGraph().find(m);
    while (tripleIter.hasNext()) {
      Triple t = tripleIter.next();
      this.value = t.getObject().toString(false);
    }
  }
示例#8
0
 /**
  * @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 Graph getGraph(Node graphNode) {
   Model model = dataset.getNamedModel(graphNode.getURI());
   if (model != null) {
     return getControlledUpdateGraph(model.getGraph());
   } else {
     return null;
   }
 }
 @Override
 public Graph getDefaultGraph() {
   Model defaultModel = dataset.getDefaultModel();
   if (defaultModel != null) {
     return getControlledUpdateGraph(defaultModel.getGraph());
   } else {
     return null;
   }
 }
示例#11
0
 /**
  * Attempts to load a graph with a given URI. In the default implementation, this uses the Jena
  * OntDocumentManager and default loading mechanisms. Subclasses can override this.
  *
  * @param uri the base URI of the graph to load
  * @return the Graph or null to ignore this
  * @throws IOException
  */
 protected Graph getImportedGraph(String uri) throws IOException {
   Model model = OntDocumentManager.getInstance().getModel(uri);
   if (model == null) {
     Model baseModel = JenaUtil.createDefaultModel();
     baseModel.read(uri);
     model = JenaUtil.createOntologyModel(OntModelSpec.OWL_MEM, baseModel);
     OntDocumentManager.getInstance().addModel(uri, model);
   }
   return model.getGraph();
 }
示例#12
0
  private Node walkTree(
      Model model,
      Dataset oldDataset,
      Node node,
      Node predicate,
      Query query,
      QuerySolution initialBinding,
      Set<Node> reached) {
    QuerySolutionMap localBinding = new QuerySolutionMap();
    localBinding.addAll(initialBinding);
    localBinding.add("arg1", model.asRDFNode(node));
    Dataset dataset = new DatasetWithDifferentDefaultModel(model, oldDataset);
    QueryExecution qexec = ARQFactory.get().createQueryExecution(query, dataset, localBinding);
    ResultSet rs = qexec.execSelect();
    try {
      if (rs.hasNext()) {
        List<String> resultVars = rs.getResultVars();
        String varName = resultVars.get(0);
        RDFNode resultNode = rs.next().get(varName);
        if (resultNode != null) {
          return resultNode.asNode();
        }
      }
    } finally {
      qexec.close();
    }

    // Recurse into parents
    ExtendedIterator<Triple> it = createIterator(model.getGraph(), node, predicate);
    try {
      while (it.hasNext()) {
        Node next = getNext(it.next());
        if ((next.isBlank() || next.isURI()) && !reached.contains(next)) {
          reached.add(next);
          Node nextResult =
              walkTree(model, oldDataset, next, predicate, query, initialBinding, reached);
          if (nextResult != null) {
            return nextResult;
          }
        }
      }
    } finally {
      it.close();
    }

    return null;
  }
示例#13
0
  /**
   * Checks if spin:imports have been declared and adds them to a union model. Will also register
   * any SPIN modules defined in those imports that haven't been loaded before.
   *
   * @param model the base Model to operate on
   * @return either model or the union of model and its spin:imports @
   */
  public Model getImportsModel(Model model) throws IOException {
    Set<String> uris = new HashSet<String>();
    StmtIterator it = model.listStatements(null, SPIN.imports, (RDFNode) null);
    while (it.hasNext()) {
      Statement s = it.nextStatement();
      if (s.getObject().isURIResource()) {
        uris.add(s.getResource().getURI());
      }
    }
    if (uris.isEmpty()) {
      return model;
    } else {
      Graph baseGraph = model.getGraph();

      MultiUnion union = JenaUtil.createMultiUnion();
      union.addGraph(baseGraph);
      union.setBaseGraph(baseGraph);

      boolean needsRegistration = false;
      for (String uri : uris) {
        Graph graph = getImportedGraph(uri);
        if (graph != null) {
          union.addGraph(graph);
          if (!registeredURIs.contains(uri)) {
            registeredURIs.add(uri);
            needsRegistration = true;
          }
        }
      }

      // Ensure that SP, SPIN and SPL are present
      ensureImported(union, SP.BASE_URI, SP.getModel());
      ensureImported(union, SPL.BASE_URI, SPL.getModel());
      ensureImported(union, SPIN.BASE_URI, SPIN.getModel());

      Model unionModel = ModelFactory.createModelForGraph(union);
      if (needsRegistration) {
        SPINModuleRegistry.get().registerAll(unionModel, null);
      }
      return unionModel;
    }
  }
示例#14
0
 /**
  * Answer a version of the model, but with all its reifiying statements added.
  *
  * @param m a model that may have reified statements
  * @return a new model, the union of m and the reification statements of m
  */
 public static Model withHiddenStatements(Model m) {
   Graph mGraph = m.getGraph();
   Graph hiddenTriples = getHiddenTriples(m);
   return new ModelCom(new DisjointUnion(mGraph, hiddenTriples));
 }
示例#15
0
 private void ensureImported(MultiUnion union, String baseURI, Model model) {
   if (!union.contains(
       Triple.create(NodeFactory.createURI(baseURI), RDF.type.asNode(), OWL.Ontology.asNode()))) {
     union.addGraph(model.getGraph());
   }
 }
示例#16
0
 public static void loadModel(Model model, String uri, int limit) {
   Graph g = model.getGraph();
   readUtil(g, uri, limit);
 }