org.apache.jena.query.ReadWrite Java Examples

The following examples show how to use org.apache.jena.query.ReadWrite. 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: AbstractTestDeltaClient.java    From rdf-delta with Apache License 2.0 6 votes vote down vote up
@Test
public void update_3() {
    // Create on the Delta link then setup DeltaClient
    DeltaLink dLink = getLink();
    String DS_NAME = "12345";

    Id dsRef = dLink.newDataSource(DS_NAME, "http://example/datasource_update_3");
    DeltaClient dClient = createDeltaClient();
    dClient.register(dsRef, LocalStorageType.MEM, SyncPolicy.NONE);
    DeltaConnection dConn = dClient.get(DS_NAME);
    Quad quad = SSE.parseQuad("(_ :s :p :o)");
    DatasetGraph dsg = dConn.getDatasetGraph();

    long x0 = Txn.calculateRead(dsg, ()->Iter.count(dsg.find()) );
    assertEquals(0, x0);

    dsg.begin(ReadWrite.WRITE);
    dsg.add(quad);
    dsg.abort();

    long x1 = Txn.calculateRead(dsg, ()->Iter.count(dsg.find()) );
    assertEquals(0, x1);
}
 
Example #3
Source File: DatasetGraphChanges.java    From rdf-delta with Apache License 2.0 6 votes vote down vote up
@Override
public void begin() {
    if ( insideBegin.get() ) {
        super.begin();
        return;
    }
    insideBegin.set(true);
    try {
        // For the sync, we have to assume it will write.
        // Any potential write causes a write-sync to be done in "begin".
        txnSyncHandler.accept(ReadWrite.WRITE);
        super.begin();
        if ( transactionMode() == ReadWrite.WRITE )
            monitor.txnBegin();
    } finally {
        insideBegin.set(false);
    }
    internalBegin();
}
 
Example #4
Source File: DatasetGraphChanges.java    From rdf-delta with Apache License 2.0 6 votes vote down vote up
@Override
public void begin(TxnType txnType) {
    if ( insideBegin.get() ) {
        super.begin(txnType);
        return;
    }

    insideBegin.set(true);
    try {
        // For the sync, we have to assume it will write.
        ReadWrite readWrite = ( txnType == TxnType.READ) ? ReadWrite.READ : ReadWrite.WRITE;
        txnSyncHandler.accept(readWrite);
        super.begin(txnType);
        if ( transactionMode() == ReadWrite.WRITE )
            monitor.txnBegin();
    } finally {
        insideBegin.set(false);
    }
    internalBegin();
}
 
Example #5
Source File: DatasetGraphChanges.java    From rdf-delta with Apache License 2.0 6 votes vote down vote up
@Override
public void begin(ReadWrite readWrite) {
    if ( insideBegin.get() ) {
        super.begin(readWrite);
        return;
    }
    insideBegin.set(true);
    try {
        txnSyncHandler.accept(readWrite);
        super.begin(readWrite);
        if ( transactionMode() == ReadWrite.WRITE )
            monitor.txnBegin();
    } finally {
        insideBegin.set(false);
    }
    internalBegin();
}
 
Example #6
Source File: DatasetGraphChanges.java    From rdf-delta with Apache License 2.0 6 votes vote down vote up
@Override
    public boolean promote(Promote type) {
        // Any potential write causes a write-sync to be done in "begin".
        // Here we are inside the transaction so calling the sync handler is not possible (nested transaction risk).
        if ( super.transactionMode() == ReadWrite.READ ) {
            boolean b = super.promote(type);
            if ( super.transactionMode() == ReadWrite.WRITE ) {
                // Promotion happened.
                // READ_PROMOTE would not reveal any new triples.
                // READ_COMMITTED_PROMOTE : can't atomically do local and remote "begin(write)"
                // Nested transaction. See above.
//                if ( transactionType() == TxnType.READ_COMMITTED_PROMOTE )
//                    txnSyncHandler.accept(ReadWrite.WRITE);
                // We have gone ReadWrite.READ -> ReadWrite.WRITE
                monitor.txnBegin();
            }
            return b;
        }
        //Already WRITE.
        return super.promote(type);
    }
 
Example #7
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 #8
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() ;
    }
}
 
Example #9
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 #10
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 #11
Source File: DeltaConnection.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
/** Sync on W transaction begin, not on R
 * <p>
 *  READ -> op, WRITE -> call {@code .sync()}.
 */
private Consumer<ReadWrite> syncerTxnBeginW() {
    return (rw)->{
        switch(rw) {
            case READ:// No action.
                break;
            case WRITE:
                this.sync();
                break;
        }
    };
}
 
Example #12
Source File: DeltaConnection.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
/** Sync on transaction begin.
 * <p>
 *  READ -> attempt to sync, WRITE -> not silently on errors.
 */
private Consumer<ReadWrite> syncerTxnBeginRW() {
    return (rw)->{
        switch(rw) {
            case READ:
                try { sync(); } catch (Exception ex) {}
                break;
            case WRITE:
                this.sync();
                break;
        }
    };
}
 
Example #13
Source File: DeltaConnection.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
private Consumer<ReadWrite> syncer(SyncPolicy syncTxnBegin) {
    switch(syncTxnBegin) {
        case NONE :     return (rw)->{} ;
        case TXN_RW :   return syncerTxnBeginRW();
        case TXN_W :    return syncerTxnBeginW();
        default :       throw new IllegalStateException();
    }
}
 
