Java Code Examples for org.apache.jena.rdf.model.Model#getGraph()

The following examples show how to use org.apache.jena.rdf.model.Model#getGraph() . 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: 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 2
Source File: SHACLUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a shapes Model for a given input Model.
 * The shapes Model is the union of the input Model with all graphs referenced via
 * the sh:shapesGraph property (and transitive includes or shapesGraphs of those).
 * @param model  the Model to create the shapes Model for
 * @return a shapes graph Model
 */
private static Model createShapesModel(Dataset dataset) {
	
	Model model = dataset.getDefaultModel();
	Set<Graph> graphs = new HashSet<Graph>();
	Graph baseGraph = model.getGraph();
	graphs.add(baseGraph);
	
	for(Statement s : model.listStatements(null, SH.shapesGraph, (RDFNode)null).toList()) {
		if(s.getObject().isURIResource()) {
			String graphURI = s.getResource().getURI();
			Model sm = dataset.getNamedModel(graphURI);
			graphs.add(sm.getGraph());
			// TODO: Include includes of sm
		}
	}
	
	if(graphs.size() > 1) {
		MultiUnion union = new MultiUnion(graphs.iterator());
		union.setBaseGraph(baseGraph);
		return ModelFactory.createModelForGraph(union);
	}
	else {
		return model;
	}
}
 
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: RoundtripIT.java    From fcrepo-import-export with Apache License 2.0 5 votes vote down vote up
private void assertIdenticalGraphs(final Model orig, final Model roundtripped) {
    final Graph roundtrippedGraph = roundtripped.getGraph();
    final ExtendedIterator<Triple> originalTripleIt = orig.getGraph().find(Node.ANY, Node.ANY, Node.ANY);
    while (originalTripleIt.hasNext()) {
        final Triple t = originalTripleIt.next();
        assertTrue("Roundtripped resource should contain triple " + t + "!", roundtrippedGraph.contains(t));
        roundtrippedGraph.delete(t);
    }
    assertTrue("Triples round in roundtripped resource that weren't in original!\n" + roundtrippedGraph,
            roundtrippedGraph.isEmpty());
}
 
Example 6
Source File: DB2Dataset.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
public DB2Dataset(Model model) 
{
defaultModel = model;
DB2Graph g = (DB2Graph) model.getGraph();
store = g.getStore();
connection = g.getConnection();
}
 
Example 7
Source File: FunctionTestCaseType.java    From shacl with Apache License 2.0 5 votes vote down vote up
private Graph parseGraph(RDFNode node) {
	Model model = JenaUtil.createDefaultModel();
	if(node.isLiteral()) {
		String str = node.asLiteral().getLexicalForm();
		model.read(new ByteArrayInputStream(str.getBytes()), "urn:x:dummy", FileUtils.langTurtle);
	}
	return model.getGraph();
}
 
Example 8
Source File: JSTarget.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
public void addTargetNodes(Dataset dataset, Collection<RDFNode> results) {
	
	boolean nested = SHACLScriptEngineManager.begin();
	JSScriptEngine engine = SHACLScriptEngineManager.getCurrentEngine();

	Model model = dataset.getDefaultModel();
	JSGraph dataJSGraph = new JSGraph(model.getGraph(), engine);
	try {
		engine.executeLibraries(as);
		engine.put(SH.JS_DATA_VAR, dataJSGraph);
		
		QuerySolutionMap bindings = new QuerySolutionMap();
		if(parameterizableTarget != null) {
			parameterizableTarget.addBindings(bindings);
		}

		Object result = engine.invokeFunction(as.getFunctionName(), bindings);
		if(NashornUtil.isArray(result)) {
			for(Object obj : NashornUtil.asArray(result)) {
				Node node = JSFactory.getNode(obj);
				results.add(model.asRDFNode(node));
			}
		}
	}
	catch(Exception ex) {
		ExceptionUtil.throwUnchecked(ex);
	}
	finally {
		dataJSGraph.close();
		SHACLScriptEngineManager.end(nested);
	}
}
 
