Java Code Examples for org.mozilla.javascript.NativeObject

The following examples show how to use org.mozilla.javascript.NativeObject. These examples are extracted from open source projects. 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
@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 2
Source Project: NewFastFrame   Source File: JSEngine.java    License: 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 3
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 4
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 5
Source Project: ditto   Source File: ScriptedIncomingMapping.java    License: 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 6
Source Project: JVoiceXML   Source File: Context.java    License: 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
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 8
Source Project: io   Source File: JSGIRequest.java    License: 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 9
Source Project: spork   Source File: JSPig.java    License: 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 10
Source Project: elasticshell   Source File: CommandModule.java    License: 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 11
Source Project: elasticshell   Source File: RhinoShellModule.java    License: 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 12
Source Project: a   Source File: BookList.java    License: 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 13
Source Project: MyBookshelf   Source File: BookList.java    License: 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 14
@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 15
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 16
Source Project: Huochexing12306   Source File: A6Util.java    License: 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 17
Source Project: PHONK   Source File: PEvents.java    License: 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 18
Source Project: PHONK   Source File: PApp.java    License: 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 19
Source Project: PHONK   Source File: PUtil.java    License: 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"));
}
 
Example 20
Source Project: ditto   Source File: ScriptedOutgoingMapping.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private ExternalMessage getExternalMessageFromObject(final Adaptable adaptable, final NativeObject result) {
    final Object contentType = result.get(EXTERNAL_MESSAGE_CONTENT_TYPE);
    final Object textPayload = result.get(EXTERNAL_MESSAGE_TEXT_PAYLOAD);
    final Object bytePayload = result.get(EXTERNAL_MESSAGE_BYTE_PAYLOAD);
    final Object mappingHeaders = result.get(EXTERNAL_MESSAGE_HEADERS);

    final Map<String, String> headers;
    if (mappingHeaders != null && !(mappingHeaders instanceof Undefined)) {
        headers = new HashMap<>();
        final Map jsHeaders = (Map) mappingHeaders;
        jsHeaders.forEach((key, value) -> headers.put(String.valueOf(key), String.valueOf(value)));
    } else {
        headers = Collections.emptyMap();
    }

    final ExternalMessageBuilder messageBuilder =
            ExternalMessageFactory.newExternalMessageBuilder(headers);

    if (!(contentType instanceof Undefined)) {
        messageBuilder.withAdditionalHeaders(ExternalMessage.CONTENT_TYPE_HEADER,
                ((CharSequence) contentType).toString());
    }

    final Optional<ByteBuffer> byteBuffer = convertToByteBuffer(bytePayload);
    if (byteBuffer.isPresent()) {
        messageBuilder.withBytes(byteBuffer.get());
    } else if (!(textPayload instanceof Undefined)) {
        messageBuilder.withText(((CharSequence) textPayload).toString());
    } else {
        throw MessageMappingFailedException.newBuilder("")
                .description("Neither <bytePayload> nor <textPayload> were defined in the outgoing script")
                .dittoHeaders(adaptable.getHeaders().orElse(DittoHeaders.empty()))
                .build();
    }

    return messageBuilder.build();
}
 
Example 21
Source Project: ditto   Source File: ScriptedIncomingMappingTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void mapExternalMessageTextAndBytes() {
    final ExternalMessage externalMessage = ExternalMessageFactory
            .newExternalMessageBuilder(new HashMap<>())
            .withTextAndBytes(PAYLOAD, ByteBuffer.wrap(BYTES))
            .build();

    final NativeObject nativeObject = ScriptedIncomingMapping.mapExternalMessageToNativeObject(externalMessage);

    final String textPayload = (String) nativeObject.get("textPayload");
    final NativeArrayBuffer bytePayload = (NativeArrayBuffer) nativeObject.get("bytePayload");
    assertThat(textPayload).isEqualTo(PAYLOAD);
    assertThat(bytePayload.getBuffer()).isEqualTo(BYTES);
}
 
Example 22
Source Project: ditto   Source File: ScriptedIncomingMappingTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private void mapExternalMessage(final ByteBuffer source) {
    final ExternalMessage externalMessage = ExternalMessageFactory
            .newExternalMessageBuilder(new HashMap<>())
            .withBytes(source)
            .build();

    final NativeObject nativeObject = ScriptedIncomingMapping.mapExternalMessageToNativeObject(externalMessage);

    final NativeArrayBuffer bytePayload = (NativeArrayBuffer) nativeObject.get("bytePayload");
    assertThat(bytePayload.getBuffer()).isEqualTo(BYTES);
}
 
Example 23
Source Project: rhino-android   Source File: JsonParserTest.java    License: 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
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 25
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 26
Source Project: JVoiceXML   Source File: Context.java    License: 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 27
Source Project: JVoiceXML   Source File: Utils.java    License: 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 28
Source Project: io   Source File: JSGIRequest.java    License: 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 29
Source Project: io   Source File: JSGIRequest.java    License: 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 30
Source Project: astor   Source File: JsonParserTest.java    License: 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));
}