Example #14
Source File: TestDatasetGraphWithAbort.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
public void abort_data_1() {
    DatasetGraph dsg = create().asDatasetGraph() ;
    Txn.executeWrite(dsg, ()->dsg.add(q1)) ;
    Assert.assertTrue(dsg.contains(q1)) ;
    Assert.assertFalse(dsg.contains(q2)) ;
    dsg.begin(ReadWrite.WRITE);
    dsg.add(q2) ;
    dsg.abort();
    dsg.end();
    Assert.assertTrue(dsg.contains(q1)) ;
    Assert.assertFalse(dsg.contains(q2)) ;
}
 
Example #15
Source File: DatasetGraphChanges.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
private void requireWriteTxn() {
    ReadWrite mode = transactionMode();
    if ( mode == ReadWrite.WRITE )
        return;
    boolean b = promote() ;
    if ( !b )
        throw new JenaTransactionException("Can't write") ;
}
 
Example #16
Source File: DatasetGraphChanges.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
/** Create a {@code DatasetGraphChanges} which calls different patch log synchronization
 *  handlers on {@link #sync} and {@link #begin}.
 *  {@code syncHandler} defaults (with null) to "no action".
 *
 *  Transactional usage preferred.
 */
public DatasetGraphChanges(DatasetGraph dsg, RDFChanges monitor, Runnable syncHandler, Consumer<ReadWrite> txnSyncHandler) {
    super(dsg);
    this.monitor = monitor;
    this.syncHandler = syncHandler == null ? identityRunnable : syncHandler;
    this.txnSyncHandler = txnSyncHandler == null ? identityConsumer() : txnSyncHandler;
}
 
Example #17
Source File: RdfDataManager.java    From rdf2neo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Uses the underlining TDB and mapping queries to create a new {@link CyNode} instance.
 * 
 * @param nodeRes the RDF/Jena resource correspnding to the Cypher node. This provides the ?iri paramter in the queries below.
 * @param labelsSparql the node labels query, which is usually taken from {@link CyNodeLoadingHandler#getLabelsSparql()}.
 * @param propsSparql the node properties query, which is usually taken from {@link CyNodeLoadingHandler#getNodePropsSparql()}.
 */
public CyNode getCyNode ( Resource nodeRes, String labelsSparql, String propsSparql )
{
	ensureOpen ();
	
	QuerySolutionMap params = new QuerySolutionMap ();
	params.add ( "iri", nodeRes );

	CyNode cyNode = new CyNode ( nodeRes.getURI () );
	
	// The node's labels
	if ( labelsSparql != null )
	{
		// If it's omitted, it will get the default label.
		Query qry = SparqlUtils.getCachedQuery ( labelsSparql );
		Function<String, String> labelIdConverter = this.getCyNodeLabelIdConverter ();
		
		boolean wasInTnx = dataSet.isInTransaction ();
		if ( !wasInTnx ) dataSet.begin ( ReadWrite.READ );
		try {
			QueryExecution qx = QueryExecutionFactory.create ( qry, this.getDataSet(), params );
			qx.execSelect ().forEachRemaining ( row ->
				cyNode.addLabel ( this.getCypherId ( row.get ( "label" ), labelIdConverter ) )
			);
		}
		finally {
			if ( !wasInTnx && dataSet.isInTransaction () ) dataSet.end ();
		}
	}
	
	// and the properties
	this.addCypherProps ( cyNode, propsSparql );
	
	return cyNode;
}
 
Example #18
Source File: DatasetGraphBuffering1.java    From rdf-delta with Apache License 2.0 4 votes vote down vote up
@Override
public ReadWrite transactionMode() {
    return null;
}
 
Example #19
Source File: DatasetGraphBuffering1.java    From rdf-delta with Apache License 2.0 4 votes vote down vote up
@Override
public void begin(ReadWrite readWrite) {}
 
Example #20
Source File: DatasetGraphChanges.java    From rdf-delta with Apache License 2.0 4 votes vote down vote up
private boolean isWriteMode() {
    return super.transactionMode() == ReadWrite.WRITE;
}
 
Example #21
Source File: DatasetWrappingDatasetGraph.java    From shacl with Apache License 2.0 4 votes vote down vote up
@Override
public void begin(ReadWrite readWrite) {
    dataset.begin(readWrite);
}
 
Example #22
Source File: DatasetWrappingDatasetGraph.java    From shacl with Apache License 2.0 4 votes vote down vote up
@Override
public ReadWrite transactionMode() {
    return dataset.transactionMode();
}
 
Example #23
Source File: DelegatingDataset.java    From shacl with Apache License 2.0 4 votes vote down vote up
@Override
public void begin(ReadWrite readWrite) {
	delegate.begin(readWrite);
}
 
Example #24
Source File: DelegatingDataset.java    From shacl with Apache License 2.0 4 votes vote down vote up
@Override
public ReadWrite transactionMode() {
    return delegate.transactionMode();
}
 
Example #25
Source File: DB2Dataset.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void begin(ReadWrite arg0)
   {
   // do nothing

   }
 
Example #26
Source File: DB2Dataset.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public ReadWrite transactionMode() {
	// TODO Auto-generated method stub
	return null;
}
 
Example #27
Source File: RDFChangesApply.java    From rdf-delta with Apache License 2.0 4 votes vote down vote up
@Override
public void txnBegin() {
    dsg.begin(ReadWrite.WRITE);
}