Java Code Examples for org.apache.jena.rdf.model.ModelFactory#createModelForGraph()

The following examples show how to use org.apache.jena.rdf.model.ModelFactory#createModelForGraph() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: QueryExecutionTest.java    From RDFstarTools with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithTTLStarString2()
{
	final String ttlsString =
			"@prefix ex: <http://example.com/> ." +
			"<< ex:s ex:p ex:o >>  ex:m1  ex:x1 . ";

	final String queryString = prefixes + "SELECT ?o WHERE { ?t ex:m1 ex:x1 . ?t ?p ?o }";

	final Graph g = RDFStarUtils.createRedundancyAugmentedGraphFromTurtleStarSnippet(ttlsString);
	final Model m = ModelFactory.createModelForGraph(g);


	final Query query = QueryFactory.create( queryString, null, SPARQLStar.syntax );
       final ResultSet rs = QueryExecutionFactory.create(query, m).execSelect();

       consume( rs, "o", "http://example.com/x1" );
}
 
Example 2
Source File: SHACLUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
/**
 * Runs the rule to infer missing rdf:type triples for certain blank nodes.
 * @param model  the input Model
 * @return a new Model containing the inferred triples
 */
public static Model createDefaultValueTypesModel(Model model) {
	String sparql = JenaUtil.getStringProperty(DASH.DefaultValueTypeRule.inModel(model), SH.construct);
	if(sparql == null) {
		throw new IllegalArgumentException("Shapes graph does not include " + TOSH.PREFIX + ":" + DASH.DefaultValueTypeRule);
	}
	Model resultModel = JenaUtil.createMemoryModel();
	MultiUnion multiUnion = new MultiUnion(new Graph[] {
		model.getGraph(),
		resultModel.getGraph()
	});
	Model unionModel = ModelFactory.createModelForGraph(multiUnion);
	Query query = ARQFactory.get().createQuery(model, sparql);
	try(QueryExecution qexec = ARQFactory.get().createQueryExecution(query, unionModel)) {
	    qexec.execConstruct(resultModel);
	    return resultModel;    
	}
}
 
Example 3
Source File: SHACLUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an includes Model for a given input Model.
 * The includes Model is the union of the input Model will all graphs linked via
 * sh:include (or owl:imports), transitively. 
 * @param model  the Model to create the includes Model for
 * @param graphURI  the URI of the named graph represented by Model
 * @return a Model including the semantics
 */
public static Model createIncludesModel(Model model, String graphURI) {
	Set<Graph> graphs = new HashSet<Graph>();
	Graph baseGraph = model.getGraph();
	
	addIncludes(baseGraph, graphURI, graphs, new HashSet<String>());
	
	if(graphs.size() == 1) {
		return model;
	}
	else {
		MultiUnion union = new MultiUnion(graphs.iterator());
		union.setBaseGraph(baseGraph);
		return ModelFactory.createModelForGraph(union);
	}
}
 
Example 4
Source File: RulesEntailment.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
public Model createModelWithEntailment(Dataset dataset, URI shapesGraphURI, ShapesGraph shapesGraph, ProgressMonitor monitor) throws InterruptedException {
	Model dataModel = dataset.getDefaultModel();
	Model inferencesModel = JenaUtil.createDefaultModel();
	MultiUnion unionGraph = new MultiUnion(new Graph[] {
		dataModel.getGraph(),
		inferencesModel.getGraph()
	});
	Model unionDataModel = ModelFactory.createModelForGraph(unionGraph);
	RuleEngine engine = new RuleEngine(dataset, shapesGraphURI, shapesGraph, inferencesModel);
	engine.setProgressMonitor(monitor);
	engine.executeAll();
	if(inferencesModel.isEmpty()) {
		return dataModel;
	}
	else {
		return unionDataModel;
	}
}
 
