|
| 1 | +package org.geoscript.js.index; |
| 2 | + |
| 3 | +import org.geoscript.js.GeoObject; |
| 4 | +import org.geoscript.js.index.*; |
| 5 | +import org.mozilla.javascript.Scriptable; |
| 6 | +import org.mozilla.javascript.ScriptableObject; |
| 7 | + |
| 8 | +import java.lang.reflect.InvocationTargetException; |
| 9 | +import java.util.Arrays; |
| 10 | +import java.util.HashMap; |
| 11 | +import java.util.List; |
| 12 | + |
| 13 | +public class Module { |
| 14 | + |
| 15 | + static HashMap<String, Scriptable> prototypes; |
| 16 | + |
| 17 | + /** |
| 18 | + * Define all geometry constructors in the given module scope. If the |
| 19 | + * provided scope is not a "top level" scope, constructors will be defined |
| 20 | + * in the top level scope for the given scope. |
| 21 | + * @param scope |
| 22 | + * @throws IllegalAccessException |
| 23 | + * @throws InstantiationException |
| 24 | + * @throws InvocationTargetException |
| 25 | + */ |
| 26 | + public static void init(Scriptable scope) throws IllegalAccessException, InstantiationException, InvocationTargetException { |
| 27 | + |
| 28 | + scope = ScriptableObject.getTopLevelScope(scope); |
| 29 | + |
| 30 | + @SuppressWarnings("unchecked") |
| 31 | + List<Class<? extends GeoObject>> classes = Arrays.asList(Quadtree.class, STRtree.class); |
| 32 | + |
| 33 | + prototypes = new HashMap<String, Scriptable>(); |
| 34 | + for (Class<? extends GeoObject> cls : classes) { |
| 35 | + String name = ScriptableObject.defineClass(scope, cls, false, true); |
| 36 | + Scriptable prototype = ScriptableObject.getClassPrototype(scope, name); |
| 37 | + prototypes.put(name, prototype); |
| 38 | + } |
| 39 | + |
| 40 | + } |
| 41 | + |
| 42 | + protected static Scriptable getClassPrototype(Class<? extends GeoObject> cls) { |
| 43 | + String name = cls.getName(); |
| 44 | + if (prototypes == null || !prototypes.containsKey(name)) { |
| 45 | + throw new RuntimeException( |
| 46 | + "Attempt to access prototype before requiring module: " + name); |
| 47 | + } |
| 48 | + return prototypes.get(name); |
| 49 | + } |
| 50 | + |
| 51 | +} |
0 commit comments