org.mozilla.javascript.EvaluatorException Java Examples

The following examples show how to use org.mozilla.javascript.EvaluatorException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JavaScriptEvaluatorScope.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #2
Source File: JavaScriptCompilerBase.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
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");
}
 
Example #3
Source File: ExpressionLanguageJavaScriptImpl.java    From oval with Eclipse Public License 2.0 6 votes vote down vote up
@Override
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();
      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));
      }
      final Script expr = expressionCache.get(expression);
      return expr.exec(ctx, scope);
   } catch (final EvaluatorException ex) {
      throw new ExpressionEvaluationException("Evaluating JavaScript expression failed: " + expression, ex);
   } finally {
      Context.exit();
   }
}
 
Example #4
Source File: SdpProcessor.java    From openwebrtc-android-sdk with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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();
    }
}
 
Example #5
Source File: SwitchGenerator.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #6
Source File: WorkflowFilesDeployerTest.java    From celos with Apache License 2.0 5 votes vote down vote up
@Test (expected = EvaluatorException.class)
public void testDeployFails() throws Exception{
    CelosCiContext context = mock(CelosCiContext.class);

    File localFolder = tempDir.newFolder();
    localFolder.mkdirs();
    File defFile = new File(localFolder, "defaults.js");
    defFile.createNewFile();

    OutputStream os = new FileOutputStream(defFile);
    os.write("var a = newfile var b = c".getBytes());
    os.flush();

    WorkflowFilesDeployer deployer = new WorkflowFilesDeployer(context);

    File remoteFolderWf = tempDir.newFolder();
    remoteFolderWf.mkdirs();

    File remoteFolderDef = tempDir.newFolder();
    remoteFolderDef.mkdirs();

    CelosCiTarget target = new CelosCiTarget(URI.create(""), URI.create(""), remoteFolderWf.toURI(), remoteFolderDef.toURI(), URI.create("hiveJdbc"));

    doReturn(localFolder).when(context).getDeployDir();
    doReturn(target).when(context).getTarget();
    doReturn("workflow").when(context).getWorkflowName();

    deployer.deploy();
}
 
Example #7
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testBadJSFile() throws Exception {
    EasyMock.replay(dpMock);
    final String fname = "broken.js";
    File f = new File(getClass().getResource(fname).toURI().getPath());
    try {
        ph.createAndPublish(f);
        fail("expected exception did not occur");
    } catch (EvaluatorException ex) {
        assertTrue("wrong exception", ex.getMessage().startsWith("syntax error")
                                   || ex.getMessage().startsWith("erreur de syntaxe"));
    }
    EasyMock.verify(dpMock);
}
 
Example #8
Source File: EcmaScriptDataModel.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
private <T extends Object> T evaluateExpression(final String expr,
        final Scope scope, final Scriptable start, final Class<T> type)
        throws SemanticError {
    if (start == null) {
        throw new SemanticError("no scope '" + scope
                + "' present to evaluate '" + expr + "'");
    }
    final String preparedExpression = prepareExpression(expr);
    if (preparedExpression == null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("ignoring empty value expr");
        }
        return null;
    }
    try {
        final Context context = getContext();
        final Object value = context.evaluateString(start,
                preparedExpression, "expr", 1, null);
        if (value == getUndefinedValue()) {
            return null;
        }
        if (LOGGER.isDebugEnabled()) {
            final String json = toString(value);
            LOGGER.debug("evaluated '" + preparedExpression + "' to '"
                    + json + "'");
        }
        @SuppressWarnings("unchecked")
        final T t = (T) Context.jsToJava(value, type);
        return t;
    } catch (EcmaError | EvaluatorException e) {
        final String message = "error evaluating '" + preparedExpression
                + "'";
        LOGGER.warn(message, e);
        final String concatenatedMessage = getConcatenadedErrorMessage(
                message, e);
        throw new SemanticError(concatenatedMessage, e);
    }
}
 
Example #9
Source File: ScriptValidator.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Validates the specified script.
 * 
 * @param script
 *            the script to validate.
 * @throws ParseException
 *             if an syntax error is found.
 */
