protected void executeSimpleHandlerCore(String handlerType, org.mozilla.javascript.Context myJavascriptContext) throws EcmaError, EvaluatorException, JavaScriptException, EngineException { handlerName = "on" + handlerType; Engine.logBeans.trace("(Transaction) Searching the " + handlerType + " handler (" + handlerName + ")"); Object object = scope.get(handlerName, scope); Engine.logBeans.trace("(Transaction) Rhino returned: [" + object.getClass().getName() + "] " + object.toString()); if (!(object instanceof Function)) { Engine.logBeans.debug("(Transaction) No " + handlerType + " handler (" + handlerName + ") found"); return; } else { Engine.logBeans.debug("(Transaction) Execution of the " + handlerType + " handler (" + handlerName + ") for the transaction '" + getName() + "'"); } function = (Function) object; Object returnedValue = function.call(myJavascriptContext, scope, scope, null); if (returnedValue instanceof org.mozilla.javascript.Undefined) { handlerResult = ""; } else { handlerResult = returnedValue.toString(); } }
/** * load * @param response */ public void load( WebResponse response ) { Function onLoadEvent=null; try { Context context = Context.enter(); context.initStandardObjects( null ); HTMLDocument htmlDocument = ((DomWindow) response.getScriptingHandler()).getDocument(); if (!(htmlDocument instanceof HTMLDocumentImpl)) return; HTMLBodyElementImpl body = (HTMLBodyElementImpl) htmlDocument.getBody(); if (body == null) return; onLoadEvent = body.getOnloadEvent(); if (onLoadEvent == null) return; onLoadEvent.call( context, body, body, new Object[0] ); } catch (JavaScriptException e) { ScriptingEngineImpl.handleScriptException(e, onLoadEvent.toString()); // HttpUnitUtils.handleException(e); } catch (EcmaError ee) { //throw ee; ScriptingEngineImpl.handleScriptException(ee, onLoadEvent.toString()); } finally { Context.exit(); } }
private void runWithExpectedStackTrace(final String _source, final String _expectedStackTrace) { final ContextAction action = new ContextAction() { public Object run(Context cx) { final Scriptable scope = cx.initStandardObjects(); try { cx.evaluateString(scope, _source, "test.js", 0, null); } catch (final JavaScriptException e) { assertEquals(_expectedStackTrace, e.getScriptStackTrace()); return null; } throw new RuntimeException("Exception expected!"); } }; Utils.runWithOptimizationLevel(action, -1); }
/** * Wraps given exception and throws it as ScriptException. * * @param ex Exception to be wrapped. * @throws ScriptException Thrown always by this method. */ public static void throwWrappedScriptException(Exception ex) throws ScriptException { if ( ex instanceof RhinoException) { RhinoException rhinoException = (RhinoException)ex; int line = rhinoException.lineNumber(); int column = rhinoException.columnNumber(); String message; if (ex instanceof JavaScriptException) { message = String.valueOf(((JavaScriptException)ex).getValue()); } else { message = ex.toString(); } ScriptException scriptException = new ScriptException(message, rhinoException.sourceName(), line, column); scriptException.initCause(ex); throw scriptException; } else { throw new ScriptException(ex); } }
/** * Executes an arbitrary expression.<br> * It fails if the expression throws a JsAssertException.<br> * It fails if the expression throws a RhinoException.<br> * * Code from JsTester (http://jstester.sf.net/) */ public Object eval(String expr) { Object value = null; try { value = context.evaluateString(globalScope, expr, "", 1, null); } catch (JavaScriptException jse) { Scriptable jsAssertException = (Scriptable) globalScope.get( "currentException", globalScope); jse.printStackTrace(); String message = (String) jsAssertException.get("message", jsAssertException); if (message != null) { fail(message); } } catch (RhinoException re) { fail(re.getMessage()); } return value; }
/** * Support setting parameter value by following methods: */ public void put( String name, Scriptable start, Object value ) { PageVariable variable = variables.get( name ); if ( variable != null ) { if ( value instanceof Wrapper ) { value = ( (Wrapper) value ).unwrap( ); } variable.setValue( value ); return; } String errorMessage = "Report variable\"" + name + "\" does not exist"; throw new JavaScriptException( errorMessage, "<unknown>", -1 ); }
/** * After having setup a compiler by (1) registering it and (2) passing in its arguments * @param lineno The starting line number of the source code to be compiled (used for debugging) * @param securityDomain * @return * @throws IOException * @throws RhinoEvaluatorException */ public String compile (int lineno, Object securityDomain) throws IOException, JavaScriptException { Context context = Context.enter(); Reader reader = new InputStreamReader(program); Object ret = context.evaluateReader(instanceScope, reader, programName, lineno, securityDomain); if (ret instanceof org.mozilla.javascript.Undefined) { // This is really 'void'. Perhaps a separate 'compile' method // should be used that has 'void' as its return type, and that // get used by the likes of the RjsConfigCompiler return ""; } else { return (String) ret; } }
@Test(expected = JavaScriptException.class) public void testAddTestCaseNoOutput() throws IOException { String configJS = "ci.addTestCase({\n" + " name: \"wordcount test case 1\",\n" + " sampleTimeStart: \"2013-11-20T11:00Z\",\n" + " sampleTimeEnd: \"2013-11-20T18:00Z\",\n" + " inputs: [\n" + " ci.hdfsInput(ci.fixDirFromResource(\"src/test/celos-ci/test-1/input/plain/input/wordcount1\"), \"input/wordcount1\"),\n" + " ci.hdfsInput(ci.fixDirFromResource(\"src/test/celos-ci/test-1/input/plain/input/wordcount11\"), \"input/wordcount11\")\n" + " ]\n" + "})\n"; TestConfigurationParser parser = new TestConfigurationParser(); parser.evaluateTestConfig(new StringReader(configJS), "string"); }
@Test(expected = JavaScriptException.class) public void testAddTestCaseNoInput() throws IOException { String configJS = "ci.addTestCase({\n" + " name: \"wordcount test case 1\",\n" + " sampleTimeStart: \"2013-11-20T11:00Z\",\n" + " sampleTimeEnd: \"2013-11-20T18:00Z\",\n" + " outputs: [\n" + " ci.plainCompare(ci.fixDirFromResource(\"src/test/celos-ci/test-1/output/plain/output/wordcount1\"), \"output/wordcount1\")\n" + " ]\n" + "})\n"; TestConfigurationParser parser = new TestConfigurationParser(); parser.evaluateTestConfig(new StringReader(configJS), "string"); }
@Test(expected = JavaScriptException.class) public void testAddTestCaseNoSampleTimeStart() throws IOException { String configJS = "ci.addTestCase({\n" + " name: \"wordcount test case 1\",\n" + " sampleTimeEnd: \"2013-11-20T18:00Z\",\n" + " inputs: [\n" + " ci.hdfsInput(ci.fixDirFromResource(\"src/test/celos-ci/test-1/input/plain/input/wordcount1\"), \"input/wordcount1\"),\n" + " ci.hdfsInput(ci.fixDirFromResource(\"src/test/celos-ci/test-1/input/plain/input/wordcount11\"), \"input/wordcount11\")\n" + " ],\n" + " outputs: [\n" + " ci.plainCompare(ci.fixDirFromResource(\"src/test/celos-ci/test-1/output/plain/output/wordcount1\"), \"output/wordcount1\")\n" + " ]\n" + "})\n"; TestConfigurationParser parser = new TestConfigurationParser(); parser.evaluateTestConfig(new StringReader(configJS), "string"); }
@Test(expected = JavaScriptException.class) public void testAddTestCaseNoSampleTimeEnd() throws IOException { String configJS = "ci.addTestCase({\n" + " name: \"wordcount test case 1\",\n" + " sampleTimeStart: \"2013-11-20T18:00Z\",\n" + " inputs: [\n" + " ci.hdfsInput(ci.fixDirFromResource(\"src/test/celos-ci/test-1/input/plain/input/wordcount1\"), \"input/wordcount1\"),\n" + " ci.hdfsInput(ci.fixDirFromResource(\"src/test/celos-ci/test-1/input/plain/input/wordcount11\"), \"input/wordcount11\")\n" + " ],\n" + " outputs: [\n" + " ci.plainCompare(ci.fixDirFromResource(\"src/test/celos-ci/test-1/output/plain/output/wordcount1\"), \"output/wordcount1\")\n" + " ]\n" + "})\n"; TestConfigurationParser parser = new TestConfigurationParser(); parser.evaluateTestConfig(new StringReader(configJS), "string"); }
public Object eval(ScriptContext context) throws ScriptException { Object result = null; Context cx = RhinoScriptEngine.enterContext(); try { Scriptable scope = engine.getRuntimeScope(context); Object ret = script.exec(cx, scope); result = engine.unwrapReturnValue(ret); } catch (RhinoException re) { int line = (line = re.lineNumber()) == 0 ? -1 : line; String msg; if (re instanceof JavaScriptException) { msg = String.valueOf(((JavaScriptException)re).getValue()); } else { msg = re.toString(); } ScriptException se = new ScriptException(msg, re.sourceName(), line); se.initCause(re); throw se; } finally { Context.exit(); } return result; }
private String compile(Scriptable rootScope, final String source, final String sourceName) { return childScope(rootScope, new DefaultScopeOperation<String>() { public String action(Scriptable compileScope, Context context) { compileScope.put("coffeeScriptSource", compileScope, source); try { return (String) context.evaluateString(compileScope, "CoffeeScript.compile(coffeeScriptSource, {});", sourceName, 0, null); } catch (JavaScriptException jse) { throw new SourceTransformationException(String.format("Failed to compile coffeescript file: %s", sourceName), jse); } } }); }
@Override protected void executeSimpleHandlerCore(String handlerType, Context myJavascriptContext) throws EcmaError, EvaluatorException, JavaScriptException, EngineException { handlerName = "on" + handlerType; Engine.logBeans.trace("(HtmlTransaction) Searching the " + handlerType + " handler (" + handlerName + ")"); HandlerStatement handlerStatement = getHandlerStatement(handlerName); handlerResult = ""; if (handlerStatement != null) { if (!handlerStatement.isEnabled()) return; Engine.logBeans.debug("(HtmlTransaction) Execution of the " + handlerType + " handler (" + handlerName + ") for the transaction '" + getName() + "'"); handlerStatement.execute(myJavascriptContext, scope); Object returnedValue = handlerStatement.getReturnedValue(); if (returnedValue instanceof org.mozilla.javascript.Undefined) { handlerResult = ""; } else { handlerResult = returnedValue.toString(); } } else { Engine.logBeans.debug("(HtmlTransaction) No " + handlerType + " handler (" + handlerName + ") found"); } }
@Override protected void executeHandlerCore(String handlerType, org.mozilla.javascript.Context javascriptContext) throws EcmaError, EvaluatorException, JavaScriptException, EngineException { if (!AbstractHttpTransaction.EVENT_DATA_RETRIEVED.equals(handlerType)) { super.executeHandlerCore(handlerType, javascriptContext); return; } executeSimpleHandlerCore(handlerType, javascriptContext); }
protected void executeHandlerCore(String handlerType, org.mozilla.javascript.Context myJavascriptContext) throws EcmaError, EvaluatorException, JavaScriptException, EngineException { if ((!Transaction.EVENT_XML_GENERATED.equals(handlerType)) && (!Transaction.EVENT_TRANSACTION_STARTED.equals(handlerType))) { throw new IllegalArgumentException("Unknown handler type: " + handlerType); } executeSimpleHandlerCore(handlerType, myJavascriptContext); }
private Object doContextAction(ContextAction action) { try { return contextFactory.call(action); } catch (JavaScriptException ex) { System.out.println("Script stack trace: " + ex.getScriptStackTrace()); Object value = ex.getValue(); if (value instanceof NativeJavaObject) { Object wrapped = ((NativeJavaObject) value).unwrap(); if (wrapped instanceof Throwable) { throw new JavascriptPassThroughException((Throwable) wrapped, ex.getScriptStackTrace()); } } throw ex; } }
/** * 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 get( String name, Scriptable start ) { PageVariable variable = variables.get( name ); if ( variable != null ) { return variable.getValue( ); } String errorMessage = "Report variable\"" + name + "\" does not exist"; throw new JavaScriptException( errorMessage, "<unknown>", -1 ); }
public Object get( String name, Scriptable start ) { Object result = getScriptableParameter( name ); if ( result == null ) { String errorMessage = CoreMessages.getFormattedString( ResourceConstants.JAVASCRIPT_PARAMETER_NOT_EXIST, name ); throw new JavaScriptException( errorMessage, "<unknown>", -1 ); } return result; }
public Object get( String name, Scriptable start ) { if ( "length".equals( name ) ) { return Integer.valueOf( ( (Map) javaObject ).size( ) ); } if ( has( name, start ) ) { return ( (Map) javaObject ).get( name ); } String errorMessage = CoreMessages.getFormattedString( ResourceConstants.JAVASCRIPT_NATIVE_NOT_FOUND, name ); throw new JavaScriptException( errorMessage, "<unknown>", -1 ); //$NON-NLS-1$ }
public Object get( int index, Scriptable start ) { String key = Integer.valueOf( index ).toString( ); if ( has( key, start ) ) { return ( (Map) javaObject ).get( key ); } String errorMessage = CoreMessages.getFormattedString( ResourceConstants.JAVASCRIPT_NATIVE_NOT_FOUND, index ); throw new JavaScriptException( errorMessage, "<unknown>", -1 ); //$NON-NLS-1$ }
public String get(String key, WebResponse wr) { //ScriptingEngineFactory se = HttpUnitOptions.getScriptingEngine(); //se.setThrowExceptionsOnError(true); //verbose("Scripting enabled: " + HttpUnitOptions.isScriptingEnabled()); /* WebResponse wr = ResourceFactory.getHttpResource().getLastResponse(); if (wr != null) { try { ScriptableObject so = (ScriptableObject) wr.getScriptableObject().getScriptEngine(); verbose("js4" + jsContext.toString(so.get("js", so))); //verbose("write" + s.getScriptEngine().executeScript("document.write ('hello '+js);")); //verbose("js3: " + jsContext.toString(jsContext.evaluateString((ScriptableObject) s.getScriptEngine(), "function get_js(){return js;}; get_js();", "httpunit3", 0, null))); } // catch (JavaScriptException e) { // fail(e.toString() + e.getValue().toString()); // } catch (org.mozilla.javascript.EvaluatorException e) { fail(e.toString() + e.getMessage()); } Object o = scope.get(key, scope); verbose(o.toString()); } */ String value = (String) map.get(key); if (value == null) { if (wr != null) { ScriptableObject so = (ScriptableObject) wr.getScriptableObject().getScriptEngine(); //value = (jsContext.toString(so.get(key, so))); try { value = jsContext.toString(jsContext.evaluateString((ScriptableObject) so, key, "xmltestsuite", 0, null)); } catch (org.mozilla.javascript.JavaScriptException e) { fail(e.toString() + e.getMessage()); } } } return value; }
public RhinoEvaluatorException(JavaScriptException e) { super(e.getValue().toString(), e); logger.error("JavaScript Source Stacktrace"); logger.error(e.getScriptStackTrace()); e.printStackTrace(); throw new EvaluatorException("An unrecoverable JavaScript compilation error occurred. See above."); }
/** * Compile LESS to JavaScript * * @return The resultant JavaScript * @throws java.io.IOException * @throws com.semperos.screwdriver.js.rhino.RhinoEvaluatorException */ @Override public String compile(File sourceFile) throws IOException, RhinoEvaluatorException { rhinoCompiler.registerCompiler("LessCompiler", "com/semperos/screwdriver/js/extension/compile-less.js"); rhinoCompiler.addSourceFilePath(sourceFile.getAbsolutePath()); rhinoCompiler.compilerArgs(new LessSource(sourceFile).getNormalizedContent()); try { return rhinoCompiler.compile(); } catch (JavaScriptException e) { throw new RhinoEvaluatorException(e, sourceFile.toString()); } }
/** * Compiles the LESS input <code>String</code> to CSS. * * @param input The LESS input <code>String</code> to compile. * @return The CSS. */ public String compile(final String input) throws LessException { synchronized(this){ if (scope == null) { init(); } } final long start = System.currentTimeMillis(); try { final Context cx = Context.enter(); final Object result = doIt.call(cx, scope, null, new Object[]{input, compress}); if (log.isDebugEnabled()) { log.debug("Finished compilation of LESS source in " + (System.currentTimeMillis() - start) + " ms."); } return result.toString(); } catch (final Exception e) { if (e instanceof JavaScriptException) { final Scriptable value = (Scriptable)((JavaScriptException)e).getValue(); if (value != null && ScriptableObject.hasProperty(value, "message")) { final String message = ScriptableObject.getProperty(value, "message").toString(); throw new LessException(message, e); } } throw new LessException(e); }finally{ Context.exit(); } }
@Test(expected = JavaScriptException.class) public void fixDirFromResourceFails() throws IOException { TestConfigurationParser parser = new TestConfigurationParser(); NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader("ci.fixDirFromResource()"), "string"); FixDirFromResourceCreator creator = (FixDirFromResourceCreator) creatorObj.unwrap(); Assert.assertEquals(new File("/stuff"), creator.getPath(testRun)); }
@Test(expected = JavaScriptException.class) public void fixFileFromResourceFails() throws IOException { TestConfigurationParser parser = new TestConfigurationParser(); NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader("ci.fixFileFromResource()"), "string"); FixFileFromResourceCreator creator = (FixFileFromResourceCreator) creatorObj.unwrap(); Assert.assertEquals(new File("stuff"), creator.getPath(testRun)); }
@Test(expected = JavaScriptException.class) public void testHdfsInputDeployerCall1() throws IOException { TestConfigurationParser parser = new TestConfigurationParser(); NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader("ci.hdfsInput()"), "string"); HdfsInputDeployer creator = (HdfsInputDeployer) creatorObj.unwrap(); Assert.assertEquals(new File("stuff"), creator.getPath()); }
@Test(expected = JavaScriptException.class) public void testRecursiveFsObjectComparer1() throws IOException { TestConfigurationParser parser = new TestConfigurationParser(); NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader("ci.plainCompare()"), "string"); RecursiveFsObjectComparer creator = (RecursiveFsObjectComparer) creatorObj.unwrap(); }
@Test(expected = JavaScriptException.class) public void testRecursiveFsObjectComparer3() throws IOException { TestConfigurationParser parser = new TestConfigurationParser(); NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader("ci.plainCompare(ci.fixFileFromResource(\"stuff\"))"), "string"); RecursiveFsObjectComparer creator = (RecursiveFsObjectComparer) creatorObj.unwrap(); }
@Test(expected = JavaScriptException.class) public void testJsonCompareFails() throws IOException { TestConfigurationParser parser = new TestConfigurationParser(); NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader("ci.jsonCompare(ci.fixDirFromResource(\"stuff\"))"), "string"); JsonContentsComparer comparer = (JsonContentsComparer) creatorObj.unwrap(); Assert.assertEquals(comparer.getIgnorePaths(), new HashSet(Lists.newArrayList("path1", "path2"))); }