Java Code Examples for org.mozilla.javascript.Function#call()

The following examples show how to use org.mozilla.javascript.Function#call() . 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: CipherManager.java    From YouTubeExtractor with Apache License 2.0 6 votes vote down vote up
private static String RhinoEngine(String s) {
	Context rhino = Context.enter();
	rhino.setOptimizationLevel(-1);
	try {
		Scriptable scope = rhino.initStandardObjects();
		rhino.evaluateString(scope, cachedDechiperFunction, "JavaScript", 1, null);
		Object obj = scope.get("decipher", scope);

		if (obj instanceof Function) {
			Function jsFunction = (Function) obj;
			Object jsResult = jsFunction.call(rhino, scope, scope, new Object[]{s});
			String result = Context.toString(jsResult);
			return result ;
		}
	}
	finally {
		Context.exit();
	}
	return s;
}
 
Example 2
Source File: CipherManager.java    From YTPlayer with GNU General Public License v3.0 6 votes vote down vote up
private static String RhinoEngine(String s) {
	Context rhino = Context.enter();
	rhino.setOptimizationLevel(-1);
	try {
		Scriptable scope = rhino.initStandardObjects();
		rhino.evaluateString(scope, cachedDechiperFunction, "JavaScript", 1, null);
		Object obj = scope.get("decipher", scope);

		if (obj instanceof Function) {
			Function jsFunction = (Function) obj;
			Object jsResult = jsFunction.call(rhino, scope, scope, new Object[]{s});
			String result = Context.toString(jsResult);
			return result ;
		}
	}
	finally {
		Context.exit();
	}
	return s;
}
 
Example 3
Source File: JSEngine.java    From NewFastFrame with Apache License 2.0 6 votes vote down vote up
/**
 * 执行JS
 */
public String runScript(String functionParams, String methodName) {
    Context rhino = Context.enter();
    rhino.setOptimizationLevel(-1);
    try {
        Scriptable scope = rhino.initStandardObjects();

        ScriptableObject.putProperty(scope, "javaContext", Context.javaToJS(this, scope));
        ScriptableObject.putProperty(scope, "javaLoader", Context.javaToJS(JSEngine.class.getClassLoader(), scope));
        rhino.evaluateString(scope, sb.toString(), JSEngine.class.getName(), 1, null);
        Function function = (Function) scope.get(methodName, scope);
        Object result = function.call(rhino, scope, scope, new Object[]{functionParams});
        if (result instanceof String) {
            return (String) result;
        } else if (result instanceof NativeJavaObject) {
            return (String) ((NativeJavaObject) result).getDefaultValue(String.class);
        } else if (result instanceof NativeObject) {
            return (String) ((NativeObject) result).getDefaultValue(String.class);
        }
        return result.toString();//(String) function.call(rhino, scope, scope, functionParams);
    } finally {
        Context.exit();
    }
}
 
Example 4
Source File: CrosstabScriptHandler.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Call JavaScript functions with an argument array.
 * 
 * @param f
 *            The function to be executed
 * @param oaArgs
 *            The Java object arguments passed to the function being
 *            executed
 */
private Object callJavaScriptFunction( Function f, Object[] oaArgs )
		throws CrosstabException

{
	final Context cx = Context.enter( );
	Object oReturnValue = null;
	try
	{
		oReturnValue = f.call( cx, scope, scope, oaArgs );
	}
	catch ( RhinoException ex )
	{
		throw convertException( ex );
	}
	finally
	{
		Context.exit( );
	}
	return oReturnValue;
}
 
Example 5
Source File: JavascriptTestUtilities.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Call a Javascript function, identified by name, on a set of arguments. Optionally, expect it to throw
 * an exception.
 *
 * @param expectingException
 * @param functionName
 * @param args
 * @return
 */
public Object rhinoCallExpectingException(final Object expectingException, final String functionName,
                                          final Object... args) {
    Object fObj = rhinoScope.get(functionName, rhinoScope);
    if (!(fObj instanceof Function)) {
        throw new RuntimeException("Missing test function " + functionName);
    }
    Function function = (Function)fObj;
    try {
        return function.call(rhinoContext, rhinoScope, rhinoScope, args);
    } catch (RhinoException angryRhino) {
        if (expectingException != null && angryRhino instanceof JavaScriptException) {
            JavaScriptException jse = (JavaScriptException)angryRhino;
            Assert.assertEquals(jse.getValue(), expectingException);
            return null;
        }
        String trace = angryRhino.getScriptStackTrace();
        Assert.fail("JavaScript error: " + angryRhino.toString() + " " + trace);
    } catch (JavaScriptAssertionFailed assertion) {
        Assert.fail(assertion.getMessage());
    }
    return null;
}
 
Example 6
Source File: DcEngineContext.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * UserScript実行.
 * @param source ユーザースクリプトソース
 * @throws IOException IO例外
 * @throws DcEngineException DcEngineException
 */