Example 9
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 10
Source File: JenaUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
/**
 * Overcomes a design mismatch with Jena: if the base model does not declare a default namespace then the
 * default namespace of an import is returned - this is not desirable for TopBraid-like scenarios.
 * @param model the Model to operate on
 * @param prefix the prefix to get the URI of
 * @return the URI of prefix
 */
public static String getNsPrefixURI(Model model, String prefix) {
	if ("".equals(prefix) && model.getGraph() instanceof MultiUnion) {
		Graph baseGraph = ((MultiUnion)model.getGraph()).getBaseGraph();
		if(baseGraph != null) {
			return baseGraph.getPrefixMapping().getNsPrefixURI(prefix);
		}
		else {
			return model.getNsPrefixURI(prefix);
		}
	}
	else {
		return model.getNsPrefixURI(prefix);
	}
}
 
Example 11
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 12
Source File: DatasetWrappingDatasetGraph.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
public Graph getGraph(Node graphNode) {
	try {
		Model model = dataset.getNamedModel(graphNode.getURI());
		if(model != null) {
			return model.getGraph();
		}
		else {
			return null;
		}
	}
	catch(Exception ex) {
		throw new IllegalArgumentException("Exception accessing named graph " + graphNode, ex);
	}
}
 
Example 13
Source File: DatasetWrappingDatasetGraph.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
public Graph getDefaultGraph() {
	Model defaultModel = dataset.getDefaultModel();
	if(defaultModel != null) {
		return defaultModel.getGraph();
	}
	else {
		return null;
	}
}
 
Example 14
Source File: ImporterTest.java    From fcrepo-import-export with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultModeRetainsLastModified() throws Exception {
    final ArgumentCaptor<InputStream> streamCapture = ArgumentCaptor.forClass(InputStream.class);
    final Importer importer = new Importer(containerArgs, clientBuilder);
    importer.run();

    verify(putBuilder).body(streamCapture.capture(), isA(String.class));
    final Model model = createDefaultModel();
    model.read(streamCapture.getValue(), "", "JSON-LD");
    final Graph graph = model.getGraph();
    assertTrue(graph.contains(Node.ANY, LAST_MODIFIED_DATE.asNode(), Node.ANY));
}
 
Example 15
Source File: ImporterTest.java    From fcrepo-import-export with Apache License 2.0 5 votes vote down vote up
@Test
public void testLegacyModeStripsLastModified() throws Exception {
    containerArgs.setLegacy(true);
    final ArgumentCaptor<InputStream> streamCapture = ArgumentCaptor.forClass(InputStream.class);
    final Importer importer = new Importer(containerArgs, clientBuilder);
    importer.run();

    verify(putBuilder).body(streamCapture.capture(), isA(String.class));
    final Model model = createDefaultModel();
    model.read(streamCapture.getValue(), "", "JSON-LD");
    final Graph graph = model.getGraph();
    assertFalse(graph.contains(Node.ANY, LAST_MODIFIED_DATE.asNode(), Node.ANY));
}
 
Example 16
Source File: ImporterIT.java    From fcrepo-import-export with Apache License 2.0 5 votes vote down vote up
@Test
public void testImportContainer() throws Exception {
    // import test-indirect

    final URI sourceURI = URI.create("http://localhost:8080/fcrepo/rest");
    final URI parentURI = URI.create(serverAddress + "indirect/1");
    final URI memberURI = URI.create(serverAddress + "indirect/2");
    final String indirectPath = TARGET_DIR + "/test-classes/sample/indirect";

    final Config config = new Config();
    config.setMode("import");
    config.setBaseDirectory(indirectPath);
    config.setPredicates(predicates);
    config.setRdfLanguage(DEFAULT_RDF_LANG);
    config.setResource(serverAddress);
    config.setMap(new String[]{sourceURI.toString(), serverAddress});
    config.setUsername(USERNAME);
    config.setPassword(PASSWORD);

    // run import
    final Importer importer = new Importer(config, clientBuilder);
    importer.run();

    // verify one title and one hasMember
    final FcrepoResponse response = clientBuilder.build().get(parentURI).accept("application/n-triples").perform();
    final Model model = createDefaultModel();
    model.read(response.getBody(), "", "N3");
    response.close();
    final Graph graph = model.getGraph();
    assertTrue("DC title should exist. \n" + graph.toString(), graph.contains(createURI(String.valueOf(parentURI)),
            createURI("http://purl.org/dc/terms/title"), createLiteral("foo")));
    assertTrue("Membership triple should exist.", graph.contains(createURI(String.valueOf(parentURI)),
            createURI("http://pcdm.org/models#hasMember"), createURI(String.valueOf(memberURI))));
}
 