protected void validateScript( String script ) throws ParseException
{
	if ( script == null )
	{
		return;
	}

	CompilerEnvirons compilerEnv = new CompilerEnvirons( );
	Parser jsParser = new Parser( compilerEnv,
			compilerEnv.getErrorReporter( ) );

	try
	{
		jsParser.parse( script, null, 0 );
	}
	catch ( EvaluatorException e )
	{
		int offset = -1;

		if ( scriptViewer != null )
		{
			String[] lines = script.split( "\n" ); //$NON-NLS-1$

			for ( int i = 0; i < e.lineNumber( ); i++ )
			{
				offset += lines[i].length( ) + 1;
			}
			offset += e.columnNumber( );
		}
		throw new ParseException( e.getLocalizedMessage( ), offset );
	}
}
 
Example #10
Source File: NativeRowObject.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public Object get( String name, Scriptable start )
{
	IQueryResultSet rset = getResultSet( );
	if ( rset == null )
	{
		return null;
	}

	if ( "_outer".equals( name ) )
	{
		IBaseResultSet parent = rset.getParent( );
		if ( parent != null
				&& parent.getType( ) == IBaseResultSet.QUERY_RESULTSET )
		{
			return new NativeRowObject( start, (IQueryResultSet) parent );
		}
		else
		{
			// TODO: return cuber object used in script
			// return new NativeCubeObject(start, parent);
		}
		return null;
	}
	try
	{
		if ( "__rownum".equals( name ) )
		{
			return Long.valueOf( rset.getRowIndex( ) );
		}
		return rset.getValue( name );
	}
	catch ( BirtException ex )
	{
		throw new EvaluatorException( ex.toString( ) );
	}
}
 
Example #11
Source File: PrimitiveWrapFactory.java    From io with Apache License 2.0 5 votes vote down vote up
@Override
public Scriptable wrapNewObject(Context cx, Scriptable scope, Object obj) {
    // JavaScriptから呼び出しを許してるクラスもコンストラクタは呼び出し不可にする
    if (obj.getClass() == DcInputStream.class
            || obj.getClass() == DcJSONObject.class
            || obj.getClass() == DcRequestBodyStream.class) {
        throw new EvaluatorException("not found");
    }
    return super.wrapNewObject(cx, scope, obj);
}
 
Example #12
Source File: JSConfigParserTest.java    From celos with Apache License 2.0 5 votes vote down vote up
@Test(expected = EvaluatorException.class)
public void testCompileFails() throws Exception {
    JSConfigParser parser = new JSConfigParser();
    File file = new File(Thread.currentThread().getContextClassLoader().getResource("com/collective/celos/read-js/incorrect-wf-js").toURI());

    parser.validateJsSyntax(new FileReader(file), file.getName());
}
 
Example #13
Source File: ErrorCollector.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @inheritDoc
 */
public EvaluatorException runtimeError(String message, String sourceName,
                                       int line, String lineSource,
                                       int lineOffset)
{
    throw new UnsupportedOperationException();
}
 
Example #14
Source File: ClassShutterExceptionTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
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
    }
}
 
Example #15
Source File: Bug714204Test.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example #16
Source File: Bug714204Test.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example #17
Source File: Bug714204Test.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example #18
Source File: Bug714204Test.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example #19
Source File: StrictModeApiTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
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();
  }
}
 
Example #20
Source File: ParserTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #21
Source File: DataFrameShellTest.java    From joinery with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testInvalidExpressions()
throws IOException {
    for (final String s : Arrays.asList(
                "[", "]", "{", "}", "(", ")", "\"", "'")) {
        final InputStream in = input(s);
        assertEquals(
                EvaluatorException.class,
                Shell.repl(in, Collections.<DataFrame<Object>>emptyList()).getClass()
            );
    }
}
 
Example #22
Source File: ParserTest.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #23
Source File: YUIException.java    From jcv-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public EvaluatorException runtimeError(String message, String sourceName,
                int line, String lineSource, int lineOffset) {
    
    error(message, sourceName, line, lineSource, lineOffset);
    return new EvaluatorException(message);
}
 
Example #24
Source File: StrictModeApiTest.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
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();
  }
}
 
Example #25
Source File: Bug782363Test.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testMaxLocals() throws IOException {
    test(339);
    try {
        test(340);
    } catch (EvaluatorException e) {
        // may fail with 'out of locals' exception
    }
}
 
Example #26
Source File: Bug714204Test.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #27
Source File: Bug714204Test.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #28
Source File: Bug714204Test.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #29
Source File: Bug714204Test.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #30
Source File: ErrorCollector.java    From JsDroidCmd with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * @inheritDoc
 */
public EvaluatorException runtimeError(String message, String sourceName,
                                       int line, String lineSource,
                                       int lineOffset)
{
    throw new UnsupportedOperationException();
}