/** * Calls JavaScript native function. * * @param function Function to be called. * @param args Call arguments. */ public static void call(final Function function, final Object... args) { Scriptable scope = function.getParentScope(); ObjectTopLevel topLevel = JavaScriptEngine.getObjectTopLevel(scope); if (topLevel != null) { Context cx = topLevel.getBrowserScriptEngine().enterContext(); try { function.call(cx, scope, scope, args); } catch (Exception ex) { try { JavaScriptEngine.throwWrappedScriptException(ex); } catch (ScriptException e) { throw new WrappedException(e); } } finally { Context.exit(); } } }
/** * Since a continuation can only capture JavaScript frames and not Java * frames, ensure that Rhino throws an exception when the JavaScript frames * don't reach all the way to the code called by * executeScriptWithContinuations or callFunctionWithContinuations. */ public void testErrorOnEvalCall() { Context cx = Context.enter(); try { cx.setOptimizationLevel(-1); // must use interpreter mode Script script = cx.compileString("eval('myObject.f(3);');", "test source", 1, null); cx.executeScriptWithContinuations(script, globalScope); fail("Should throw IllegalStateException"); } catch (WrappedException we) { Throwable t = we.getWrappedException(); assertTrue(t instanceof IllegalStateException); assertTrue(t.getMessage().startsWith("Cannot capture continuation")); } finally { Context.exit(); } }
/** * Calls {@link Callable#call(Context, Scriptable, Scriptable, Object[])} of * <code>callable</code> under restricted security domain where an action is * allowed only if it is allowed according to the Java stack on the * moment of the <code>callWithDomain</code> call and * <code>securityDomain</code>. Any call to * {@link #getDynamicSecurityDomain(Object)} during execution of * {@link Callable#call(Context, Scriptable, Scriptable, Object[])} * should return a domain incorporate restrictions imposed by * <code>securityDomain</code>. */ public Object callWithDomain(Object securityDomain, final Context cx, final Callable callable, final Scriptable scope, final Scriptable thisObj, final Object[] args) { AccessControlContext acc; if (securityDomain instanceof AccessControlContext) acc = (AccessControlContext)securityDomain; else { RhinoClassLoader loader = (RhinoClassLoader)securityDomain; acc = loader.rhinoAccessControlContext; } PrivilegedExceptionAction execAction = new PrivilegedExceptionAction() { public Object run() { return callable.call(cx, scope, thisObj, args); } }; try { return AccessController.doPrivileged(execAction, acc); } catch (Exception e) { throw new WrappedException(e); } }
public Object call( Context cx, Scriptable scope, Scriptable thisObj, java.lang.Object[] args ) { Object[] convertedArgs = JavascriptEvalUtil .convertToJavaObjects( args ); try { if ( convertedArgs.length == 2 ) report.setUserProperty( (String) convertedArgs[0], (String) convertedArgs[1] ); else if ( convertedArgs.length == 3 ) report.setUserProperty( (String) convertedArgs[0], convertedArgs[1], (String) convertedArgs[2] ); } catch ( SemanticException e ) { throw new WrappedException( e ); } return null; }
/** * This method evaluates a piece of ECMAScript. * @param scriptReader a <code>java.io.Reader</code> on the piece of script * @param description description which can be later used (e.g., for error * messages). * @return if no exception is thrown during the call, should return the * value of the last expression evaluated in the script. */ public Object evaluate(final Reader scriptReader, final String description) throws IOException { ContextAction evaluateAction = new ContextAction() { public Object run(Context cx) { try { return cx.evaluateReader(globalObject, scriptReader, description, 1, rhinoClassLoader); } catch (IOException ioe) { throw new WrappedException(ioe); } } }; try { return contextFactory.call(evaluateAction); } catch (JavaScriptException e) { // exception from JavaScript (possibly wrapping a Java Ex) Object value = e.getValue(); Exception ex = value instanceof Exception ? (Exception) value : e; throw new InterpreterException(ex, ex.getMessage(), -1, -1); } catch (WrappedException we) { Throwable w = we.getWrappedException(); if (w instanceof Exception) { throw new InterpreterException ((Exception) w, w.getMessage(), -1, -1); } else { throw new InterpreterException(w.getMessage(), -1, -1); } } catch (InterruptedBridgeException ibe) { throw ibe; } catch (RuntimeException re) { throw new InterpreterException(re, re.getMessage(), -1, -1); } }
public Object call(Context cx, Scriptable scope, Scriptable thisObj, java.lang.Object[] args) { try { return jsFunction_render((args.length == 0) ? null : args[0]); } catch(RenderException e) { throw new WrappedException(e); } }
public void assignValue(Object value) { if (isReadOnly()) { throw new ReadOnlyScriptBlockException(getScriptText()); } Context cx = RhinoUtil.enter(); try { Scriptable scope = RhinoUtil.getScope(); if (_elStyle) { Object host = getELStyleHost(cx, scope); if (host == null) { scope.put(_elStyleName, scope, value); } else if (host instanceof Scriptable) { ((Scriptable) host).put(_elStyleName, scope, value); } else if (host instanceof AttributeScope) { ((AttributeScope) host).setAttribute(_elStyleName, value); } else { ObjectUtil.setProperty(host, _elStyleName, value); } } else { throw new IllegalStateException(); } } catch (WrappedException e) { RhinoUtil.removeWrappedException(e); } finally { Context.exit(); } }
/** * Rhinoスクリプト実行中に発生した例外を、wrapされていない元の例外にして * 再度throwします。もしwrapされていた例外がRuntimeExceptionでない場合、 * RuntimeExceptionでwrapしてthrowします。 * * @param e Rhinoスクリプト中で発生した例外 */ public static void removeWrappedException(WrappedException e) { Throwable t = e.getWrappedException(); if (t instanceof RuntimeException) { throw (RuntimeException) t; } throw new RuntimeException(t); }
public Object execute(Object[] args) { Context cx = RhinoUtil.enter(); Object ret = null; try { compileFromSource(cx, getSource()); Object jsRet = _rhinoScript.exec(cx, RhinoUtil.getScope()); ret = RhinoUtil.convertResult(cx, getExpectedClass(), jsRet); } catch (WrappedException e) { RhinoUtil.removeWrappedException(e); } finally { Context.exit(); } return ret; }
private void handleError(Throwable t) throws BSFException { if (t instanceof WrappedException) { t = ((WrappedException) t).getWrappedException(); } String message = null; Throwable target = t; if (t instanceof JavaScriptException) { message = t.getLocalizedMessage(); // Is it an exception wrapped in a JavaScriptException? Object value = ((JavaScriptException) t).getValue(); if (value instanceof Throwable) { // likely a wrapped exception from a LiveConnect call. // Display its stack trace as a diagnostic target = (Throwable) value; } } else if (t instanceof EvaluatorException || t instanceof SecurityException) { message = t.getLocalizedMessage(); } else if (t instanceof RuntimeException) { message = "Internal Error: " + t.toString(); } else if (t instanceof StackOverflowError) { message = "Stack Overflow"; } if (message == null) { message = t.toString(); } if (t instanceof Error && !(t instanceof StackOverflowError)) { // Re-throw Errors because we're supposed to let the JVM see it // Don't re-throw StackOverflows, because we know we've // corrected the situation by aborting the loop and // a long stacktrace would end up on the user's console throw (Error) t; } else { throw new BSFException(BSFException.REASON_OTHER_ERROR, "JavaScript Error: " + message, target); } }
private static List<Runner> runnersFromJs(final Class<?> cls) throws InitializationError, IOException { final JavascriptResource js = cls.getAnnotation(JavascriptResource.class); final List<Runner> runners = new LinkedList<>(); try (final LineNumberReader reader = new LineNumberReader( new InputStreamReader(ClassLoader.getSystemResourceAsStream(js.name())))) { while (true) { final String expr = reader.readLine(); final int line = reader.getLineNumber(); if (expr == null) { break; } if (!expr.trim().isEmpty() && !expr.trim().startsWith("//")) { runners.add(new Runner() { @Override public Description getDescription() { final String[] parts = expr.split(" *; *"); final String desc = parts[parts.length - 1]; return Description.createTestDescription(cls, String.format("%s:%s => %s", js.name(), line, desc), js); } @Override public void run(final RunNotifier notifier) { notifier.fireTestStarted(getDescription()); // should really do something more generic here // instead of hard-coded setup, explicit // data frame construction... System.setIn(new ByteArrayInputStream( String.format("tmp = frames[0]; df = frames[1]; %s;", expr).getBytes())); try { final DataFrame<Object> df = DataFrame.readCsv(ClassLoader.getSystemResourceAsStream("grouping.csv")); final Object result = Shell.repl(Arrays.asList(new DataFrame<>(), df)); if (result instanceof WrappedException) { throw WrappedException.class.cast(result).getWrappedException(); } else if (result instanceof Throwable) { throw Throwable.class.cast(result); } org.junit.Assert.assertFalse(result == null); } catch (final IOException ioe) { notifier.fireTestAssumptionFailed(new Failure(getDescription(), ioe)); } catch (final AssertionError err) { notifier.fireTestFailure(new Failure(getDescription(), err)); } catch (final Throwable ex) { notifier.fireTestFailure(new Failure(getDescription(), ex)); } finally { notifier.fireTestFinished(getDescription()); } } }); } } } return runners; }
private void initFunctions( ) { Method[] tmpMethods = this.getClass( ).getDeclaredMethods( ); HashMap<String, Method> methods = new LinkedHashMap<String, Method>( ); for ( int i = 0; i < tmpMethods.length; i++ ) { Method tmpMethod = tmpMethods[i]; String methodName = tmpMethod.getName( ); // must handle special case with long parameter or polymiorphism if ( "getReportElementByID".equals( methodName ) //$NON-NLS-1$ || "setUserProperty".equals( methodName ) ) //$NON-NLS-1$ continue; if ( ( tmpMethod.getModifiers( ) & Modifier.PUBLIC ) != 0 ) methods.put( methodName, tmpMethod ); } Context.enter( ); try { for ( final Entry<String, Method> entry : methods.entrySet( ) ) { this.defineProperty( entry.getKey( ), new BaseFunction( ) { public Object call( Context cx, Scriptable scope, Scriptable thisObj, Object[] args ) { Object[] convertedArgs = JavascriptEvalUtil .convertToJavaObjects( args ); try { Method method = entry.getValue( ); return method.invoke( ReportDesign.this, convertedArgs ); } catch ( Exception e ) { throw new WrappedException( e ); } } }, DONTENUM ); } } finally { Context.exit( ); } this.defineProperty( "getReportElementByID", //$NON-NLS-1$ new Function_getReportElementByID( ), DONTENUM ); this.defineProperty( "setUserProperty", //$NON-NLS-1$ new Function_setUserProperty( ), DONTENUM ); }
private void handleError(Throwable t) throws BSFException { if (t instanceof WrappedException) t = ((WrappedException) t).getWrappedException(); String message = null; Throwable target = t; if (t instanceof JavaScriptException) { message = t.getLocalizedMessage(); // Is it an exception wrapped in a JavaScriptException? Object value = ((JavaScriptException) t).getValue(); if (value instanceof Throwable) { // likely a wrapped exception from a LiveConnect call. // Display its stack trace as a diagnostic target = (Throwable) value; } } else if (t instanceof EvaluatorException || t instanceof SecurityException) { message = t.getLocalizedMessage(); } else if (t instanceof RuntimeException) { message = "Internal Error: " + t.toString(); } else if (t instanceof StackOverflowError) { message = "Stack Overflow"; } if (message == null) message = t.toString(); if (t instanceof Error && !(t instanceof StackOverflowError)) { // Re-throw Errors because we're supposed to let the JVM see it // Don't re-throw StackOverflows, because we know we've // corrected the situation by aborting the loop and // a long stacktrace would end up on the user's console throw (Error) t; } else { throw new BSFException(BSFException.REASON_OTHER_ERROR, "JavaScript Error: " + message, target); } }
protected Scriptable doBeforeProcess(final Context parentContext, final Scriptable parentScope, final Scriptable thisObj, final Pair<Scriptable, Function> beforeProcessCallback) { final Context cx = Context.enter(); try { this.scriptProcessor.inheritCallChain(parentContext); final Scriptable processScope = cx.newObject(parentScope); processScope.setPrototype(null); processScope.setParentScope(null); // check for registerChildScope function on logger and register process scope if function is available final Object loggerValue = ScriptableObject.getProperty(parentScope, RhinoLogFunction.LOGGER_OBJ_NAME); if (loggerValue instanceof Scriptable) { final Scriptable loggerObj = (Scriptable) loggerValue; final Object registerChildScopeFuncValue = ScriptableObject.getProperty(loggerObj, RhinoLogFunction.REGISTER_CHILD_SCOPE_FUNC_NAME); if (registerChildScopeFuncValue instanceof Function) { final Function registerChildScopeFunc = (Function) registerChildScopeFuncValue; registerChildScopeFunc.call(cx, parentScope, thisObj, new Object[] { processScope }); } } if (beforeProcessCallback.getSecond() != null) { final Scriptable beforeProcessOriginalCallScope = beforeProcessCallback.getFirst(); final Scriptable beforeProcessCallScope = this.facadeFactory.toFacadedObject(beforeProcessOriginalCallScope, parentScope); final Function beforeProcessFn = beforeProcessCallback.getSecond(); if (beforeProcessFn instanceof NativeFunction) { // native function has parent scope based on location in source code // per batch function contract we need to execute it in our process scope final NativeFunction nativeFn = (NativeFunction) beforeProcessFn; final ThreadLocalParentScope threadLocalParentScope = (ThreadLocalParentScope) nativeFn.getParentScope(); threadLocalParentScope.setEffectiveParentScope(processScope); try { // execute with thread local parent scope nativeFn.call(cx, processScope, beforeProcessCallScope, new Object[0]); } finally { threadLocalParentScope.removeEffectiveParentScope(); } } else { // not a native function, so has no associated scope - calling as-is beforeProcessFn.call(cx, processScope, beforeProcessCallScope, new Object[0]); } } return processScope; } catch (final WrappedException ex) { final Throwable wrappedException = ex.getWrappedException(); if (wrappedException instanceof RuntimeException) { throw (RuntimeException) wrappedException; } throw ex; } finally { Context.exit(); } }
protected void doProcess(final Context parentContext, final Scriptable parentScope, final Scriptable processScope, final Scriptable thisObj, final Pair<Scriptable, Function> processCallback, final Object element) { final Context cx = Context.enter(); try { this.scriptProcessor.inheritCallChain(parentContext); final Scriptable processOriginalCallScope = processCallback.getFirst(); final Scriptable processCallScope = this.facadeFactory.toFacadedObject(processOriginalCallScope, parentScope); final Function processFn = processCallback.getSecond(); if (processFn instanceof NativeFunction) { // native function has parent scope based on location in source code // per batch function contract we need to execute it in our process scope final NativeFunction nativeFn = (NativeFunction) processFn; final ThreadLocalParentScope threadLocalParentScope = (ThreadLocalParentScope) nativeFn.getParentScope(); threadLocalParentScope.setEffectiveParentScope(processScope); try { // execute with thread local parent scope nativeFn.call(cx, processScope, processCallScope, new Object[] { element }); } finally { threadLocalParentScope.removeEffectiveParentScope(); } } else { // not a native function, so has not associated scope - calling as-is processFn.call(cx, processScope, processCallScope, new Object[] { element }); } } catch (final WrappedException ex) { final Throwable wrappedException = ex.getWrappedException(); if (wrappedException instanceof RuntimeException) { throw (RuntimeException) wrappedException; } throw ex; } finally { Context.exit(); } }
protected void doAfterProcess(final Context parentContext, final Scriptable parentScope, final Scriptable processScope, final Scriptable thisObj, final Pair<Scriptable, Function> afterProcessCallback) { final Context cx = Context.enter(); try { this.scriptProcessor.inheritCallChain(parentContext); if (afterProcessCallback.getSecond() != null) { final Scriptable afterProcessOriginalCallScope = afterProcessCallback.getFirst(); final Scriptable afterProcessCallScope = this.facadeFactory.toFacadedObject(afterProcessOriginalCallScope, parentScope); final Function afterProcessFn = afterProcessCallback.getSecond(); if (afterProcessFn instanceof NativeFunction) { // native function has parent scope based on location in source code // per batch function contract we need to execute it in our process scope final NativeFunction nativeFn = (NativeFunction) afterProcessFn; final ThreadLocalParentScope threadLocalParentScope = (ThreadLocalParentScope) nativeFn.getParentScope(); threadLocalParentScope.setEffectiveParentScope(processScope); try { // execute with thread local parent scope nativeFn.call(cx, processScope, afterProcessCallScope, new Object[0]); } finally { threadLocalParentScope.removeEffectiveParentScope(); } } else { // not a native function, so has not associated scope - calling as-is afterProcessFn.call(cx, processScope, afterProcessCallScope, new Object[0]); } } } catch (final WrappedException ex) { final Throwable wrappedException = ex.getWrappedException(); if (wrappedException instanceof RuntimeException) { throw (RuntimeException) wrappedException; } throw ex; } finally { Context.exit(); // clear thread-local facade mapping this.facadeFactory.clearThread(); } }
public Object execute(Object[] args) { Context cx = RhinoUtil.enter(); Object ret = null; try { Scriptable scope = RhinoUtil.getScope(); Object jsRet; if (_elStyle && args != null) { Object host = getELStyleHost(cx, scope); jsRet = functionExecute(cx, scope, host, args); } else { jsRet = normalExecute(cx, scope); } ret = RhinoUtil.convertResult(cx, getExpectedClass(), jsRet); } catch (RhinoException e) { if (e instanceof WrappedException) { WrappedException we = (WrappedException) e; Throwable wrapped = we.getWrappedException(); if (wrapped instanceof RenderingBrake) { RhinoUtil.removeWrappedException(we); } } // エラーとなったソース情報が微妙なので微調整。 // 行番号はスクリプト次第でずれてしまう。 int offsetLine; String message; String sourceName; if (e instanceof JavaScriptException && ((JavaScriptException)e).getValue() instanceof IdScriptableObject) { offsetLine = -1; IdScriptableObject scriptable = (IdScriptableObject) ((JavaScriptException) e).getValue(); Object messageProperty = scriptable.get("message", scriptable); if (messageProperty != Scriptable.NOT_FOUND) { message = messageProperty.toString(); } else { message = scriptable.toString(); } } else { offsetLine = e.lineNumber() - _lineNumber + 1; // one "\n" is added message = e.details() + " in script=\n" + getText(); } if (e.lineSource() == null && message != null) { String[] lines = message.split("\n"); offsetLine = (lines.length > offsetLine) ? offsetLine : _offsetLine; if (offsetLine >= 0 && lines.length > offsetLine) { e.initLineSource(lines[offsetLine]); sourceName = _sourceName; } else { sourceName = e.sourceName(); } } else { sourceName = e.sourceName(); } throw new OffsetLineRhinoException( message, sourceName, e.lineNumber(), e.lineSource(), e.columnNumber(), offsetLine, e.getCause()); } finally { Context.exit(); } return ret; }