org.apache.jena.sparql.core.DatasetGraphFactory Java Examples

The following examples show how to use org.apache.jena.sparql.core.DatasetGraphFactory. 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: DatasetDeclarationPlan.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
protected final Context prepareDataset(Binding binding, Context context) {
	if (fromClauses == null || fromClauses.isEmpty()) {
		return context;
	}
	final DatasetGraph dsg = DatasetGraphFactory.createGeneral();
	fromClauses.forEach((fromClause) -> {
		if (fromClause.getGenerate() == null) {
			if (!fromClause.isNamed()) {
				addDefaultGraph(binding, context, dsg, fromClause.getName());
			} else {
				addNamedGraph(binding, context, dsg, fromClause.getName());
			}
		} else {
			SPARQLExtQuery generate = fromClause.getGenerate();
			if (!fromClause.isNamed()) {
				addDefaultGraph(binding, context, dsg, generate);
			} else {
				addNamedGraph(binding, context, dsg, generate, fromClause.getName());
			}
		}
	});
	Dataset newDataset = DatasetFactory.wrap(dsg);
	return ContextUtils.fork(context).setDataset(newDataset).fork();
}
 
Example #2
Source File: AbstractTestDeltaConnection.java    From rdf-delta with Apache License 2.0 6 votes vote down vote up
@Test
public void change_2() {
    String NAME = "change_2";
    DeltaClient dClient = createRegister(NAME);
    try(DeltaConnection dConn = dClient.get(NAME)) {
        Id dsRef = dConn.getDataSourceId();
        Version version = dConn.getRemoteVersionLatest();

        DatasetGraph dsg = dConn.getDatasetGraph();
        Txn.executeWrite(dsg, ()->{
            Quad q = SSE.parseQuad("(_ :s1 :p1 :o1)");
            dsg.add(q);
        });
        // Rebuild directly.
        DatasetGraph dsg2 = DatasetGraphFactory.createTxnMem();
        Version ver = dConn.getRemoteVersionLatest();
        RDFPatch patch1 = dConn.getLink().fetch(dsRef, ver) ;
        RDFPatchOps.applyChange(dsg2, patch1);

        Set<Quad> set1 = Txn.calculateRead(dsg, ()->Iter.toSet(dsg.find()));
        Set<Quad> set2 = Txn.calculateRead(dsg2, ()->Iter.toSet(dsg2.find()));

        assertEquals(set1, set2);
    }
}
 
Example #3
Source File: DeltaEx01_DatasetWithPatchLog.java    From rdf-delta with Apache License 2.0 6 votes vote down vote up
public static void main(String ...args) {
    // -- Base dataset
    DatasetGraph dsgBase = DatasetGraphFactory.createTxnMem();

    // -- Destination for changes.
    // Text form of output.
    OutputStream out = System.out;
    // Create an RDFChanges that writes to "out".
    RDFChanges changeLog = RDFPatchOps.textWriter(out);

    // Combined datasetgraph and changes.
    DatasetGraph dsg = RDFPatchOps.changes(dsgBase, changeLog);

    // Wrap in the Dataset API
    Dataset ds = DatasetFactory.wrap(dsg);

    // --------
    // Do something. Read in data.ttl inside a transaction.
    // (data.ttl is in src/main/resources/)
    Txn.executeWrite(ds,
        ()->RDFDataMgr.read(dsg, "data.ttl")
        );
}
 
Example #4
Source File: DeltaEx03_FusekiLogChanges.java    From rdf-delta with Apache License 2.0 6 votes vote down vote up
public static void main2(String ...args) {
        int PORT = 2020;
        DatasetGraph dsgBase = DatasetGraphFactory.createTxnMem();
        RDFChanges changeLog = RDFPatchOps.textWriter(System.out);
        DatasetGraph dsg = RDFPatchOps.changes(dsgBase, changeLog);

        // Create a server with the changes-enables dataset.
        // Plain server. No other registration necessary.
        FusekiServer server =
            FusekiServer.create()
                .port(PORT)
                .add("/ds", dsg)
                .build();
        server.start();

        RDFConnection conn = RDFConnectionFactory.connect("http://localhost:"+PORT+"/ds");
        UpdateRequest update = UpdateFactory.create("PREFIX : <http://example/> INSERT DATA { :s :p 123 }");
        // Note - no prefix in changes. The SPARQL Update prefix is not a chnage to the dataset prefixes.
        conn.update(update);

        server.stop();
//        // Server in the background so explicitly exit.
//        System.exit(0);
    }
 
