Ejemplo n.º 1
0
  @Test
  public void getIdsShouldIncludeBothIndexAndNormalProperties() {
    array.put(0, array, "index");
    array.put("a", array, "normal");

    assertThat(array.getIds(), is(new Object[] {0, "a"}));
  }
Ejemplo n.º 2
0
 /**
  * 将Native对象转换为String数组 @Title: toStringArray @Description: TODO(这里用一句话描述这个方法的作用)
  *
  * @param 参数
  * @return String[] 返回类型
  * @throws
  */
 public static String[] toStringArray(NativeArray nv) {
   String[] result = new String[(int) nv.getLength()];
   for (int i = 0; i < result.length; i++) {
     result[i] = StringUtils.toString(nv.get(i, null));
   }
   return result;
 }
  public void bsync(NativeObject jsRWB) {
    Map<String, Object> jRWB = (Map) Context.jsToJava(jsRWB, Map.class);

    RWBStatement stmt = RWBStatement.make();
    Object req = jRWB.get("request");
    if (req != null) {
      if (req instanceof BEvent) {
        stmt = stmt.request((BEvent) req);
      } else if (req instanceof NativeArray) {
        NativeArray arr = (NativeArray) req;
        stmt =
            stmt.request(
                Arrays.asList(arr.getIndexIds())
                    .stream()
                    .map(i -> (BEvent) arr.get(i))
                    .collect(toSet()));
      }
    }

    stmt =
        stmt.waitFor(convertToEventSet(jRWB.get("waitFor")))
            .block(convertToEventSet(jRWB.get("block")))
            .breakUpon(convertToEventSet(jRWB.get("breakUpon")));

    bthread.bsync(stmt);
  }
  public JavascriptArrayFileNameProvider(
      FileProvider fileProvider, String sourceFile, String variableName) throws IOException {

    BufferedReader source = fileProvider.getResource(sourceFile);
    try {
      Context cx = Context.enter();
      Scriptable scope = cx.initStandardObjects();
      cx.evaluateReader(scope, source, sourceFile, 1, null);
      Object x = scope.get(variableName, scope);

      if (!(x instanceof NativeArray)) {
        throw new RuntimeException(
            "Could not find array called " + variableName + " in source file " + sourceFile);
      }
      NativeArray array = (NativeArray) x;
      for (int i = 0; i < array.getLength(); i++) {
        Object o = array.get(i, null);
        if (!(o instanceof String)) {
          throw new RuntimeException(
              "Array contained objects which are not Strings, cannot continue");
        }
        fileNames.add("/" + o);
      }
    } finally {
      Context.exit();
    }
  }
Ejemplo n.º 5
0
  public void testOnSizeExceeded() throws Exception {
    renderView("/queue-size.xhtml");

    for (int i = 0; i <= 3; i++) {
      clickOnTime(i, "form:button" + i);
    }

    TestsResult result = getTestsResult();
    List<RequestData> dataList = result.getDataList();

    assertEquals(2, dataList.size());

    // dropNext is default
    checkRequestData(dataList.get(0), "form:button0", 0, DEFAULT_REQUEST_TIME, false);
    checkRequestData(
        dataList.get(1), "form:button3", DEFAULT_REQUEST_TIME, DEFAULT_REQUEST_TIME * 2, false);

    NativeArray handlersData = (NativeArray) executeJavaScript("defaultExceededQueueResults");

    assertEquals(2, handlersData.getLength());

    ScriptableObject firstHandlerData = (ScriptableObject) handlersData.get(0, handlersData);
    Double firstEventTime = (Double) firstHandlerData.get("_time", firstHandlerData);

    assertEquals(2d, firstEventTime);

    ScriptableObject secondHandlerData = (ScriptableObject) handlersData.get(1, handlersData);
    Double secondEventTime = (Double) secondHandlerData.get("_time", secondHandlerData);

    assertEquals(3d, secondEventTime);
  }
Ejemplo n.º 6
0
 private static Object[] convertArray(NativeArray jsArray, Map<Object, Boolean> identities) {
   Object[] ids = jsArray.getIds();
   Object[] result = new Object[ids.length];
   for (int i = 0; i < ids.length; i++) {
     Object id = ids[i];
     int index = (Integer) id;
     Object jsValue = jsArray.get(index, jsArray);
     result[i] = jsToJava(jsValue, identities);
   }
   return result;
 }
