]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/util/RelativeReference.java
Added resourceId and GUID to diagram DnD content
[simantics/platform.git] / bundles / org.simantics.db.layer0 / src / org / simantics / db / layer0 / util / RelativeReference.java
1 package org.simantics.db.layer0.util;
2
3 import java.util.ArrayList;
4
5 import org.simantics.databoard.util.URIStringUtils;
6 import org.simantics.db.ReadGraph;
7 import org.simantics.db.Resource;
8 import org.simantics.db.common.uri.UnescapedChildMapOfResource;
9 import org.simantics.db.exception.DatabaseException;
10 import org.simantics.layer0.Layer0;
11
12 public class RelativeReference {
13     public final Resource base;
14     public final String path;
15     
16     public RelativeReference(Resource base, String path) {
17         this.base = base;
18         this.path = path;
19     }
20     
21     public Resource resolve(ReadGraph graph) throws DatabaseException {
22         return resolve(graph, base, path);
23     }
24
25     public static Resource resolve(ReadGraph graph, 
26             Resource base, 
27             String path) throws DatabaseException {
28         String[] splitPath = path.split("/");
29         for(String name : splitPath) {            
30             base = graph.syncRequest(new UnescapedChildMapOfResource(base)).get(
31                     URIStringUtils.unescape(name)
32                     );
33             if(base == null)
34                 return null;                    
35         }
36         return base;
37     }
38     
39     public static RelativeReference createReference(ReadGraph graph, Resource baseType, Resource resource) throws DatabaseException {
40         ArrayList<String> path = new ArrayList<String>();
41         Layer0 L0 = Layer0.getInstance(graph);
42         try {
43             while(!graph.isInstanceOf(resource, baseType)) {
44                 path.add((String)graph.getRelatedValue(resource, L0.HasName));
45                 resource = graph.getSingleObject(resource, L0.PartOf);
46             }
47         } catch(DatabaseException e) {
48             return null;
49         }
50         StringBuilder b = new StringBuilder();
51         for(int i=path.size()-1;i>=0;--i) {
52             b.append(URIStringUtils.escape(path.get(i)));
53             if(i > 0)
54                 b.append('/');
55         }
56         return new RelativeReference(resource, b.toString());
57     }
58 }