summaryrefslogtreecommitdiffstats
path: root/contrib/java/src/org/uscxml/datamodel/ecmascript/ECMAScriptDataModel.java
blob: e3f4f2c245b0e0bef2fe824ff038c50e3eb839d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package org.uscxml.datamodel.ecmascript;

import org.mozilla.javascript.Callable;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.NativeJSON;
import org.mozilla.javascript.NativeJavaObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.Undefined;
import org.uscxml.Data;
import org.uscxml.DataNative;
import org.uscxml.Event;
import org.uscxml.Interpreter;
import org.uscxml.JavaDataModel;
import org.uscxml.StringSet;

public class ECMAScriptDataModel extends JavaDataModel {

	private class NullCallable implements Callable {
		@Override
		public Object call(Context context, Scriptable scope,
				Scriptable holdable, Object[] objects) {
			return objects[1];
		}
	}

	public Context ctx;
	public Scriptable scope;

	public Data getScriptableAsData(Object object) {
		Data data = new Data();

		Scriptable s;
		try {
			s = (Scriptable) object;
			String className = s.getClassName(); // ECMA class name
//			System.out.println("Scriptable: " + className);
			if (className.toLowerCase().equals("object")) {
				ScriptableObject obj = (ScriptableObject) Context.toObject(s,
						scope);
				for (Object key : obj.getIds()) {
					data.compound.put(Context.toString(key),
							getScriptableAsData(obj.get(key)));
				}
			}
		} catch (ClassCastException e) {
			if (object instanceof Boolean) {
				data.atom = (Context.toBoolean(object) ? "true" : "false");
				data.type = Data.Type.INTERPRETED;
			} else if (object instanceof String) {
				data.atom = (String) object;
				data.type = Data.Type.VERBATIM;
			} else if (object instanceof Integer) {
				data.atom = ((Integer) object).toString();
				data.type = Data.Type.INTERPRETED;
			} else {
				throw new RuntimeException("Unhandled ECMA type "
						+ object.getClass().getName());
			}
		}

		return data;
	}

	public ScriptableObject getDataAsScriptable(Data data) {
		// TODO!
		throw new UnsupportedOperationException("Not implemented");
	}

	@Override
	public JavaDataModel create(Interpreter interpreter) {
		/**
		 * Called when an SCXML interpreter wants an instance of this datamodel
		 * Be careful to instantiate attributes of instance returned and not
		 * *this*
		 */
		ECMAScriptDataModel newDM = new ECMAScriptDataModel();

		newDM.ctx = Context.enter();
		try {
			newDM.scope = newDM.ctx.initStandardObjects();
//          ScriptableObject.defineClass(newDM.scope, ECMAEvent.class);
//          ScriptableObject.defineClass(newDM.scope, ECMAEventScriptable.class);
		} catch (Exception e) {
			System.err.println(e);
		}

		return newDM;
	}

	@Override
	public StringSet getNames() {
		/**
		 * Register with the following names for the datamodel attribute at the
		 * scxml element. <scxml datamodel="one of these">
		 */
		StringSet ss = new StringSet();
		ss.insert("ecmascript");
		return ss;
	}

	@Override
	public boolean validate(String location, String schema) {
		/**
		 * Validate the datamodel. This make more sense for XML datamodels and
		 * is pretty much unused but required as per draft.
		 */
		return true;
	}

	@Override
	public void setEvent(Event event) {
		/**
		 * Make the current event available as the variable _event in the
		 * datamodel.
		 */

		Data data = new Data(event.getData());
		
//		Object[] args = { event };
//        Scriptable ecmaEvent = ctx.newObject(scope, "Event", args);

//		ECMAEvent ecmaEvent = new ECMAEvent(event);
//		NativeJavaObject njo = new NativeJavaObject(scope, ecmaEvent, ECMAEvent.class, true);

		ECMAEvent ecmaEvent = new ECMAEvent(event);

//		for (Object key : ecmaEvent.getIds()) {
//			System.out.println(key);
//		}
		
		scope.put("_event", scope, ecmaEvent);
	}