Ejemplo n.º 7
0
 /**
  * 将NativeArray返回结果转换为int[]对象 @Title: toIntArray @Description: TODO(这里用一句话描述这个方法的作用)
  *
  * @param 参数
  * @return int[] 返回类型
  * @throws
  */
 public static int[] toIntArray(NativeArray nv) {
   int[] result = new int[(int) nv.getLength()];
   for (int i = 0; i < result.length; i++) {
     Object obj = nv.get(i, null);
     if (obj instanceof Number) {
       result[i] = ((Number) obj).intValue();
     } else {
       result[i] = StringUtils.toInt(StringUtils.toString(obj), 0);
     }
   }
   return result;
 }
Ejemplo n.º 8
0
 public static Object map(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
   NativeJavaObject njo = (NativeJavaObject) args[0];
   NativeArray array = (NativeArray) cx.newArray(thisObj, 0);
   Function f = (Function) args[1];
   Collection list = (Collection) njo.unwrap();
   int i = 0;
   for (Object o : list) {
     Object[] argx = {o, Context.javaToJS(i, f), njo};
     Object r = f.call(cx, thisObj, f, argx);
     array.put((int) array.getLength(), array, Context.javaToJS(r, f));
     i++;
   }
   return array;
 }
Ejemplo n.º 9
0
  public static Object filter(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
    NativeArray array = (NativeArray) cx.newArray(thisObj, 0);
    NativeJavaObject njo = (NativeJavaObject) args[0];
    Function f = (Function) args[1];
    Collection list = (Collection) njo.unwrap();
    int i = 0;
    for (Object o : list) {
      Object[] argx = {o, i, njo};
      Object r = f.call(cx, thisObj, f, argx);
      if (r != null && r.getClass() != Undefined.class && !r.equals(false)) {
        array.put((int) array.getLength(), array, o);
      }
    }

    return array;
  }
Ejemplo n.º 10
0
Archivo: DB.java Proyecto: o-nix/Kafra
  protected Object wrap(List<?> result) {
    Context context = Context.getCurrentContext();
    Scriptable scope = getParentScope();
    NativeArray array = (NativeArray) context.newArray(scope, result.size());
    int i = 0;

    for (Object part : result) {
      Object value = part;

      if (value instanceof ODocument) value = wrap((ODocument) part);
      else value = Context.javaToJS(value, scope);

      array.put(i, array, value);
      i++;
    }

    return array;
  }
Ejemplo n.º 11
0
  public void testSingleSizedQueueIgnoreDupResponses() throws Exception {
    renderView("/queue-size.xhtml");

    ParametersBuilder parametersBuilder =
        createAjaxParameters().eventsQueue("singleSizedDefaultQueue").requestDelay(0);

    ajax(0, "a", parametersBuilder);
    ajax(500, "b", parametersBuilder);

    TestsResult result = getTestsResult();
    List<RequestData> list = result.getDataList();

    assertEquals(1, list.size());
    checkRequestData(list.get(0), "a", 0, DEFAULT_REQUEST_TIME, false);

    NativeArray handlersData = (NativeArray) executeJavaScript("defaultSingleSizedQueueResults");

    assertEquals(1, handlersData.getLength());
    assertEquals("a", handlersData.get(0, handlersData));
  }
