1 16 package org.apache.cocoon.components.flow.javascript; 17 18 import org.apache.commons.jxpath.DynamicPropertyHandler; 19 import org.mozilla.javascript.Context; 20 import org.mozilla.javascript.Function; 21 import org.mozilla.javascript.JavaScriptException; 22 import org.mozilla.javascript.Scriptable; 23 import org.mozilla.javascript.ScriptableObject; 24 import org.mozilla.javascript.Undefined; 25 import org.mozilla.javascript.Wrapper; 26 27 31 public class ScriptablePropertyHandler implements DynamicPropertyHandler { 32 33 public Object getProperty(Object obj, String propertyName) { 34 Context cx = null; 35 try { 36 cx = Context.enter(); 37 Scriptable s = (Scriptable)obj; 38 Object result = ScriptableObject.getProperty(s, propertyName); 39 if (result == Scriptable.NOT_FOUND) { 40 result = ScriptableObject.getProperty(s, "get" + propertyName.substring(0, 1).toUpperCase() + (propertyName.length() > 1 ? propertyName.substring(1) : "")); 41 if (result != Scriptable.NOT_FOUND && 42 result instanceof Function) { 43 try { 44 result = ((Function)result).call(cx, 45 ScriptableObject.getTopLevelScope(s), s, new Object [] {}); 46 } catch (JavaScriptException exc) { 47 exc.printStackTrace(); 48 result = Undefined.instance; 49 } 50 } 51 if (result == Undefined.instance || 52 result == Scriptable.NOT_FOUND) { 53 result = null; 54 } 55 } else if (result instanceof Wrapper) { 56 result = ((Wrapper)result).unwrap(); 57 } else if (result == Undefined.instance) { 58 result = null; 59 } 60 return result; 61 } finally { 62 Context.exit(); 63 } 64 } 65 66 public String [] getPropertyNames(Object obj) { 67 Context.enter(); 68 try { 69 Object [] ids; 70 if (obj instanceof ScriptableObject) { 71 ids = ((ScriptableObject)obj).getAllIds(); 72 } else { 73 ids = ((Scriptable)obj).getIds(); 74 } 75 String [] result = new String [ids.length]; 76 for (int i = 0; i < result.length; i++) { 77 result[i] = (String )ids[i]; 78 } 79 return result; 80 } finally { 81 Context.exit(); 82 } 83 } 84 85 public void setProperty(Object obj, String propertyName, 86 Object value) { 87 Context.enter(); 88 try { 89 if (!(value == null 90 || value instanceof String 91 || value instanceof Number 92 || value instanceof Boolean )) { 93 value = Context.toObject(value, 94 (Scriptable)obj); 95 } 96 ScriptableObject.putProperty((Scriptable)obj, 97 propertyName, value); 98 } finally { 99 Context.exit(); 100 } 101 } 102 } 103 | Popular Tags |