Example 5
Source File: TargetContainsPFunction.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
public QueryIterator exec(Binding binding, PropFuncArg argSubject,
		Node predicate, PropFuncArg argObject, ExecutionContext execCxt) {

	argSubject = Substitute.substitute(argSubject, binding);
	argObject = Substitute.substitute(argObject, binding);
	
	if(!argObject.getArg().isVariable()) {
		throw new ExprEvalException("Right hand side of tosh:targetContains must be a variable");
	}
	
	Node targetNode = argSubject.getArgList().get(0);
	Node shapesGraphNode = argSubject.getArgList().get(1);
	
	Model currentModel = ModelFactory.createModelForGraph(execCxt.getActiveGraph());
	Dataset dataset = new DatasetWithDifferentDefaultModel(currentModel, DatasetImpl.wrap(execCxt.getDataset()));

	Model model = dataset.getNamedModel(shapesGraphNode.getURI());
	Resource target = (Resource) model.asRDFNode(targetNode);

	Set<Node> focusNodes = new HashSet<Node>();
	SHACLUtil.addNodesInTarget(target, dataset, focusNodes);
	return new QueryIterExtendByVar(binding, (Var) argObject.getArg(), focusNodes.iterator(), execCxt);
}
 
Example 6
Source File: FromDataset.java    From shacl with Apache License 2.0 6 votes vote down vote up
private void initDefaultModel() throws GraphNotFoundException {
	if(defaultGraphs.isEmpty()) {
		defaultModel = super.getDefaultModel();
	}
	else {
		if(defaultGraphs.size() == 1) {
			String defaultGraphURI = defaultGraphs.iterator().next();
			defaultModel = getNamedModel(defaultGraphURI);
			if(defaultModel == null) {
				throw new GraphNotFoundException("Named graph " + defaultGraphURI + " not found");
			}
		}
		else {
			MultiUnion multiUnion = JenaUtil.createMultiUnion();
			for(String graphURI : defaultGraphs) {
				Model model = getNamedModel(graphURI);
				if(model == null) {
					throw new GraphNotFoundException("Named graph " + graphURI + " not found");
				}
				multiUnion.addGraph(model.getGraph());
			}
			defaultModel = ModelFactory.createModelForGraph(multiUnion);
		}
	}
}
 
Example 7
Source File: HDTModelFactory.java    From Stargraph with MIT License 6 votes vote down vote up
@Override
protected Model createModel(String dbId) {
    Model model = null;
    try {
        File hdtFile = getHDTPath(dbId).toFile();
        if (hdtFile.exists()) {
            boolean useIdx = useIndex(dbId);
            String hdtFilePathStr = hdtFile.getAbsolutePath();
            logger.info(marker, "Loading '{}', useIndex={}", hdtFilePathStr, useIdx);
            HDT hdt = useIdx ? HDTManager.mapIndexedHDT(hdtFilePathStr, null) : HDTManager.loadHDT(hdtFilePathStr, null);
            HDTGraph graph = new HDTGraph(hdt);
            model = ModelFactory.createModelForGraph(graph);
            return model;
        }

       throw new FileNotFoundException("HDT file not found: '" + hdtFile + "'");

    } catch (Exception e) {
        throw new StarGraphException(e);
    }
    finally {
        if (model == null) {
            logger.error(marker, "No Graph Model instantiated for {}", dbId);
        }
    }
}
 
Example 8
Source File: DatasetLoader.java    From rdflint with MIT License 6 votes vote down vote up
static Model loadRdfSet(RdfLintParameters params, String targetDir) throws IOException {
  String parentPath = new File(targetDir).getCanonicalPath();
  String baseUri = params.getBaseUri();

  Graph g = Factory.createGraphMem();
  Files.walk(Paths.get(parentPath))
      .filter(e -> e.toString().endsWith(".rdf") || e.toString().endsWith(".ttl"))
      .forEach(e -> {
        Graph gf = Factory.createGraphMem();
        String filename = e.toString().substring(parentPath.length() + 1);
        String subdir = filename.substring(0, filename.lastIndexOf('/') + 1);
        RDFParser.source(e.toString()).base(baseUri + subdir).parse(gf);
        List<Triple> lst = gf.find().toList();
        gf.close();
        lst.forEach(g::add);

        gf.getPrefixMapping().getNsPrefixMap()
            .forEach((k, v) -> g.getPrefixMapping().setNsPrefix(k, v));
      });

  return ModelFactory.createModelForGraph(g);
}
 