Ejemplo n.º 12
0
  public Document[] map(final String docid, final String doc) {
    context.putThreadLocal("docid", docid);
    Object ret = systemFun.call(context, scope, null, new Object[] {doc, userFun});
    if (ret == null || ret instanceof Undefined) {
      return new Document[] {};
    } else if (ret instanceof RhinoDocument) {
      return new Document[] {((RhinoDocument) ret).doc};
    } else if (ret instanceof NativeArray) {
      final NativeArray na = (NativeArray) ret;
      final Document[] mapped = new Document[(int) na.getLength()];
      for (int i = 0; i < (int) na.getLength(); i++) {
        ret = na.get(i, null);
        if (!(ret instanceof RhinoDocument)) {
          throw new RuntimeException("Invalid object type: " + ret.getClass().getName());
        }
        mapped[i] = ((RhinoDocument) ret).doc;
      }
      return mapped;
    }

    throw new RuntimeException("Invalid object type: " + ret.getClass().getName());
  }
  private EventSet convertToEventSet(Object jsObject) {
    if (jsObject == null) return Events.emptySet;

    // This covers event sets AND events.
    if (jsObject instanceof EventSet) {
      return (EventSet) jsObject;

    } else if (jsObject instanceof NativeArray) {
      NativeArray arr = (NativeArray) jsObject;
      if (Stream.of(arr.getIds()).anyMatch(id -> arr.get(id) == null)) {
        throw new RuntimeException("EventSet Array contains null sets.");
      }
      return ComposableEventSet.anyOf(
          Arrays.asList(arr.getIndexIds())
              .stream()
              .map(i -> (EventSet) arr.get(i))
              .collect(toSet()));
    } else {
      final String errorMessage =
          "Cannot convert " + jsObject + " of class " + jsObject.getClass() + " to an event set";
      Logger.getLogger(BThread.class.getName()).log(Level.SEVERE, errorMessage);
      throw new IllegalArgumentException(errorMessage);
    }
  }
Ejemplo n.º 14
0
 @Test
 public void getIndexIdsShouldNotIncludeNegativeIds() {
   array.put(-1, array, "a");
   assertThat(array.getIndexIds(), is(new Integer[] {}));
 }
Ejemplo n.º 15
0
 @Test
 public void getIndexIdsShouldNotIncludeIdsGreaterThanOrEqualTo2ToThe32() {
   array.put((1L << 31) + "", array, "a");
   assertThat(array.getIndexIds(), is(new Integer[] {}));
 }
Ejemplo n.º 16
0
 @Test
 public void getIndexIdsShouldNotReturnNonNumericIds() {
   array.put("x", array, "a");
   assertThat(array.getIndexIds(), is(new Integer[] {}));
 }
  protected static Resource _processItem(
      NativeObject itemNO,
      String baseURL,
      SailConnection dataConnection,
      SailConnection metaConnection,
      Map<String, String> itemIDToURI)
      throws SailException {
    String id = _getStringProperty(itemNO, "id");
    String label = _getStringProperty(itemNO, "label");
    String uri = _getStringProperty(itemNO, "uri");

    if (id == null) {
      if (label == null) {
        throw new InternalError("Missing both label and id");
      } else {
        id = label;
      }
    }

    Resource itemResource;
    try {
      itemResource = new URIImpl(uri);
    } catch (Exception e) {
      uri = baseURL + _encode(id);
      itemResource = new URIImpl(uri);
    }

    String typeID = _getStringProperty(itemNO, "type");
    Resource type;
    if (typeID == null) {
      type = ExhibitOntology.ITEM;
    } else {
      type = _ensureTypeExists(typeID, baseURL, metaConnection);
    }

    dataConnection.addStatement(itemResource, RDF.TYPE, type);
    dataConnection.addStatement(itemResource, ExhibitOntology.ID, new LiteralImpl(id));
    if (label != null) {
      dataConnection.addStatement(itemResource, RDFS.LABEL, new LiteralImpl(label));
    }

    Object[] propertiesIds = ScriptableObject.getPropertyIds(itemNO);
    for (Object propertyId : propertiesIds) {
      String propertyID = propertyId.toString();
      if (!propertyID.equals("type")
          && !propertyID.equals("label")
          && !propertyID.equals("uri")
          && !propertyID.equals("id")) {

        URI predicate = _ensurePropertyExists(propertyID, baseURL, metaConnection);

        Object valueO = ScriptableObject.getProperty(itemNO, propertyID);
        if (valueO instanceof NativeArray) {
          NativeArray valuesArray = (NativeArray) valueO;

          long count = valuesArray.getLength();
          for (int i = 0; i < count; i++) {
            Object itemO = valuesArray.get(i, valuesArray);

            _addItemProperty(
                itemResource,
                predicate,
                itemO,
                baseURL,
                dataConnection,
                metaConnection,
                itemIDToURI);
          }
        } else {
          _addItemProperty(
              itemResource,
              predicate,
              valueO,
              baseURL,
              dataConnection,
              metaConnection,
              itemIDToURI);
        }
      }
    }

    return itemResource;
  }
  public static void loadExhibitDataFile(
      Reader baseReader,
      String url,
      String namespace,
      Map<String, NativeObject> types,
      Map<String, NativeObject> properties,
      List<NativeObject> items)
      throws IOException {
    ChainingReader reader = new ChainingReader();
    reader.addReader(new StringReader("("));
    reader.addReader(baseReader);
    reader.addReader(new StringReader(")"));

    try {
      Context context = Context.enter();
      Scriptable scope = context.initStandardObjects();

      Object o = context.evaluateReader(scope, reader, url, 1, null);
      if (o instanceof NativeObject) {
        NativeObject no = (NativeObject) o;

        Object typesO = ScriptableObject.getProperty(no, "types");
        if (typesO instanceof NativeObject) {
          NativeObject typesNO = (NativeObject) typesO;
          Object[] propertiesIds = ScriptableObject.getPropertyIds(typesNO);

          for (Object propertyId : propertiesIds) {
            String typeID = propertyId.toString();
            Object typeO = ScriptableObject.getProperty(typesNO, typeID);
            if (typeO instanceof NativeObject) {
              types.put(typeID, (NativeObject) typeO);
            }
          }
        }

        Object propertiesO = ScriptableObject.getProperty(no, "properties");
        if (propertiesO instanceof NativeObject) {
          NativeObject propertiesNO = (NativeObject) propertiesO;
          Object[] propertiesIds = ScriptableObject.getPropertyIds(propertiesNO);

          for (Object propertyId : propertiesIds) {
            String propertyID = propertyId.toString();
            Object propertyO = ScriptableObject.getProperty(propertiesNO, propertyID);
            if (propertyO instanceof NativeObject) {
              properties.put(propertyID, (NativeObject) propertyO);
            }
          }
        }

        Object itemsO = ScriptableObject.getProperty(no, "items");
        if (itemsO instanceof NativeArray) {
          NativeArray itemsArray = (NativeArray) itemsO;

          long count = itemsArray.getLength();
          for (int i = 0; i < count; i++) {
            Object itemO = itemsArray.get(i, itemsArray);
            if (itemO instanceof NativeObject) {
              items.add((NativeObject) itemO);
            }
          }
        }
      }
    } finally {
      reader.close();
    }
  }
