01: package org.ontoware.rdf2go.util.transform;
02:
03: import java.util.Map;
04:
05: import org.ontoware.aifbcommons.collection.ClosableIterator;
06: import org.ontoware.rdf2go.RDF2Go;
07: import org.ontoware.rdf2go.model.Model;
08: import org.ontoware.rdf2go.model.Statement;
09: import org.ontoware.rdf2go.model.impl.DiffImpl;
10: import org.ontoware.rdf2go.model.node.Node;
11: import org.ontoware.rdf2go.model.node.Resource;
12: import org.ontoware.rdf2go.model.node.URI;
13: import org.ontoware.rdf2go.model.node.impl.URIImpl;
14:
15: /**
16: * Replaces one prefix of all URIs with another prefix.
17: *
18: * @author voelkel
19: */
20: public class NamespaceSearchReplaceRule implements TransformerRule {
21:
22: private String searchURIPrefix, replaceURIPrefix;
23:
24: public NamespaceSearchReplaceRule(String searchURIPrefix,
25: String replaceURIPrefix) {
26: super ();
27: this .searchURIPrefix = searchURIPrefix;
28: this .replaceURIPrefix = replaceURIPrefix;
29: }
30:
31: /*
32: * Namespace-map is ignored for this rule (non-Javadoc)
33: *
34: * @see org.ontoware.rdf2go.util.transform.TransformerRule#applyRule(org.ontoware.rdf2go.model.Model,
35: * java.util.Map)
36: */
37: public void applyRule(Model model, Map<String, URI> namespaceMap) {
38: searchAndReplace(model, searchURIPrefix, replaceURIPrefix);
39: }
40:
41: public static void searchAndReplace(Model model,
42: String searchURIPrefix, String replaceURIPrefix) {
43: Model add = RDF2Go.getModelFactory().createModel();
44: add.open();
45:
46: Model remove = RDF2Go.getModelFactory().createModel();
47: remove.open();
48:
49: ClosableIterator<Statement> it = model.iterator();
50: while (it.hasNext()) {
51: Statement stmt = it.next();
52: Resource s = stmt.getSubject();
53: URI p = stmt.getPredicate();
54: Node o = stmt.getObject();
55:
56: boolean match = false;
57: if (s instanceof URI
58: && s.asURI().toString().startsWith(searchURIPrefix)) {
59: match = true;
60: String sURI = s.asURI().toString().replace(
61: searchURIPrefix, replaceURIPrefix);
62: s = new URIImpl(sURI);
63: }
64: if (p.toString().startsWith(searchURIPrefix)) {
65: match = true;
66: String pURI = p.toString().replace(searchURIPrefix,
67: replaceURIPrefix);
68: p = new URIImpl(pURI);
69:
70: }
71: if (o instanceof URI
72: && o.asURI().toString().startsWith(searchURIPrefix)) {
73: match = true;
74: String oURI = o.asURI().toString().replace(
75: searchURIPrefix, replaceURIPrefix);
76: o = new URIImpl(oURI);
77: }
78:
79: if (match) {
80: remove.addStatement(stmt);
81: add.addStatement(s, p, o);
82: }
83: }
84: it.close();
85: ClosableIterator<Statement> addIt = add.iterator();
86: ClosableIterator<Statement> removeIt = remove.iterator();
87: model.update(new DiffImpl(addIt, removeIt));
88: addIt.close();
89: removeIt.close();
90: add.close();
91: remove.close();
92: }
93:
94: }
|