org.mozilla.javascript.NativeObject Java Examples

The following examples show how to use org.mozilla.javascript.NativeObject. 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: RhinoShellModule.java    From elasticshell with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
    bind(ScriptLoader.class).to(RhinoScriptLoader.class).asEagerSingleton();
    bind(new TypeLiteral<JsonToString<NativeObject>>() {}).to(RhinoJsonToString.class).asEagerSingleton();
    bind(new TypeLiteral<StringToJson<Object>>(){}).to(RhinoStringToJson.class).asEagerSingleton();
    bind(Unwrapper.class).to(RhinoUnwrapper.class).asEagerSingleton();
    bind(new TypeLiteral<ShellScope<RhinoShellTopLevel>>(){}).to(RhinoShellScope.class).asEagerSingleton();
    bind(ScriptExecutor.class).to(RhinoScriptExecutor.class).asEagerSingleton();
    bind(InputAnalyzer.class).to(RhinoInputAnalyzer.class).asEagerSingleton();
    bind(Shell.class).to(RhinoShell.class).asEagerSingleton();

    bind(new TypeLiteral<ClientScopeSynchronizerFactory<RhinoClientNativeJavaObject>>(){})
            .to(RhinoClientScopeSynchronizerFactory.class).asEagerSingleton();

    bind(new TypeLiteral<ClientWrapper<RhinoClientNativeJavaObject, NativeObject, Object>>(){})
            .to(RhinoClientWrapper.class).asEagerSingleton();

    bind(new TypeLiteral<ClientFactory<RhinoClientNativeJavaObject>>() {})
            .to(new TypeLiteral<DefaultClientFactory<RhinoClientNativeJavaObject, NativeObject, Object>>() {})
            .asEagerSingleton();

    bind(new TypeLiteral<NodeFactory<RhinoClientNativeJavaObject, NativeObject, Object>>(){})
            .to(new TypeLiteral<DefaultNodeFactory<RhinoClientNativeJavaObject, NativeObject, Object>>() {})
            .asEagerSingleton();
}
 
Example #2
Source File: BaseAnalyzerPresenter.java    From HaoReader with GNU General Public License v3.0 6 votes vote down vote up
@Override
public final String getTextDirectly(String rule) {
    final Object object = getParser().getPrimitive();
    if (object instanceof NativeObject) {
        return StringUtils.valueOf(((NativeObject) object).get(rule));
    } else if (object instanceof Element) {
        Element element = (Element) object;
        if (StringUtils.isBlank(rule)) {
            return element.text();
        }
        Element find = element.selectFirst(rule);
        return StringUtils.checkNull(find == null ? null : find.text(), element.text());
    } else if (object instanceof JXNode) {
        return StringUtils.valueOf(((JXNode) object).selOne(rule));
    }
    return getText(rule);
}
 