Example 9
Source File: CustomQueryValidator.java    From rdflint with MIT License 6 votes vote down vote up
@Override
public void validateTripleSet(LintProblemSet problems, String file, List<Triple> tripeSet) {
  if (this.getParameters().getRules() == null) {
    return;
  }
  // execute sparql & custom validation
  Graph g = Factory.createGraphMem();
  tripeSet.forEach(g::add);
  Model m = ModelFactory.createModelForGraph(g);

  this.getParameters().getRules().stream()
      .filter(r -> file.matches(r.getTarget()))
      .forEach(r -> {
        Query query = QueryFactory.create(r.getQuery());
        QueryExecution qe = QueryExecutionFactory.create(query, m);

        Binding binding = new Binding();
        binding.setVariable("rs", qe.execSelect());
        binding.setVariable("log", new ProblemLogger(this, problems, file, r.getName()));
        GroovyShell shell = new GroovyShell(binding, new CompilerConfiguration());
        shell.evaluate(r.getValid());
      });
}
 
Example 10
Source File: QueryExecutionTest.java    From RDFstarTools with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithTTLStarString()
{
	final String ttlsString =
			"@prefix ex: <http://example.com/> ." +
			"<< ex:s ex:p ex:o >>  ex:m1  ex:x1 . " +
			"<< ex:s ex:p ex:o >>  ex:m2  ex:x2 . ";

	final String queryString = prefixes + "SELECT ?o WHERE { ?t ex:m1 ex:x1 . ?t ex:m2 ?o }";

	final Graph g = RDFStarUtils.createRedundancyAugmentedGraphFromTurtleStarSnippet(ttlsString);
	final Model m = ModelFactory.createModelForGraph(g);


	final Query query = QueryFactory.create( queryString, null, SPARQLStar.syntax );
       final ResultSet rs = QueryExecutionFactory.create(query, m).execSelect();

       consume( rs, "o", "http://example.com/x2" );
}
 
Example 11
Source File: RdfStoreFactory.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Connects to a already created tripleStore/Dataset in the RDFStore.
 * 
 * @connection identifies the database and schema in which the dataset exists
 * @datasetName a unique identifier for the dataset in the DB/Schema
 * @return the default Model/Graph of the created dataset
 */

public static Dataset connectDataset(Store store, Connection connection, Backend backend)
   {
   StoreHelper.setSchema(connection, backend, store.getSchemaName());
   if (backend == Backend.db2)
      {
      StoreHelper.setPath(connection, store.getSchemaName());
      }
   DB2Graph g = new DB2Graph(store, connection, Constants.DEFAULT_GRAPH_MONIKER);
   Model model = ModelFactory.createModelForGraph(g);
   return new DB2Dataset(model);

   }
 
Example 12
Source File: JenaUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static Model getBaseModel(Model model) {
	Graph baseGraph = getBaseGraph(model);
	if(baseGraph == model.getGraph()) {
		return model;
	}
	else {
		return ModelFactory.createModelForGraph(baseGraph);
	}
}
 
Example 13
Source File: ValidationUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static Model ensureToshTriplesExist(Model shapesModel) {
	// Ensure that the SHACL, DASH and TOSH graphs are present in the shapes Model
	if(!shapesModel.contains(TOSH.hasShape, RDF.type, (RDFNode)null)) { // Heuristic
		Model unionModel = SHACLSystemModel.getSHACLModel();
		MultiUnion unionGraph = new MultiUnion(new Graph[] {
			unionModel.getGraph(),
			shapesModel.getGraph()
		});
		shapesModel = ModelFactory.createModelForGraph(unionGraph);
	}
	return shapesModel;
}
 
