package org.simantics.db.layer0.util; import java.util.Collection; import org.simantics.databoard.util.URIStringUtils; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.Statement; import org.simantics.db.common.request.FunctionalStatementMapOfResource; import org.simantics.db.common.uri.UnescapedChildMapOfResource; import org.simantics.db.exception.DatabaseException; import org.simantics.layer0.Layer0; import org.simantics.scl.runtime.tuple.Tuple2; public class ExtendedUris { public static Resource resolveAbsoluteUri(ReadGraph graph, String uri) throws DatabaseException { if(!uri.startsWith("http:/")) throw new IllegalArgumentException("Invalid absolute URI '" + uri + "'."); return resolveRelativeUri(graph, graph.getRootLibrary(), uri.substring(6)); } public static Resource resolveRelativeUri(ReadGraph graph, Resource parent, String uri) throws DatabaseException { int beginPos = 0; while(beginPos < uri.length()) { int endPos; for(endPos = beginPos+1; endPos < uri.length(); ++endPos) { char c = uri.charAt(endPos); if(c == '/' || c == '#') break; } char c = uri.charAt(beginPos); if(c == '/') { String escapedName = uri.substring(beginPos+1, endPos); String name = URIStringUtils.unescape(escapedName); parent = graph.syncRequest(new UnescapedChildMapOfResource(parent)).get(name); if(parent == null) throw new DatabaseException("Didn't find a child " + name + " for " + uri.substring(0, beginPos)); } else if(c == '#') { String escapedName = uri.substring(beginPos+1, endPos); String name = URIStringUtils.unescape(escapedName); parent = graph.syncRequest(new FunctionalStatementMapOfResource(parent)).get(name); if(parent == null) throw new DatabaseException("Didn't find a property " + name); } else throw new IllegalArgumentException("Invalid relative URI '" + uri + "'."); beginPos = endPos; } return parent; } private static boolean initialized = false; private static Resource ElementToComponent; private static void initialize(ReadGraph graph) throws DatabaseException { ElementToComponent = graph.getResource("http://www.simantics.org/Modeling-1.2/ElementToComponent"); initialized = true; } public static Tuple2 getPrimaryFunctionalReference(ReadGraph graph, Resource r) throws DatabaseException { if(!initialized) initialize(graph); Statement stat = graph.getPossibleStatement(r, ElementToComponent); if(stat != null) return statementToResult(graph, stat); return null; } public static Tuple2 getSecondaryFunctionalReference(ReadGraph graph, Resource r) throws DatabaseException { Layer0 L0 = Layer0.getInstance(graph); Collection statements = graph.getStatements(r, L0.PropertyOf); if(statements.size() == 1) for(Statement stat : statements) return statementToResult(graph, stat); return null; } private static Tuple2 statementToResult(ReadGraph graph, Statement stat) throws DatabaseException { return new Tuple2(stat.getObject(), graph.getInverse(stat.getPredicate())); } }