private Object evalUserScript(final String source, JSGIRequest dcReq) throws DcEngineException {
    cx.evaluateString(scope, "fn_jsgi = " + source, null, 1, null);

    Object fObj = scope.get("fn_jsgi", scope);
    Object result = null;
    if (!(fObj instanceof Function)) {
        log.warn("fn_jsgi not found");
        throw new DcEngineException("Server Error", DcEngineException.STATUSCODE_SERVER_ERROR);
    }

    Object[] functionArgs = {dcReq.getRequestObject() };
    Function f = (Function) fObj;
    result = f.call(cx, scope, scope, functionArgs);
    return result;
}
 
Example 7
Source File: JavascriptTemplate.java    From manifold with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
public static String renderToStringImpl( ScriptableObject scope, JSTNode templateNode, Object... args )
{
  try
  {
    //make argument list including the raw string list
    Object[] argsWithStrings = Arrays.copyOf( args, args.length + 1 );

    List rawStrings = templateNode.getChildren( RawStringNode.class )
      .stream()
      .map( node -> node.genCode() )
      .collect( Collectors.toList() );

    argsWithStrings[argsWithStrings.length - 1] = rawStrings;

    Function renderToString = (Function)scope.get( "renderToString", scope );
    return (String)renderToString.call( Context.getCurrentContext(), scope, scope, argsWithStrings );
  }
  catch( Exception e )
  {
    throw new RuntimeException( e );
  }
}
 
Example 8
Source File: AbstractScriptHandler.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Call JavaScript functions with an argument array.
 * 
 * @param f
 *            The function to be executed
 * @param oaArgs
 *            The Java object arguments passed to the function being
 *            executed
 */
private final Object callJavaScriptFunction( Function f, Object[] oaArgs )
		throws ChartException

{
	final Context cx = Context.enter( );
	Object oReturnValue = null;
	// #229402
	ClassLoader oldLoader = cx.getApplicationClassLoader( );
	ClassLoader appLader = SecurityUtil.getClassLoader( AbstractScriptHandler.this.getClass( ) );
	cx.setApplicationClassLoader( appLader );

	// Initialize BIRT functions, register them into current script context.
	new CoreJavaScriptInitializer( ).initialize( cx, scope );

	try
	{
		oReturnValue = f.call( cx, scope, scope, oaArgs );
	}
	catch ( RhinoException ex )
	{
		throw convertException( ex );
	}
	finally
	{
		cx.setApplicationClassLoader( oldLoader );
		Context.exit( );
	}
	return oReturnValue;
}
 
Example 9
Source File: JsXMLHttpRequest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void notifyReadyStateChangeListener() {
    if (readyStateChangeListener instanceof Function) {
        LOG.fine("notify " + readyState);
        // for now, call with no args.
        Function listenerFunction = (Function)readyStateChangeListener;
        listenerFunction.call(Context.getCurrentContext(), getParentScope(), null, new Object[] {});
    }
}
 
Example 10
Source File: CaliperObjectBenchmark.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
@Benchmark
@SuppressWarnings("unused")
void deleteFields(int count)
{
    Function create = (Function)ScriptableObject.getProperty(scope, "createObject");
    Object o = create.call(cx, scope, null, new Object[]{1, strings, ints});
    Function delete = (Function)ScriptableObject.getProperty(scope, "deleteObject");
    delete.call(cx, scope, null, new Object[] {count, o, strings, ints});
}
 
Example 11
Source File: CaliperObjectBenchmark.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
@Benchmark
@SuppressWarnings("unused")
void ownKeysFields(long count)
{
    Function create = (Function)ScriptableObject.getProperty(scope, "createObject");
    Object o = create.call(cx, scope, null, new Object[]{1, strings, ints});
    Function iterate = (Function)ScriptableObject.getProperty(scope, "iterateOwnKeysObject");
    iterate.call(cx, scope, null, new Object[] {count, o});
}
 
Example 12
Source File: CaliperObjectBenchmark.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
@Benchmark
@SuppressWarnings("unused")
void iterateFields(long count)
{
    Function create = (Function)ScriptableObject.getProperty(scope, "createObject");
    Object o = create.call(cx, scope, null, new Object[]{1, strings, ints});
    Function iterate = (Function)ScriptableObject.getProperty(scope, "iterateObject");
    iterate.call(cx, scope, null, new Object[] {count, o});
}
 
Example 13
Source File: CaliperObjectBenchmark.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
@Benchmark
@SuppressWarnings("unused")
void accessFields(int count)
{
    Function create = (Function)ScriptableObject.getProperty(scope, "createObject");
    Object o = create.call(cx, scope, null, new Object[]{1, strings, ints});
    Function access = (Function)ScriptableObject.getProperty(scope, "accessObject");
    access.call(cx, scope, null, new Object[] {count, o, strings, ints});
}
 
Example 14
Source File: CaliperObjectBenchmark.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
@Benchmark
@SuppressWarnings("unused")
void createFields(int count)
{
    Function create = (Function)ScriptableObject.getProperty(scope, "createObject");
    create.call(cx, scope, null, new Object[]{count, strings, ints});
}
 