Example #5
Source File: QueryExecutionTest.java    From RDFstarTools with Apache License 2.0 5 votes vote down vote up
protected Dataset loadDataset( String filename )
{
	final String fullFilename = getClass().getResource("/TurtleStar/"+filename).getFile();

	final DatasetGraph dsg = DatasetGraphFactory.createTxnMem();
   	final DatasetGraph dsgWrapped = new DatasetGraphWrapperStar(dsg);
   	final Dataset ds = DatasetFactory.wrap(dsgWrapped);
	RDFDataMgr.read(ds, fullFilename);
	return ds;
}
 
Example #6
Source File: QueryOperation.java    From robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Load an ontology into a DatasetGraph. The ontology is not changed.
 *
 * @deprecated use {@link #loadOntologyAsDataset(OWLOntology)} instead.
 * @param ontology The ontology to load into the graph
 * @return A new DatasetGraph with the ontology loaded into the default graph
 * @throws OWLOntologyStorageException rarely
 */
@Deprecated
public static DatasetGraph loadOntology(OWLOntology ontology) throws OWLOntologyStorageException {
  ByteArrayOutputStream os = new ByteArrayOutputStream();
  ontology.getOWLOntologyManager().saveOntology(ontology, new TurtleDocumentFormat(), os);
  DatasetGraph dsg = DatasetGraphFactory.create();
  RDFDataMgr.read(dsg.getDefaultGraph(), new ByteArrayInputStream(os.toByteArray()), Lang.TURTLE);
  return dsg;
}
 
Example #7
Source File: Zone.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
/**
 * Create a dataset appropriate to the storage type.
 * This does <em>not</em> write the configuration details into the on-disk zone information.
 */
public DatasetGraph localStorage(LocalStorageType storage, Path dataPath) {
    switch(storage) {
        case EXTERNAL:     return null;
        case MEM:          return DatasetGraphFactory.createTxnMem();
        case TDB:
            return TDBFactory.createDatasetGraph(IOX.asLocation(dataPath));
        case TDB2:
            return DatabaseMgr.connectDatasetGraph(dataPath.toString());
        case NONE:         return null;
        default :
            throw new NotImplemented("Zone::localStorage = "+storage);
    }
}
 
Example #8
Source File: DeltaEx06_LocalDatasetToFuseki.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
public static void main2(String ...args) {
    // ---- Fuseki server with patch operation.
    int PORT = 2020 ;
    // In-memory dataset
    DatasetGraph dsgFuseki = DatasetGraphFactory.createTxnMem();

    String serviceName = "patch";
    FusekiServer server = fusekiServerWithPatch("/ds", PORT, dsgFuseki, serviceName);
    server.start();

    // ---- Destination for changes is the Fuseki patch opration.
    String url = "http://localhost:"+PORT+"/ds/"+serviceName;

    RDFChanges changeSender = DeltaClientLib.destination(url);
    // In the case of http/https URLs, this is done with
    //    RDFChanges changeSender = new RDFChangesHTTP(url);

    // ---- Local dataset.
    DatasetGraph dsgLocal = DatasetGraphFactory.createTxnMem();
    // Combined datasetgraph and changes.
    // Changes will be POSTed to the URL.
    DatasetGraph dsg = RDFPatchOps.changes(dsgLocal, changeSender);

    // ---- Do something. Read in data.ttl inside a transaction.
    // (data.ttl is in src/main/resources/)
    Txn.executeWrite(dsg,
        ()->RDFDataMgr.read(dsg, "data.ttl")
        );

    // ---- Query Fuseki
    RDFConnection conn = RDFConnectionFactory.connect("http://localhost:"+PORT+"/ds");
    try( QueryExecution qExec = conn.query("PREFIX ex: <http://example.org/> SELECT * { ?s ?p ?o }") ) {
        ResultSet rs = qExec.execSelect();
        ResultSetFormatter.out(rs, qExec.getQuery());
    }
}
 
Example #9
Source File: DeltaEx02_DatasetCollectPatch.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
public static void main(String ...args) {
    // -- Base dataset
    DatasetGraph dsgBase = DatasetGraphFactory.createTxnMem();

    // -- Destination for changes.
    // Text form of output.
    OutputStream out = System.out;
    // Create an RDFChanges that writes to "out".
    RDFChanges changeLog = RDFPatchOps.textWriter(out);


    // ---- Collect up changes.
    //RDFPatchOps.collect();
    RDFChangesCollector rcc = new RDFChangesCollector();
    DatasetGraph dsg = RDFPatchOps.changes(dsgBase, rcc);
    Dataset ds = DatasetFactory.wrap(dsg);
    Txn.executeWrite(ds,
                     ()->RDFDataMgr.read(dsg, "data.ttl")
                     );
    // Again - different bnodes.
    // Note all changes are recorded - even if they have no effect
    // (e.g the prefix, the triple "ex:s ex:p ex:o").
    Txn.executeWrite(ds,
                     ()->RDFDataMgr.read(dsg, "data.ttl")
                     );

    // Collected (in-memory) patch.
    RDFPatch patch = rcc.getRDFPatch();
    // Write it.
    patch.apply(changeLog);
}
 
Example #10
Source File: TestPatchFuseki.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
private Pair<FusekiServer, DatasetGraph> create() {
    int port = WebLib.choosePort();
    DatasetGraph dsg = DatasetGraphFactory.createTxnMem();
    String dsName = "/ds";
    FusekiServer server =
        DeltaFuseki.fusekiWithPatch()
            .add(dsName, dsg)
            .addOperation(dsName, DeltaFuseki.patchOp)
            .build();
    return Pair.create(server, dsg);
}
 
Example #11
Source File: TestAssemblerFileLog.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
@Test public void assemData() {
    Dataset ds = (Dataset)AssemblerUtils.build(ADIR+"/assem-logged.ttl", VocabPatch.tLoggedDataset);
    Txn.executeWrite(ds, ()->RDFDataMgr.read(ds, ADIR+"/data.ttl"));

    String patchfile = "target/filelog/log.rdfp.0001";
    assertTrue("Patch file does not exist: "+patchfile, FileOps.exists(patchfile));
    RDFPatch patch = RDFPatchOps.read(patchfile);
    DatasetGraph dsg1 = DatasetGraphFactory.createTxnMem();
    RDFPatchOps.applyChange(dsg1, patch);
    // Same term, no bnode isomorphism.
    boolean b = IsoMatcher.isomorphic(ds.asDatasetGraph(), dsg1);
    assertTrue(b);
}
 
Example #12
Source File: TestRDFChangesDataset.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
private DatasetGraph replay() {
    IO.close(bout);
    try(ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray())) {
        DatasetGraph dsg2 = DatasetGraphFactory.createTxnMem();
        RDFPatchOps.applyChange(dsg2, bin);
        return dsg2;
    } catch (IOException ex) { IO.exception(ex); return null; }
}
 