	@Override
	public DataNative getStringAsData(String content) {
		/**
		 * Evaluate the string as a value expression and transform it into a
		 * JSON-like Data structure
		 */
		if (content.length() == 0) {
			return Data.toNative(new Data());
		}

		// is it a json expression?
		try {
			Object json = NativeJSON.parse(ctx, scope, content,
					new NullCallable());
			if (json != NativeJSON.NOT_FOUND) {
				return Data.toNative(getScriptableAsData(json));
			}
		} catch (org.mozilla.javascript.EcmaError e) {
		}
		
		// is it a function call or variable?
		Object x = ctx.evaluateString(scope, content, "uscxml", 0, null);
		if (x == Undefined.instance) {
			// maybe a literal string?
			x = ctx.evaluateString(scope, '"' + content + '"', "uscxml", 0,
					null);
		}
		return Data.toNative(getScriptableAsData(x));
	}

	@Override
	public long getLength(String expr) {
		/**
		 * Return the length of the expression if it were an array, used by
		 * foreach element.
		 */

		Object x = scope.get(expr, scope);
		if (x == Undefined.instance) {
			return 0;
		}

		Scriptable result = Context.toObject(x, scope);
		if (result.has("length", result)) {
			return (long) Context.toNumber(result.get("length", result));
		}
		return 0;
	}

	@Override
	public void setForeach(String item, String array, String index,
			long iteration) {
		/**
		 * Prepare an iteration of the foreach element, by setting the variable
		 * in index to the current iteration and setting the variable in item to
		 * the current item from array.
		 */

		try {
			// get the array object
			Scriptable arr = (Scriptable) scope.get(array, scope);

			if (arr.has((int) iteration, arr)) {
				ctx.evaluateString(scope, item + '=' + array + '[' + iteration
						+ ']', "uscxml", 1, null);
				if (index.length() > 0) {
					ctx.evaluateString(scope, index + '=' + iteration,
							"uscxml", 1, null);
				}
			} else {
				// we ought to throw a error.execution
			}

		} catch (ClassCastException e) {
			System.err.println(e);
		}
	}

	@Override
	public void eval(String scriptElem, String expr) {
		/**
		 * Evaluate the given expression in the datamodel. This is used foremost
		 * with script elements.
		 */
		ctx.evaluateString(scope, expr, "uscxml", 1, null);

	}

	@Override
	public String evalAsString(String expr) {
		/**
		 * Evaluate the expression as a string e.g. for the log element.
		 */
		Object result = ctx.evaluateString(scope, expr, "uscxml", 1, null);
		return Context.toString(result);
	}

	@Override
	public boolean evalAsBool(String elem, String expr) {
		/**
		 * Evaluate the expression as a boolean for cond attributes in if and
		 * transition elements.
		 */
		Object result = ctx.evaluateString(scope, expr, "uscxml", 1, null);
		return Context.toBoolean(result);
	}

	@Override
	public boolean isDeclared(String expr) {
		/**
		 * The interpreter is supposed to raise an error if we assign to an
		 * undeclared variable. This method is used to check whether a location
		 * from assign is declared.
		 */
		Object x = scope.get(expr, scope);
		return x != Scriptable.NOT_FOUND;
	}

	@Override
	public void init(String dataElem, String location, String content) {
		/**
		 * Called when we pass data elements.
		 */
		if (("null").equals(location))
			return;

		if (("null").equals(content) || content.length() == 0) {
			scope.put(location, scope, Context.getUndefinedValue());
			return;
		}

		try {
			Object json = NativeJSON.parse(ctx, scope, content,
					new NullCallable());
			if (json != NativeJSON.NOT_FOUND) {
				scope.put(location, scope, json);
			} else {
				scope.put(location, scope, content);
			}
		} catch (org.mozilla.javascript.EcmaError e) {
			scope.put(location, scope, content);
		}
	}

	@Override
	public void assign(String assignElem, String location, String content) {
		/**
		 * Called when we evaluate assign elements
		 */
		if (("null").equals(location))
			return;

		if (("null").equals(content) || content.length() == 0) {
			scope.put(location, scope, Context.getUndefinedValue());
			return;
		}

		String expr = location + "=" + content;
		ctx.evaluateString(scope, expr, "uscxml", 1, null);		
	}

}