org.mozilla.javascript.NativeArray Java Examples
The following examples show how to use
org.mozilla.javascript.NativeArray.
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: RhinoValueConverter.java From pentaho-reporting with GNU Lesser General Public License v2.1 | 6 votes |
public Object convert( final Object o ) { if ( o instanceof NativeJavaObject ) { final NativeJavaObject object = (NativeJavaObject) o; return object.unwrap(); } if ( o instanceof NativeArray ) { final NativeArray array = (NativeArray) o; final Object[] result = new Object[(int) array.getLength()]; for ( final Object val : array.getIds() ) { final int index = (Integer) val; result[index] = array.get( index, null ); } return result; } return null; }
Example #2
Source File: DcResponse.java From io with Apache License 2.0 | 6 votes |
/** * JavaScriptのforEachをJavaで処理するためのメソッド. * @param element forEachの要素が一件ずつ渡される * @param number 渡された要素のindexが渡される * @param object forEach対象のオブジェクトの全要素の配列が渡される * @throws IOException IOException */ public void bodyResponseFunction(Object element, double number, NativeArray object) throws IOException { if (element instanceof DcInputStream) { // 現状はEngine上のJavaScriptでバイナリを直接扱わず // JavaのストリームをそのままJavaScript内で扱うことで対応 DcInputStream io = (DcInputStream) element; byte[] buf = new byte[BUFFER_SIZE]; int bufLength; while ((bufLength = io.read(buf)) != -1) { this.output.write(buf, 0, bufLength); } } else { // 文字列はユーザスクリプトがContent-typeのcharsetで指定した文字エンコーディングで出力。 this.output.write(((String) element).getBytes(charset)); } }
Example #3
Source File: EcmaScriptDataModel.java From JVoiceXML with GNU Lesser General Public License v2.1 | 6 votes |
private int createArray(final String arrayName, final int dimension, final Scope scope, final Scriptable start) { if (start == null) { return ERROR_SCOPE_NOT_FOUND; } final Scriptable targetScope = getAndCreateScope(start, arrayName); final String name; int dotPos = arrayName.lastIndexOf('.'); if (dotPos >= 0) { name = arrayName.substring(dotPos + 1); } else { name = arrayName; } if (ScriptableObject.hasProperty(targetScope, name)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("'" + arrayName + "' already defined"); } return ERROR_VARIABLE_ALREADY_DEFINED; } final NativeArray array = new NativeArray(dimension); ScriptableObject.putProperty(targetScope, name, array); if (LOGGER.isDebugEnabled()) { LOGGER.debug("created '" + arrayName + "' in scope '" + getScope(targetScope) + "' as an array of " + dimension); } // Fill the array for (int i = 0; i < dimension; i++) { final Context context = getContext(); final Scriptable scriptable = context.newObject(topmostScope); ScriptableObject.putProperty(array, i, scriptable); } return NO_ERROR; }
Example #4
Source File: CoreJavaScriptWrapperTest.java From birt with Eclipse Public License 1.0 | 6 votes |
@Test public void testWrap( ) { // test nativeArray NativeArray nativeArray = new NativeArray( new Object[]{ "one", "two" } ); Object object = coreWrapper.wrap( cx, scope, nativeArray, null ); assertTrue( object instanceof org.mozilla.javascript.NativeArray ); // test list List<Integer> list = new ArrayList<>( ); object = coreWrapper.wrap( cx, scope, list, null ); assertTrue( object instanceof NativeJavaList ); // test map Map<Integer, Integer> linkedHashMap = new LinkedHashMap<>( ); object = coreWrapper.wrap( cx, scope, linkedHashMap, null ); assertTrue( object instanceof NativeJavaLinkedHashMap ); // test BirtHashMap BirtHashMap birtHashMap = new BirtHashMap( ); object = coreWrapper.wrap( cx, scope, birtHashMap, null ); assertTrue( object instanceof NativeJavaMap ); }
Example #5
Source File: PList.java From PHONK with GNU General Public License v3.0 | 6 votes |
public void init(NativeArray data, ReturnInterfaceWithReturn createCallback, ReturnInterfaceWithReturn bindingCallback) { styler = new Styler(mAppRunner, this, props); styler.apply(); mGridLayoutManager = new GridLayoutManager(mContext, nNumCols); setLayoutManager(mGridLayoutManager); // setLayoutManager(new StaggeredGridLayoutManager(2, VERTICAL)); mViewAdapter = new PViewItemAdapter(mContext, data, createCallback, bindingCallback); // Get GridView and set adapter setHasFixedSize(true); setAdapter(mViewAdapter); notifyDataChanged(); setItemAnimator(null); }
Example #6
Source File: PBluetooth.java From PHONK with GNU General Public License v3.0 | 6 votes |
@PhonkMethod(description = "Send bluetooth serial message", example = "") @PhonkMethodParam(params = {"string"}) public NativeArray getBondedDevices() { start(); Set<BluetoothDevice> listDevices = mAdapter.getBondedDevices(); MLog.d(TAG, "listDevices " + listDevices); int listSize = listDevices.size(); PhonkNativeArray array = new PhonkNativeArray(listSize); MLog.d(TAG, "array " + array); int counter = 0; for (BluetoothDevice b : listDevices) { MLog.d(TAG, "bt " + b); ReturnObject btDevice = new ReturnObject(); btDevice.put("name", b.getName()); btDevice.put("mac", b.getAddress()); array.addPE(counter++, btDevice); } return array; }
Example #7
Source File: PostmanJsVariables.java From postman-runner with Apache License 2.0 | 5 votes |
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 #8
Source File: DataFrameAdapter.java From joinery with GNU General Public License v3.0 | 5 votes |
private static List<Object> asList(final NativeArray array) { final List<Object> list = new ArrayList<>((int)array.getLength()); for (final Object id : array.getIds()) { list.add(array.get((int)id, null)); } return list; }
Example #9
Source File: DataFrameAdapter.java From joinery with GNU General Public License v3.0 | 5 votes |
public static Scriptable jsFunction_groupBy(final Context ctx, final Scriptable object, final Object[] args, final Function func) { if (args.length == 1 && args[0] instanceof Function) { @SuppressWarnings("unchecked") final KeyFunction<Object> f = (KeyFunction<Object>)Context.jsToJava(args[0], KeyFunction.class); return new DataFrameAdapter(object, cast(object).df.groupBy(f)); } if (args.length == 1 && args[0] instanceof NativeArray) { return new DataFrameAdapter(object, cast(object).df.groupBy(asList(args[0]).toArray())); } return new DataFrameAdapter(object, cast(object).df.groupBy(args)); }
Example #10
Source File: DataFrameAdapter.java From joinery with GNU General Public License v3.0 | 5 votes |
public static Scriptable jsFunction_reindex(final Context ctx, final Scriptable object, final Object[] args, final Function func) { if (args.length > 0 && args[0] instanceof NativeArray) { if (args.length > 1) { return new DataFrameAdapter(object, cast(object).df.reindex( asList(args[0]).toArray(), Context.toBoolean(args[1]))); } return new DataFrameAdapter(object, cast(object).df.reindex(asList(args[0]).toArray())); } return new DataFrameAdapter(object, cast(object).df.reindex(args)); }
Example #11
Source File: DataFrameAdapter.java From joinery with GNU General Public License v3.0 | 5 votes |
public static Scriptable jsFunction_add(final Context ctx, final Scriptable object, final Object[] args, final Function func) { if (args.length == 2 && args[1] instanceof NativeArray) { return new DataFrameAdapter(object, cast(object).df.add(args[0], asList(args[1]))); } if (args.length == 1 && args[0] instanceof NativeArray) { return new DataFrameAdapter(object, cast(object).df.add(asList(args[0]))); } return new DataFrameAdapter(object, cast(object).df.add(args)); }
Example #12
Source File: DataFrameAdapter.java From joinery with GNU General Public License v3.0 | 5 votes |
public static Scriptable jsConstructor(final Context ctx, final Object[] args, final Function ctor, final boolean newExpr) { if (args.length == 3 && args[0] instanceof NativeArray) { final List<List<Object>> data = new ArrayList<>(); final NativeArray array = NativeArray.class.cast(args[2]); final Object[] ids = array.getIds(); for (int i = 0; i < array.getLength(); i++) { data.add(asList(array.get((int)ids[i], null))); } return new DataFrameAdapter( new DataFrame<Object>( asList(args[0]), asList(args[1]), data ) ); } else if (args.length == 2 && args[0] instanceof NativeArray) { return new DataFrameAdapter(new DataFrame<Object>( asList(args[0]), asList(args[1]) )); } else if (args.length == 1 && args[0] instanceof NativeArray) { return new DataFrameAdapter(new DataFrame<Object>( asList(args[0]) )); } else if (args.length > 0) { final String[] columns = new String[args.length]; for (int i = 0; i < args.length; i++) { columns[i] = Context.toString(args[i]); } return new DataFrameAdapter(new DataFrame<>(columns)); } return new DataFrameAdapter(new DataFrame<>()); }
Example #13
Source File: JsonParserTest.java From astor with GNU General Public License v2.0 | 5 votes |
@Test @SuppressWarnings("unchecked") public void shouldParseHeterogeneousJsonArray() throws Exception { NativeArray actual = (NativeArray) parser .parseValue("[ \"hello\" , 3, null, [false] ]"); assertEquals("hello", actual.get(0, actual)); assertEquals(3, actual.get(1, actual)); assertEquals(null, actual.get(2, actual)); NativeArray innerArr = (NativeArray) actual.get(3, actual); assertEquals(false, innerArr.get(0, innerArr)); assertEquals(4, actual.getLength()); }
Example #14
Source File: Bug492525Test.java From astor with GNU General Public License v2.0 | 5 votes |
@Test public void getAllIdsShouldIncludeArrayIndices() { NativeArray array = new NativeArray(new String[]{"a", "b"}); Object[] expectedIds = new Object[] {0, 1, "length"}; Object[] actualIds = array.getAllIds(); assertArrayEquals(expectedIds, actualIds); }
Example #15
Source File: PrimitiveWrapFactory.java From io with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Override public Object wrap(Context cx, Scriptable scope, Object obj, Class<?> staticType) { if (obj instanceof Number) { return obj; } else if (obj instanceof String) { return obj; } else if (obj instanceof InputStream && !(obj instanceof DcInputStream)) { return new DcInputStream((InputStream) obj); } else if (obj instanceof JSONObject && !(obj instanceof DcJSONObject)) { return ((JSONObject) obj).toJSONString(); } else if (obj instanceof ArrayList) { // クライアントライブラリからJava配列を直接返された時(ACLなど扱う処理で返される)に、 // NativeArrayに置き換えてJava配列をJavaScriptに見せないようにする。 ArrayList<Object> list = (ArrayList<Object>) obj; NativeArray na = new NativeArray(list.size()); for (int i = 0; i < list.size(); i++) { na.put(i, na, list.get(i)); } na.setPrototype(scope); return na; } return super.wrap(cx, scope, obj, staticType); }
Example #16
Source File: JSGIRequest.java From io with Apache License 2.0 | 5 votes |
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 #17
Source File: NativeTypedArrayView.java From JsDroidCmd with Mozilla Public License 2.0 | 5 votes |
private void setRange(NativeArray a, int off) { if (off > length) { throw ScriptRuntime.constructError("RangeError", "offset out of range"); } if ((off + a.size()) > length) { throw ScriptRuntime.constructError("RangeError", "offset + length out of range"); } int pos = off; for (Object val : a) { js_set(pos, val); pos++; } }
Example #18
Source File: DcResponse.java From io with Apache License 2.0 | 5 votes |
/** * JavaScriptのforEachをJavaで処理するためのメソッド(レスポンス内容チェック用). * @param element forEachの要素が一件ずつ渡される * @param number 渡された要素のindexが渡される * @param object forEach対象のオブジェクトの全要素の配列が渡される * @throws Exception Exception */ public void bodyCheckFunction(Object element, double number, NativeArray object) throws Exception { if (!(element instanceof DcInputStream) && !(element instanceof String)) { String msg = "response body illegal type."; log.info(msg); throw new Exception(msg); } }
Example #19
Source File: JSLintValidator.java From APICloud-Studio with GNU General Public License v3.0 | 5 votes |
Object javaToJS(Object o, Scriptable scope) { Class<?> cls = o.getClass(); if (cls.isArray()) { return new NativeArray((Object[]) o); } return Context.javaToJS(o, scope); }
Example #20
Source File: JsonParserTest.java From rhino-android with Apache License 2.0 | 5 votes |
@Test @SuppressWarnings("unchecked") public void shouldParseHeterogeneousJsonArray() throws Exception { NativeArray actual = (NativeArray) parser .parseValue("[ \"hello\" , 3, null, [false] ]"); assertEquals("hello", actual.get(0, actual)); assertEquals(3, actual.get(1, actual)); assertEquals(null, actual.get(2, actual)); NativeArray innerArr = (NativeArray) actual.get(3, actual); assertEquals(false, innerArr.get(0, innerArr)); assertEquals(4, actual.getLength()); }
Example #21
Source File: PViewItemAdapter.java From PHONK with GNU General Public License v3.0 | 5 votes |
public PViewItemAdapter(Context c, NativeArray data, ReturnInterfaceWithReturn creating, ReturnInterfaceWithReturn binding) { mContext = c; mData = data; // MLog.d(TAG, "" + data); mCreating = creating; mBinding = binding; }
Example #22
Source File: PUtil.java From PHONK with GNU General Public License v3.0 | 5 votes |
public NativeArray getAnArray() { ArrayList array = new ArrayList(); array.add("1"); array.add("2"); // NativeArray ret = (NativeArray) getAppRunner().interp.newNativeArrayFrom(array.toArray()); // return ret; return null; }
Example #23
Source File: Bug492525Test.java From rhino-android with Apache License 2.0 | 5 votes |
@Test public void getAllIdsShouldIncludeArrayIndices() { NativeArray array = new NativeArray(new String[]{"a", "b"}); Object[] expectedIds = new Object[] {0, 1, "length"}; Object[] actualIds = array.getAllIds(); assertArrayEquals(expectedIds, actualIds); }
Example #24
Source File: PNetwork.java From PHONK with GNU General Public License v3.0 | 4 votes |
@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(); */ }
Example #25
Source File: JavascriptEvalUtil.java From birt with Eclipse Public License 1.0 | 4 votes |
/** * Handles a Rhino script evaluation result, converting Javascript object * into equivalent Java objects if necessary. * @param inputObj Object returned by rhino engine. * @return If inputObj is a native Javascript object, its equivalent Java object * is returned; otherwise inputObj is returned */ public static Object convertJavascriptValue(Object inputObj) { if ( inputObj instanceof Undefined ) { return null; } if ( inputObj instanceof IdScriptableObject ) { // Return type is possibly a Javascript native object // Convert to Java object with same value String jsClass = ((Scriptable) inputObj).getClassName(); if ( "Date".equals(jsClass) ) { return Context.toType( inputObj, Date.class ); } else if ( "Boolean".equals(jsClass)) { return Boolean.valueOf( Context.toBoolean( inputObj ) ); } else if ( "Number".equals(jsClass)) { return new Double(Context.toNumber(inputObj)); } else if( "String".equals(jsClass) ) { return inputObj.toString(); } else if ( "Array".equals( jsClass ) ) { Object[] obj = new Object[(int) ( (NativeArray) inputObj ).getLength( )]; for ( int i = 0; i < obj.length; i++ ) { obj[i] = convertJavascriptValue( ( (NativeArray) inputObj ).get( i, null ) ); } return obj; } } else if ( inputObj instanceof Wrapper ) { return ( (Wrapper) inputObj ).unwrap( ); } else if ( inputObj instanceof Scriptable ) { return ((Scriptable) inputObj).getDefaultValue( null ); } return inputObj; }
Example #26
Source File: PList.java From PHONK with GNU General Public License v3.0 | 4 votes |
@PhonkMethod(description = "", example = "") @PhonkMethodParam(params = {""}) public void items(NativeArray data) { mViewAdapter.setArray(data); }
Example #27
Source File: PViewItemAdapter.java From PHONK with GNU General Public License v3.0 | 4 votes |
public void setArray(NativeArray data) { this.mData = data; }
Example #28
Source File: DataFrameAdapter.java From joinery with GNU General Public License v3.0 | 4 votes |
private static List<Object> asList(final Object array) { return asList(NativeArray.class.cast(array)); }
Example #29
Source File: PGrid.java From PHONK with GNU General Public License v3.0 | 4 votes |
@PhonkMethod(description = "", example = "") @PhonkMethodParam(params = {""}) public PGrid using(NativeArray array) { return this; }
Example #30
Source File: DataFrameAdapter.java From joinery with GNU General Public License v3.0 | 4 votes |
public static Scriptable jsFunction_append(final Context ctx, final Scriptable object, final Object[] args, final Function func) { if (args.length == 2 && args[1] instanceof NativeArray) { return new DataFrameAdapter(object, cast(object).df.append(args[0], asList(args[1]))); } return new DataFrameAdapter(object, cast(object).df.append(asList(args[0]))); }