mobile/android/base/tests/helpers/JavascriptBridge.java

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

michael@0 1 /* This Source Code Form is subject to the terms of the Mozilla Public
michael@0 2 * License, v. 2.0. If a copy of the MPL was not distributed with this
michael@0 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
michael@0 4
michael@0 5 package org.mozilla.gecko.tests.helpers;
michael@0 6
michael@0 7 import java.lang.reflect.InvocationTargetException;
michael@0 8 import java.lang.reflect.Method;
michael@0 9
michael@0 10 import junit.framework.AssertionFailedError;
michael@0 11
michael@0 12 import org.json.JSONArray;
michael@0 13 import org.json.JSONException;
michael@0 14 import org.json.JSONObject;
michael@0 15
michael@0 16 import org.mozilla.gecko.Actions;
michael@0 17 import org.mozilla.gecko.Actions.EventExpecter;
michael@0 18 import org.mozilla.gecko.Assert;
michael@0 19 import org.mozilla.gecko.tests.UITestContext;
michael@0 20
michael@0 21 /**
michael@0 22 * Javascript bridge allows calls to and from JavaScript.
michael@0 23 *
michael@0 24 * To establish communication, create an instance of JavascriptBridge in Java and pass in
michael@0 25 * an object that will receive calls from JavaScript. For example:
michael@0 26 *
michael@0 27 * {@code final JavascriptBridge js = new JavascriptBridge(javaObj);}
michael@0 28 *
michael@0 29 * Next, create an instance of JavaBridge in JavaScript and pass in another object
michael@0 30 * that will receive calls from Java. For example:
michael@0 31 *
michael@0 32 * {@code let java = new JavaBridge(jsObj);}
michael@0 33 *
michael@0 34 * Once a link is established, calls can be made using the methods syncCall and asyncCall.
michael@0 35 * syncCall waits for the call to finish before returning. For example:
michael@0 36 *
michael@0 37 * {@code js.syncCall("abc", 1, 2, 3);} will synchronously call the JavaScript method
michael@0 38 * jsObj.abc and pass in arguments 1, 2, and 3.
michael@0 39 *
michael@0 40 * {@code java.asyncCall("def", 4, 5, 6);} will asynchronously call the Java method
michael@0 41 * javaObj.def and pass in arguments 4, 5, and 6.
michael@0 42 *
michael@0 43 * Supported argument types include int, double, boolean, String, and JSONObject. Note
michael@0 44 * that only implicit conversion is done, meaning if a floating point argument is passed
michael@0 45 * from JavaScript to Java, the call will fail if the Java method has an int argument.
michael@0 46 *
michael@0 47 * Because JavascriptBridge and JavaBridge use one underlying communication channel,
michael@0 48 * creating multiple instances of them will not create independent links.
michael@0 49 *
michael@0 50 * Note also that because Robocop tests finish as soon as the Java test method returns,
michael@0 51 * the last call to JavaScript from Java must be a synchronous call. Otherwise, the test
michael@0 52 * will finish before the JavaScript method is run. Calls to Java from JavaScript do not
michael@0 53 * have this requirement. Because of these considerations, calls from Java to JavaScript
michael@0 54 * are usually synchronous and calls from JavaScript to Java are usually asynchronous.
michael@0 55 * See testJavascriptBridge.java for examples.
michael@0 56 */
michael@0 57 public final class JavascriptBridge {
michael@0 58
michael@0 59 private static enum MessageStatus {
michael@0 60 QUEUE_EMPTY, // Did not process a message; queue was empty.
michael@0 61 PROCESSED, // A message other than sync was processed.
michael@0 62 REPLIED, // A sync message was processed.
michael@0 63 SAVED, // An async message was saved; see processMessage().
michael@0 64 };
michael@0 65
michael@0 66 @SuppressWarnings("serial")
michael@0 67 public static class CallException extends RuntimeException {
michael@0 68 public CallException() {
michael@0 69 super();
michael@0 70 }
michael@0 71
michael@0 72 public CallException(final String msg) {
michael@0 73 super(msg);
michael@0 74 }
michael@0 75
michael@0 76 public CallException(final String msg, final Throwable e) {
michael@0 77 super(msg, e);
michael@0 78 }
michael@0 79
michael@0 80 public CallException(final Throwable e) {
michael@0 81 super(e);
michael@0 82 }
michael@0 83 }
michael@0 84
michael@0 85 public static final String EVENT_TYPE = "Robocop:JS";
michael@0 86
michael@0 87 private static Actions sActions;
michael@0 88 private static Assert sAsserter;
michael@0 89
michael@0 90 // Target of JS-to-Java calls
michael@0 91 private final Object mTarget;
michael@0 92 // List of public methods in subclass
michael@0 93 private final Method[] mMethods;
michael@0 94 // Parser for handling xpcshell assertions
michael@0 95 private final JavascriptMessageParser mLogParser;
michael@0 96 // Expecter of our internal Robocop event
michael@0 97 private final EventExpecter mExpecter;
michael@0 98 // Saved async message; see processMessage() for its purpose.
michael@0 99 private JSONObject mSavedAsyncMessage;
michael@0 100 // Number of levels in the synchronous call stack
michael@0 101 private int mCallStackDepth;
michael@0 102 // If JavaBridge has been loaded
michael@0 103 private boolean mJavaBridgeLoaded;
michael@0 104
michael@0 105 /* package */ static void init(final UITestContext context) {
michael@0 106 sActions = context.getActions();
michael@0 107 sAsserter = context.getAsserter();
michael@0 108 }
michael@0 109
michael@0 110 public JavascriptBridge(final Object target) {
michael@0 111 mTarget = target;
michael@0 112 mMethods = target.getClass().getMethods();
michael@0 113 mExpecter = sActions.expectGeckoEvent(EVENT_TYPE);
michael@0 114 // The JS here is unrelated to a test harness, so we
michael@0 115 // have our message parser end on assertion failure.
michael@0 116 mLogParser = new JavascriptMessageParser(sAsserter, true);
michael@0 117 }
michael@0 118
michael@0 119 /**
michael@0 120 * Synchronously calls a method in Javascript.
michael@0 121 *
michael@0 122 * @param method Name of the method to call
michael@0 123 * @param args Arguments to pass to the Javascript method; must be a list of
michael@0 124 * values allowed by JSONObject.
michael@0 125 */
michael@0 126 public void syncCall(final String method, final Object... args) {
michael@0 127 mCallStackDepth++;
michael@0 128
michael@0 129 sendMessage("sync-call", method, args);
michael@0 130 try {
michael@0 131 while (processPendingMessage() != MessageStatus.REPLIED) {
michael@0 132 }
michael@0 133 } catch (final AssertionFailedError e) {
michael@0 134 // Most likely an event expecter time out
michael@0 135 throw new CallException("Cannot call " + method, e);
michael@0 136 }
michael@0 137
michael@0 138 // If syncCall was called reentrantly from processPendingMessage(), mCallStackDepth
michael@0 139 // will be greater than 1 here. In that case we don't have to wait for pending calls
michael@0 140 // because the outermost syncCall will do it for us.
michael@0 141 if (mCallStackDepth == 1) {
michael@0 142 // We want to wait for all asynchronous calls to finish,
michael@0 143 // because the test may end immediately after this method returns.
michael@0 144 finishPendingCalls();
michael@0 145 }
michael@0 146 mCallStackDepth--;
michael@0 147 }
michael@0 148
michael@0 149 /**
michael@0 150 * Asynchronously calls a method in Javascript.
michael@0 151 *
michael@0 152 * @param method Name of the method to call
michael@0 153 * @param args Arguments to pass to the Javascript method; must be a list of
michael@0 154 * values allowed by JSONObject.
michael@0 155 */
michael@0 156 public void asyncCall(final String method, final Object... args) {
michael@0 157 sendMessage("async-call", method, args);
michael@0 158 }
michael@0 159
michael@0 160 /**
michael@0 161 * Disconnect the bridge.
michael@0 162 */
michael@0 163 public void disconnect() {
michael@0 164 mExpecter.unregisterListener();
michael@0 165 }
michael@0 166
michael@0 167 /**
michael@0 168 * Process a new message; wait for new message if necessary.
michael@0 169 *
michael@0 170 * @return MessageStatus value to indicate result of processing the message
michael@0 171 */
michael@0 172 private MessageStatus processPendingMessage() {
michael@0 173 // We're on the test thread.
michael@0 174 // We clear mSavedAsyncMessage in maybeProcessPendingMessage() but not here,
michael@0 175 // because we always have a new message for processing here, so we never
michael@0 176 // get a chance to clear mSavedAsyncMessage.
michael@0 177 try {
michael@0 178 final String message = mExpecter.blockForEventData();
michael@0 179 return processMessage(new JSONObject(message));
michael@0 180 } catch (final JSONException e) {
michael@0 181 throw new IllegalStateException("Invalid message", e);
michael@0 182 }
michael@0 183 }
michael@0 184
michael@0 185 /**
michael@0 186 * Process a message if a new or saved message is available.
michael@0 187 *
michael@0 188 * @return MessageStatus value to indicate result of processing the message
michael@0 189 */
michael@0 190 private MessageStatus maybeProcessPendingMessage() {
michael@0 191 // We're on the test thread.
michael@0 192 final String message = mExpecter.blockForEventDataWithTimeout(0);
michael@0 193 if (message != null) {
michael@0 194 try {
michael@0 195 return processMessage(new JSONObject(message));
michael@0 196 } catch (final JSONException e) {
michael@0 197 throw new IllegalStateException("Invalid message", e);
michael@0 198 }
michael@0 199 }
michael@0 200 if (mSavedAsyncMessage != null) {
michael@0 201 // processMessage clears mSavedAsyncMessage.
michael@0 202 return processMessage(mSavedAsyncMessage);
michael@0 203 }
michael@0 204 return MessageStatus.QUEUE_EMPTY;
michael@0 205 }
michael@0 206
michael@0 207 /**
michael@0 208 * Wait for all asynchronous messages from Javascript to be processed.
michael@0 209 */
michael@0 210 private void finishPendingCalls() {
michael@0 211 MessageStatus result;
michael@0 212 do {
michael@0 213 result = maybeProcessPendingMessage();
michael@0 214 if (result == MessageStatus.REPLIED) {
michael@0 215 throw new IllegalStateException("Sync reply was unexpected");
michael@0 216 }
michael@0 217 } while (result != MessageStatus.QUEUE_EMPTY);
michael@0 218 }
michael@0 219
michael@0 220 private void ensureJavaBridgeLoaded() {
michael@0 221 while (!mJavaBridgeLoaded) {
michael@0 222 processPendingMessage();
michael@0 223 }
michael@0 224 }
michael@0 225
michael@0 226 private void sendMessage(final String innerType, final String method, final Object[] args) {
michael@0 227 ensureJavaBridgeLoaded();
michael@0 228
michael@0 229 // Call from Java to Javascript
michael@0 230 final JSONObject message = new JSONObject();
michael@0 231 final JSONArray jsonArgs = new JSONArray();
michael@0 232 try {
michael@0 233 if (args != null) {
michael@0 234 for (final Object arg : args) {
michael@0 235 jsonArgs.put(convertToJSONValue(arg));
michael@0 236 }
michael@0 237 }
michael@0 238 message.put("type", EVENT_TYPE)
michael@0 239 .put("innerType", innerType)
michael@0 240 .put("method", method)
michael@0 241 .put("args", jsonArgs);
michael@0 242 } catch (final JSONException e) {
michael@0 243 throw new IllegalStateException("Unable to create JSON message", e);
michael@0 244 }
michael@0 245 sActions.sendGeckoEvent(EVENT_TYPE, message.toString());
michael@0 246 }
michael@0 247
michael@0 248 private MessageStatus processMessage(JSONObject message) {
michael@0 249 final String type;
michael@0 250 final String methodName;
michael@0 251 final JSONArray argsArray;
michael@0 252 final Object[] args;
michael@0 253 try {
michael@0 254 if (!EVENT_TYPE.equals(message.getString("type"))) {
michael@0 255 throw new IllegalStateException("Message type is not " + EVENT_TYPE);
michael@0 256 }
michael@0 257 type = message.getString("innerType");
michael@0 258
michael@0 259 if ("progress".equals(type)) {
michael@0 260 // Javascript harness message
michael@0 261 mLogParser.logMessage(message.getString("message"));
michael@0 262 return MessageStatus.PROCESSED;
michael@0 263
michael@0 264 } else if ("notify-loaded".equals(type)) {
michael@0 265 mJavaBridgeLoaded = true;
michael@0 266 return MessageStatus.PROCESSED;
michael@0 267
michael@0 268 } else if ("sync-reply".equals(type)) {
michael@0 269 // Reply to Java-to-Javascript sync call
michael@0 270 return MessageStatus.REPLIED;
michael@0 271
michael@0 272 } else if ("sync-call".equals(type) || "async-call".equals(type)) {
michael@0 273
michael@0 274 if ("async-call".equals(type)) {
michael@0 275 // Save this async message until another async message arrives, then we
michael@0 276 // process the saved message and save the new one. This is done as a
michael@0 277 // form of tail call optimization, by making sync-replies come before
michael@0 278 // async-calls. On the other hand, if (message == mSavedAsyncMessage),
michael@0 279 // it means we're currently processing the saved message and should clear
michael@0 280 // mSavedAsyncMessage.
michael@0 281 final JSONObject newSavedMessage =
michael@0 282 (message != mSavedAsyncMessage ? message : null);
michael@0 283 message = mSavedAsyncMessage;
michael@0 284 mSavedAsyncMessage = newSavedMessage;
michael@0 285 if (message == null) {
michael@0 286 // Saved current message and there wasn't an already saved one.
michael@0 287 return MessageStatus.SAVED;
michael@0 288 }
michael@0 289 }
michael@0 290
michael@0 291 methodName = message.getString("method");
michael@0 292 argsArray = message.getJSONArray("args");
michael@0 293 args = new Object[argsArray.length()];
michael@0 294 for (int i = 0; i < args.length; i++) {
michael@0 295 args[i] = convertFromJSONValue(argsArray.get(i));
michael@0 296 }
michael@0 297 invokeMethod(methodName, args);
michael@0 298
michael@0 299 if ("sync-call".equals(type)) {
michael@0 300 // Reply for sync messages
michael@0 301 sendMessage("sync-reply", methodName, null);
michael@0 302 }
michael@0 303 return MessageStatus.PROCESSED;
michael@0 304 }
michael@0 305 throw new IllegalStateException("Message type is unexpected");
michael@0 306
michael@0 307 } catch (final JSONException e) {
michael@0 308 throw new IllegalStateException("Unable to retrieve JSON message", e);
michael@0 309 }
michael@0 310 }
michael@0 311
michael@0 312 /**
michael@0 313 * Given a method name and a list of arguments,
michael@0 314 * call the most suitable method in the subclass.
michael@0 315 */
michael@0 316 private Object invokeMethod(final String methodName, final Object[] args) {
michael@0 317 final Class<?>[] argTypes = new Class<?>[args.length];
michael@0 318 for (int i = 0; i < argTypes.length; i++) {
michael@0 319 if (args[i] == null) {
michael@0 320 argTypes[i] = Object.class;
michael@0 321 } else {
michael@0 322 argTypes[i] = args[i].getClass();
michael@0 323 }
michael@0 324 }
michael@0 325
michael@0 326 // Try using argument types directly without casting.
michael@0 327 try {
michael@0 328 return invokeMethod(mTarget.getClass().getMethod(methodName, argTypes), args);
michael@0 329 } catch (final NoSuchMethodException e) {
michael@0 330 // getMethod() failed; try fallback below.
michael@0 331 }
michael@0 332
michael@0 333 // One scenario for getMethod() to fail above is that we don't have the exact
michael@0 334 // argument types in argTypes (e.g. JS gave us an int but we're using a double,
michael@0 335 // or JS gave us a null and we don't know its intended type), or the number of
michael@0 336 // arguments is incorrect. Now we find all the methods with the given name and
michael@0 337 // try calling them one-by-one. If one call fails, we move to the next call.
michael@0 338 // Java will try to convert our arguments to the right types.
michael@0 339 Throwable lastException = null;
michael@0 340 for (final Method method : mMethods) {
michael@0 341 if (!method.getName().equals(methodName)) {
michael@0 342 continue;
michael@0 343 }
michael@0 344 try {
michael@0 345 return invokeMethod(method, args);
michael@0 346 } catch (final IllegalArgumentException e) {
michael@0 347 lastException = e;
michael@0 348 // Try the next method
michael@0 349 } catch (final UnsupportedOperationException e) {
michael@0 350 // "Cannot access method" exception below, see if there are other public methods
michael@0 351 lastException = e;
michael@0 352 // Try the next method
michael@0 353 }
michael@0 354 }
michael@0 355 // Now we're out of options
michael@0 356 throw new UnsupportedOperationException(
michael@0 357 "Cannot call method " + methodName + " (not public? wrong argument types?)",
michael@0 358 lastException);
michael@0 359 }
michael@0 360
michael@0 361 private Object invokeMethod(final Method method, final Object[] args) {
michael@0 362 try {
michael@0 363 return method.invoke(mTarget, args);
michael@0 364 } catch (final IllegalAccessException e) {
michael@0 365 throw new UnsupportedOperationException(
michael@0 366 "Cannot access method " + method.getName(), e);
michael@0 367 } catch (final InvocationTargetException e) {
michael@0 368 final Throwable cause = e.getCause();
michael@0 369 if (cause instanceof CallException) {
michael@0 370 // Don't wrap CallExceptions; this can happen if a call is nested on top
michael@0 371 // of existing sync calls, and the nested call throws a CallException
michael@0 372 throw (CallException) cause;
michael@0 373 }
michael@0 374 throw new CallException("Failed to invoke " + method.getName(), cause);
michael@0 375 }
michael@0 376 }
michael@0 377
michael@0 378 private Object convertFromJSONValue(final Object value) {
michael@0 379 if (value == JSONObject.NULL) {
michael@0 380 return null;
michael@0 381 }
michael@0 382 return value;
michael@0 383 }
michael@0 384
michael@0 385 private Object convertToJSONValue(final Object value) {
michael@0 386 if (value == null) {
michael@0 387 return JSONObject.NULL;
michael@0 388 }
michael@0 389 return value;
michael@0 390 }
michael@0 391 }

mercurial