01: package org.ontoware.rdfreactor.generator;
02:
03: import java.util.HashMap;
04: import java.util.HashSet;
05: import java.util.Iterator;
06: import java.util.List;
07: import java.util.Map;
08: import java.util.Set;
09:
10: import org.ontoware.rdf2go.model.Model;
11: import org.ontoware.rdf2go.model.Statement;
12: import org.ontoware.rdf2go.model.impl.StatementImpl;
13: import org.ontoware.rdf2go.model.node.BlankNode;
14: import org.ontoware.rdf2go.model.node.Node;
15: import org.ontoware.rdf2go.model.node.URI;
16: import org.ontoware.rdf2go.model.node.impl.URIImpl;
17:
18: public class Utils {
19:
20: /**
21: * Generate a unique URI for a BlankNode and put the BlankNode/URI pair into
22: * the given map.
23: *
24: * @param blankNode -
25: * generate a URI for this BlankNode
26: * @param replacement -
27: * Map of BlankNode/URI pairs
28: * @return URI generated for the BlankNode
29: */
30: public static URI toURI(BlankNode blankNode,
31: Map<BlankNode, URI> replacement, long counter) {
32: URI result = replacement.get(blankNode);
33: if (result == null)
34: result = new URIImpl("blank://" + counter++);
35: // TODO BlankNode identity might be too weak
36: replacement.put(blankNode, result);
37: return result;
38: }
39:
40: /**
41: * Remove all Statements with BlankNodes as Subjects or Objects from the
42: * given RDF2Go model.
43: *
44: * @param m -
45: * de-anonymise this model
46: * @throws Exception
47: */
48: public static void deanonymize(Model m) throws Exception {
49: Iterator<Statement> it = m.iterator();
50: long counter = 0;
51: Map<BlankNode, URI> replacement = new HashMap<BlankNode, URI>();
52: Set<Statement> badStatements = new HashSet<Statement>();
53: Set<Statement> goodStatements = new HashSet<Statement>();
54: while (it.hasNext()) {
55: Statement s = it.next();
56: org.ontoware.rdf2go.model.node.Resource subject = s
57: .getSubject();
58: if (s.getSubject() instanceof BlankNode) {
59: badStatements.add(s);
60: subject = toURI((BlankNode) subject, replacement,
61: counter);
62: }
63: Node object = s.getObject();
64: if (object instanceof BlankNode) {
65: badStatements.add(s);
66: object = toURI((BlankNode) object, replacement, counter);
67: }
68: goodStatements.add(new StatementImpl(m.getContextURI(),
69: subject, s.getPredicate(), object));
70: }
71: for (Statement s : badStatements)
72: m.removeStatement(s);
73: for (Statement s : goodStatements)
74: m.addStatement(s);
75:
76: }
77:
78: public static String toJavaComment(List<String> rdfComments) {
79: StringBuffer buf = new StringBuffer();
80: for (int i = 0; i < rdfComments.size(); i++) {
81: buf.append(rdfComments.get(i));
82: if (i + 1 < rdfComments.size()) {
83: buf.append("\n");
84: }
85: }
86: return buf.toString();
87: }
88:
89: }
|