]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.browsing.ui.model/src/org/simantics/browsing/ui/model/tests/InstanceOfTest.java
70b6ecaa419854896a7d09675c1f3ea2bdd7a72e
[simantics/platform.git] / bundles / org.simantics.browsing.ui.model / src / org / simantics / browsing / ui / model / tests / InstanceOfTest.java
1 package org.simantics.browsing.ui.model.tests;
2
3 import org.eclipse.core.runtime.Platform;
4 import org.osgi.framework.Bundle;
5 import org.simantics.databoard.Bindings;
6 import org.simantics.db.ReadGraph;
7 import org.simantics.db.Resource;
8 import org.simantics.db.exception.DatabaseException;
9 import org.simantics.viewpoint.ontology.ViewpointResource;
10
11 /**
12  * A visual contribution rule test that checks whether the input content is an
13  * instance of a Java class. The class is specified by identifying the source
14  * bundle and the class name.
15  * 
16  * @author Tuukka Lehtonen
17  */
18 public class InstanceOfTest implements Test {
19
20     String   bundleName;
21     String   className;
22     Class<?> clazz;
23     boolean  failed;
24
25     public InstanceOfTest(String bundle, String className) {
26         this.bundleName = bundle;
27         this.className = className;
28     }
29
30     public InstanceOfTest(ReadGraph graph, Resource test) throws DatabaseException {
31         ViewpointResource VP = ViewpointResource.getInstance(graph);
32         this.bundleName = graph.getRelatedValue(test, VP.InstanceOfTest_bundleName, Bindings.STRING);
33         this.className = graph.getRelatedValue(test, VP.InstanceOfTest_className, Bindings.STRING);
34     }
35
36     private Class<?> resolveClass() {
37         if (failed)
38             return null;
39         if (clazz != null)
40             return clazz;
41         Bundle b = Platform.getBundle(bundleName);
42         if (b == null) {
43             System.err.println(getClass() + " could not resolve class " + className + ", bundle " + bundleName + " not found in platform");
44             failed = true;
45             return null;
46         }
47         try {
48             this.clazz = b.loadClass(className);
49             return clazz;
50         } catch (ClassNotFoundException e) {
51             System.err.println(getClass() + " could not resolve class " + className + ", from bundle " + bundleName);
52             failed = true;
53             return null;
54         }
55     }
56
57     @Override
58     public boolean isCompatible(Class<?> contentType) {
59         Class<?> clazz = resolveClass();
60         return clazz != null && clazz.equals(contentType);
61     }
62
63     @Override
64     public boolean test(ReadGraph graph, Object content)
65             throws DatabaseException {
66         Class<?> clazz = resolveClass();
67         return clazz != null && clazz.isInstance(content);
68     }
69
70 }