1 package org.simantics.graph.representation;
3 import java.io.BufferedInputStream;
4 import java.io.DataInput;
5 import java.io.DataInputStream;
6 import java.io.InputStream;
7 import java.math.BigInteger;
8 import java.nio.file.Files;
9 import java.nio.file.Path;
10 import java.nio.file.Paths;
11 import java.security.MessageDigest;
12 import java.security.NoSuchAlgorithmException;
13 import java.util.ArrayList;
14 import java.util.Arrays;
15 import java.util.HashMap;
16 import java.util.HashSet;
17 import java.util.List;
19 import java.util.Map.Entry;
21 import java.util.TreeMap;
22 import java.util.TreeSet;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
25 import java.util.stream.Collectors;
27 import org.simantics.databoard.Bindings;
28 import org.simantics.databoard.binding.Binding;
29 import org.simantics.databoard.binding.mutable.Variant;
30 import org.simantics.databoard.container.DataContainers;
31 import org.simantics.databoard.parser.DataValuePrinter;
32 import org.simantics.databoard.parser.PrintFormat;
33 import org.simantics.databoard.parser.repository.DataValueRepository;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
37 import gnu.trove.list.array.TIntArrayList;
38 import gnu.trove.map.hash.THashMap;
39 import gnu.trove.map.hash.TIntIntHashMap;
40 import gnu.trove.map.hash.TIntObjectHashMap;
41 import gnu.trove.procedure.TIntIntProcedure;
42 import gnu.trove.set.hash.TLongHashSet;
45 * @author Antti Villberg
48 public class PrettyPrintTG {
50 private static final Logger LOGGER = LoggerFactory.getLogger(PrettyPrintTG.class);
52 private static final boolean DEBUG = false;
55 int newBlankCounter = 0;
56 Map<String, String> blankRewrites = new HashMap<>();
59 private final Pattern versionExtractPattern = Pattern.compile("^.*-(\\d+\\.\\d+)");
61 final StringBuilder output;
62 final Map<String, String> ontologies = new HashMap<>(knownOntologies);
63 final Set<String> referencedOntologies = new TreeSet<>();
65 private boolean ignoreIdentifiers;
67 static class ResourceInfo {
71 boolean newResource = false;
75 boolean inlined = false;
77 // -1 = no owner, -2 = multiple owners
79 // Set<ResourceInfo> ownedBy
80 Set<ResourceInfo> ownedBy = new HashSet<>();
82 // A Map<Integer, Integer> containing information about resource that
83 // this resource owns and what are the predicates for forming this
85 TIntIntHashMap ownedResourcesWithPredicates = new TIntIntHashMap();
88 // int ownerPredicate = 0;
89 String aliasURI = null;
90 TIntArrayList owned = new TIntArrayList();
92 // TIntObjectHashMap<TIntHashSet> statements = new
93 // TIntObjectHashMap<TIntHashSet>();
94 public ResourceInfo(boolean hasURI, String name, int resource, int parent) {
97 this.resource = resource;
102 public String toString() {
103 return name + (aliasURI != null ? " = <" + aliasURI + ">" : "");
107 public PrettyPrintTG(StringBuilder b, boolean ignoreIdentifiers) throws NoSuchAlgorithmException {
109 m = MessageDigest.getInstance("SHA-256");
110 this.ignoreIdentifiers = ignoreIdentifiers;
113 public PrettyPrintTG() throws NoSuchAlgorithmException {
114 this(new StringBuilder(), false);
117 TreeMap<String, ResourceInfo> orderedInfos = new TreeMap<>();
118 TIntObjectHashMap<ResourceInfo> infos = new TIntObjectHashMap<>();
120 String tgNodeName(String name) {
121 if (name.contains(" "))
122 return "\"" + name + "\"";
127 ResourceInfo recurseURI(TransferableGraph1 graph, Identity parent, String parentName, int parentId) {
128 String name = parentName + "." + tgNodeName(TransferableGraphUtils.getName(parent));
129 ResourceInfo info = new ResourceInfo(true, name, parent.resource, parentId);
130 orderedInfos.put(name, info);
131 // infos.put(parent.resource, info);
132 for (Identity child : TransferableGraphUtils.getChildren(graph, parent)) {
133 recurseURI(graph, child, name, info.resource);
138 private TreeMap<String, TreeSet<Integer>> sortByPredicateUniqueStatements(TransferableGraph1 graph, int resource) {
139 TreeMap<String, TreeSet<Integer>> results = new TreeMap<>();
140 TIntArrayList statements = TransferableGraphUtils.getStatements(graph, resource);
141 for (int i = 0; i < statements.size(); i += 2) {
142 int predicate = statements.get(i);
143 String predicateURI = TransferableGraphUtils.getURI(graph, predicate);
144 TreeSet<Integer> objects = results.get(predicateURI);
145 if (objects == null) {
146 objects = new TreeSet<>();
148 objects.add(statements.get(i + 1));
149 results.put(predicateURI, objects);
154 void discoverBlank(TransferableGraph1 graph, int resource, TIntArrayList todo) throws Exception {
155 // TIntArrayList statements =
156 // TransferableGraphUtils.getStatements(graph, resource);
157 // for(int i=0;i<statements.size();i+=2) {
158 for (TreeSet<Integer> objects : sortByPredicateUniqueStatements(graph, resource).values()) {
159 for (int object : objects) {
160 // int object = statements.get(i+1);
161 Identity objectId = TransferableGraphUtils.getIdentity(graph, object);
162 if (objectId != null) {
163 if (objectId.definition instanceof External)
166 Value value = TransferableGraphUtils.findValue(graph, object);
168 infos.put(object, new ResourceInfo(false, printValue(value), object, resource));
171 ResourceInfo existing = infos.get(object);
172 if (existing == null) {
174 existing = new ResourceInfo(false, "blank" + blankCounter++, object, resource);
176 // System.out.println("created blank" + blankCounter + "
177 // with object " + object + " resource " + resource);
178 infos.put(object, existing);
185 private String makeHash(byte[] data) {
187 m.update(data, 0, data.length);
188 return new BigInteger(1, m.digest()).toString(16);
191 void discoverOwners(TransferableGraph1 graph, ResourceInfo info) {
192 log("Discovering owners for {}", info);
193 int resource = info.resource;
194 TIntArrayList statements = TransferableGraphUtils.getStatements(graph, resource);
195 for (int i = 0; i < statements.size(); i += 2) {
196 int predicate = statements.get(i);
197 int object = statements.get(i + 1);
198 ResourceInfo existing = infos.get(object);
199 if (existing != null) {
200 // Add all owners here for now and resolve the best owner later
202 // Check if predicate is inverse, this just resolves all
203 // predicates to be inverse with ending "Inverse"..
204 String predicateUri = rewritePredicateURI(graph, predicate);
205 if (!predicateUri.endsWith("Inverse") && !predicateUri.endsWith("Of")) {
206 existing.ownedResourcesWithPredicates.put(resource, predicate);
207 // if (predicateUri.endsWith("Of")) {
208 // System.out.println("asd");
210 existing.ownedBy.add(info);
211 log(" {} owns {} with {}", existing, info, predicateUri);
214 // System.out.println("asd");
220 DataValueRepository repo = new DataValueRepository();
221 DataValuePrinter printer = new DataValuePrinter(null, repo);
223 String printValue(Value value) throws Exception {
224 StringBuilder sb = new StringBuilder();
225 printer.setFormat(PrintFormat.SINGLE_LINE);
226 printer.setOutput(sb);
228 Variant variant = value.value;
229 printer.print(variant.getBinding(), variant.getValue());
230 String formattedOutput = sb.toString();
231 if (formattedOutput.length() > 100) {
232 // Ok, value too long, lets calculate a hash for it and store first
233 // 100 chars as comment
234 byte[] data = Bindings.getSerializerUnchecked(variant.getBinding()).serialize(variant.getValue());
236 m.update(data, 0, data.length);
237 String hash = "\"" + new BigInteger(1, m.digest()).toString(16) + "\"";
238 return hash + " // " + formattedOutput.substring(0, 100) + "..";
240 return formattedOutput;
244 public static String getExternalURI(TransferableGraph1 tg, External ext) {
245 String name = ext.name;
246 if (name.contains(" "))
247 name = name.replace(" ", "_").replaceAll("@", "_");// name = "\"" +
249 int parentId = ext.parent;
250 // if(parentId == 0) return ext.name;
252 Identity id = TransferableGraphUtils.getIdentity(tg, parentId);
253 if (id.definition instanceof External) {
254 return getExternalURI(tg, (External) id.definition) + "/" + name;
255 } else if (id.definition instanceof Root) {
256 Root root = (Root) id.definition;
257 return "http:/" + root.name + "/" + name;
264 public static String getExternalURI(TransferableGraph1 tg, int resource) {
265 Identity id = TransferableGraphUtils.getIdentity(tg, resource);
268 if (id.definition instanceof External) {
269 External ext = (External) id.definition;
270 return getExternalURI(tg, ext);
275 String rewritePredicateURI(TransferableGraph1 graph, int predicate) {
277 String uri = getExternalURI(graph, predicate);
279 ResourceInfo info = infos.get(predicate);
285 for (String ontology : ontologies.keySet()) {
286 if (uri.contains(ontology)) {
287 String key = ontologies.get(ontology);
288 uri = uri.replace(ontology, key);
289 referencedOntologies.add(ontology);
293 uri = uri.replace("/", ".");
299 static void indent(StringBuilder output, int indent) {
300 for (int i = 0; i < indent; i++)
304 String printBlank(TransferableGraph1 graph, String predicateURI2, ResourceInfo info, int indent) {
309 StringBuilder output = new StringBuilder();
311 String infoName = info.name;
312 if (infoName.startsWith("blank")) {
313 infoName = getBlankRewrite(infoName);
316 if (ignoreIdentifiers) {
317 if (predicateURI2.contains("L0.identifier")) {
320 indent(output, indent);
321 output.append(predicateURI2 + " " + infoName + "\n");
324 indent(output, indent);
325 output.append(predicateURI2 + " " + infoName + "\n");
328 if (info.ownedResourcesWithPredicates.isEmpty()) {
330 System.out.print("printBlank");
331 String uri = printURI(graph, info, false, indent, false);
335 // if(info.owner < 0) {
336 // printURI(graph, info, false, indent);
338 return output.toString();
341 private String getBlankRewrite(String infoName) {
342 String rewrite = blankRewrites.get(infoName);
343 if (rewrite == null) {
344 rewrite = "rblank" + newBlankCounter++;
346 System.out.println("rewrote " + infoName + " to " + rewrite);
347 blankRewrites.put(infoName, rewrite);
353 static long longStm(int predicate, int object) {
354 return ((predicate & 0xffffffffL) << 32) | (object & 0xffffffffL);
357 private void addInlineStatement(TransferableGraph1 graph, Map<String, Set<String>> statements, String predicate,
358 ResourceInfo objectInfo, int indent) {
359 Set<String> objects = statements.get(predicate);
360 if (objects == null) {
361 objects = new TreeSet<>();
362 statements.put(predicate, objects);
364 String uri = printURI(graph, objectInfo, false, indent + 1, true);
366 // TODO: this is not the right place to remove trailing newline
367 uri = uri.endsWith("\n") ? uri.substring(0, uri.length() - 2) : uri;
370 objectInfo.inlined = true;
373 void addStatement(Map<String, Set<String>> statements, String predicate, String object) {
375 if (predicate.endsWith("Inverse"))
377 Set<String> objects = statements.get(predicate);
378 if (objects == null) {
379 objects = new TreeSet<>();
380 statements.put(predicate, objects);
385 String printURI(TransferableGraph1 graph, ResourceInfo info, boolean requireURI, int indent, boolean inline) {
387 if (requireURI && !info.hasURI)
390 // Check if this ResourceInfo is already inlined with some other
395 Map<String, Set<String>> statements = new TreeMap<>();
396 Identity consistsOf = TransferableGraphUtils.findExternal(graph,
397 "http://www.simantics.org/Layer0-1.1/ConsistsOf");
398 // Identity partOf = TransferableGraphUtils.findExternal(graph,
399 // "http://www.simantics.org/Layer0-1.1/PartOf");
400 TLongHashSet processed = new TLongHashSet();
402 System.out.println("info.owned.size " + info.owned.size() + info.owned);
403 for (int i = 0; i < info.owned.size(); i += 2) {
404 int predicate = info.owned.get(i);
405 int object = info.owned.get(i + 1);
406 long stmId = longStm(predicate, object);
409 " " + stmId + " is already processed as it is owned (" + predicate + " " + object + ")");
410 processed.add(stmId);
413 TreeMap<String, Integer> predicateURIs = new TreeMap<>();
415 TIntArrayList rawStatements = TransferableGraphUtils.getStatements(graph, info.resource);
418 "rawStatements size for " + info.name + " : " + rawStatements.size() + " " + rawStatements);
419 for (int i = 0; i < rawStatements.size(); i += 2) {
420 int predicate = rawStatements.get(i);
421 int object = rawStatements.get(i + 1);
422 long stmId = longStm(predicate, object);
423 if (!processed.add(stmId)) {
425 System.out.println(" " + stmId + " is already processed (" + (predicate & 0xffffffffL) + " "
426 + (object & 0xffffffffL) + ")");
430 System.out.println(" " + stmId + " is currently being processed (" + (predicate & 0xffffffffL) + " "
431 + (object & 0xffffffffL) + ")");
432 // if (partOf.resource == rawStatements.get(i))
434 if (consistsOf.resource == predicate) {
435 // if (!info.owned.isEmpty() && !info.name.startsWith("blank"))
438 System.out.println(" is consistsof " + predicate + " (" + consistsOf.resource + ")");
441 // // this will be inlined so lets indent
445 String predicateURI = rewritePredicateURI(graph, predicate);
446 predicateURIs.put(predicateURI, object);
448 for (Entry<String, Integer> entry : predicateURIs.entrySet()) {
449 String predicateURI = entry.getKey();
450 int object = entry.getValue();
452 ResourceInfo objectInfo = infos.get(object);
453 if (objectInfo == null) {
454 String objectURI = rewritePredicateURI(graph, object);
456 System.out.println(" adding statement " + predicateURI + " " + objectURI);
457 addStatement(statements, predicateURI, objectURI);
458 } else if (objectInfo.ownedBy.size() == 1 && objectInfo.ownedBy.contains(info)) {
459 // inline printing with _
461 System.out.println(" adding inline statement " + predicateURI + " " + objectInfo.name);
462 addInlineStatement(graph, statements, predicateURI, objectInfo, indent);
464 String objectName = objectInfo.name;
465 if (objectName.startsWith("blank")) {
466 objectName = getBlankRewrite(objectName);
469 System.out.println(" adding statement " + predicateURI + " " + objectName);
470 addStatement(statements, predicateURI, objectName);
476 "statements size for " + info.name + " : " + statements.size() + " " + statements.keySet());
478 StringBuilder output = new StringBuilder();
480 if (indent == 0 || inline) {
481 if ("ROOT".equals(info.name)) {
482 output.append("ROOT=<http:/>");
483 } else if (info.aliasURI != null) {
484 output.append(info.name + " = <" + info.aliasURI + ">");
486 String infoName = info.name;
487 if (infoName.startsWith("blank")) {
488 infoName = getBlankRewrite(infoName);
490 output.append(inline ? "_" : infoName);
492 Set<String> instanceOfs = statements.get("L0.InstanceOf");
493 if (instanceOfs != null) {
494 for (String instanceOf : instanceOfs) {
495 output.append(" : " + instanceOf);
498 Set<String> subrelationOfs = statements.get("L0.SubrelationOf");
499 if (subrelationOfs != null) {
500 for (String subrelationOf : subrelationOfs) {
501 output.append(" <R " + subrelationOf);
504 Set<String> inherits = statements.get("L0.Inherits");
505 if (inherits != null) {
506 for (String inherit : inherits) {
507 output.append(" <T " + inherit);
513 if (info.newResource)
514 output.append(" @L0.new\n");
516 for (Map.Entry<String, Set<String>> entry : statements.entrySet()) {
517 String predicate = entry.getKey();
518 if (ignoreIdentifiers) {
519 if (predicate.equals("L0.identifier")) {
523 if ("L0.InstanceOf".equals(predicate))
525 if ("L0.SubrelationOf".equals(predicate))
527 if ("L0.Inherits".equals(predicate))
529 if ("L0.PartOf".equals(predicate))
532 // predicates can be blank
533 if (predicate.startsWith("blan")) {
534 predicate = getBlankRewrite(predicate);
537 Set<String> objects = entry.getValue();
538 indent(output, indent + 1);
539 if (objects.size() == 1) {
540 output.append(predicate + " " + objects.iterator().next() + "\n");
542 output.append(predicate + "\n");
543 for (String object : objects) {
544 indent(output, indent + 1);
545 output.append(" " + object + "\n");
550 TreeMap<String, Integer> ownedOrdered = new TreeMap<>();
552 for (int i = 0; i < info.owned.size(); i += 2) {
553 String predicateURI = rewritePredicateURI(graph, info.owned.get(i));
554 ownedOrdered.put(predicateURI, info.owned.get(i + 1));
558 System.out.println(info.name + " : " + ownedOrdered.keySet());
560 for (Entry<String, Integer> entry : ownedOrdered.entrySet()) {
561 String predicateURI = entry.getKey();
562 int owned = entry.getValue();
563 ResourceInfo ownedInfo = infos.get(owned);
565 String blank = printBlank(graph, predicateURI, ownedInfo, indent + 1);
567 output.append(blank);
571 return output.toString();
574 void prettyPrint(Path input, Path output) throws Exception {
576 System.out.format("Converting exported shared ontology%n\t" + input.toString()
577 + "%nto bundle-compatible ontology%n\t" + output.toString());
578 try (InputStream is = new BufferedInputStream(Files.newInputStream(input), 128 * 1024)) {
579 DataInput dis = new DataInputStream(is);
580 org.simantics.databoard.container.DataContainer container = DataContainers.readFile(dis);
581 Binding binding = TransferableGraph1.BINDING;
582 TransferableGraph1 graph = (TransferableGraph1) container.content.getValue(binding);
584 Files.write(output, this.output.toString().getBytes());
590 static Map<String, String> knownOntologies = new HashMap<>();
593 knownOntologies.put("http://www.simantics.org/Layer0-1.1", "L0");
594 knownOntologies.put("http://www.simantics.org/Layer0X-1.1", "L0X");
595 knownOntologies.put("http://www.simantics.org/Modeling-1.2", "MOD");
596 knownOntologies.put("http://www.simantics.org/Diagram-2.2", "DIA");
597 knownOntologies.put("http://www.simantics.org/Structural-1.2", "STR");
598 knownOntologies.put("http://www.simantics.org/Document-1.2", "DOC");
599 knownOntologies.put("http://www.simantics.org/Documentation-1.2", "DOCU");
600 knownOntologies.put("http://www.simantics.org/G2D-1.1", "G2D");
601 knownOntologies.put("http://www.simantics.org/SelectionView-1.2", "SEL");
602 knownOntologies.put("http://www.simantics.org/Viewpoint-1.2", "VP");
603 knownOntologies.put("http://www.simantics.org/Image2-1.2", "IMAGE2");
604 knownOntologies.put("http://www.simantics.org/GraphFile-0.1", "GRAPHFILE");
605 knownOntologies.put("http://www.simantics.org/Project-1.2", "PROJECT");
606 knownOntologies.put("http://www.semantum.fi/Simupedia-1.0", "SIMUPEDIA");
607 knownOntologies.put("http://www.semantum.fi/SimupediaWorkbench-1.0", "SIMUPEDIA_WORKBENCH");
610 void prettyPrint(TransferableGraph1 graph) throws Exception {
611 log("Starting prettyPrint for TransferableGraph with {} resources, {} identities, {} statements and {} values",
612 graph.resourceCount, graph.identities, graph.statements.length, graph.values.length);
614 for (Identity id : graph.identities) {
615 if (id.definition instanceof Internal) {
616 Internal internal = (Internal) id.definition;
617 Identity parent = TransferableGraphUtils.getIdentity(graph, internal.parent);
618 if (parent.definition instanceof External) {
619 log("Resolving internal identity {}", id);
620 String name = "BASE";
621 ResourceInfo info = new ResourceInfo(true, name, id.resource, -1);
622 info.aliasURI = TransferableGraphUtils.getURI(graph, id.resource);
623 info.newResource = true;
624 orderedInfos.put(name, info);
625 // infos.put(id.resource, info);
626 log(" which parent is external {} and has an aliasURI {}", parent, info.aliasURI);
627 for (Identity child : TransferableGraphUtils.getChildren(graph, id)) {
628 recurseURI(graph, child, name, info.resource);
630 log(" and has {} children", infos.size());
632 } else if (id.definition instanceof External) {
633 External ext = (External) id.definition;
634 // Try to detect shared libraries
635 if (ext.name.contains("@")) {
637 log("Detected an external shared library {}", ext);
639 int index = ext.name.indexOf('@');
640 String prefix = ext.name.substring(0, index);
641 int index2 = ext.name.indexOf('/', index);
642 String ontology = index2 == -1 ? ext.name : ext.name.substring(0, index2);
643 String uri = TransferableGraphUtils.getURI(graph, id.resource);
645 log(" which was resolved as URI={} and prefix={}", uri, prefix);
647 ontologies.put(uri, prefix);
649 } else if (ext.name.contains("-")) {
650 log("Resolving possible ontology {}", ext);
651 String uri = TransferableGraphUtils.getURI(graph, id.resource);
652 Matcher m = versionExtractPattern.matcher(uri);
654 if (!ontologies.containsKey(uri)) {
655 int index = ext.name.indexOf('-');
656 String prefix = ext.name.substring(0, index);
657 log(" and it was resolved as URI={} and prefix {}", uri, prefix);
658 ontologies.put(uri, prefix);
665 // Discover other resources
666 log("Discovering other resources..");
668 TIntArrayList todo = new TIntArrayList();
669 for (ResourceInfo info : orderedInfos.values()) {
670 todo.add(info.resource);
672 // put orderedInfos to infos
673 infos.put(info.resource, info);
676 while (!todo.isEmpty()) {
677 int resource = todo.removeAt(todo.size() - 1);
678 discoverBlank(graph, resource, todo);
680 for (ResourceInfo info : infos.valueCollection())
681 discoverOwners(graph, info);
682 // for(ResourceInfo info : infos.valueCollection())
683 // fixInstanceOf(graph, info);
685 for (ResourceInfo info : infos.valueCollection()) {
686 // Old implementation
687 // if (info.owner >= 0) {
688 // ResourceInfo ownerInfo = infos.get(info.owner);
689 // System.out.println("originalOwner : " + info.owner + "
690 // originalPredicate: " + info.ownerPredicate);
691 // ownerInfo.owned.add(info.ownerPredicate);
692 // ownerInfo.owned.add(info.resource);
695 if (!info.ownedResourcesWithPredicates.isEmpty() && info.ownedResourcesWithPredicates.size() == 1) {
696 info.ownedResourcesWithPredicates.forEachEntry(new TIntIntProcedure() {
699 public boolean execute(int owner, int predicate) {
700 ResourceInfo ownerInfo = infos.get(owner);
701 ownerInfo.owned.add(predicate);
702 ownerInfo.owned.add(info.resource);
709 // Resolve inverses from ownedBy list
710 for (ResourceInfo info : infos.valueCollection()) {
711 for (int i = 0; i < info.owned.size(); i += 2) {
712 int object = info.owned.get(i + 1);
713 ResourceInfo inf = infos.get(object);
715 info.ownedBy.remove(inf);
720 Identity routeGraphConn = TransferableGraphUtils.findExternal(graph,
721 "http://www.simantics.org/Diagram-2.2/RouteGraphConnection");
722 Identity instanceOf = TransferableGraphUtils.findExternal(graph,
723 "http://www.simantics.org/Layer0-1.1/InstanceOf");
724 Identity diagramConnetionToConnection = TransferableGraphUtils.findExternal(graph,
725 "http://www.simantics.org/Modeling-1.2/DiagramConnectionToConnection");
727 for (ResourceInfo infoo : infos.valueCollection()) {
728 Identity elemTo = TransferableGraphUtils.findExternal(graph, "http://www.simantics.org/Modeling-1.2/ElementToComponent");
729 if (elemTo != null) {
730 int elemToComponent = TransferableGraphUtils.getPossibleObject2(graph, infoo.resource, elemTo);
731 if (elemToComponent != TransferableGraphUtils.NOT_FOUND) {
733 Identity component = TransferableGraphUtils.getIdentity(graph, elemToComponent);
734 Identity internal = TransferableGraphUtils.getIdentity(graph, infoo.resource);
735 if (internal.definition instanceof Internal && component.definition instanceof Internal) {
736 Internal iComponent = (Internal) component.definition;
737 infoo.name = infoo.name.substring(0, infoo.name.lastIndexOf(".") + 1) + iComponent.name;
742 if (instanceOf != null) {
743 int instOf = TransferableGraphUtils.getPossibleObject2(graph, infoo.resource, instanceOf);
744 if (instOf != TransferableGraphUtils.NOT_FOUND && routeGraphConn != null) {
745 if (instOf == routeGraphConn.resource) {
746 // Found routegraphconnection, change name
747 // Lets go to configuration
749 int connection = TransferableGraphUtils.getPossibleObject2(graph, infoo.resource,
750 diagramConnetionToConnection);
751 if (connection != TransferableGraphUtils.NOT_FOUND) {
752 // Gather all inverse statements to construct unique
754 List<String> nameParts = new ArrayList<>();
755 TIntArrayList statements = TransferableGraphUtils.getStatements(graph, connection);
756 for (int i = 0; i < statements.size(); i += 2) {
757 int predicate = statements.get(i);
758 Identity possibleInverse = TransferableGraphUtils.getIdentity(graph, predicate);
759 if (possibleInverse != null) {
760 int inverseRelation = TransferableGraphUtils.NOT_FOUND;
761 int parentId = TransferableGraphUtils.NOT_FOUND;
762 if (possibleInverse.definition instanceof Internal) {
763 Internal iPossibleInverse = (Internal) possibleInverse.definition;
764 if (iPossibleInverse.name.equals("Inverse")) {
765 inverseRelation = TransferableGraphUtils.getPossibleObject2(graph,
766 connection, possibleInverse);
767 parentId = iPossibleInverse.parent;
769 log("Unsupported inverse relation found for {} {}", infoo, iPossibleInverse);
771 } else if (possibleInverse.definition instanceof External) {
772 External ePossibleInverse = (External) possibleInverse.definition;
773 if (ePossibleInverse.name.equals("Inverse")) {
774 inverseRelation = TransferableGraphUtils.getPossibleObject2(graph,
775 connection, possibleInverse);
776 parentId = ePossibleInverse.parent;
778 log("This external inverse is unsupported for {} {}", infoo, ePossibleInverse);
781 log("This type of definition is not supported {}", infoo);
783 if (inverseRelation != TransferableGraphUtils.NOT_FOUND) {
784 // Ok found something
785 Identity object = TransferableGraphUtils.getIdentity(graph, inverseRelation);
786 Identity parent = TransferableGraphUtils.getIdentity(graph, parentId);
787 String objectName, parentName;
788 if (object.definition instanceof Internal) {
789 objectName = ((Internal) object.definition).name;
790 } else if (object.definition instanceof External) {
791 objectName = ((External) object.definition).name;
793 log("This type of definition is not supported {}", infoo);
794 throw new Error("UNSUPPORTED " + infoo);
796 if (parent.definition instanceof Internal) {
797 parentName = ((Internal) parent.definition).name;
798 } else if (parent.definition instanceof External) {
799 parentName = ((External) parent.definition).name;
801 log("This type of definition is not supported {}", infoo);
802 throw new Error("UNSUPPORTED " + infoo);
804 String fullName = parentName + "_" + objectName;
805 nameParts.add(fullName);
807 log("No inverse relation found for {}", infoo);
810 log("Did not find possible inverse relation for {}", infoo);
813 nameParts.sort((o1, o2) -> o1.compareTo(o2));
815 for (String namep : nameParts) {
818 infoo.name = infoo.name.substring(0, infoo.name.lastIndexOf(".") + 1) + name;
820 LOGGER.error("Could not find connection for " + infoo + ". Statements of graph below");
821 LOGGER.error(Arrays.toString(graph.statements));
822 LOGGER.error("Subject -> Predicate : " + infoo.resource + " -> "
823 + diagramConnetionToConnection.resource);
829 for (ResourceInfo info : infos.valueCollection()) {
830 if (info.name.startsWith("blank")) {
831 info.name = "blank" + findHash(graph, info);
835 TreeMap<String, ResourceInfo> order = new TreeMap<>();
836 for (ResourceInfo info : infos.valueCollection())
837 order.put(info.name, info);
839 for (ResourceInfo info : order.values()) {
841 System.out.print("info ");
842 String uri = printURI(graph, info, true, 0, false);
847 TreeMap<String, ResourceInfo> rblanks = new TreeMap<>();
849 for (ResourceInfo info : order.values()) {
850 if (!info.hasURI && info.ownedResourcesWithPredicates.size() != 1) {
852 System.out.print("ownedResources ");
853 if (info.name.startsWith("blank")) {
854 // These will be printed later
855 rblanks.put(getBlankRewrite(info.name), info);
857 String uri = printURI(graph, info, false, 0, false);
863 // Now print blanks in order
864 for (ResourceInfo info : rblanks.values()) {
865 if (!info.hasURI && info.ownedResourcesWithPredicates.size() != 1) {
867 System.out.print("ownedResources ");
868 String uri = printURI(graph, info, false, 0, false);
874 // for(ResourceInfo info : order.values())
875 // if(!info.hasURI && info.owner < 0)
876 // printURI(graph, info, false, 0);
878 StringBuilder refs = new StringBuilder();
879 for (String ontology : referencedOntologies) {
880 String key = ontologies.get(ontology);
881 refs.append(key + " = <" + ontology + ">\n");
883 if (!referencedOntologies.isEmpty())
885 output.insert(0, refs.toString());
889 private String calculateHash(TransferableGraph1 graph, ResourceInfo info) {
890 StringBuilder statementHash = new StringBuilder();
891 TreeSet<String> parts = new TreeSet<>();
892 for (int i = 0; i < info.owned.size(); i += 2) {
893 int predicate = info.owned.get(i);
894 int object = info.owned.get(i + 1);
895 // Lets resolve a unique name for this based on the statements this
898 String predicatee = rewritePredicateURI(graph, predicate);
899 ResourceInfo objInfo = infos.get(object);
900 parts.add(predicatee + "->" + objInfo.name + ";;;");
902 // Remove this from the list
903 List<ResourceInfo> filtered = info.ownedBy.stream().filter(ri -> !ri.name.startsWith("blank"))
904 .collect(Collectors.toList());
905 for (ResourceInfo ownedBy : filtered) {
906 parts.add(ownedBy.name);
909 ResourceInfo parentInfo = infos.get(info.parent);
910 if (parentInfo != null && !parentInfo.name.startsWith("blank")) {
911 parts.add("parent" + parentInfo.name);
913 // LOGGER.error("This should not happen");
915 for (String s : parts) {
916 statementHash.append(s);
918 String hash = makeHash(statementHash.toString().getBytes());
920 System.out.println(statementHash + " -> " + hash);
924 private String findHash(TransferableGraph1 graph, ResourceInfo info) {
925 if (info.name.startsWith("blank")) {
926 String hash = hashes.get(info.name);
928 String oldName = info.name;
930 System.out.print("calculating hash for " + oldName + " ");
931 hash = calculateHash(graph, info);
932 if (hashes.put(oldName, hash) != null) {
933 System.err.println("!!!!A clash occured for " + info + " with hash " + hash);
942 private THashMap<String, String> hashes = new THashMap<>();
944 public static String print(TransferableGraph1 tg, boolean ignoreIdentifiers) throws Exception {
945 StringBuilder b = new StringBuilder();
946 new PrettyPrintTG(b, ignoreIdentifiers).prettyPrint(tg);
950 public static void main(String[] args) throws Exception {
951 if (args.length < 1) {
952 System.out.println("Required arguments: <input .sharedOntology file> [<output .tg file>]");
953 } else if (args.length < 2) {
954 Path input = Paths.get(args[0]);
955 Path output = input.getParent().resolve(input.getName(input.getNameCount() - 1) + ".fixed");
956 new PrettyPrintTG().prettyPrint(input, output);
958 new PrettyPrintTG().prettyPrint(Paths.get(args[0]), Paths.get(args[1]));
962 private static void log(String string, Object... args) {
963 if (LOGGER.isDebugEnabled() && DEBUG)
964 LOGGER.debug(string, args);