Java Code Examples for org.apache.jena.query.Dataset#getDefaultModel()

The following examples show how to use org.apache.jena.query.Dataset#getDefaultModel() . 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: RdfDataManagerTest.java    From rdf2neo with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Loads the test TDB used in this class with a bounch of RDF data.
 */
@BeforeClass
public static void initData ()
{
	rdfMgr.open ( TDB_PATH );
	Dataset ds = rdfMgr.getDataSet ();
	Model m = ds.getDefaultModel ();
	ds.begin ( ReadWrite.WRITE );
	try 
	{
		//if ( m.size () > 0 ) return;
		m.read ( IOUtils.openResourceReader ( "test_data.ttl" ), null, "TURTLE" );
		ds.commit ();
	}
	catch ( Exception ex ) {
		ds.abort ();
		throw new RuntimeException ( "Test error: " + ex.getMessage (), ex );
	}
	finally { 
		ds.end ();
	}
}
 
Example 2
Source File: RdfDataManagerTest.java    From rdf2neo with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testNodes ()
{
	log.info ( "Verifying Nodes" );

	Dataset ds = rdfMgr.getDataSet ();
	Model m = ds.getDefaultModel ();
	
	CyNode cyNode = rdfMgr.getCyNode ( m.getResource ( iri ( "ex:1" ) ), SPARQL_NODE_LABELS, SPARQL_NODE_PROPS );
	assertNotNull ( "CyNode 1 not found!", cyNode );
	log.info ( "Got node 1" );

	assertEquals ( "CyNode 1's Label not found!", 1, cyNode.getLabels ().size () );
	assertEquals ( "CyNode 1's Label not found!", "TestNode", cyNode.getLabels ().iterator ().next () );
	
	assertEquals ( "CyNode 1's wrong properties count!", 2, cyNode.getProperties ().size () );
	assertEquals ( "CyNode 1's prop1 not found!", "10.0", cyNode.getPropValue ( "attrib1" ) );
	assertEquals ( "CyNode 1's prop2 not found!", "a string", cyNode.getPropValue ( "attrib2" ) );
	
	log.info ( "End" );
}
 
Example 3
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 4
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 5
Source File: ValidatingDatasetProvider.java    From Processor with Apache License 2.0 6 votes vote down vote up
public Dataset validate(Dataset dataset)
{
    Validator validator = new Validator(getOntology().getOntModel());
    
    List<ConstraintViolation> cvs = validator.validate(dataset.getDefaultModel());
    if (!cvs.isEmpty())
    {
        if (log.isDebugEnabled()) log.debug("SPIN constraint violations: {}", cvs);
        throw new ConstraintViolationException(cvs, dataset.getDefaultModel());
    }
    
    Iterator<String> it = dataset.listNames();
    while (it.hasNext())
    {
        String graphURI = it.next();
        cvs = validator.validate(dataset.getNamedModel(graphURI));

        if (!cvs.isEmpty())
        {
            if (log.isDebugEnabled()) log.debug("SPIN constraint violations: {}", cvs);
            throw new ConstraintViolationException(cvs, dataset.getNamedModel(graphURI), graphURI);
        }
    }
    
    return dataset;
}
 
Example 6
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 7
Source File: SHACLEntailment.java    From shacl with Apache License 2.0 5 votes vote down vote up
public Dataset withEntailment(Dataset dataset, URI shapesGraphURI, ShapesGraph shapesGraph, Resource entailment, ProgressMonitor monitor) throws InterruptedException {
	if(entailment == null || dataset.getDefaultModel() == null) {
		return dataset;
	}
	else {
		Engine engine = getEngine(entailment.getURI());
		if(engine != null) {
			Model newDefaultModel = engine.createModelWithEntailment(dataset, shapesGraphURI, shapesGraph, monitor);
			return new DatasetWithDifferentDefaultModel(newDefaultModel, dataset);
		}
		else {
			return null;
		}
	}
}
 
Example 8
Source File: IOHelper.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Given a path to an RDF/XML or TTL file and a RDF language, load the file as the default model
 * of a TDB dataset backed by a directory to improve processing time. Return the new dataset.
 *
 * <p>WARNING - this creates a directory at given tdbDir location!
 *
 * @param inputPath input path of RDF/XML or TTL file
 * @param tdbDir location to put TDB mappings
 * @return Dataset instantiated with triples
 * @throws JenaException if TDB directory can't be written to
 */
public static Dataset loadToTDBDataset(String inputPath, String tdbDir) throws JenaException {
  Dataset dataset;
  if (new File(tdbDir).isDirectory()) {
    dataset = TDBFactory.createDataset(tdbDir);
    if (!dataset.isEmpty()) {
      return dataset;
    }
  }
  dataset = TDBFactory.createDataset(tdbDir);
  logger.debug(String.format("Parsing input '%s' to dataset", inputPath));
  // Track parsing time
  long start = System.nanoTime();
  Model m;
  dataset.begin(ReadWrite.WRITE);
  try {
    m = dataset.getDefaultModel();
    FileManager.get().readModel(m, inputPath);
    dataset.commit();
  } catch (JenaException e) {
    dataset.abort();
    dataset.end();
    dataset.close();
    throw new JenaException(String.format(syntaxError, inputPath));
  } finally {
    dataset.end();
  }
  long time = (System.nanoTime() - start) / 1000000000;
  logger.debug(String.format("Parsing complete - took %s seconds", String.valueOf(time)));
  return dataset;
}
 
Example 9
Source File: JenaUtil.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
public static void addTupleSet(Dataset dataset, TupleSet tt, BasicUniverse u, Instance t2) {
	if (tt != null) {
		for(Tuple t : tt) {
			Object graph = t.atom(0);
			Model m = QuadTableRelations.defaultGraph.equals(graph)? dataset.getDefaultModel(): dataset.getNamedModel(graph.toString());
			m.add(fromTuple(m, t, u, t2));
		}
	}
}
 
Example 10
Source File: ExTDB1.java    From xcurator with Apache License 2.0 5 votes vote down vote up
public static void main(String... argv)
{
    // Direct way: Make a TDB-back Jena model in the named directory.
    String directory = "MyDatabases/DB1" ;
    Dataset ds = TDBFactory.createDataset(directory) ;
    Model model = ds.getDefaultModel() ;
    
    // ... do work ...
    
    // Close the dataset.
    ds.close();
    
}
 
Example 11
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);
	}
}