]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.browsing.ui.model/src/org/simantics/browsing/ui/model/children/RelationChildRule.java
Fixed all line endings of the repository
[simantics/platform.git] / bundles / org.simantics.browsing.ui.model / src / org / simantics / browsing / ui / model / children / RelationChildRule.java
1 /*******************************************************************************
2  * Copyright (c) 2010, 2011 Association for Decentralized Information Management in
3  * Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.browsing.ui.model.children;
13
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Collections;
17
18 import org.simantics.browsing.ui.model.tests.Test;
19 import org.simantics.db.ReadGraph;
20 import org.simantics.db.Resource;
21 import org.simantics.db.exception.DatabaseException;
22 import org.simantics.db.exception.NoInverseException;
23
24 /**
25  * A child rule that says that there is exactly one child node whose content 
26  * is equal to the content of the parent.
27  * @author Hannu Niemistö
28  */
29 public class RelationChildRule implements ChildRule {
30
31     Resource relation;
32     Test test;
33     
34     public RelationChildRule(Resource relation, Test test) {
35         this.relation = relation;
36         this.test = test;
37     }
38     
39     @Override
40     public Collection<?> getChildren(ReadGraph graph, Object parent) throws DatabaseException {
41         Collection<Resource> result = graph.getObjects((Resource)parent, relation);
42         if(test != null) {
43             ArrayList<Resource> filtered = new ArrayList<Resource>(result.size());
44             for(Resource r : result)
45                 if(test.test(graph, r))
46                     filtered.add(r); 
47             result = filtered;
48         }
49         return result;
50     }
51
52     @Override
53     public Collection<?> getParents(ReadGraph graph, Object child)
54             throws DatabaseException {
55         try {
56             if(child instanceof Resource) {
57                 Resource inverse = graph.getInverse(relation);            
58                 return graph.getObjects((Resource)child, inverse);
59             }
60         } catch(NoInverseException e) {
61         }   
62         return Collections.emptyList();
63     }
64     
65     @Override
66     public boolean isCompatible(Class<?> contentType) {
67         return contentType.equals(Resource.class);
68     }
69 }