summaryrefslogtreecommitdiffstats
path: root/embedding/java/src/org/uscxml/datamodel/ecmascript/ECMAScriptDataModel.java
blob: 679581dedaa145c22d0f23303bf85b996d7661ad (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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package org.uscxml.datamodel.ecmascript;

import java.lang.reflect.Method;
import java.util.Map;

import org.mozilla.javascript.Callable;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.EvaluatorException;
import org.mozilla.javascript.FunctionObject;
import org.mozilla.javascript.NativeJSON;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.Undefined;
import org.uscxml.Data;
import org.uscxml.DataModel;
import org.uscxml.Event;
import org.uscxml.Interpreter;
import org.uscxml.NativeIOProcessor;
import org.uscxml.NativeInvoker;
import org.uscxml.StringList;

public class ECMAScriptDataModel extends DataModel {

	public static boolean debug = true;
	
	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 Interpreter interpreter;

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

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

		return data;
	}

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

	public static boolean jsIn(String stateName) {
		return true;
	}

	@Override
	public DataModel 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.swigReleaseOwnership();
		newDM.interpreter = interpreter;
		newDM.ctx = Context.enter();

		try {
			newDM.scope = newDM.ctx.initStandardObjects();
		} catch (Exception e) {
			System.err.println(e);
		}

		newDM.scope.put("_name", newDM.scope, interpreter.getName());
		newDM.scope.put("_sessionid", newDM.scope, interpreter.getSessionId());

		// ioProcessors
		{
			Data ioProcs = new Data();
			Map<String, NativeIOProcessor> ioProcNatives = interpreter.getIOProcessors();
			for (String key : ioProcNatives.keySet()) {
				ioProcs.put(key, ioProcNatives.get(key).getDataModelVariables());
			}
			newDM.scope
					.put("_ioprocessors", newDM.scope, new ECMAData(ioProcs));
		}

		// invokers
		{
			Data invokers = new Data();
			Map<String, NativeInvoker> invokersNatives = interpreter.getInvokers();
			for (String key : invokersNatives.keySet()) {
				invokers.put(key, invokersNatives.get(key).getDataModelVariables());
			}
			newDM.scope
					.put("_ioprocessors", newDM.scope, new ECMAData(invokers));
		}
		
		// In predicate (not working as static is required) see:
		// http://stackoverflow.com/questions/3441947/how-do-i-call-a-method-of-a-java-instance-from-javascript/16479685#16479685
		try {
			Class[] parameters = new Class[] { String.class };
			Method inMethod = ECMAScriptDataModel.class.getMethod("jsIn",
					parameters);
			FunctionObject inFunc = new FunctionObject("In", inMethod,
					newDM.scope);
			newDM.scope.put("In", newDM.scope, inFunc);
		} catch (SecurityException e) {
			System.err.println(e);
		} catch (NoSuchMethodException e) {
			System.err.println(e);
		}

		return newDM;
	}

	@Override
	public StringList getNames() {
		/**
		 * Register with the following names for the datamodel attribute at the
		 * scxml element. <scxml datamodel="one of these">
		 */
		StringList ss = new StringList();
		ss.add("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) {
		if (debug) {
			System.out.println(interpreter.getName() + " setEvent");
		}
		
		/**
		 * Make the current event available as the variable _event in the
		 * datamodel.
		 */
		ECMAEvent ecmaEvent = new ECMAEvent(event);
		scope.put("_event", scope, ecmaEvent);
	}

	@Override
	public Data getStringAsData(String content) {
		if (debug) {
			System.out.println(interpreter.getName() + " getStringAsData");
		}

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

		// is it a json expression?
		try {
			Object json = NativeJSON.parse(ctx, scope, content,
					new NullCallable());
			if (json != NativeJSON.NOT_FOUND) {
				return getScriptableAsData(json);
			}
		} catch (org.mozilla.javascript.EcmaError e) {
			System.err.println(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 getScriptableAsData(x);
	}

	@Override
	public long getLength(String expr) {
		if (debug) {
			System.out.println(interpreter.getName() + " getLength");
		}

		/**
		 * 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) {
		if (debug) {
			System.out.println(interpreter.getName() + " setForeach");
		}

		/**
		 * 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 {
				handleException("");
			}

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

	@Override
	public void eval(String scriptElem, String expr) {
		if (debug) {
			System.out.println(interpreter.getName() + " eval");
		}

		/**
		 * 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) {
		if (debug) {
			System.out.println(interpreter.getName() + " evalAsString: " + expr);
		}

		/**
		 * Evaluate the expression as a string e.g. for the log element.
		 */
		if (!ctx.stringIsCompilableUnit(expr)) {
			handleException("");
			return "";
		}
		try {
			Object result = ctx.evaluateString(scope, expr, "uscxml", 1, null);
			return Context.toString(result);
		} catch (IllegalStateException e) {
			System.err.println(e);
			handleException("");
		} catch (EvaluatorException e) {
			System.err.println(e);
			handleException("");
		}
		return "";
	}

	@Override
	public boolean evalAsBool(String elem, String expr) {
		if (debug) {
			System.out.println(interpreter.getName() + " evalAsBool");
		}

		/**
		 * 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) {
		if (debug) {
			System.out.println(interpreter.getName() + " isDeclared");
		}

		/**
		 * 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) {
		if (debug) {
			System.out.println(interpreter.getName() + " init");
		}

		/**
		 * 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) {
		if (debug) {
			System.out.println(interpreter.getName() + " assign");
		}

		/**
		 * 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);
	}

	public void handleException(String cause) {
		Event exceptionEvent = new Event();
		exceptionEvent.setName("error.execution");
		exceptionEvent.setEventType(Event.Type.PLATFORM);

		interpreter.receiveInternal(exceptionEvent);
	}
}