Java Code Examples for org.mozilla.javascript.NativeObject#get()

The following examples show how to use org.mozilla.javascript.NativeObject#get() . 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: 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 2
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 3
Source File: ScriptedOutgoingMapping.java    From ditto with 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 4
Source File: ScriptedIncomingMappingTest.java    From ditto with 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 5
Source File: ScriptedIncomingMappingTest.java    From ditto with 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 6
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 7
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 8
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 9
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 10
Source File: PNetwork.java    From PHONK with GNU General Public License v3.0 4 votes vote down vote up
@PhonkMethod(description = "Simple http post request. It needs an object to be sent. If an element of the object contains the key file then it will try to upload the resource indicated in the value as Uri ", example = "")
@PhonkMethodParam(params = {"url", "params", "function(responseString)"})
public void httpPost(final String url, final NativeArray parts, final ReturnInterface callbackfn) {
    final OkHttpClient client = new OkHttpClient();

    Thread t = new Thread(() -> {

        MultipartBody.Builder formBody = new MultipartBody.Builder();
        formBody.setType(MultipartBody.FORM);

        for (int i = 0; i < parts.size(); i++) {
            NativeObject o = (NativeObject) parts.get(i);

            // go through elements
            String name = o.get("name").toString();
            String content = o.get("content").toString();
            String type = o.get("type").toString();

            if (type.equals("file")) {
                String mediaType = (String) o.get("mediaType");
                File f = new File(getAppRunner().getProject().getFullPathForFile(content));
                MLog.d("nn1", f.getAbsolutePath() + " " + content + " " + name + " " + mediaType);
                formBody.addFormDataPart(name, content, RequestBody.create(MediaType.parse(mediaType), f));
            } else {
                formBody.addFormDataPart(name, content);
            }
        }
        MultipartBody body = formBody.build();

        Request request = new Request.Builder().url(url).post(body).build();
        Response response = null;
        final ReturnObject ret = new ReturnObject();
        try {
            response = client.newCall(request).execute();
            ret.put("response", response.body().string());
            ret.put("status", response.code());
            mHandler.post(() -> callbackfn.event(ret));
        } catch (IOException e) {
            e.printStackTrace();
        }


    });
    t.start();


    /*
    final HttpClient httpClient = new DefaultHttpClient();
    final HttpContext localContext = new BasicHttpContext();
    final HttpPost httpPost = new HttpPost(url);

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    for (int i = 0; i < parts.size(); i++) {
        NativeObject o = (NativeObject) parts.get(i);

        // go through elements
        String name = (String) o.get("name");
        String content = (String) o.get("content");
        String type = (String) o.get("type");

        // create the multipart
        if (type.contains("file")) {
            File f = new File(getAppRunner().getProject().getFullPathForFile(content));
            ContentBody cbFile = new FileBody(f);
            entity.addPart(name, cbFile);
        } else if (type.equals("text")){ // Normal string data
            entity.addPart(name, new StringBody(content, ContentType.TEXT_PLAIN));
        } else if (type.equals("json")){ // Normal string data
            entity.addPart(name, new StringBody(content, ContentType.APPLICATION_JSON));
        }
    }

    // send
    httpPost.setEntity(entity);
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                HttpResponse response = httpClient.execute(httpPost, localContext);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                String responseString = out.toString();

                ReturnObject o = new ReturnObject();
                o.put("status", response.getStatusLine().toString());
                o.put("response", responseString);
                callbackfn.event(o);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

    */
}