Example #3
Source File: CommandModule.java    From elasticshell with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
    Multibinder<Command> multiBinder = Multibinder.newSetBinder(binder(), Command.class);
    multiBinder.addBinding().to(ExitCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(HelpCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(PrintCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(SaveCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(HistoryCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(VersionCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(LoadCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(HttpGetCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(HttpHeadCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(HttpPostCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(HttpPutCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(HttpDeleteCommand.class).asEagerSingleton();

    //Rhino specific commands
    multiBinder.addBinding().to(new TypeLiteral<ToJsonCommand<Object>>() {}).asEagerSingleton();
    multiBinder.addBinding().to(new TypeLiteral<TransportClientCommand<RhinoClientNativeJavaObject>>(){}).asEagerSingleton();
    multiBinder.addBinding().to(new TypeLiteral<NodeClientCommand<RhinoClientNativeJavaObject>>(){}).asEagerSingleton();
    multiBinder.addBinding().to(new TypeLiteral<LocalNodeCommand<RhinoClientNativeJavaObject, NativeObject, Object>>(){}).asEagerSingleton();

    bind(RhinoCommandRegistrar.class).asEagerSingleton();
}
 
Example #4
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 #5
Source File: ScriptPreferenceService.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public NativeObject getPreferences(String userName, String preferenceFilter)
{
    // It's a tad unusual to return a NativeObject like this - at least within Alfresco.
    // But we can't change it to e.g. a ScriptableHashMap as the API is published.
    Map<String, Serializable> prefs = this.preferenceService.getPreferences(userName, preferenceFilter);        
    NativeObject result = new NativeObjectDV();
    
    for (Map.Entry<String, Serializable> entry : prefs.entrySet())
    {
        String key = entry.getKey();
        String[] keys;
        int colonIndex = key.indexOf(":");
        if (colonIndex > -1)
        {
            keys = key.substring(0, colonIndex).replace(".", "+").split("\\+");
            keys[keys.length - 1] = keys[keys.length - 1].concat(key.substring(colonIndex));
        }
        else
        {
            keys = key.replace(".", "+").split("\\+");
        }
        setPrefValue(keys, entry.getValue(), result);
    }        
    
    return result;
}
 
Example #6
Source File: Context.java    From JVoiceXML with GNU Lesser General Public License v2.1 6 votes vote down vote up
static Object getOutApplyDefaultAssignmentIfNeeded(
        org.mozilla.javascript.Context context, Scriptable ruleScope,
        boolean ruleRefProcessed) {

    Object out = context.evaluateString(ruleScope, "out;", "Context:out",
            0, null);
    // If out is still an empty object, perform the default assignment
    if (out instanceof NativeObject
            && ((NativeObject) out).getIds().length == 0) {
        if (ruleRefProcessed) {
            LOGGER.debug("default assignment(lastrule)");
            out = context.evaluateString(ruleScope,
                    "out = rules.latest();", "Context:out", 0, null);
        } else {
            String ruleMetaCurrent = (String) context.evaluateString(
                    ruleScope, "meta.current().text;",
                    "Context:rule get meta", 0, null);
            LOGGER.debug("default assignment(meta): " + ruleMetaCurrent);
            out = context.evaluateString(ruleScope, "out = '"
                    + ruleMetaCurrent + "';", "Context:out", 0, null);
        }
    }
    return out;
}
 
Example #7
Source File: ScriptPreferenceService.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void getPrefValues(NativeObject currentObject, String currentKey, Map<String, Serializable> values)
{
    Object[] ids = currentObject.getIds();
    for (Object id : ids)
    {
        String key = getAppendedKey(currentKey, id.toString());
        Object value = currentObject.get(id.toString(), currentObject);
        if (value instanceof NativeObject)
        {
            getPrefValues((NativeObject)value, key, values);
        }
        else
        {
            values.put(key, (Serializable)value);
        }
    }
}
 
Example #8
Source File: JSPig.java    From spork with Apache License 2.0 6 votes vote down vote up
/**
 * javascript helper for binding parameters. 
 * See: {@link Pig#bind(Map)}
 * @param o a javascript object to be converted into a Map
 * @return the bound script
 * @throws IOException if {@link Pig#bind(Map)} throws an IOException
 */
public BoundScript bind(Object o) throws IOException {
    NativeObject vars = (NativeObject)o;
    Map<String, Object> params = new HashMap<String, Object>();
    Object[] ids = vars.getIds();
    for (Object id : ids) {
        if (id instanceof String) {
            String name = (String) id;
            Object value = vars.get(name, vars);
            if (!(value instanceof NativeFunction) && value != null) {
                params.put(name, value.toString());
            }
        }
    }
    return pig.bind(params);
}
 
Example #9
Source File: ScriptedIncomingMapping.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
static NativeObject mapExternalMessageToNativeObject(final ExternalMessage message) {
    final NativeObject headersObj = new NativeObject();
    message.getHeaders().forEach((key, value) -> headersObj.put(key, headersObj, value));

    final NativeArrayBuffer bytePayload =
            message.getBytePayload()
                    .map(bb -> {
                        final NativeArrayBuffer nativeArrayBuffer = new NativeArrayBuffer(bb.remaining());
                        bb.get(nativeArrayBuffer.getBuffer());
                        return nativeArrayBuffer;
                    })
                    .orElse(null);

    final String contentType = message.getHeaders().get(ExternalMessage.CONTENT_TYPE_HEADER);
    final String textPayload = message.getTextPayload().orElse(null);

    final NativeObject externalMessage = new NativeObject();
    externalMessage.put(EXTERNAL_MESSAGE_HEADERS, externalMessage, headersObj);
    externalMessage.put(EXTERNAL_MESSAGE_TEXT_PAYLOAD, externalMessage, textPayload);
    externalMessage.put(EXTERNAL_MESSAGE_BYTE_PAYLOAD, externalMessage, bytePayload);
    externalMessage.put(EXTERNAL_MESSAGE_CONTENT_TYPE, externalMessage, contentType);
    return externalMessage;
}
 
Example #10
Source File: PacScriptParser.java    From SmartZPN with GNU Lesser General Public License v3.0 6 votes vote down vote up
private String runScript(String js, String functionName, Object[] functionParams) {
    Context rhino = Context.enter();
    rhino.setOptimizationLevel(-1);
    try {
        Scriptable scope = rhino.initStandardObjects();
        rhino.evaluateString(scope, js, "JavaScript", js.split("\n").length, 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();
    } finally {
        Context.exit();
    }
}
 
Example #11
Source File: JSGIRequest.java    From io with Apache License 2.0 6 votes vote down vote up
private static void dump(NativeObject request) {
    String format = "[%s]-[%s]";
    log.debug("-jsgi-request-object-dump-start-");
    log.debug(String.format(format, "method", request.get("method", request)));
    log.debug(String.format(format, "scriptName", request.get("scriptName", request)));
    log.debug(String.format(format, "pathInfo", request.get("pathInfo", request)));
    log.debug(String.format(format, "queryString", request.get("queryString", request)));
    log.debug(String.format(format, "host", request.get("host", request)));
    log.debug(String.format(format, "port", request.get("port", request)));
    log.debug(String.format(format, "scheme", request.get("scheme", request)));

    log.debug(request.get("headers", request).toString());
    log.debug(request.get("jsgi", request).toString());
    log.debug(request.get("env", request).toString());
    log.debug("-jsgi-request-object-dump-finish-");
}
 
Example #12
Source File: DetermineBasalResultMA.java    From AndroidAPS with GNU Affero General Public License v3.0 5 votes vote down vote up
DetermineBasalResultMA(NativeObject result, JSONObject j) {
    json = j;
    if (result.containsKey("error")) {
        reason = (String) result.get("error");
        tempBasalRequested = false;
        rate = -1;
        duration = -1;
        mealAssist = "";
    } else {
        reason = result.get("reason").toString();
        eventualBG = (Double) result.get("eventualBG");
        snoozeBG = (Double) result.get("snoozeBG");
        if (result.containsKey("rate")) {
            rate = (Double) result.get("rate");
            if (rate < 0d) rate = 0d;
            tempBasalRequested = true;
        } else {
            rate = -1;
            tempBasalRequested = false;
        }
        if (result.containsKey("duration")) {
            duration = ((Double) result.get("duration")).intValue();
            //changeRequested as above
        } else {
            duration = -1;
            tempBasalRequested = false;
        }
        if (result.containsKey("mealAssist")) {
            mealAssist = result.get("mealAssist").toString();
        } else mealAssist = "";
    }
}
 
Example #13
Source File: DetermineBasalResultAMA.java    From AndroidAPS with GNU Affero General Public License v3.0 5 votes vote down vote up
DetermineBasalResultAMA(NativeObject result, JSONObject j) {
    this();
    date = DateUtil.now();
    json = j;
    if (result.containsKey("error")) {
        reason = result.get("error").toString();
        tempBasalRequested = false;
        rate = -1;
        duration = -1;
    } else {
        reason = result.get("reason").toString();
        if (result.containsKey("eventualBG")) eventualBG = (Double) result.get("eventualBG");
        if (result.containsKey("snoozeBG")) snoozeBG = (Double) result.get("snoozeBG");
        if (result.containsKey("rate")) {
            rate = (Double) result.get("rate");
            if (rate < 0d) rate = 0d;
            tempBasalRequested = true;
        } else {
            rate = -1;
            tempBasalRequested = false;
        }
        if (result.containsKey("duration")) {
            duration = ((Double) result.get("duration")).intValue();
            //changeRequested as above
        } else {
            duration = -1;
            tempBasalRequested = false;
        }
    }
    bolusRequested = false;
}
 
Example #14
Source File: Context.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void dumpScope(final Scriptable scope, String pad) {
    java.lang.Object[] ids = scope.getIds();
    for (Object id : ids) {
        Object o = null;
        if (id instanceof String) {
            o = scope.get((String) id, scope);
            LOGGER.debug(pad + id + "=" + o + " ("
                    + o.getClass().getCanonicalName() + ")");
        } else {
            o = scope.get((int) id, scope);
            LOGGER.debug(pad + id + "=" + o + " ("
                    + o.getClass().getCanonicalName() + ")");
        }

        if (o instanceof Scriptable)
            dumpScope((Scriptable) o, pad + " ");
        else if (o instanceof NativeObject) {
            for (Map.Entry<Object, Object> item : ((NativeObject) o)
                    .entrySet()) {
                LOGGER.debug(pad + " " + item.getKey() + "="
                        + item.getValue() + " ("
                        + item.getValue().getClass().getCanonicalName()
                        + ")");
            }
        }
    }
}
 
Example #15
Source File: Utils.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void dumpScope(final Scriptable scope, String pad) {
    java.lang.Object[] ids = scope.getIds();
    for (Object id : ids) {
        Object o = null;
        if (id instanceof String) {
            o = scope.get((String) id, scope);
            Logger.getRootLogger().debug(
                    pad + id + "=" + o + " ("
                            + o.getClass().getCanonicalName() + ")");
        } else {
            o = scope.get((int) id, scope);
            Logger.getRootLogger().debug(
                    pad + id + "=" + o + " ("
                            + o.getClass().getCanonicalName() + ")");
        }

        if (o instanceof Scriptable)
            dumpScope((Scriptable) o, pad + " ");
        else if (o instanceof NativeObject) {
            for (Map.Entry<Object, Object> item : ((NativeObject) o)
                    .entrySet()) {
                Logger.getRootLogger().debug(
                        pad
                                + " "
                                + item.getKey()
                                + "="
                                + item.getValue()
                                + " ("
                                + item.getValue().getClass()
                                        .getCanonicalName() + ")");
            }
        }
    }
}
 
Example #16
Source File: JSGIRequest.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * サーブレットのリクエストからJavaScriptのJSGIオブジェクトを生成する.
 * @return JavaScript用JSGIオブジェクト
 */
public NativeObject getRequestObject() {
    NativeObject request = new NativeObject();
    request.put("method", request, this.req.getMethod());
    request.put("host", request, this.req.getAttribute("host").toString());
    request.put("port", request, this.req.getAttribute("port").toString());
    request.put("scriptName", request, this.req.getAttribute("scriptName").toString());
    request.put("pathInfo", request, this.req.getPathInfo());
    // サーバ動作時のPOSTでservlet.getQueryStringでクエリが取れないために以下の取り方で実現。
    String[] urlItems = this.req.getAttribute("env.requestUri").toString().split("\\?");
    String queryString = "";
    if (urlItems.length > 1) {
        queryString = urlItems[1];
    }
    request.put("queryString", request, queryString);
    request.put("scheme", request, this.req.getAttribute("scheme").toString());

    request.put("headers", request, this.headers());

    request.put("env", request, this.env());

    request.put("jsgi", request, this.makeJSGI());

    request.put("input", request, this.input);

    dump(request);
    return request;
}
 
Example #17
Source File: JSGIRequest.java    From io with Apache License 2.0 5 votes vote down vote up
private NativeObject makeJSGI() {
    NativeObject jsgi = new NativeObject();
    NativeArray version = new NativeArray(new Object[]{JSGI_VERSION_MAJOR, JSGI_VERSION_MINOR});
    jsgi.put("version", jsgi, version);
    jsgi.put("errors", jsgi, "");
    jsgi.put("multithread", jsgi, "");
    jsgi.put("multiprocess", jsgi, "");
    jsgi.put("run_once", jsgi, "");
    jsgi.put("cgi", jsgi, "");
    jsgi.put("ext", jsgi, "");
    return jsgi;
}
 
Example #18
Source File: JsonParserTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
@SuppressWarnings({ "serial", "unchecked" })
public void shouldParseJsonObject() throws Exception {
    String json = "{" +
            "\"bool\" : false, " +
            "\"str\"  : \"xyz\", " +
            "\"obj\"  : {\"a\":1} " +
            "}";
NativeObject actual = (NativeObject) parser.parseValue(json);
assertEquals(false, actual.get("bool", actual));
assertEquals("xyz", actual.get("str", actual));

NativeObject innerObj = (NativeObject) actual.get("obj", actual);
assertEquals(1, innerObj.get("a", innerObj));
}
 
Example #19
Source File: PostmanJsVariables.java    From postman-runner with Apache License 2.0 5 votes vote down vote up
private void prepareJsVariables(PostmanHttpResponse httpResponse) {

		this.responseCode = new NativeObject();
		if (httpResponse != null) {
			List<Object> headerList = new ArrayList<Object>(httpResponse.headers.size());
			for (Map.Entry<String, String> h : httpResponse.headers.entrySet()) {
				NativeObject hobj = new NativeObject();
				hobj.put("key", hobj, h.getKey());
				hobj.put("value", hobj, h.getValue());
				headerList.add(hobj);
			}
			this.responseHeaders = new NativeArray(headerList.toArray());
			this.responseBody = Context.javaToJS(httpResponse.body, scope);

			this.responseCode.put("code", responseCode, httpResponse.code);
		} else {
			this.responseHeaders = new NativeArray(new Object[] {});
			this.responseBody = Context.javaToJS("", scope);

			this.responseCode.put("code", responseCode, 0);
		}

		// TODO: fix me
		this.responseTime = Context.javaToJS(0.0, scope);

		// TODO: fix me
		this.iteration = Context.javaToJS(0, scope);

		// The postman js var is only used to setEnvironmentVariables()
		this.postman = Context.javaToJS(this.env, scope);

		this.environment = new NativeObject();
		Set<Map.Entry<String, PostmanEnvValue>> map = this.env.lookup.entrySet();
		for (Map.Entry<String, PostmanEnvValue> e : map) {
			this.environment.put(e.getKey(), environment, e.getValue().value);
		}

		this.tests = new NativeObject();
		this.preRequestScript = new NativeObject();
	}
 
Example #20
Source File: JsFunction.java    From spork with Apache License 2.0 5 votes vote down vote up
@Override
public Object exec(Tuple tuple) throws IOException {
	Schema inputSchema = this.getInputSchema();
    if (LOG.isDebugEnabled()) {
        LOG.debug( "CALL " + stringify(outputSchema) + " " + functionName + " " + stringify(inputSchema));
    }
    // UDF always take a tuple: unwrapping when not necessary to simplify UDFs
    if (inputSchema.size() == 1 && inputSchema.getField(0).type == DataType.TUPLE) {
        inputSchema = inputSchema.getField(0).schema;
    }

    Scriptable params = pigTupleToJS(tuple, inputSchema, 0);

    Object[] passedParams = new Object[inputSchema.size()];
    for (int j = 0; j < passedParams.length; j++) {
        passedParams[j] = params.get(inputSchema.getField(j).alias, params);
    }

    Object result = jsScriptEngine.jsCall(functionName, passedParams);
    if (LOG.isDebugEnabled()) {
        LOG.debug( "call "+functionName+"("+Arrays.toString(passedParams)+") => "+toString(result));
    }

    // We wrap the result with an object in the following cases:
    //   1. Result is not an object type.
    //   2. OutputSchema is a tuple type. 
    if (!(result instanceof NativeObject) || outputSchema.getField(0).type == DataType.TUPLE) {
        Scriptable wrapper = jsScriptEngine.jsNewObject();
        wrapper.put(outputSchema.getField(0).alias, wrapper, result);
        result = wrapper;
    }
    Tuple evalTuple = jsToPigTuple((Scriptable)result, outputSchema, 0);
    Object eval = outputSchema.size() == 1 ? evalTuple.get(0) : evalTuple;
    LOG.debug(eval);
    return eval;
}
 
Example #21
Source File: UsesDetailFalseTest.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Get result list
 * @param resultIt
 * @return List[] rowList, sumList, sglList, eglList
 * @throws DataException
 */
private List[] getQueryResult( IResultIterator resultIt ) throws Exception
{
	List rowList = new ArrayList( );
	List sumList = new ArrayList( );
	List sglList = new ArrayList( );
	List eglList = new ArrayList( );
	List subList = new ArrayList( );

	Scriptable subScope = new NativeObject( );
	subScope.setPrototype( jsScope );
	subScope.setParentScope( jsScope );

	while ( resultIt.next( ) )
	{
		rowList.add( resultIt.getValue( keyName1 ) );
		sumList.add( resultIt.getValue( aggrName1 ) );
		sglList.add( new Integer( resultIt.getStartingGroupLevel( ) ) );
		eglList.add( new Integer( resultIt.getEndingGroupLevel( ) ) );

		List subKeyRow1List = new ArrayList( );
		List subKeyRow2List = new ArrayList( );
		List subAggregaList = new ArrayList( );
		IResultIterator subIterator = resultIt.getSecondaryIterator( "IAMTEST",
				subScope );			
		while ( subIterator.next( ) )
		{
			subKeyRow1List.add( subIterator.getValue( keyName2 ) );
			subKeyRow2List.add( subIterator.getValue( keyName3 ) );
			subAggregaList.add( subIterator.getValue( aggrName2 ) );
		}
		subList.add( subKeyRow1List );
		subList.add( subKeyRow2List );
		subList.add( subAggregaList );
	}

	return new List[]{
			rowList, sumList, sglList, eglList, subList
	};
}
 
Example #22
Source File: RhinoClientWrapper.java    From elasticshell with Apache License 2.0 5 votes vote down vote up
@Inject
RhinoClientWrapper(ShellScope<RhinoShellTopLevel> shellScope,
                   RhinoJsonToString jsonToString, RhinoStringToJson stringToJson,
                   DumpSaver<NativeObject> dumpSaver, DumpRestorer dumpRestorer) {
    super(jsonToString, stringToJson, dumpSaver, dumpRestorer);
    this.shellScope = shellScope;
}
 
Example #23
Source File: JsonParserTest.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings({ "serial", "unchecked" })
public void shouldParseJsonObject() throws Exception {
    String json = "{" +
            "\"bool\" : false, " +
            "\"str\"  : \"xyz\", " +
            "\"obj\"  : {\"a\":1} " +
            "}";
NativeObject actual = (NativeObject) parser.parseValue(json);
assertEquals(false, actual.get("bool", actual));
assertEquals("xyz", actual.get("str", actual));

NativeObject innerObj = (NativeObject) actual.get("obj", actual);
assertEquals(1, innerObj.get("a", innerObj));
}
 
Example #24
Source File: BookList.java    From MyBookshelf with GNU General Public License v3.0 5 votes vote down vote up
private SearchBookBean getItemAllInOne(AnalyzeRule analyzer, Object object, String baseUrl, boolean printLog) {
    SearchBookBean item = new SearchBookBean();
    analyzer.setBook(item);
    NativeObject nativeObject = (NativeObject) object;
    Debug.printLog(tag, 1, "┌获取书名", printLog);
    String bookName = StringUtils.formatHtml(String.valueOf(nativeObject.get(ruleName)));
    Debug.printLog(tag, 1, "└" + bookName, printLog);
    if (!isEmpty(bookName)) {
        item.setTag(tag);
        item.setOrigin(sourceName);
        item.setName(bookName);
        Debug.printLog(tag, 1, "┌获取作者", printLog);
        item.setAuthor(StringUtils.formatHtml(String.valueOf(nativeObject.get(ruleAuthor))));
        Debug.printLog(tag, 1, "└" + item.getAuthor(), printLog);
        Debug.printLog(tag, 1, "┌获取分类", printLog);
        item.setKind(String.valueOf(nativeObject.get(ruleKind)));
        Debug.printLog(tag, 111, "└" + item.getKind(), printLog);
        Debug.printLog(tag, 1, "┌获取最新章节", printLog);
        item.setLastChapter(String.valueOf(nativeObject.get(ruleLastChapter)));
        Debug.printLog(tag, 1, "└" + item.getLastChapter(), printLog);
        Debug.printLog(tag, 1, "┌获取简介", printLog);
        item.setIntroduce(String.valueOf(nativeObject.get(ruleIntroduce)));
        Debug.printLog(tag, 1, "└" + item.getIntroduce(), printLog, true);
        Debug.printLog(tag, 1, "┌获取封面", printLog);
        if (!isEmpty(ruleCoverUrl))
            item.setCoverUrl(NetworkUtils.getAbsoluteURL(baseUrl, String.valueOf(nativeObject.get(ruleCoverUrl))));
        Debug.printLog(tag, 1, "└" + item.getCoverUrl(), printLog);
        Debug.printLog(tag, 1, "┌获取书籍网址", printLog);
        String resultUrl = String.valueOf(nativeObject.get(ruleNoteUrl));
        if (isEmpty(resultUrl)) resultUrl = baseUrl;
        item.setNoteUrl(resultUrl);
        Debug.printLog(tag, 1, "└" + item.getNoteUrl(), printLog);
        return item;
    }
    return null;
}
 
Example #25
Source File: BaseAnalyzerPresenter.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
@Override
public final String getRawUrlDirectly(String rule) {
    final Object object = getParser().getPrimitive();
    if (object instanceof NativeObject) {
        return StringUtils.valueOf(((NativeObject) object).get(rule));
    } else if (object instanceof Element) {
        Element element = (Element) object;
        return element.attr(rule);
    } else if (object instanceof JXNode) {
        return StringUtils.valueOf(((JXNode) object).selOne(rule));
    }
    return getRawUrl(rule);
}
 
Example #26
Source File: ScriptPreferenceService.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void setPreferences(String userName, NativeObject preferences)
{
    Map<String, Serializable> values = new HashMap<String, Serializable>(10);
    getPrefValues(preferences, null, values);
    
    this.preferenceService.setPreferences(userName, values);
}
 
Example #27
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 #28
Source File: PEvents.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
public void sendEvent(String name, NativeObject obj) {
    //get all matching listeners and send event

    for (int i = 0; i < eventsList.size(); i++) {
        if (name.equals(eventsList.get(i).name)) {
            eventsList.get(i).cb.event(obj);
        }
    }
}
 
Example #29
Source File: PApp.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Start an activity
 *
 * @param params
 * @throws JSONException
 * @advanced
 * @status TODO
 */
@PhonkMethod
public void startActivity(NativeObject params) throws JSONException {
    Intent intent = new Intent();

    JSONObject jsonParams = new JSONObject(params);

    String action = (String) jsonParams.get("action");
    intent.setAction(action);

    JSONObject extras = (JSONObject) jsonParams.get("extras");
    Iterator<String> iterator = extras.keys();
    while (iterator.hasNext()) {
        String key = iterator.next();
        String value = (String) extras.get(key);
        intent.putExtra(key, value);
    }

    String data = (String) jsonParams.get("data");
    intent.setData(Uri.parse(data));

    String type = (String) jsonParams.get("type");
    intent.setType(type);

    JSONObject component = (JSONObject) jsonParams.get("component");
    intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));

    // JSONArray flags = (JSONArray) jsonParams.get("flags");
    // intent.setFlags(flags);

    getContext().startActivity(intent);

    // getActivity().startActivityForResult();
}
 
Example #30
Source File: PUtil.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
public void setAnObject(NativeObject obj) {
    for (Map.Entry<Object, Object> entry : obj.entrySet()) {
        String key = (String) entry.getKey();
        Object o = entry.getValue();

        MLog.d(TAG, "setAnObject -> " + key + " " + o);
    }

    MLog.d(TAG, "q --> " + obj.get("q"));
}