Example 14
Source File: QueryExecutionTest.java    From RDFstarTools with Apache License 2.0 5 votes vote down vote up
protected Model loadModel( String filename )
{
	final String fullFilename = getClass().getResource("/TurtleStar/"+filename).getFile();

	final Graph g = new GraphWrapperStar( GraphFactory.createDefaultGraph() );
	final Model m = ModelFactory.createModelForGraph(g);
	RDFDataMgr.read(m, fullFilename);
	return m;
}
 
Example 15
Source File: JenaUtil.java    From shacl with Apache License 2.0 4 votes vote down vote up
/**
 * Wraps the result of {@link #createDefaultGraph()} into a Model and initializes namespaces. 
 * @return a default Model
 * @see #createDefaultGraph()
 */
public static Model createDefaultModel() {
	Model m = ModelFactory.createModelForGraph(createDefaultGraph());
	initNamespaces(m);
	return m;
}
 
Example 16
Source File: DB2Dataset.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
public Model getNamedModel(String namedModel)
{
return ModelFactory.createModelForGraph(getGraph(NodeFactory.createURI(namedModel)));
}
 
Example 17
Source File: EvalExprPFunction.java    From shacl with Apache License 2.0 4 votes vote down vote up
@Override
public QueryIterator exec(Binding binding, PropFuncArg argSubject,
		Node predicate, PropFuncArg argObject, ExecutionContext execCxt) {

	argSubject = Substitute.substitute(argSubject, binding);
	argObject = Substitute.substitute(argObject, binding);
	
	if(!argObject.getArg().isVariable()) {
		throw new ExprEvalException("Right hand side of tosh:exprEval must be a variable");
	}
	
	Node exprNode = argSubject.getArgList().get(0);
	Node focusNode = argSubject.getArgList().get(1);
	
	Model model = ModelFactory.createModelForGraph(execCxt.getActiveGraph());
	Dataset dataset = ARQFactory.get().getDataset(model);
	URI shapesGraphURI = URI.create("urn:x-topbraid:dummyShapesGraph");
	dataset.addNamedModel(shapesGraphURI.toString(), model);
	
	ShapesGraph[] shapesGraph = new ShapesGraph[1];
	
	NodeExpression n = NodeExpressionFactory.get().create(model.asRDFNode(exprNode));
	ExtendedIterator<RDFNode> it = n.eval(model.asRDFNode(focusNode), new NodeExpressionContext() {
		
		@Override
		public URI getShapesGraphURI() {
			return shapesGraphURI;
		}
		
		@Override
		public ShapesGraph getShapesGraph() {
			if(shapesGraph[0] == null) {
				shapesGraph[0] = new ShapesGraph(model);
			}
			return shapesGraph[0];
		}
		
		@Override
		public Dataset getDataset() {
			return dataset;
		}
	});
	
	Iterator<Node> nit = it.mapWith(rdfNode -> rdfNode.asNode());

	return new QueryIterExtendByVar(binding, (Var) argObject.getArg(), nit, execCxt);
}
 
Example 18
Source File: IsInTargetOfFunction.java    From shacl with Apache License 2.0 4 votes vote down vote up
@Override
protected NodeValue exec(Node nodeNode, Node shapeNode, FunctionEnv env) {
	Model model = ModelFactory.createModelForGraph(env.getActiveGraph());
	SHShape shape = SHFactory.asShape(model.asRDFNode(shapeNode));
	return NodeValue.makeBoolean(shape.hasTargetNode(model.asRDFNode(nodeNode)));
}
 
Example 19
Source File: SHACLUtil.java    From shacl with Apache License 2.0 4 votes vote down vote up
public static Model withDefaultValueTypeInferences(Model model) {
	return ModelFactory.createModelForGraph(new MultiUnion(new Graph[] {
			model.getGraph(),
			SHACLUtil.createDefaultValueTypesModel(model).getGraph()
	}));
}
 
Example 20
Source File: JenaUtil.java    From shacl with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a memory Model with no reification.
 * @return a new memory Model
 */
public static Model createMemoryModel() {
	return ModelFactory.createModelForGraph(createMemoryGraph());
}