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

The following examples show how to use org.apache.jena.query.Dataset#begin() . 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: RdfDataManager.java    From rdf2neo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Take an existing {@link CypherEntity} and adds the properties that can be mapped from the underlining TDB by means 
 * of a property query, like {@link CyNodeLoadingHandler#getNodePropsSparql()}, or 
 * {@link CyRelationLoadingHandler#getRelationPropsSparql()}.
 * 
 * It doesn't do anything if the query is null.
 * 
 */
protected void addCypherProps ( CypherEntity cyEnt, String propsSparql )
{
	ensureOpen ();		
	Dataset dataSet = this.getDataSet ();
	
	QuerySolutionMap params = new QuerySolutionMap ();
	params.add ( "iri", dataSet.getUnionModel().getResource ( cyEnt.getIri () ) );

	// It may be omitted, if you don't have any property except the IRI.
	if ( propsSparql == null ) return;
	
	Query qry = SparqlUtils.getCachedQuery ( propsSparql );
	Function<String, String> propIdConverter = this.getCyPropertyIdConverter ();
	
	boolean wasInTnx = dataSet.isInTransaction ();
	if ( !wasInTnx ) dataSet.begin ( ReadWrite.READ );
	try
	{
		QueryExecution qx = QueryExecutionFactory.create ( qry, dataSet, params );
		qx.execSelect ().forEachRemaining ( row ->
		{
			String propName = this.getCypherId ( row.get ( "name" ), propIdConverter );
			if ( propName == null ) throw new IllegalArgumentException ( 
				"Null property name for " + cyEnt.getIri () 
			);
			
			String propValue = JENAUTILS.literal2Value ( row.getLiteral ( "value" ) ).get ();
			cyEnt.addPropValue ( propName, propValue );
		});
	}
	finally {
		if ( !wasInTnx && dataSet.isInTransaction () ) dataSet.end ();
	}
}
 
Example 3
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 4
Source File: ExTDB_Txn2.java    From xcurator with Apache License 2.0 5 votes vote down vote up
public static void main(String... argv)
{
    String directory = "MyDatabases/DB1" ;
    Dataset dataset = TDBFactory.createDataset(directory) ;

    // Start WRITE transaction. 
    //   It's possible to read from the datet inside the write transaction.

    //   An application can have other Datasets, in the same JVM, 
    //   tied to the same TDB database performing read
    //   transactions concurrently. If another write transaction
    //   starts, the call of dataset.begin(WRITE) blocks until
    //   existing writer finishes.
    
    dataset.begin(ReadWrite.WRITE) ;
    try
    {
        GraphStore graphStore = GraphStoreFactory.create(dataset) ;
        // Do a SPARQL Update.
        String sparqlUpdateString = StrUtils.strjoinNL(
             "PREFIX . <http://example/>",
             "INSERT { :s :p ?now } WHERE { BIND(now() AS ?now) }"
             ) ;

        execUpdate(sparqlUpdateString, graphStore) ;
        dataset.commit() ;
        // Or call .abort()
        
    } finally
    {
        // Notify the end of the transaction.
        // The transaction was finished at the point .commit or .abort was called.
        // .end will force an abort() if no previous call to .commit() or .abort()
        // has occurred, so .end() help manage track the state of the transaction.
        // .end() can be called multiple times for the same .begin(WRITE)
        dataset.end() ;
    }
}
 
Example 5
Source File: ExTDB_Txn1.java    From xcurator with Apache License 2.0 5 votes vote down vote up
public static void main(String... argv)
{
    String directory = "MyDatabases/DB1" ;
    Dataset dataset = TDBFactory.createDataset(directory) ;

    // Start READ transaction. 
    //   No updates or changes to the dataset are possible while this
    //   dataset is used for a read transaction.
    //   An application can have other Datasets, in the same JVM, 
    //   tied to the same TDB database performing read or write
    //   transactions concurrently.
    
    dataset.begin(ReadWrite.READ) ;
    try
    {
        // Do some queries
        String sparqlQueryString1 = "SELECT (count(*) AS ?count) { ?s ?p ?o }" ;
        execQuery(sparqlQueryString1, dataset) ;
        
        String sparqlQueryString2 = "SELECT * { ?s ?p ?o }" ;
        execQuery(sparqlQueryString2, dataset) ;
        
        // Can also call dataset.abort() or dataset.commit() here 
    } finally
    {
        // Notify the end of the READ transaction.
        // Any use of dataset.abort() or dataset.commit() or dataset.end()
        // .end() can be called multiple times for the same .begin(READ)
        dataset.end() ;
    }
}