private void compressJs(String sourceName, InputStream in, OutputStream out) throws IOException { CompilerOptions options = new CompilerOptions(); CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options); SourceFile input = SourceFile.fromInputStream(sourceName, in, Charset.forName("UTF-8")); com.google.javascript.jscomp.Compiler compiler = new com.google.javascript.jscomp.Compiler(); compiler.compile(Collections.EMPTY_LIST, Collections.singletonList(input), options); if (compiler.hasErrors()) { throw new EvaluatorException(compiler.getErrors()[0].description); } String compressed = compiler.toSource(); IOUtils.copy(new StringReader(compressed), out); }
public void setFilter(String filter) throws ServiceException { if (filter == null) { filter = ""; } if (!this.filter.equals(filter)) { this.filter = filter; if (filter.length() != 0) { Context js_context = Context.enter(); try { js_and.reset(filter); js_or.reset(js_and.replaceAll(" && ")); filter = js_or.replaceAll(" || "); js_filter = js_context.compileString(filter, "filter", 0, null); } catch (EvaluatorException e) { throw new ServiceException("Failed to compile JS filter : " + e.getMessage(), e); } finally { Context.exit(); } } else { js_filter = null; } bContinue = false; } }
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(); } }
@Override public EvaluatorException runtimeError(String msg, String scriptName, int lineNum, String line, int linePos) { StringBuilder summary = new StringBuilder(); summary.append(r.getString("error.preamble", scriptName) + "\n"); summary.append(msg + "\n"); for( String error : errors ) { summary.append(r.getString("label.error") + ": " + error + "\n"); } for( String warning : warnings ) { summary.append(r.getString("label.warning") + ": " + warning + "\n"); } return new EvaluatorException(summary.toString()); }
public void receiveError(final EvaluatorException err) { if(isForeground) { MainActivity.UIThread(new Runnable() { @Override public void run() { MainActivity.settingPower.setChecked(false); Toast.makeText(ctx, "Error: EvaluatorException (" + err.lineNumber() + ", " + err.columnNumber() + ")\n" + err.toString(), Toast.LENGTH_SHORT).show(); } }); } Logger.Log log = new Logger.Log(); log.type = Logger.Type.ERROR; log.title = "Error: EvaluatorException"; log.index = "at (" + err.lineNumber() + ", " + err.columnNumber() + ")\n" + err.toString(); Logger.getInstance().add(log); }
public static Script loadScriptFromSource(Context cx, String scriptSource, String path, int lineno, Object securityDomain) { try { return cx.compileString(scriptSource, path, lineno, securityDomain); } catch (EvaluatorException ee) { // Already printed message. exitCode = EXITCODE_RUNTIME_ERROR; } catch (RhinoException rex) { ToolErrorReporter.reportException( cx.getErrorReporter(), rex); exitCode = EXITCODE_RUNTIME_ERROR; } catch (VirtualMachineError ex) { // Treat StackOverflow and OutOfMemory as runtime errors ex.printStackTrace(); String msg = ToolErrorReporter.getMessage( "msg.uncaughtJSException", ex.toString()); exitCode = EXITCODE_RUNTIME_ERROR; Context.reportError(msg); } return null; }
public Object evaluateExpression(Script expression) { ensureContext(); Object value = expression.exec(context, scope); Object javaValue; // not converting Number objects because the generic conversion call below // always converts to Double if (value == null || value instanceof Number) { javaValue = value; } else { try { javaValue = Context.jsToJava(value, Object.class); } catch (EvaluatorException e) { throw new JRRuntimeException(e); } } return javaValue; }
public void addError(EvaluatorException error) { ++errorCount; errors.append(errorCount); errors.append(". "); String message = error.getMessage(); errors.append(message); errors.append(" at column "); errors.append(error.columnNumber()); String lineSource = error.lineSource(); if (lineSource != null) { errors.append(" in line\n"); errors.append(lineSource); } errors.append("\n"); }
public Object evaluate(final String expression, final Map<String, ?> values) throws ExpressionEvaluationException { LOG.debug("Evaluating JavaScript expression: {1}", expression); try { final Context ctx = ContextFactory.getGlobal().enterContext(); Script script = scriptCache.get(expression); if (script == null) { ctx.setOptimizationLevel(9); script = ctx.compileString(expression, "<cmd>", 1, null); scriptCache.put(expression, script); } final Scriptable scope = ctx.newObject(parentScope); scope.setPrototype(parentScope); scope.setParentScope(null); for (final Entry<String, ?> entry : values.entrySet()) { scope.put(entry.getKey(), scope, Context.javaToJS(entry.getValue(), scope)); } return script.exec(ctx, scope); } catch (final EvaluatorException ex) { throw new ExpressionEvaluationException("Evaluating JavaScript expression failed: " + expression, ex); } finally { Context.exit(); } }
static String jsonToSdp(JSONObject json) throws InvalidDescriptionException { synchronized (SdpProcessor.class) { if (sInstance == null) { sInstance = new SdpProcessor(); } } Context context = Context.enter(); context.setOptimizationLevel(-1); context.setLanguageVersion(Context.VERSION_1_8); try { ScriptableObject scope = sInstance.getScope(); Object result = sInstance.getJsonToSdpFunction().call(context, scope, scope, new Object[]{json.toString()}); return "" + result; } catch (EvaluatorException e) { throw new InvalidDescriptionException("failed to parse sdp: " + e.getMessage(), e); } finally { Context.exit(); } }
private Object compileJavascriptAssertions(AssertionsJavascriptWrapper assertionsJavascriptWrapper) throws Exception { String javascriptText = assertionsJavascriptWrapper.getJavascriptText(); HashMap<String, Object> referencedObjects = assertionsJavascriptWrapper.getReferencedObjects(); Object compiledJavascriptObject = null; Context rhinoContext = Context.enter(); try { ScriptableObject scope = rhinoContext.initStandardObjects(); for (String key : referencedObjects.keySet()) { Object referencedObject = referencedObjects.get(key); Object wrappedObject = Context.javaToJS(referencedObject, scope); ScriptableObject.putProperty(scope, key, wrappedObject); } Scriptable that = rhinoContext.newObject(scope); Function fct = rhinoContext.compileFunction(scope, javascriptText, "script", 1, null); Object result = fct .call(rhinoContext, scope, that, new Object[] {}); compiledJavascriptObject = result == Context.getUndefinedValue() ? null : Context .jsToJava(result, Object.class); } catch (EvaluatorException ee) { ee.printStackTrace(); } finally { Context.exit(); } return compiledJavascriptObject; }
private Set<String> getVariableNames(String expression) { if (CommonUtils.isNullOrEmpty(expression)) { return Collections.emptySet(); } Set<String> set = parameterReferencesByExpression.get(expression); if (set == null) { set = new HashSet<String>(); parameterReferencesByExpression.put(expression, set); try { set.addAll(FormulaInfo.getVariableNames(expression)); } catch (EvaluatorException e) { try { // Sometimes the 'expression' is a duration, so that is okay DurationFormat.parseFormattedDuration(expression); set = new HashSet<String>(); } catch (Exception x) { trace.error("couldn't parse expression: " + expression, e); } } } return set; }
@Override public Object get(int index, Scriptable start) { PropertyInfo pinfo = this.classWrapper.getIntegerIndexer(); if (pinfo == null) { return super.get(index, start); } else { try { Method getter = pinfo.getGetter(); if (getter == null) { throw new EvaluatorException("Indexer is write-only"); } // Cannot retain delegate with a strong reference. Object javaObject = this.getJavaObject(); if (javaObject == null) { throw new IllegalStateException("Java object (class=" + this.classWrapper + ") is null."); } Object raw = getter.invoke(javaObject, new Object[] { Integer.valueOf(index) }); if (raw != null) { return JavaScript.getInstance().getJavascriptObject(raw, this.getParentScope()); } } catch (Exception err) { err.getCause(); } } return Scriptable.NOT_FOUND; }
@Override public void put(int index, Scriptable start, Object value) { PropertyInfo pinfo = this.classWrapper.getIntegerIndexer(); if (pinfo == null) { super.put(index, start, value); } else { try { Method setter = pinfo.getSetter(); if (setter == null) { throw new EvaluatorException("Indexer is read-only"); } Object actualValue; actualValue = JavaScript.getInstance().getJavaObject(value, pinfo.getPropertyType()); setter.invoke(this.getJavaObject(), new Object[] { Integer.valueOf(index), actualValue }); } catch (Exception err) { err.getCause(); } } }
/** * Creates an EvaluatorException that may be thrown. * runtimeErrors, unlike errors, will always terminate the * current script. * * @param message a String describing the error * @param sourceName a String describing the JavaScript source * where the error occured; typically a filename or URL * @param line the line number associated with the error * @param lineSource the text of the line (may be null) * @param lineOffset the offset into lineSource where problem was detected * @return an EvaluatorException that will be thrown. */ public EvaluatorException runtimeError(String message, String sourceName, int line, String lineSource, int lineOffset) { String msg = formatMessage(message, sourceName, line, lineSource, lineOffset); if(upstreamReporter != null) upstreamReporter.errorReport(msg, null); else System.out.println("ECMA.RuntimeError: " + msg); return new EvaluatorException(msg); }
/** * @inheritDoc */ public EvaluatorException runtimeError(String message, String sourceName, int line, String lineSource, int lineOffset) { throw new UnsupportedOperationException(); }
@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 EvaluatorException on_same_pair_fail(IdValuePair a, IdValuePair b) { int line1 = a.getLineNumber(), line2 = b.getLineNumber(); if (line2 > line1) { int tmp = line1; line1 = line2; line2 = tmp; } String error_text = ToolErrorReporter.getMessage( "msg.idswitch.same_string", a.id, new Integer(line2)); return R.runtimeError(error_text, source_file, line1, null, 0); }
public void testThrowingEcmaError() { try { // JavaScript exceptions with no reference to Java // should not be affected by the ClassShutter helper("friggin' syntax error!"); fail("Should have thrown an exception"); } catch (EvaluatorException e) { // should have thrown an exception for syntax error } }
public void testStrictModeError() { contextFactory = new MyContextFactory(); Context cx = contextFactory.enterContext(); try { global = cx.initStandardObjects(); try { runScript("({}.nonexistent);"); fail(); } catch (EvaluatorException e) { assertTrue(e.getMessage().startsWith("Reference to undefined property")); } } finally { Context.exit(); } }
@Test(expected = EvaluatorException.class) public void test_var_this() { StringBuilder sb = new StringBuilder(); sb.append("function F() {\n"); sb.append(" var [this.x] = arguments;\n"); sb.append("}\n"); cx.compileString(sb.toString(), "<eval>", 1, null); }
@Test(expected = EvaluatorException.class) public void test_let_this() { StringBuilder sb = new StringBuilder(); sb.append("function F() {\n"); sb.append(" let [this.x] = arguments;\n"); sb.append("}\n"); cx.compileString(sb.toString(), "<eval>", 1, null); }
@Test(expected = EvaluatorException.class) public void test_const_this() { StringBuilder sb = new StringBuilder(); sb.append("function F() {\n"); sb.append(" const [this.x] = arguments;\n"); sb.append("}\n"); cx.compileString(sb.toString(), "<eval>", 1, null); }
@Test(expected = EvaluatorException.class) public void test_args_this() { StringBuilder sb = new StringBuilder(); sb.append("function F([this.x]) {\n"); sb.append("}\n"); cx.compileString(sb.toString(), "<eval>", 1, null); }
@Test public void testMaxLocals() throws IOException { test(339); try { test(340); } catch (EvaluatorException e) { // may fail with 'out of locals' exception } }
private AstRoot parse( String string, final String [] errors, final String [] warnings, boolean jsdoc) { TestErrorReporter testErrorReporter = new TestErrorReporter(errors, warnings) { @Override public EvaluatorException runtimeError( String message, String sourceName, int line, String lineSource, int lineOffset) { if (errors == null) { throw new UnsupportedOperationException(); } return new EvaluatorException( message, sourceName, line, lineSource, lineOffset); } }; environment.setErrorReporter(testErrorReporter); environment.setRecordingComments(true); environment.setRecordingLocalJsDocComments(jsdoc); Parser p = new Parser(environment, testErrorReporter); AstRoot script = null; try { script = p.parse(string, null, 0); } catch (EvaluatorException e) { if (errors == null) { // EvaluationExceptions should not occur when we aren't expecting // errors. throw e; } } assertTrue(testErrorReporter.hasEncounteredAllErrors()); assertTrue(testErrorReporter.hasEncounteredAllWarnings()); return script; }
/** * @inheritDoc */ @Override public EvaluatorException runtimeError(String message, String sourceName, int line, String lineSource, int lineOffset) { throw new UnsupportedOperationException(); }