Example #13
Source File: TestRDFChangesGraph.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
private static Graph txnGraph(String graphName) {
        DatasetGraph dsg = DatasetGraphFactory.createTxnMem();
        Node gn = NodeFactory.createURI(graphName);
        Graph g = dsg.getGraph(gn);
        // Jena 3.5.0 and earlier.
//      g = new GraphWrapper(g) {
//          @Override public TransactionHandler getTransactionHandler() { return new TransactionHandlerView(dsg); }
//      };
        return g;
    }
 
Example #14
Source File: TestRDFChangesGraph.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
private static Graph txnGraph() {
        DatasetGraph dsg = DatasetGraphFactory.createTxnMem();
        Graph g = dsg.getDefaultGraph();
        // Jena 3.5.0 and earlier.
//        g = new GraphWrapper(g) {
//            @Override public TransactionHandler getTransactionHandler() { return new TransactionHandlerViewX(dsg); }
//        };
        return g;
    }
 
Example #15
Source File: TestZone.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
@Test public void zone_03() {
    assertTrue(zone.localConnections().isEmpty());
    DatasetGraph dsgBase = DatasetGraphFactory.createTxnMem();
    String NAME = "ABC";
    Id dsRef = registerExternal(NAME, dsgBase);
    assertFalse(zone.localConnections().isEmpty());
    Quad quad = SSE.parseQuad("(_ :s :p :o)");
    try(DeltaConnection dConn = deltaClient.get(dsRef)) {
        DatasetGraph dsg  = dConn.getDatasetGraph();
        Txn.executeWrite(dsg, ()->dsg.add(quad));
    }
    // read log.
    PatchLogInfo info = deltaLink.getPatchLogInfo(dsRef);
    assertEquals(Version.create(1), info.getMaxVersion());
}
 
