Thanks, this is very useful.
Martin
On 03/06/17 17:34, Andy Seaborne wrote:
Hi Martin,
There's nothing the API IIRC.
The crude way is to write out to byte array and parse it.
Here's my (limited testing) attempt: I chose to work with the Graph API
because if you use the Model API there is both up and down casting to
match new Statement(Resources, Predicate, RDFNode).
public static void main(String... args) {
Model mSrc = ModelFactory.createDefaultModel();
RDFDataMgr.read(mSrc, "some-suitable-test-data.nt");
Model mDst = ModelFactory.createDefaultModel();
Map map = new HashMap<>();
Iter.asStream(mSrc.getGraph().find(Triple.ANY))
.map(t->clone(map, t))
.forEach(mDst.getGraph()::add);
// The N-triples writer uses the internal ID for the label.
RDFDataMgr.write(System.out, mSrc, Lang.NT);
System.out.println("");
RDFDataMgr.write(System.out, mDst, Lang.NT);
}
public static Triple clone(Map map, Triple t) {
return Triple.create(clone(map, t.getSubject()),
clone(map, t.getPredicate()),
clone(map, t.getObject()));
}
public static Node clone(Map map, Node n) {
if ( ! n.isBlank() )
return n;
// Just (_)-> in Java9
return map.computeIfAbsent(n, NodeFactory::createBlankNode);
}
On 02/06/17 17:14, Martin G. Skjæveland wrote:
Hi,
I would like a method Model clone (Model) that creates a copy of a
model such that any blank nodes in the copy are kept apart from the
source.
The test case below illustrates the intended use: adding the clone of
a model back into the model should increase the size of the model, if
the model contains blank nodes.
Is there such a method in the API, or need I invent my own? If so, any
suggestion of an optimal way will be greatly appreciated.
I have tried by adding a model into a fresh model. My other
suggestions are to iterate over all blank nodes in a model and replace
all instances with a fresh node, or to use a SPARQL query CONSTRUCT {
?s ?p ?o } WHERE { ?s ?p ?o }.
Thanks!
Martin
import static org.junit.Assert.*;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.OWL;
import org.apache.jena.vocabulary.RDF;
import org.junit.Test;
public class ModelsTest {
@Test
public void shouldCloneModel () {
// create the model: [] a Thing .
Model source = ModelFactory.createDefaultModel();
source.add(ResourceFactory.createResource(), RDF.type, OWL.Thing);
// OK
assertEquals(1, source.size());
// clone
Model copy = clone(source);
// OK
assertEquals(1, copy.size());
// adding cloned copy back into source
source.add(copy);
// Fails with current implementation
assertEquals(2, source.size());
}
public Model clone (Model source) {
Model copy = ModelFactory.createDefaultModel();
copy.add(source);
return copy;
}
}