Example 17
Source File: EntityIterator.java    From Stargraph with MIT License 5 votes vote down vote up
private Iterator<Node> createIterator() {
    Model model = core.getGraphModel();
    Graph g = model.getGraph();
    ExtendedIterator<Triple> exIt = g.find(Node.ANY, null, null);
    ExtendedIterator<Node> subjIt = exIt.mapWith(Triple::getSubject);
    exIt = g.find(null, null, Node.ANY);
    ExtendedIterator<Node> objIt = exIt.mapWith(Triple::getObject);
    return Iterators.concat(subjIt, objIt);
}
 
Example 18
Source File: AbstractJSExecutor.java    From shacl with Apache License 2.0 4 votes vote down vote up
@Override
public void executeConstraint(Constraint constraint, ValidationEngine validationEngine, Collection<RDFNode> focusNodes) {
	
	JSScriptEngine jsEngine = SHACLScriptEngineManager.getCurrentEngine();
	
	Dataset dataset = validationEngine.getDataset();
	URI shapesGraphURI = validationEngine.getShapesGraphURI();
	String functionName = null;
	JSGraph shapesJSGraph = new JSGraph(validationEngine.getShapesModel().getGraph(), jsEngine);
	Model dataModel = dataset.getDefaultModel();
	Object oldSHACL = jsEngine.get(SHACL);
	jsEngine.put(SHACL, new SHACLObject(validationEngine.getShapesGraph(), shapesGraphURI, dataset));
	JSGraph dataJSGraph = new JSGraph(dataModel.getGraph(), jsEngine);
	try {
		
		jsEngine.put(SH.JS_SHAPES_VAR, shapesJSGraph);
		jsEngine.put(SH.JS_DATA_VAR, dataJSGraph);
		
		QuerySolutionMap bindings = new QuerySolutionMap();
		bindings.add(SH.currentShapeVar.getName(), constraint.getShapeResource());
		addBindings(constraint, bindings);

		SHJSExecutable executable = getExecutable(constraint);
		functionName = executable.getFunctionName();
		jsEngine.executeLibraries(executable);
		
		long startTime = System.currentTimeMillis();
		for(RDFNode theFocusNode : focusNodes) {
			validationEngine.checkCanceled();
			Object resultObj;
			bindings.add(SH.thisVar.getVarName(), theFocusNode);
			
			for(RDFNode valueNode : getValueNodes(validationEngine, constraint, bindings, theFocusNode)) {
				bindings.add("value", valueNode);
				resultObj = jsEngine.invokeFunction(functionName, bindings);
				handleJSResultObject(resultObj, validationEngine, constraint, theFocusNode, valueNode, executable, bindings);
			}
		}
		if(ExecStatisticsManager.get().isRecording()) {
			long endTime = System.currentTimeMillis();
			long duration = endTime - startTime;
			String label = getLabel(constraint);
			ExecStatistics stats = new ExecStatistics(label, null, duration, startTime, constraint.getComponent().asNode());
			ExecStatisticsManager.get().add(Collections.singletonList(stats));
		}
	}
	catch(Exception ex) {
		ex.printStackTrace();
		Resource result = validationEngine.createResult(DASH.FailureResult, constraint, null);
		result.addProperty(SH.resultMessage, "Could not execute JavaScript constraint");
		if(SH.JSConstraintComponent.equals(constraint.getComponent())) {
			result.addProperty(SH.sourceConstraint, constraint.getParameterValue());
		}
		FailureLog.get().logFailure("Could not execute JavaScript function \"" + functionName + "\": " + ex);
	}
	finally {
		dataJSGraph.close();
		shapesJSGraph.close();
		jsEngine.put(SHACL, oldSHACL);
	}
}
 
