static Object jsToJava(final Object obj) { if (obj instanceof Scriptable) { final Object javaObj = Context.jsToJava(obj, Object.class); if (javaObj instanceof NativeArray) { return new ScriptableList((NativeArray) javaObj); } if (javaObj instanceof Scriptable) { return new ScriptableMap((Scriptable) javaObj); } return javaObj; } if (obj instanceof Wrapper) { return ((Wrapper) obj).unwrap(); } if (obj == Scriptable.NOT_FOUND) { return null; } return obj; }
@ProtoMethod(description = "Send bluetooth serial message", example = "") @ProtoMethodParam(params = {"string"}) public NativeArray getBondedDevices() { start(); Set<BluetoothDevice> listDevices = mAdapter.getBondedDevices(); MLog.d(TAG, "listDevices " + listDevices); int listSize = listDevices.size(); ProtocoderNativeArray array = new ProtocoderNativeArray(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; }
public void init(NativeArray data, int numCols, ReturnInterfaceWithReturn createCallback, ReturnInterfaceWithReturn bindingCallback) { styler = new Styler(mAppRunner, this, props); styler.apply(); mGridLayoutManager = new GridLayoutManager(mContext, numCols); 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); }
@Nullable private List<KeyEntry> getKeyEntries(Map.Entry<Object, Object> entry) { if (!(entry.getValue() instanceof NativeArray)) { return null; } NativeArray nativeArray = (NativeArray) entry.getValue(); if (nativeArray.isEmpty()) { return null; } List<KeyEntry> keyList = new ArrayList<>(); final int size = nativeArray.size(); for (int i = 0; i < size; i++) { NativeObject elem = (NativeObject) nativeArray.get(i); keyList.add(new KeyEntry( Context.toString(elem.get("text")), (int) Context.toNumber(elem.get("keyCode")), Context.toBoolean(elem.get("enabled")), Context.toBoolean(elem.get("isFunKey")) )); } return keyList; }
/** * Mete dato multivaluado para un elemento * @param indiceElemento Indice elemento * @param column Columna * @param data Dato */ public void setDatoMultivaluadoElemento(int indiceElemento,String column, NativeArray data){ if (indiceElemento > elementos.size()) return; HashMap dataElemento = (HashMap) elementos.get(indiceElemento - 1); // Pasamos NativeArray a List List dataList = new ArrayList(); Object [] ids = data.getIds(); for ( int i = 0; i < ids.length; i++ ) { Object valor = data.get( (( Integer ) ids[i] ).intValue() , data ); dataList.add( valor.toString() ); } // Guardamos datos dataElemento.put(column,dataList); }
private String parseCalloutResponse(String calloutResponse, List<NativeArray> returnedArray) { String initS = "id=\"paramArray\">"; String resp = calloutResponse.substring(calloutResponse.indexOf(initS) + initS.length()); resp = resp.substring(0, resp.indexOf("</SCRIPT")).trim(); if (!resp.contains("new Array(") && !resp.contains("[[")) { return null; } try { Context cx = Context.enter(); Scriptable scope = cx.initStandardObjects(); cx.evaluateString(scope, resp, "<cmd>", 1, null); NativeArray array = (NativeArray) scope.get("respuesta", scope); Object calloutName = scope.get("calloutName", scope); String calloutNameS = calloutName == null ? null : calloutName.toString(); log.debug("Callout Name: " + calloutNameS); for (int i = 0; i < array.getLength(); i++) { returnedArray.add((NativeArray) array.get(i, null)); } return calloutNameS; } catch (Exception e) { log.error("Couldn't parse callout response. The parsed response was: " + resp, e); } return null; }
@Test public void testCompiledJs() throws Exception { // The main module calls a soy template and alerts the output. // Replace alert with something that lets us capture the output. cx.evaluateString( scope, "var _alerts_ = []; alert = function (s) { _alerts_.push(s); }", "test", 1, null); loadJsModule("/closure/js/main.js"); loadJsModule("/closure/js/hello.world.js"); NativeArray alerts = (NativeArray) ScriptableObject.getProperty(scope, "_alerts_"); assertEquals( "<div id=\"greeting\">Hello, <b class=\"b\">Cle<eland</b>!</div>", Context.toString(alerts.get(0))); }
static public Map<String,Object> deserialize(NativeObject object) { HashMap<String,Object> map = new HashMap<>(); for (Object key : object.keySet()) { Object value = object.get(key); if (value == null) { map.put(key.toString(), null); } else if (value instanceof Number) { map.put(key.toString(), value); } else if (value instanceof Boolean) { map.put(key.toString(), value); } else if (value instanceof NativeObject) { map.put(key.toString(), deserialize((NativeObject)value)); } else if (value instanceof NativeArray) { NativeArray array = (NativeArray)value; Object[] a = new Object[(int)array.getLength()]; for (int i = 0; i < array.getLength(); ++i) { Object o = array.get(i); a[i] = deserialize(o); } map.put(key.toString(), a); } else { map.put(key.toString(), value.toString()); } } return map; }
static Object deserialize(Object value) { if (value == null) { return null; } else if (value instanceof Number) { return value; } else if (value instanceof Boolean) { return value; } else if (value instanceof NativeObject) { return deserialize((NativeObject)value); } else if (value instanceof NativeArray) { NativeArray array = (NativeArray)value; Object[] a = new Object[(int)array.getLength()]; for (int i = 0; i < array.getLength(); ++i) { Object o = array.get(i); a[i] = deserialize(o); } return a; } else { return value.toString(); } }
private List<MappingAssertionStatement> generateAssertionStatements(Object compiledJavascriptObject) { List<MappingAssertionStatement> assertionStatements = new ArrayList<MappingAssertionStatement>(); if (compiledJavascriptObject != null && compiledJavascriptObject instanceof NativeArray) { NativeArray array = (NativeArray) compiledJavascriptObject; for (Object object : array) { NativeObject nativeObject = (NativeObject) object; String actualValuePath = (String) nativeObject .get("actualValuePath"); Object actualValue = nativeObject.get("actualValue"); String operator = (String) nativeObject.get("operator"); Object expectedValue = nativeObject.get("expectedValue"); if (expectedValue instanceof NativeArray) { NativeArray expectedValueNativeArray = (NativeArray) expectedValue; expectedValue = expectedValueNativeArray.toArray(); } assertionStatements.add(new MappingAssertionStatement( actualValuePath, actualValue, operator, expectedValue)); } } return assertionStatements; }
public List<MappingAssertionStatement> getAssertionStatementMetadataList() { if (this.compiledJavascriptObject != null && this.compiledJavascriptObject instanceof NativeArray) { NativeArray array = (NativeArray) this.compiledJavascriptObject; for (Object object : array) { NativeObject nativeObject = (NativeObject) object; String actualValuePath = (String) nativeObject .get("actualValuePath"); Object actualValue = nativeObject.get("actualValue"); String operator = (String) nativeObject.get("operator"); Object expectedValue = nativeObject.get("expectedValue"); this.assertionStatementMetadataList.add(new MappingAssertionStatement( actualValuePath, actualValue, operator, expectedValue)); } } return this.assertionStatementMetadataList; }
/** * Adds the values of a row to the JavaScript scope * * @param scope * @param inputRow * @param columns * @param arrayName */ public static void addToScope(final Scriptable scope, final InputRow inputRow, final InputColumn<?>[] columns, final String arrayName) { final NativeArray values = new NativeArray(columns.length * 2); for (int i = 0; i < columns.length; i++) { final InputColumn<?> column = columns[i]; Object value = inputRow.getValue(column); if (value != null) { final Class<?> dataType = column.getDataType(); if (ReflectionUtils.isNumber(dataType)) { value = Context.toNumber(value); } else if (ReflectionUtils.isBoolean(dataType)) { value = Context.toBoolean(value); } } values.put(i, values, value); values.put(column.getName(), values, value); addToScope(scope, value, column.getName(), column.getName().toLowerCase(), column.getName().toUpperCase()); } addToScope(scope, values, arrayName); }
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { measureChildren(widthMeasureSpec, heightMeasureSpec); int width=0, height=0; if (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY && MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY) { NativeArray calc = (NativeArray) callFunc("onMeasure"); width = ((Number) calc.get(0)).intValue(); height= ((Number) calc.get(1)).intValue(); } else { super.onMeasure(widthMeasureSpec, heightMeasureSpec); return; } if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY) { width = MeasureSpec.getSize(widthMeasureSpec); } if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) { height = MeasureSpec.getSize(heightMeasureSpec); } setMeasuredDimension(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); }
/** * Adds the values of a row to the JavaScript scope * * @param scope * @param inputRow * @param columns * @param arrayName */ public static void addToScope(Scriptable scope, InputRow inputRow, InputColumn<?>[] columns, String arrayName) { NativeArray values = new NativeArray(columns.length * 2); for (int i = 0; i < columns.length; i++) { InputColumn<?> column = columns[i]; Object value = inputRow.getValue(column); if (value != null) { Class<?> dataType = column.getDataType(); if (ReflectionUtils.isNumber(dataType)) { value = Context.toNumber(value); } else if (ReflectionUtils.isBoolean(dataType)) { value = Context.toBoolean(value); } } values.put(i, values, value); values.put(column.getName(), values, value); addToScope(scope, value, column.getName(), column.getName().toLowerCase(), column.getName().toUpperCase()); } addToScope(scope, values, arrayName); }
@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 ); }
@Test public void shouldListJobs(){ try { Context cx = Context.enter(); Scriptable scope = cx.initStandardObjects(); scriptJobService.setScope(scope); final NativeArray allJobs = (NativeArray) scriptJobService.getAllJobs(); Assert.assertTrue(allJobs.getIds().length > 0); ScriptJob job = (ScriptJob) allJobs.get(0); Assert.assertNotNull(job.jobName); Assert.assertNotNull(job.nextFireTime); }finally{ Context.exit(); } }
@Override public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (args.length == 0) { throw new RuntimeException("'load' function takes at least one argument"); } for (Object arg : args) { if (arg instanceof NativeArray) { NativeArray array = (NativeArray)arg; for (int i = 0; i < array.getLength(); i++) { Object path = array.get(i); if (path != null) { load(path.toString(), cx, scope); } else { throw new NullPointerException("Cannot have null argument in load function"); } } } else if (arg == null) { throw new NullPointerException("Cannot have null argument in load function"); } else { load(arg.toString(), cx, scope); } } return null; }
/** * {@inheritDoc} */ @Override public boolean canConvertValueForJava(final Object value, final ValueConverter globalDelegate, final Class<?> expectedClass) { // in Rhino 1.7, NativeArray implements List which makes things difficult boolean canConvert = value instanceof List<?> && !(value instanceof NativeArray) && (expectedClass.isAssignableFrom(List.class) || expectedClass.equals(value.getClass())); final List<?> list = (List<?>) value; for (int idx = 0, size = list.size(); idx < size; idx++) { final Object valueForKey = list.get(idx); canConvert = canConvert && globalDelegate.canConvertValueForJava(valueForKey); } return canConvert; }
/** * * {@inheritDoc} */ @Override public void afterPropertiesSet() { PropertyCheck.mandatory(this, "registry", this.registry); // Collection registered previously but now handled by ScriptableFacadeListConverter this.registry.registerValueInstanceConverter(Object[].class, this); this.registry.registerValueInstanceConverter(byte[].class, this); this.registry.registerValueInstanceConverter(short[].class, this); this.registry.registerValueInstanceConverter(char[].class, this); this.registry.registerValueInstanceConverter(int[].class, this); this.registry.registerValueInstanceConverter(long[].class, this); this.registry.registerValueInstanceConverter(float[].class, this); this.registry.registerValueInstanceConverter(double[].class, this); this.registry.registerValueInstanceConverter(boolean[].class, this); this.registry.registerValueInstanceConverter(NativeArray.class, this); }
/** * * {@inheritDoc} */ @Override public int getForScriptConversionConfidence(final Class<?> valueInstanceClass, final Class<?> expectedClass) { final int confidence; if ((valueInstanceClass.isArray() || Collection.class.isAssignableFrom(valueInstanceClass)) && expectedClass.isAssignableFrom(NativeArray.class)) { confidence = HIGHEST_CONFIDENCE; } else { confidence = LOWEST_CONFIDENCE; } return confidence; }
/** * * {@inheritDoc} */ @Override public int getForJavaConversionConfidence(final Class<?> valueInstanceClass, final Class<?> expectedClass) { final int confidence; if (NativeArray.class.isAssignableFrom(valueInstanceClass) && (expectedClass.isAssignableFrom(Collection.class) || expectedClass.isAssignableFrom(Map.class) || expectedClass .isArray())) { confidence = HIGHEST_CONFIDENCE; } else { confidence = LOWEST_CONFIDENCE; } return confidence; }
public Object convertFromScriptObject(Object scriptObject, Class expectedClass) { if (scriptObject != null && conversionRequires(scriptObject, expectedClass)) { Object result = RhinoUtil.convertResult(null, expectedClass, scriptObject); if (result instanceof NativeArray) { NativeArray jsArray = (NativeArray) result; int length = (int) jsArray.getLength(); Object[] array = new Object[length]; for (int i = 0; i < length; i++) { array[i] = jsArray.get(i, null); } result = array; } return result; } return scriptObject; }
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++; } }
public static String toString(Object ob) { String parameterToString; if (ob != null) { if (ob instanceof NativeObject) { NativeObject nativeObject = (NativeObject) ob; parameterToString = nativeToString(nativeObject); } else if (ob instanceof NativeJavaObject) { NativeJavaObject nativeJavaObject = (NativeJavaObject) ob; parameterToString = toString(nativeJavaObject.unwrap()); } else if (ob instanceof NativeJavaArray || ob instanceof NativeArray || ob.getClass().isArray() || ob instanceof Collection<?>) { parameterToString = toStringList(ob).toString(); } else if (ob instanceof NodeList) { parameterToString = ""; NodeList nl = (NodeList) ob; for (int i = 0; i < nl.getLength(); i++) { parameterToString += nodeToString(nl.item(i)); } } else if (ob instanceof Node) { parameterToString = nodeToString((Node)ob); } else { parameterToString = ob.toString(); } } else { parameterToString = null; } return parameterToString; }
public static List<String> toStringList(Object ob) { List<String> list; if (ob != null) { if (ob instanceof NativeJavaObject) { NativeJavaObject nativeJavaObject = (NativeJavaObject) ob; list = toStringList(nativeJavaObject.unwrap()); } else if (ob instanceof NativeJavaArray) { Object object = ((NativeJavaArray) ob).unwrap(); list = toStringList(object); } else if (ob.getClass().isArray()) { list = toStringList(Arrays.asList((Object[]) ob)); } else if (ob instanceof NativeArray) { NativeArray array = (NativeArray) ob; list = new ArrayList<String>((int) array.getLength()); for (java.util.Iterator<?> i = array.iterator(); i.hasNext();) { list.add(toString(i.next())); } } else if (ob instanceof Collection<?>) { Collection<?> collection = GenericUtils.cast(ob); list = new ArrayList<String>(collection.size()); for (Object o : collection) { list.add(toString(o)); } } else { list = Arrays.asList(toString(ob)); } } else { list = Collections.emptyList(); } return list; }
private void init() { if ((evaluated != null) && (list == null)) { if (evaluated instanceof NodeList) { list = new ArrayList<Object>(); NodeList nodeList = (NodeList)evaluated; for (int i=0; i<nodeList.getLength(); i++) list.add(nodeList.item(i)); } else if (evaluated instanceof Collection<?>) { list = new ArrayList<Object>((Collection<?>) evaluated); } else if (evaluated instanceof NativeJavaArray) { Object object = ((NativeJavaArray)evaluated).unwrap(); list = Arrays.asList((Object[])object); } else if (evaluated instanceof NativeArray) { list = new ArrayList<Object>(); NativeArray array = (NativeArray)evaluated; for (int i=0; i<array.getLength(); i++) list.add(array.get(i,array)); } // else if (evaluated instanceof NativeJavaObject) { // list = Arrays.asList(new String[] {(String) ((NativeJavaObject)evaluated).getDefaultValue(String.class)}); // } else if (evaluated.getClass().isArray()) { list = Arrays.asList((Object[])evaluated); } else list = Arrays.asList(new Object[] {evaluated.toString()}); } }
@Override public boolean execute(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { if (super.execute(javascriptContext, scope)) { HttpConnector connector = this.getConnector(); if(connector.handleCookie){ HttpState httpState = this.getParentTransaction().context.httpState; if(httpState==null){ connector.resetHttpState(this.getParentTransaction().context); httpState = this.getParentTransaction().context.httpState; } evaluate(javascriptContext, scope, expression, "CookiesGet", true); if(evaluated!=null){ if(evaluated instanceof NativeArray){ NativeArray array = (NativeArray)evaluated; long len = array.getLength(); for(int i=0;i<len;i++) addCookie(httpState, array.get(i, array).toString()); }else{ addCookie(httpState, evaluated.toString()); } } } return true; } } return false; }
@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); }
@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()); }
public PViewItemAdapter(Context c, NativeArray data, ReturnInterfaceWithReturn creating, ReturnInterfaceWithReturn binding) { mContext = c; mData = data; // MLog.d(TAG, "" + data); mCreating = creating; mBinding = binding; }
public NativeArray getAnArray() { ArrayList array = new ArrayList(); array.add("1"); array.add("2"); NativeArray ret = (NativeArray) getAppRunner().interp.newNativeArrayFrom(array.toArray()); return ret; }
/** * Devuelve el valor de autocalcular un campo. * * Devuelve un string para campos monovaluados o una lista (de strings) para campos multivaluados * * @ejb.interface-method */ public Object expresionAutocalculoCampo(String nombre) { Campo campo = pantallaActual.findCampo(nombre); if (campo == null) return new ArrayList(); String script = campo.getExpresionAutocalculo(); if (script == null || script.trim().length() == 0) { return new ArrayList(); } Object result = ScriptUtil.evalScript(script, variablesScriptActuals()); if (result instanceof NativeArray) { List lstParams = new LinkedList(); // Array de strings NativeArray params = (NativeArray) result; if ( params != null ) { Object [] ids = params.getIds(); for ( int i = 0; i < ids.length; i++ ) { Object valorParametro = params.get( (( Integer ) ids[i] ).intValue() , params ); lstParams.add( valorParametro.toString() ); } } return lstParams; }else { // Cadena simple return ((result!=null?result.toString():"")); } }
/** * Recupera valores de un dominio. El resto de funciones de recuperar valores invocara a esta usando menos parametros. * * @param nombreDominio Identificador del dominio * @param params Parametros del dominio * @param idKeyColumn Columna que se empleara como codigo para montar los ValoresPosibles * @param valueKeyColumn Columna que se empleara como valor para montar los ValoresPosibles * @param parentKeyColumn Permite establecer jerarqu�a entre los valores indicando que columna se utiliza para establecer el padre (el valor de esta columna ser� null para roots). Se utiliza para controles de selecci�n en �rbol. * @param defaultValue Valor que ser� marcado como valor por defecto */ public DominioSistraPlugin( String nombreDominio, NativeArray params,String idKeyColumn,String valueKeyColumn,String parentKeyColumn, String defaultValue) { this.nombreDominio = nombreDominio; this.idKeyColumn=idKeyColumn; this.valueKeyColumn=valueKeyColumn; this.parentKeyColumn=parentKeyColumn; this.defaultValue = defaultValue; this.params = params; if ( inicializado == null ) { try { // Obtenemos propiedades configuracion Properties config = DelegateUtil.getConfiguracionDelegate().obtenerConfiguracion(); // Establecemos tiempo particularizado de tiempo en cache para dominios sistra this.tiempoEnCache = Long.parseLong(config.getProperty("tiempoEnCache")); // Url modulo sistra para resolucion de dominios (en caso de que este en otro servidor) this.urlSistra = config.getProperty("dominio.sistra.plugin.url"); } catch( Exception exc ) { log.error( "Error obteniendo configuracion del plugin", exc ); } } }
public CoolDowns(Object cd) { if (cd != null) { try { if (cd.getClass().equals(NativeArray.class)) { List<Double> cd_list = (List<Double>) cd; switch (cd_list.size()) { case 0: type = 0; break; case 1: init = cd_list.get(0).intValue(); type = 1; break; case 2: init = cd_list.get(0).intValue(); max = cd_list.get(1).intValue(); type = 2; break; default: type = 0; break; } } else if (cd.getClass().equals(Double.class)) { init = ((Double) cd).intValue(); type = 1; } else type = 0; } catch (Exception e) { e.printStackTrace(); } } else type = 0; }
public static <T> T getVar(Scriptable scope, String name) { Object o = scope.get(name, scope); if (o instanceof Map) { Map nativeResult = (Map) scope.get(name, scope); Map mappedResult = new LinkedHashMap(); mappedResult.putAll(nativeResult); return (T) mappedResult; } if (o instanceof NativeArray) { NativeArray na = (NativeArray) o; return (T) na; } return (T) o; }
public static String[] toStringList(Object value) { if (value == null) { return null; } else if (value instanceof NativeArray) { NativeArray array = (NativeArray)value; String[] a = new String[(int)array.getLength()]; for (int i = 0; i < array.getLength(); ++i) { Object o = array.get(i); a[i] = toString(o); } return a; } else { return null; } }
@Override public Object randomElement(NativeArray array) { if (array.size() == 0) { return null; } int i = random(array.size()); return array.get(i); }
@Override public void type(String selector, NativeArray text) { HashMap<String,Object> params = new HashMap<>(); params.put("selector", selector); params.put("text", new Object[] {text}); checkResponseForErrors(pizzaHandler.sendCommand("type", params)); }