Ejemplo n.º 19
0
 @Test
 public void deleteShouldRemoveNormalProperties() {
   array.put("p", array, "a");
   array.delete("p");
   assertThat(array.has("p", array), is(false));
 }
Ejemplo n.º 20
0
 @Test
 public void deleteShouldRemoveIndexProperties() {
   array.put(0, array, "a");
   array.delete(0);
   assertThat(array.has(0, array), is(false));
 }
Ejemplo n.º 21
0
 @Test
 public void putShouldAddIndexProperties() {
   array.put(0, array, "a");
   assertThat(array.has(0, array), is(true));
 }
Ejemplo n.º 22
0
Archivo: DB.java Proyecto: o-nix/Kafra
 public static Object[] jsStaticFunction_objectsToDocuments(NativeArray object) {
   return DbObjects.objectsToDocuments(object.toArray());
 }
Ejemplo n.º 23
0
 @Test
 public void putShouldAddNormalProperties() {
   array.put("p", array, "a");
   assertThat(array.has("p", array), is(true));
 }
Ejemplo n.º 24
0
 @Test
 public void getShouldReturnNormalProperties() {
   array.put("p", array, "a");
   assertThat((String) array.get("p", array), is("a"));
 }
Ejemplo n.º 25
0
 @Test
 public void getIndexIdsShouldIncludeIdsLessThan2ToThe32() {
   int maxIndex = (int) (1L << 31) - 1;
   array.put(maxIndex, array, "a");
   assertThat(array.getIndexIds(), is(new Integer[] {maxIndex}));
 }
Ejemplo n.º 26
0
 @Test
 public void getIndexIdsShouldBeAZeroForSimpleSingletonArray() {
   array.put(0, array, "a");
   assertThat(array.getIndexIds(), is(new Integer[] {0}));
 }
Ejemplo n.º 27
0
 @Test
 public void getIndexIdsShouldWorkWhenIndicesSetAsString() {
   array.put("0", array, "a");
   assertThat(array.getIndexIds(), is(new Integer[] {0}));
 }