]> gerrit.simantics Code Review - simantics/platform.git/blobdiff - bundles/org.simantics.graph/src/org/simantics/graph/representation/PrettyPrintTG.java
Improve PrettyPrintTG performance
[simantics/platform.git] / bundles / org.simantics.graph / src / org / simantics / graph / representation / PrettyPrintTG.java
index 2d4171e1ce8855f097999eb033b77db3d158de2e..cb06d6addd1604bb13070f5249428816d120bf73 100644 (file)
@@ -11,7 +11,6 @@ import java.nio.file.Paths;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
@@ -64,6 +63,8 @@ public class PrettyPrintTG {
 
     private boolean ignoreIdentifiers;
 
+    private TransferableGraphQueries query;
+
     static class ResourceInfo {
         final boolean hasURI;
         String name;
@@ -104,43 +105,51 @@ public class PrettyPrintTG {
         }
     }
 
-    public PrettyPrintTG(StringBuilder b, boolean ignoreIdentifiers) throws NoSuchAlgorithmException {
+    public PrettyPrintTG(TransferableGraph1 tg, StringBuilder b, boolean ignoreIdentifiers) throws NoSuchAlgorithmException {
         output = b;
         m = MessageDigest.getInstance("SHA-256");
         this.ignoreIdentifiers = ignoreIdentifiers;
+        
+        this.query = new TransferableGraphQueries(tg);
     }
 
-    public PrettyPrintTG() throws NoSuchAlgorithmException {
-        this(new StringBuilder(), false);
+    public PrettyPrintTG(TransferableGraph1 tg) throws NoSuchAlgorithmException {
+        this(tg, new StringBuilder(), false);
     }
 
     TreeMap<String, ResourceInfo> orderedInfos = new TreeMap<>();
     TIntObjectHashMap<ResourceInfo> infos = new TIntObjectHashMap<>();
 
-    String tgNodeName(String name) {
+    private static String tgNodeName(String name) {
         if (name.contains(" "))
             return "\"" + name + "\"";
         else
             return name;
     }
 
-    ResourceInfo recurseURI(TransferableGraph1 graph, Identity parent, String parentName, int parentId) {
-        String name = parentName + "." + tgNodeName(TransferableGraphUtils.getName(parent));
-        ResourceInfo info = new ResourceInfo(true, name, parent.resource, parentId);
-        orderedInfos.put(name, info);
-        // infos.put(parent.resource, info);
-        for (Identity child : TransferableGraphUtils.getChildren(graph, parent)) {
-            recurseURI(graph, child, name, info.resource);
-        }
+    private ResourceInfo recurseURI(Map<String, ResourceInfo> infos, Identity identity, String parentName, int parentId) {
+        String name = parentName + "." + tgNodeName(TransferableGraphUtils.getName(identity));
+        int identityResource = identity.resource;
+        ResourceInfo info = new ResourceInfo(true, name, identityResource, parentId);
+        infos.put(name, info);
+        for (Identity child : query.getChildren(identity))
+            recurseURI(infos, child, name, identityResource);
         return info;
     }
 
-    private TreeMap<String, TreeSet<Integer>> sortByPredicateUniqueStatements(TransferableGraph1 graph, int resource) {
+    /**
+     * Sorts statements by predicateURI in natural order
+     * 
+     * @param graph
+     * @param resource
+     * @return
+     */
+    private TreeMap<String, TreeSet<Integer>> sortByPredicateUniqueStatements(int resource) {
         TreeMap<String, TreeSet<Integer>> results = new TreeMap<>();
-        TIntArrayList statements = TransferableGraphUtils.getStatements(graph, resource);
+        TIntArrayList statements = query.getStatements(resource);
         for (int i = 0; i < statements.size(); i += 2) {
             int predicate = statements.get(i);
-            String predicateURI = TransferableGraphUtils.getURI(graph, predicate);
+            String predicateURI = query.getURI(predicate);
             TreeSet<Integer> objects = results.get(predicateURI);
             if (objects == null) {
                 objects = new TreeSet<>();
@@ -151,32 +160,32 @@ public class PrettyPrintTG {
         return results;
     }
 
-    void discoverBlank(TransferableGraph1 graph, int resource, TIntArrayList todo) throws Exception {
+    void discoverBlank(int resource, TIntArrayList todo) throws Exception {
         // TIntArrayList statements =
         // TransferableGraphUtils.getStatements(graph, resource);
         // for(int i=0;i<statements.size();i+=2) {
-        for (TreeSet<Integer> objects : sortByPredicateUniqueStatements(graph, resource).values()) {
+        for (TreeSet<Integer> objects : sortByPredicateUniqueStatements(resource).values()) {
             for (int object : objects) {
                 // int object = statements.get(i+1);
-                Identity objectId = TransferableGraphUtils.getIdentity(graph, object);
+                Identity objectId = query.getIdentity(object);
                 if (objectId != null) {
                     if (objectId.definition instanceof External)
                         continue;
                 }
-                Value value = TransferableGraphUtils.findValue(graph, object);
+                Value value = query.findValue(object);
                 if (value != null) {
                     infos.put(object, new ResourceInfo(false, printValue(value), object, resource));
-                    continue;
-                }
-                ResourceInfo existing = infos.get(object);
-                if (existing == null) {
-
-                    existing = new ResourceInfo(false, "blank" + blankCounter++, object, resource);
-
-                    // System.out.println("created blank" + blankCounter + "
-                    // with object " + object + " resource " + resource);
-                    infos.put(object, existing);
-                    todo.add(object);
+                } else {
+                    ResourceInfo existing = infos.get(object);
+                    if (existing == null) {
+    
+                        existing = new ResourceInfo(false, "blank" + blankCounter++, object, resource);
+    
+                        // System.out.println("created blank" + blankCounter + "
+                        // with object " + object + " resource " + resource);
+                        infos.put(object, existing);
+                        todo.add(object);
+                    }
                 }
             }
         }
@@ -188,10 +197,10 @@ public class PrettyPrintTG {
         return new BigInteger(1, m.digest()).toString(16);
     }
 
-    void discoverOwners(TransferableGraph1 graph, ResourceInfo info) {
+    void discoverOwners(ResourceInfo info) {
         log("Discovering owners for {}", info);
         int resource = info.resource;
-        TIntArrayList statements = TransferableGraphUtils.getStatements(graph, resource);
+        TIntArrayList statements = query.getStatements(resource);
         for (int i = 0; i < statements.size(); i += 2) {
             int predicate = statements.get(i);
             int object = statements.get(i + 1);
@@ -201,7 +210,7 @@ public class PrettyPrintTG {
 
                 // Check if predicate is inverse, this just resolves all
                 // predicates to be inverse with ending "Inverse"..
-                String predicateUri = rewritePredicateURI(graph, predicate);
+                String predicateUri = rewritePredicateURI(predicate);
                 if (!predicateUri.endsWith("Inverse") && !predicateUri.endsWith("Of")) {
                     existing.ownedResourcesWithPredicates.put(resource, predicate);
                     // if (predicateUri.endsWith("Of")) {
@@ -241,7 +250,7 @@ public class PrettyPrintTG {
         }
     }
 
-    public static String getExternalURI(TransferableGraph1 tg, External ext) {
+    public String getExternalURI(External ext) {
         String name = ext.name;
         if (name.contains(" "))
             name = name.replace(" ", "_").replaceAll("@", "_");// name = "\"" +
@@ -249,9 +258,9 @@ public class PrettyPrintTG {
         int parentId = ext.parent;
         // if(parentId == 0) return ext.name;
         // else {
-        Identity id = TransferableGraphUtils.getIdentity(tg, parentId);
+        Identity id = query.getIdentity(parentId);
         if (id.definition instanceof External) {
-            return getExternalURI(tg, (External) id.definition) + "/" + name;
+            return getExternalURI((External) id.definition) + "/" + name;
         } else if (id.definition instanceof Root) {
             Root root = (Root) id.definition;
             return "http:/" + root.name + "/" + name;
@@ -261,20 +270,20 @@ public class PrettyPrintTG {
         // }
     }
 
-    public static String getExternalURI(TransferableGraph1 tg, int resource) {
-        Identity id = TransferableGraphUtils.getIdentity(tg, resource);
+    public String getExternalURI(int resource) {
+        Identity id = query.getIdentity(resource);
         if (id == null)
             return null;
         if (id.definition instanceof External) {
             External ext = (External) id.definition;
-            return getExternalURI(tg, ext);
+            return getExternalURI(ext);
         }
         return null;
     }
 
-    String rewritePredicateURI(TransferableGraph1 graph, int predicate) {
+    String rewritePredicateURI(int predicate) {
 
-        String uri = getExternalURI(graph, predicate);
+        String uri = getExternalURI(predicate);
         if (uri == null) {
             ResourceInfo info = infos.get(predicate);
             if (info != null)
@@ -301,7 +310,7 @@ public class PrettyPrintTG {
             output.append("  ");
     }
 
-    String printBlank(TransferableGraph1 graph, String predicateURI2, ResourceInfo info, int indent) {
+    String printBlank(String predicateURI2, ResourceInfo info, int indent) {
 
         if (info.hasURI)
             return null;
@@ -328,7 +337,7 @@ public class PrettyPrintTG {
         if (info.ownedResourcesWithPredicates.isEmpty()) {
             if (DEBUG)
                 System.out.print("printBlank");
-            String uri = printURI(graph, info, false, indent, false);
+            String uri = printURI(info, false, indent, false);
             if (uri != null)
                 output.append(uri);
         }
@@ -354,14 +363,14 @@ public class PrettyPrintTG {
         return ((predicate & 0xffffffffL) << 32) | (object & 0xffffffffL);
     }
 
-    private void addInlineStatement(TransferableGraph1 graph, Map<String, Set<String>> statements, String predicate,
+    private void addInlineStatement(Map<String, Set<String>> statements, String predicate,
             ResourceInfo objectInfo, int indent) {
         Set<String> objects = statements.get(predicate);
         if (objects == null) {
             objects = new TreeSet<>();
             statements.put(predicate, objects);
         }
-        String uri = printURI(graph, objectInfo, false, indent + 1, true);
+        String uri = printURI(objectInfo, false, indent + 1, true);
         if (uri != null) {
             // TODO: this is not the right place to remove trailing newline
             uri = uri.endsWith("\n") ? uri.substring(0, uri.length() - 2) : uri;
@@ -382,7 +391,7 @@ public class PrettyPrintTG {
         objects.add(object);
     }
 
-    String printURI(TransferableGraph1 graph, ResourceInfo info, boolean requireURI, int indent, boolean inline) {
+    String printURI(ResourceInfo info, boolean requireURI, int indent, boolean inline) {
 
         if (requireURI && !info.hasURI)
             return null;
@@ -393,8 +402,7 @@ public class PrettyPrintTG {
             return null;
 
         Map<String, Set<String>> statements = new TreeMap<>();
-        Identity consistsOf = TransferableGraphUtils.findExternal(graph,
-                "http://www.simantics.org/Layer0-1.1/ConsistsOf");
+        Identity consistsOf = query.findExternalByURI("http://www.simantics.org/Layer0-1.1/ConsistsOf");
         // Identity partOf = TransferableGraphUtils.findExternal(graph,
         // "http://www.simantics.org/Layer0-1.1/PartOf");
         TLongHashSet processed = new TLongHashSet();
@@ -410,9 +418,9 @@ public class PrettyPrintTG {
             processed.add(stmId);
         }
 
-        TreeMap<String, Integer> predicateURIs = new TreeMap<>();
+        TreeMap<String, List<Integer>> predicateURIs = new TreeMap<>();
 
-        TIntArrayList rawStatements = TransferableGraphUtils.getStatements(graph, info.resource);
+        TIntArrayList rawStatements = query.getStatements(info.resource);
         if (DEBUG)
             System.out.println(
                     "rawStatements size for " + info.name + " : " + rawStatements.size() + " " + rawStatements);
@@ -442,32 +450,38 @@ public class PrettyPrintTG {
                 // indent++;
                 // }
             }
-            String predicateURI = rewritePredicateURI(graph, predicate);
-            predicateURIs.put(predicateURI, object);
+            String predicateURI = rewritePredicateURI(predicate);
+            List<Integer> objects = predicateURIs.get(predicateURI);
+            if (objects == null) {
+                objects = new ArrayList<>();
+                predicateURIs.put(predicateURI, objects);
+            }
+            objects.add(object);
         }
-        for (Entry<String, Integer> entry : predicateURIs.entrySet()) {
+        for (Entry<String, List<Integer>> entry : predicateURIs.entrySet()) {
             String predicateURI = entry.getKey();
-            int object = entry.getValue();
-
-            ResourceInfo objectInfo = infos.get(object);
-            if (objectInfo == null) {
-                String objectURI = rewritePredicateURI(graph, object);
-                if (DEBUG)
-                    System.out.println("  adding statement " + predicateURI + " " + objectURI);
-                addStatement(statements, predicateURI, objectURI);
-            } else if (objectInfo.ownedBy.size() == 1 && objectInfo.ownedBy.contains(info)) {
-                // inline printing with _
-                if (DEBUG)
-                    System.out.println("  adding inline statement " + predicateURI + " " + objectInfo.name);
-                addInlineStatement(graph, statements, predicateURI, objectInfo, indent);
-            } else {
-                String objectName = objectInfo.name;
-                if (objectName.startsWith("blank")) {
-                    objectName = getBlankRewrite(objectName);
+            List<Integer> objects = entry.getValue();
+            for (int object : objects) {
+                ResourceInfo objectInfo = infos.get(object);
+                if (objectInfo == null) {
+                    String objectURI = rewritePredicateURI(object);
+                    if (DEBUG)
+                        System.out.println("  adding statement " + predicateURI + " " + objectURI);
+                    addStatement(statements, predicateURI, objectURI);
+                } else if (objectInfo.ownedBy.size() == 1 && objectInfo.ownedBy.contains(info)) {
+                    // inline printing with _
+                    if (DEBUG)
+                        System.out.println("  adding inline statement " + predicateURI + " " + objectInfo.name);
+                    addInlineStatement(statements, predicateURI, objectInfo, indent);
+                } else {
+                    String objectName = objectInfo.name;
+                    if (objectName.startsWith("blank")) {
+                        objectName = getBlankRewrite(objectName);
+                    }
+                    if (DEBUG)
+                        System.out.println("  adding statement " + predicateURI + " " + objectName);
+                    addStatement(statements, predicateURI, objectName);
                 }
-                if (DEBUG)
-                    System.out.println("  adding statement " + predicateURI + " " + objectName);
-                addStatement(statements, predicateURI, objectName);
             }
         }
 
@@ -547,46 +561,37 @@ public class PrettyPrintTG {
             }
         }
 
-        TreeMap<String, Integer> ownedOrdered = new TreeMap<>();
+        TreeMap<String, Set<Integer>> ownedOrdered = new TreeMap<>();
 
         for (int i = 0; i < info.owned.size(); i += 2) {
-            String predicateURI = rewritePredicateURI(graph, info.owned.get(i));
-            ownedOrdered.put(predicateURI, info.owned.get(i + 1));
+            String predicateURI = rewritePredicateURI(info.owned.get(i));
+            Set<Integer> owneds = ownedOrdered.get(predicateURI);
+            if (owneds == null) {
+                owneds = new TreeSet<>();
+                ownedOrdered.put(predicateURI, owneds);
+            }
+            owneds.add(info.owned.get(i + 1));
         }
 
         if (DEBUG)
             System.out.println(info.name + " : " + ownedOrdered.keySet());
 
-        for (Entry<String, Integer> entry : ownedOrdered.entrySet()) {
+        for (Entry<String, Set<Integer>> entry : ownedOrdered.entrySet()) {
             String predicateURI = entry.getKey();
-            int owned = entry.getValue();
-            ResourceInfo ownedInfo = infos.get(owned);
-
-            String blank = printBlank(graph, predicateURI, ownedInfo, indent + 1);
-            if (blank != null) {
-                output.append(blank);
+            Set<Integer> owneds = entry.getValue();
+            for (int owned : owneds) {
+                ResourceInfo ownedInfo = infos.get(owned);
+    
+                String blank = printBlank(predicateURI, ownedInfo, indent + 1);
+                if (blank != null) {
+                    output.append(blank);
+                }
             }
         }
 
         return output.toString();
     }
 
-    void prettyPrint(Path input, Path output) throws Exception {
-
-        System.out.format("Converting exported shared ontology%n\t" + input.toString()
-                + "%nto bundle-compatible ontology%n\t" + output.toString());
-        try (InputStream is = new BufferedInputStream(Files.newInputStream(input), 128 * 1024)) {
-            DataInput dis = new DataInputStream(is);
-            org.simantics.databoard.container.DataContainer container = DataContainers.readFile(dis);
-            Binding binding = TransferableGraph1.BINDING;
-            TransferableGraph1 graph = (TransferableGraph1) container.content.getValue(binding);
-            prettyPrint(graph);
-            Files.write(output, this.output.toString().getBytes());
-
-        }
-
-    }
-
     static Map<String, String> knownOntologies = new HashMap<>();
 
     static {
@@ -607,26 +612,26 @@ public class PrettyPrintTG {
         knownOntologies.put("http://www.semantum.fi/SimupediaWorkbench-1.0", "SIMUPEDIA_WORKBENCH");
     }
 
-    void prettyPrint(TransferableGraph1 graph) throws Exception {
+    void prettyPrint() throws Exception {
         log("Starting prettyPrint for TransferableGraph with {} resources, {} identities, {} statements and {} values",
-                graph.resourceCount, graph.identities, graph.statements.length, graph.values.length);
+                query.getGraph().resourceCount, query.getGraph().identities, query.getGraph().statements.length, query.getGraph().values.length);
 
-        for (Identity id : graph.identities) {
+        query.forIdentities(id -> {
+            int identityResource = id.resource;
             if (id.definition instanceof Internal) {
                 Internal internal = (Internal) id.definition;
-                Identity parent = TransferableGraphUtils.getIdentity(graph, internal.parent);
-                if (parent.definition instanceof External) {
+                Identity parent = query.getIdentity(internal.parent);
+                if (parent.definition instanceof External || parent.definition instanceof Root) {
                     log("Resolving internal identity {}", id);
                     String name = "BASE";
-                    ResourceInfo info = new ResourceInfo(true, name, id.resource, -1);
-                    info.aliasURI = TransferableGraphUtils.getURI(graph, id.resource);
+                    ResourceInfo info = new ResourceInfo(true, name, identityResource, -1);
+                    info.aliasURI = query.getURI(identityResource);
                     info.newResource = true;
                     orderedInfos.put(name, info);
                     // infos.put(id.resource, info);
                     log("    which parent is external {} and has an aliasURI {}", parent, info.aliasURI);
-                    for (Identity child : TransferableGraphUtils.getChildren(graph, id)) {
-                        recurseURI(graph, child, name, info.resource);
-                    }
+                    for (Identity child : query.getChildren(id))
+                        recurseURI(orderedInfos, child, name, identityResource);
                     log("    and has {} children", infos.size());
                 }
             } else if (id.definition instanceof External) {
@@ -640,7 +645,7 @@ public class PrettyPrintTG {
                     String prefix = ext.name.substring(0, index);
                     int index2 = ext.name.indexOf('/', index);
                     String ontology = index2 == -1 ? ext.name : ext.name.substring(0, index2);
-                    String uri = TransferableGraphUtils.getURI(graph, id.resource);
+                    String uri = query.getURI(identityResource);
 
                     log("    which was resolved as URI={} and prefix={}", uri, prefix);
 
@@ -648,7 +653,7 @@ public class PrettyPrintTG {
 
                 } else if (ext.name.contains("-")) {
                     log("Resolving possible ontology {}", ext);
-                    String uri = TransferableGraphUtils.getURI(graph, id.resource);
+                    String uri = query.getURI(identityResource);
                     Matcher m = versionExtractPattern.matcher(uri);
                     if (m.matches()) {
                         if (!ontologies.containsKey(uri)) {
@@ -660,7 +665,8 @@ public class PrettyPrintTG {
                     }
                 }
             }
-        }
+            return true;
+        });
 
         // Discover other resources
         log("Discovering other resources..");
@@ -675,10 +681,10 @@ public class PrettyPrintTG {
 
         while (!todo.isEmpty()) {
             int resource = todo.removeAt(todo.size() - 1);
-            discoverBlank(graph, resource, todo);
+            discoverBlank(resource, todo);
         }
         for (ResourceInfo info : infos.valueCollection())
-            discoverOwners(graph, info);
+            discoverOwners(info);
         // for(ResourceInfo info : infos.valueCollection())
         // fixInstanceOf(graph, info);
 
@@ -697,12 +703,15 @@ public class PrettyPrintTG {
 
                     @Override
                     public boolean execute(int owner, int predicate) {
+                       
                         ResourceInfo ownerInfo = infos.get(owner);
                         ownerInfo.owned.add(predicate);
                         ownerInfo.owned.add(info.resource);
                         return false;
                     }
                 });
+            } else {
+                System.err.println("Here we are with " + info);
             }
         }
 
@@ -717,21 +726,18 @@ public class PrettyPrintTG {
             }
         }
 
-        Identity routeGraphConn = TransferableGraphUtils.findExternal(graph,
-                "http://www.simantics.org/Diagram-2.2/RouteGraphConnection");
-        Identity instanceOf = TransferableGraphUtils.findExternal(graph,
-                "http://www.simantics.org/Layer0-1.1/InstanceOf");
-        Identity diagramConnetionToConnection = TransferableGraphUtils.findExternal(graph,
-                "http://www.simantics.org/Modeling-1.2/DiagramConnectionToConnection");
+        Identity routeGraphConn = query.findExternalByURI("http://www.simantics.org/Diagram-2.2/RouteGraphConnection");
+        Identity instanceOf = query.findExternalByURI("http://www.simantics.org/Layer0-1.1/InstanceOf");
+        Identity diagramConnetionToConnection = query.findExternalByURI("http://www.simantics.org/Modeling-1.2/DiagramConnectionToConnection");
 
+        Identity elemTo = query.findExternalByURI("http://www.simantics.org/Modeling-1.2/ElementToComponent");
         for (ResourceInfo infoo : infos.valueCollection()) {
-            Identity elemTo = TransferableGraphUtils.findExternal(graph, "http://www.simantics.org/Modeling-1.2/ElementToComponent");
             if (elemTo != null) {
-                int elemToComponent = TransferableGraphUtils.getPossibleObject2(graph, infoo.resource, elemTo);
+                int elemToComponent = query.getPossibleObject(infoo.resource, elemTo);
                 if (elemToComponent != TransferableGraphUtils.NOT_FOUND) {
 
-                    Identity component = TransferableGraphUtils.getIdentity(graph, elemToComponent);
-                    Identity internal = TransferableGraphUtils.getIdentity(graph, infoo.resource);
+                    Identity component = query.getIdentity(elemToComponent);
+                    Identity internal = query.getIdentity(infoo.resource);
                     if (internal.definition instanceof Internal && component.definition instanceof Internal) {
                         Internal iComponent = (Internal) component.definition;
                         infoo.name = infoo.name.substring(0, infoo.name.lastIndexOf(".") + 1) + iComponent.name;
@@ -740,29 +746,29 @@ public class PrettyPrintTG {
             }
 
             if (instanceOf != null) {
-                int instOf = TransferableGraphUtils.getPossibleObject2(graph, infoo.resource, instanceOf);
+                int instOf = query.getPossibleObject( infoo.resource, instanceOf);
                 if (instOf != TransferableGraphUtils.NOT_FOUND && routeGraphConn != null) {
                     if (instOf == routeGraphConn.resource) {
                         // Found routegraphconnection, change name
                         // Lets go to configuration
 
-                        int connection = TransferableGraphUtils.getPossibleObject2(graph, infoo.resource,
+                        int connection = query.getPossibleObject( infoo.resource,
                                 diagramConnetionToConnection);
                         if (connection != TransferableGraphUtils.NOT_FOUND) {
                             // Gather all inverse statements to construct unique
                             // name
                             List<String> nameParts = new ArrayList<>();
-                            TIntArrayList statements = TransferableGraphUtils.getStatements(graph, connection);
+                            TIntArrayList statements = query.getStatements(connection);
                             for (int i = 0; i < statements.size(); i += 2) {
                                 int predicate = statements.get(i);
-                                Identity possibleInverse = TransferableGraphUtils.getIdentity(graph, predicate);
+                                Identity possibleInverse = query.getIdentity(predicate);
                                 if (possibleInverse != null) {
                                     int inverseRelation = TransferableGraphUtils.NOT_FOUND;
                                     int parentId = TransferableGraphUtils.NOT_FOUND;
                                     if (possibleInverse.definition instanceof Internal) {
                                         Internal iPossibleInverse = (Internal) possibleInverse.definition;
                                         if (iPossibleInverse.name.equals("Inverse")) {
-                                            inverseRelation = TransferableGraphUtils.getPossibleObject2(graph,
+                                            inverseRelation = query.getPossibleObject(
                                                     connection, possibleInverse);
                                             parentId = iPossibleInverse.parent;
                                         } else {
@@ -771,7 +777,7 @@ public class PrettyPrintTG {
                                     } else if (possibleInverse.definition instanceof External) {
                                         External ePossibleInverse = (External) possibleInverse.definition;
                                         if (ePossibleInverse.name.equals("Inverse")) {
-                                            inverseRelation = TransferableGraphUtils.getPossibleObject2(graph,
+                                            inverseRelation = query.getPossibleObject(
                                                     connection, possibleInverse);
                                             parentId = ePossibleInverse.parent;
                                         } else {
@@ -782,8 +788,8 @@ public class PrettyPrintTG {
                                     }
                                     if (inverseRelation != TransferableGraphUtils.NOT_FOUND) {
                                         // Ok found something
-                                        Identity object = TransferableGraphUtils.getIdentity(graph, inverseRelation);
-                                        Identity parent = TransferableGraphUtils.getIdentity(graph, parentId);
+                                        Identity object = query.getIdentity(inverseRelation);
+                                        Identity parent = query.getIdentity(parentId);
                                         String objectName, parentName;
                                         if (object.definition instanceof Internal) {
                                             objectName = ((Internal) object.definition).name;
@@ -818,7 +824,6 @@ public class PrettyPrintTG {
                             infoo.name = infoo.name.substring(0, infoo.name.lastIndexOf(".") + 1) + name;
                         } else {
                             LOGGER.error("Could not find connection for " + infoo + ". Statements of graph below");
-                            LOGGER.error(Arrays.toString(graph.statements));
                             LOGGER.error("Subject -> Predicate : " + infoo.resource + " -> "
                                     + diagramConnetionToConnection.resource);
                         }
@@ -828,7 +833,7 @@ public class PrettyPrintTG {
         }
         for (ResourceInfo info : infos.valueCollection()) {
             if (info.name.startsWith("blank")) {
-                info.name = "blank" + findHash(graph, info);
+                info.name = "blank" + findHash(info);
             }
         }
 
@@ -839,7 +844,7 @@ public class PrettyPrintTG {
         for (ResourceInfo info : order.values()) {
             if (DEBUG)
                 System.out.print("info ");
-            String uri = printURI(graph, info, true, 0, false);
+            String uri = printURI(info, true, 0, false);
             if (uri != null)
                 output.append(uri);
         }
@@ -854,7 +859,7 @@ public class PrettyPrintTG {
                     // These will be printed later
                     rblanks.put(getBlankRewrite(info.name), info);
                 } else {
-                    String uri = printURI(graph, info, false, 0, false);
+                    String uri = printURI(info, false, 0, false);
                     if (uri != null)
                         output.append(uri);
                 }
@@ -865,7 +870,7 @@ public class PrettyPrintTG {
             if (!info.hasURI && info.ownedResourcesWithPredicates.size() != 1) {
                 if (DEBUG)
                     System.out.print("ownedResources ");
-                String uri = printURI(graph, info, false, 0, false);
+                String uri = printURI(info, false, 0, false);
                 if (uri != null)
                     output.append(uri);
             }
@@ -886,7 +891,7 @@ public class PrettyPrintTG {
 
     }
 
-    private String calculateHash(TransferableGraph1 graph, ResourceInfo info) {
+    private String calculateHash(ResourceInfo info) {
         StringBuilder statementHash = new StringBuilder();
         TreeSet<String> parts = new TreeSet<>();
         for (int i = 0; i < info.owned.size(); i += 2) {
@@ -895,7 +900,7 @@ public class PrettyPrintTG {
             // Lets resolve a unique name for this based on the statements this
             // one has
 
-            String predicatee = rewritePredicateURI(graph, predicate);
+            String predicatee = rewritePredicateURI(predicate);
             ResourceInfo objInfo = infos.get(object);
             parts.add(predicatee + "->" + objInfo.name + ";;;");
         }
@@ -921,14 +926,14 @@ public class PrettyPrintTG {
         return hash;
     }
 
-    private String findHash(TransferableGraph1 graph, ResourceInfo info) {
+    private String findHash(ResourceInfo info) {
         if (info.name.startsWith("blank")) {
             String hash = hashes.get(info.name);
             if (hash == null) {
                 String oldName = info.name;
                 if (DEBUG)
                     System.out.print("calculating hash for " + oldName + " ");
-                hash = calculateHash(graph, info);
+                hash = calculateHash(info);
                 if (hashes.put(oldName, hash) != null) {
                     System.err.println("!!!!A clash occured for " + info + " with hash " + hash);
                 }
@@ -943,19 +948,31 @@ public class PrettyPrintTG {
 
     public static String print(TransferableGraph1 tg, boolean ignoreIdentifiers) throws Exception {
         StringBuilder b = new StringBuilder();
-        new PrettyPrintTG(b, ignoreIdentifiers).prettyPrint(tg);
+        new PrettyPrintTG(tg, b, ignoreIdentifiers).prettyPrint();
         return b.toString();
     }
 
     public static void main(String[] args) throws Exception {
         if (args.length < 1) {
             System.out.println("Required arguments: <input .sharedOntology file> [<output .tg file>]");
-        } else if (args.length < 2) {
-            Path input = Paths.get(args[0]);
-            Path output = input.getParent().resolve(input.getName(input.getNameCount() - 1) + ".fixed");
-            new PrettyPrintTG().prettyPrint(input, output);
+        }
+        Path input;
+        Path output;
+        if (args.length < 2) {
+            input = Paths.get(args[0]);
+            output = input.getParent().resolve(input.getName(input.getNameCount() - 1) + ".fixed");
         } else {
-            new PrettyPrintTG().prettyPrint(Paths.get(args[0]), Paths.get(args[1]));
+            input = Paths.get(args[0]);
+            output = Paths.get(args[1]);
+        }
+        System.out.format("Converting exported shared ontology%n\t" + input.toString()
+        + "%nto bundle-compatible ontology%n\t" + output.toString());
+        try (InputStream is = new BufferedInputStream(Files.newInputStream(input), 128 * 1024)) {
+            DataInput dis = new DataInputStream(is);
+            org.simantics.databoard.container.DataContainer container = DataContainers.readFile(dis);
+            Binding binding = TransferableGraph1.BINDING;
+            TransferableGraph1 graph = (TransferableGraph1) container.content.getValue(binding);
+            new PrettyPrintTG(graph).prettyPrint();
         }
     }