Example #16
Source File: TestZone.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
@Test public void zone_01_registerExternal() {
    DatasetGraph dsgBase = DatasetGraphFactory.createTxnMem();
    String NAME = "ABC";
    Id dsRef = registerExternal(NAME, dsgBase);

    try(DeltaConnection dConn = deltaClient.get(dsRef)) {
        DatasetGraph storage = dConn.getStorage();
        assertEquals(dsgBase, storage);
    }
}
 
Example #17
Source File: TestZone.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
@Test public void zone_01_createExternal() {
    DatasetGraph dsgBase = DatasetGraphFactory.createTxnMem();
    String NAME = "ABC";
    Id dsRef = createExternal(NAME, dsgBase);

    try(DeltaConnection dConn = deltaClient.get(dsRef)) {
        DatasetGraph storage = dConn.getStorage();
        assertEquals(dsgBase, storage);
    }
}
 
Example #18
Source File: ExecuteSPARQLStar.java    From RDFstarTools with Apache License 2.0 5 votes vote down vote up
@Override
public Dataset createDataset()
{
	final DatasetGraph dsg = DatasetGraphFactory.createTxnMem();
	final DatasetGraph dsgWrapped = new DatasetGraphWrapperStar(dsg);
	final Dataset ds = DatasetFactory.wrap(dsgWrapped);
	addGraphs(ds);
	dataset = ds;
	return dataset;
}
 
Example #19
Source File: TestDatasetGraphWithAbort.java    From rdf-delta with Apache License 2.0 4 votes vote down vote up
protected Dataset create() {
    DatasetGraph dsg1 = DatasetGraphFactory.create() ;
    DatasetGraphBuffering dsg = new DatasetGraphBuffering(dsg1) ;
    return DatasetFactory.wrap(dsg) ;
}
 
Example #20
Source File: JenaIOService.java    From trellis with Apache License 2.0 4 votes vote down vote up
@Override
public void write(final Stream<Triple> triples, final OutputStream output, final RDFSyntax syntax,
        final String baseUrl, final IRI... profiles) {
    requireNonNull(triples, "The triples stream may not be null!");
    requireNonNull(output, "The output stream may not be null!");
    requireNonNull(syntax, "The RDF syntax value may not be null!");

    try {
        if (RDFA.equals(syntax)) {
            writeHTML(triples, output, baseUrl);
        } else {
            final Lang lang = JenaCommonsRDF.toJena(syntax).orElseThrow(() ->
                    new TrellisRuntimeException("Invalid content type: " + syntax.mediaType()));

            final RDFFormat format = defaultSerialization(lang);

            if (format != null) {
                LOGGER.debug("Writing stream-based RDF: {}", format);
                final StreamRDF stream = getWriterStream(output, format, null);
                stream.start();
                nsService.getNamespaces().forEach(stream::prefix);
                if (shouldUseRelativeIRIs(relativeIRIs, profiles)) {
                    stream.base(baseUrl);
                }
                triples.map(JenaCommonsRDF::toJena).forEachOrdered(stream::triple);
                stream.finish();
            } else {
                LOGGER.debug("Writing buffered RDF: {}", lang);
                final org.apache.jena.graph.Graph graph = createDefaultGraph();
                graph.getPrefixMapping().setNsPrefixes(nsService.getNamespaces());
                triples.map(JenaCommonsRDF::toJena).forEachOrdered(graph::add);
                if (JSONLD.equals(lang)) {
                    writeJsonLd(output, DatasetGraphFactory.create(graph), profiles);
                } else {
                    RDFDataMgr.write(output, graph, lang);
                }
            }
        }
    } catch (final AtlasException ex) {
        throw new TrellisRuntimeException(ex);
    }
}
 
Example #21
Source File: QueryIterTripleStarPatternTest.java    From RDFstarTools with Apache License 2.0 4 votes vote down vote up
protected ExecutionContext createTestExecCxt()
{
	final DatasetGraph dsg = DatasetGraphFactory.create( createTestGraph() );
	final Context context = ARQ.getContext();
	return new ExecutionContext( context, dsg.getDefaultGraph(), dsg, QC.getFactory(context) );
}
 
Example #22
Source File: GraphColoringHashingFamily.java    From quetzal with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Load dataset from CLOB field in database
 * 
 * @param store
 * @param schema
 * @return
 */
public static DatasetGraph loadDataset(InputStream inputStream) {

	// Read the dataset from CLOB
	DatasetGraph dsg = DatasetGraphFactory.createMem();
	RDFDataMgr.read(dsg,inputStream,  Lang.NQUADS);
	
	
	return dsg;
}