Example 19
Source File: ExTDB6.java    From xcurator with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    /// turn off the "No BGP optimizer warning"
    TDB.setOptimizerWarningFlag(false);

    final IRIFactory iriFactory = IRIFactory.semanticWebImplementation();

    final String DATASET_DIR_NAME = "data0";
    final Dataset data0 = TDBFactory.createDataset( DATASET_DIR_NAME );

    // show the currently registered names
    for (Iterator<String> it = data0.listNames(); it.hasNext(); ) {
        out.println("NAME="+it.next());
    }

    out.println("getting named model...");
    /// this is the OWL portion
    final Model model = data0.getNamedModel( MY_NS );
    out.println("Model := "+model);

    out.println("getting graph...");
    /// this is the DATA in that MODEL
    final Graph graph = model.getGraph();
    out.println("Graph := "+graph);

    if (graph.isEmpty()) {
        final Resource product1 = model.createResource(
                iriFactory.construct( MY_NS +"product/1" )
                    .toString() );

        final Property hasName = model.createProperty( MY_NS, "#hasName");
        final Statement stmt = model.createStatement(
                product1, hasName, model.createLiteral("Beach Ball","en") );
        out.println("Statement = " + stmt);

        model.add(stmt);

        // just for fun
        out.println("Triple := " + stmt.asTriple().toString());
    } else {
        out.println("Graph is not Empty; it has "+graph.size()+" Statements");
        long t0, t1;
        t0 = System.currentTimeMillis();
        final Query q = QueryFactory.create(
                "PREFIX exns: <"+MY_NS+"#>\n"+
                "PREFIX exprod: <"+MY_NS+"product/>\n"+
                " SELECT * "
                // if you don't provide the Model to the
                // QueryExecutionFactory below, then you'll need
                // to specify the FROM;
                // you *can* always specify it, if you want
                // +" FROM <"+MY_NS+">\n"
                // +" WHERE { ?node <"+MY_NS+"#hasName> ?name }"
                // +" WHERE { ?node exns:hasName ?name }"
                // +" WHERE { exprod:1 exns:hasName ?name }"
                +" WHERE { ?res ?pred ?obj }"
                );
        out.println("Query := "+q);
        t1 = System.currentTimeMillis();
        out.println("QueryFactory.TIME="+(t1 - t0));

        t0 = System.currentTimeMillis();
        final QueryExecution qExec = QueryExecutionFactory
                // if you query the whole DataSet,
                // you have to provide a FROM in the SparQL
                //.create(q, data0);
                .create(q, model);
        t1 = System.currentTimeMillis();
        out.println("QueryExecutionFactory.TIME="+(t1 - t0));

        try {
            t0 = System.currentTimeMillis();
            ResultSet rs = qExec.execSelect();
            t1 = System.currentTimeMillis();
            out.println("executeSelect.TIME="+(t1 - t0));
            while (rs.hasNext()) {
                QuerySolution sol = rs.next();
                out.println("Solution := "+sol);
                for (Iterator<String> names = sol.varNames(); names.hasNext(); ) {
                    final String name = names.next();
                    out.println("\t"+name+" := "+sol.get(name));
                }
            }
        } finally {
            qExec.close();
        }
    }
    out.println("closing graph");
    graph.close();
    out.println("closing model");
    model.close();
    //out.println("closing DataSetGraph");
    //dsg.close();
    out.println("closing DataSet");
    data0.close();
}
 
Example 20
Source File: RdfStoreQueryExecutionFactory.java    From quetzal with Eclipse Public License 2.0 3 votes vote down vote up
public static QueryExecution create(Query query, Model model, OWLQLSPARQLCompiler compiler) {
	checkArg(model);

	return new DB2QueryExecutionImpl( (com.ibm.research.rdf.store.jena.Query)query,
			(DB2Graph) model.getGraph(), compiler);

}