Example 15
Source File: JsRuntime.java    From manifold with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
public static <T> T invokeProg( ScriptableObject scope, String func, Object... args )
{
  try
  {
    Function renderToString = (Function)scope.get( func, scope );
    //noinspection unchecked
    return (T)renderToString.call( Context.getCurrentContext(), scope, scope, args );
  }
  catch( Exception e )
  {
    throw new RuntimeException( e );
  }
}
 
Example 16
Source File: AppRunnerInterpreter.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
public void callJsFunction(String name, Object... params) {
    Object obj = getJsFunction(name);
    if (obj instanceof Function) {
        Function function = (Function) obj;
        // NativeObject result = (NativeObject)
        function.call(rhino, scope, scope, params);
        processResult(RESULT_OK, "");
    }
}
 
Example 17
Source File: A6Util.java    From Huochexing12306 with Apache License 2.0 5 votes vote down vote up
/**
 * 执行JS
 * 
 * @param js js代码
 * @param functionName js方法名称
 * @param functionParams js方法参数
 * @return
 */
public static String runScript(Context context, String js, String functionName, Object[] functionParams) {
	org.mozilla.javascript.Context rhino = org.mozilla.javascript.Context.enter();
	rhino.setOptimizationLevel(-1);
	try {
		Scriptable scope = rhino.initStandardObjects();

		ScriptableObject.putProperty(scope, "javaContext", org.mozilla.javascript.Context.javaToJS(context, scope));
		ScriptableObject.putProperty(scope, "javaLoader", org.mozilla.javascript.Context.javaToJS(context.getClass().getClassLoader(), scope));

		rhino.evaluateString(scope, js, context.getClass().getSimpleName(), 1, null);

		Function function = (Function) scope.get(functionName, scope);

		Object result = function.call(rhino, scope, scope, functionParams);
		if (result instanceof String) {
			return (String) result;
		} else if (result instanceof NativeJavaObject) {
			return (String) ((NativeJavaObject) result).getDefaultValue(String.class);
		} else if (result instanceof NativeObject) {
			return (String) ((NativeObject) result).getDefaultValue(String.class);
		}
		return result.toString();//(String) function.call(rhino, scope, scope, functionParams);
	} finally {
		org.mozilla.javascript.Context.exit();
	}
}
 
Example 18
Source File: JSScriptEngine.java    From KakaoBot with GNU General Public License v3.0 4 votes vote down vote up
public void invoke(String func, Object... parameter) {
    Function function = (Function) scope.get(func);
    function.call(context, scope, scope, parameter);
}
 
Example 19
Source File: JSAcceptFacet.java    From emissary with Apache License 2.0 4 votes vote down vote up
/**
 * Test the specified payload and itinerary entries for acceptance. Itinerary steps will be removed from the list if
 * they are not accepted.
 *
 * @param payload the data object being routed
 * @param itinerary list of keys selected so far, can be modified
 */
public void accept(final IBaseDataObject payload, final List<DirectoryEntry> itinerary) {
    // Check conditions
    if (payload == null || itinerary == null) {
        logger.debug("Cannot operate on null payload or null itinerary");
        return;
    }

    if (itinerary.size() == 0) {
        return;
    }

    final Context ctx = this.contextFactory.enterContext();
    try {
        // One standard scope will do
        final Scriptable scope = makeAcceptFacetScope(ctx);

        // Get a function for each itinerary key present
        // and call the accept method on it
        // nb: no enhanced for loop due to i.remove() below
        for (Iterator<DirectoryEntry> i = itinerary.iterator(); i.hasNext();) {
            final DirectoryEntry de = i.next();
            logger.debug("Looking at itinerary item " + de.getKey());
            final Function func = getFunction(de);
            if (func == null) {
                continue;
            }

            MDC.put(MDCConstants.SERVICE_LOCATION, getResourceName(de));
            try {
                final Object accepted = func.call(ctx, scope, scope, new Object[] {payload});

                // If the javascript function says not to accept
                // we remote the key from the itinerary here
                if (accepted != Scriptable.NOT_FOUND && Boolean.FALSE.equals(accepted)) {
                    logger.debug("Removing directory entry " + getFunctionKey(de) + " due to js function false");
                    i.remove();
                }
            } catch (Exception ex) {
                logger.warn("Unable to run function for " + getFunctionKey(de), ex);
            } finally {
                MDC.remove(MDCConstants.SERVICE_LOCATION);
            }
        }
    } finally {
        Context.exit();
    }
}
 
Example 20
Source File: JsScriptEngine.java    From spork with Apache License 2.0 2 votes vote down vote up
/**
 * call a javascript function
 * @param functionName the name of the function
 * @param passedParams the parameters to pass
 * @return the result of the function
 */
public Object jsCall(String functionName, Object[] passedParams) {
    Function f = (Function)scope.get(functionName, scope);
    Object result = f.call(getContext(), scope, scope, passedParams);
    return result;
}