elemental.json.JsonArray Java Examples

The following examples show how to use elemental.json.JsonArray. 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: TemplateDataAnalyzer.java    From flow with Apache License 2.0 6 votes vote down vote up
private void collectCustomElement(org.jsoup.nodes.Element element,
        org.jsoup.nodes.Element templateRoot) {
    String tag = element.tagName();

    if (TemplateInitializer.getUsesClass(templateClass, tag).isPresent()) {
        if (isInsideTemplate(element, templateRoot)) {
            throw new IllegalStateException(String.format(
                    "Couldn't parse the template '%s': "
                            + "sub-templates are not supported. Sub-template found: %n'%s'",
                    modulePath, element.toString()));
        }

        String id = element.hasAttr("id") ? element.attr("id") : null;
        JsonArray path = getPath(element, templateRoot);
        addSubTemplate(id, tag, path);
    }
}
 
Example #2
Source File: CubaVaadinServletService.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
protected void sendUploadResponse(VaadinRequest request, VaadinResponse response,
                                  String fileName, long contentLength) throws IOException {
    JsonArray json = Json.createArray();
    JsonObject fileInfo = Json.createObject();
    fileInfo.put("name", fileName);
    fileInfo.put("size", contentLength);

    // just fake addresses and parameters
    fileInfo.put("url", fileName);
    fileInfo.put("thumbnail_url", fileName);
    fileInfo.put("delete_url", fileName);
    fileInfo.put("delete_type", "POST");
    json.set(0, fileInfo);

    PrintWriter writer = response.getWriter();
    writer.write(json.toJson());
    writer.close();
}
 
Example #3
Source File: DependencyLoaderTest.java    From flow with Apache License 2.0 6 votes vote down vote up
private JsMap<LoadMode, JsonArray> createDependenciesMap(
        JsonObject... dependencies) {
    JsMap<LoadMode, JsonArray> result = JsCollections.map();
    for (int i = 0; i < dependencies.length; i++) {
        JsonObject dependency = dependencies[i];
        LoadMode loadMode = LoadMode
                .valueOf(dependency.getString(Dependency.KEY_LOAD_MODE));
        JsonArray jsonArray = Json.createArray();
        jsonArray.set(0, dependency);

        JsonArray oldResult = result.get(loadMode);
        if (oldResult == null) {
            result.set(loadMode, jsonArray);
        } else {
            mergeArrays(oldResult, jsonArray);
        }
    }
    return result;
}
 
Example #4
Source File: PolymerTemplateTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void initModel_requestPopulateModel_onlyUnsetPropertiesAreSent() {
    UI ui = UI.getCurrent();
    InitModelTemplate template = new InitModelTemplate();

    template.getModel().setMessage("foo");

    ui.add(template);

    ui.getInternals().getStateTree().runExecutionsBeforeClientResponse();

    Assert.assertEquals(2, executionOrder.size());
    Assert.assertEquals("this.populateModelProperties($0, $1)",
            executionOrder.get(1));

    Serializable[] params = executionParams.get(1);
    JsonArray properties = (JsonArray) params[1];
    Assert.assertEquals(1, properties.length());
    Assert.assertEquals("title", properties.get(0).asString());
}
 
Example #5
Source File: PublishedServerEventHandlerRpcHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void methodWithSeveralArgsAndVarArg_acceptNoValues() {
    JsonArray array = Json.createArray();

    JsonArray firstArg = Json.createArray();
    firstArg.set(0, 5.6d);
    firstArg.set(1, 78.36d);

    array.set(0, firstArg);

    MethodWithParameters component = new MethodWithParameters();
    PublishedServerEventHandlerRpcHandler.invokeMethod(component,
            component.getClass(), "method2", array, -1);

    Assert.assertArrayEquals(
            new Double[] { firstArg.getNumber(0), firstArg.getNumber(1) },
            component.doubleArg);

    Assert.assertNotNull(component.varArg);
    Assert.assertEquals(0, component.varArg.length);
}
 
Example #6
Source File: TreeChangeProcessorTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void testDetachRemovesNode() {
    AtomicInteger unregisterCount = new AtomicInteger(0);

    StateNode childNode = new StateNode(2, tree);
    childNode.addUnregisterListener(e -> unregisterCount.incrementAndGet());

    tree.registerNode(childNode);

    Assert.assertSame(childNode, tree.getNode(childNode.getId()));
    Assert.assertEquals(0, unregisterCount.get());

    JsonArray changes = toArray(detachChange(childNode.getId()));
    JsSet<StateNode> updatedNodes = TreeChangeProcessor.processChanges(tree,
            changes);

    Assert.assertNull(tree.getNode(childNode.getId()));
    Assert.assertEquals(1, unregisterCount.get());

    Assert.assertEquals(1, updatedNodes.size());
    Assert.assertTrue(updatedNodes.has(childNode));
}
 
Example #7
Source File: NodeUpdateImportsTest.java    From flow with Apache License 2.0 6 votes vote down vote up
private void assertTokenFileWithFallBack(JsonObject object)
        throws IOException {
    JsonObject fallback = object.getObject("chunks").getObject("fallback");

    JsonArray modules = fallback.getArray("jsModules");
    Set<String> modulesSet = new HashSet<>();
    for (int i = 0; i < modules.length(); i++) {
        modulesSet.add(modules.getString(i));
    }
    Assert.assertTrue(modulesSet.contains("@polymer/a.js"));
    Assert.assertTrue(modulesSet.contains("./extra-javascript.js"));

    JsonArray css = fallback.getArray("cssImports");
    Assert.assertEquals(1, css.length());
    JsonObject cssImport = css.get(0);
    Assert.assertEquals("extra-bar", cssImport.getString("include"));
    Assert.assertEquals("extra-foo", cssImport.getString("themeFor"));
    Assert.assertEquals("./extra-css.css", cssImport.getString("value"));
}
 
Example #8
Source File: TreeChangeProcessor.java    From flow with Apache License 2.0 6 votes vote down vote up
private static JsSet<StateNode> processAttachChanges(StateTree tree,
        JsonArray changes) {
    JsSet<StateNode> nodes = JsCollections.set();
    int length = changes.length();
    for (int i = 0; i < length; i++) {
        JsonObject change = changes.getObject(i);
        if (isAttach(change)) {
            int nodeId = (int) change.getNumber(JsonConstants.CHANGE_NODE);

            if (nodeId != tree.getRootNode().getId()) {
                StateNode node = new StateNode(nodeId, tree);
                tree.registerNode(node);
                nodes.add(node);
            }
        }
    }
    return nodes;
}
 
Example #9
Source File: AbstractSinglePropertyFieldTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void jsonField() {
    JsonField field = new JsonField();
    ValueChangeMonitor<JsonValue> monitor = new ValueChangeMonitor<>(field);

    Assert.assertEquals(JsonType.NULL, field.getValue().getType());
    monitor.assertNoEvent();

    field.setValue(
            JsonUtils.createArray(Json.create("foo"), Json.create(42)));
    monitor.discard();
    Assert.assertEquals("[\"foo\",42]",
            ((JsonArray) field.getElement().getPropertyRaw("property"))
                    .toJson());

    field.getElement().setPropertyJson("property", Json.createObject());
    monitor.discard();
    Assert.assertEquals("{}", field.getValue().toJson());

    field.getElement().setProperty("property", "text");
    monitor.discard();
    Assert.assertEquals("\"text\"", field.getValue().toJson());
}
 
Example #10
Source File: ClientJsonCodec.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Decodes a value encoded on the server using
 * {@link JsonCodec#encodeWithTypeInfo(Object)}.
 *
 * @param tree
 *            the state tree to use for resolving nodes and elements
 * @param json
 *            the JSON value to decode
 * @return the decoded value
 */
public static Object decodeWithTypeInfo(StateTree tree, JsonValue json) {
    if (json.getType() == JsonType.ARRAY) {
        JsonArray array = (JsonArray) json;
        int typeId = (int) array.getNumber(0);
        switch (typeId) {
        case JsonCodec.NODE_TYPE: {
            int nodeId = (int) array.getNumber(1);
            Node domNode = tree.getNode(nodeId).getDomNode();
            return domNode;
        }
        case JsonCodec.ARRAY_TYPE:
            return jsonArrayAsJsArray(array.getArray(1));
        case JsonCodec.RETURN_CHANNEL_TYPE:
            return createReturnChannelCallback((int) array.getNumber(1),
                    (int) array.getNumber(2),
                    tree.getRegistry().getServerConnector());
        default:
            throw new IllegalArgumentException(
                    "Unsupported complex type in " + array.toJson());
        }
    } else {
        return decodeWithoutTypeInfo(json);
    }
}
 
Example #11
Source File: MultiselectComboBox.java    From multiselect-combo-box-flow with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an empty multiselect combo box with the defined page size for
 * lazy loading.
 * <p>
 * The default page size is 50.
 * <p>
 * The page size is also the largest number of items that can support
 * client-side filtering. If you provide more items than the page size, the
 * component has to fall back to server-side filtering.
 *
 * @param pageSize
 *            the amount of items to request at a time for lazy loading
 * @see #setPageSize
 */
public MultiselectComboBox(int pageSize) {
    super("selectedItems", Collections.emptySet(), JsonArray.class,
            MultiselectComboBox::presentationToModel,
            MultiselectComboBox::modelToPresentation);

    dataGenerator.addDataGenerator((item, jsonObject) -> jsonObject
            .put(ITEM_LABEL_PATH, generateLabel(item)));

    setItemIdPath(ITEM_VALUE_PATH);
    setItemValuePath(ITEM_VALUE_PATH);
    setItemLabelPath(ITEM_LABEL_PATH);
    setPageSize(pageSize);

    addAttachListener(e -> initConnector());

    runBeforeClientResponse(ui -> {
        // If user didn't provide any data, initialize with empty data set.
        if (dataCommunicator == null) {
            setItems();
        }
    });
}
 
Example #12
Source File: ServerRpcHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Processes invocations data received from the client.
 * <p>
 * The invocations data can contain any number of RPC calls.
 *
 * @param ui
 *            the UI receiving the invocations data
 * @param invocationsData
 *            JSON containing all information needed to execute all
 *            requested RPC calls.
 */
private void handleInvocations(UI ui, JsonArray invocationsData) {
    List<JsonObject> data = new ArrayList<>(invocationsData.length());
    List<Runnable> pendingChangeEvents = new ArrayList<>();

    RpcInvocationHandler mapSyncHandler = getInvocationHandlers()
            .get(JsonConstants.RPC_TYPE_MAP_SYNC);

    for (int i = 0; i < invocationsData.length(); i++) {
        JsonObject invocationJson = invocationsData.getObject(i);
        String type = invocationJson.getString(JsonConstants.RPC_TYPE);
        assert type != null;
        if (JsonConstants.RPC_TYPE_MAP_SYNC.equals(type)) {
            // Handle these before any RPC invocations.
            mapSyncHandler.handle(ui, invocationJson)
                    .ifPresent(pendingChangeEvents::add);
        } else {
            data.add(invocationJson);
        }
    }

    pendingChangeEvents.forEach(runnable -> runMapSyncTask(ui, runnable));
    data.forEach(json -> handleInvocationData(ui, json));
}
 
Example #13
Source File: MessageSender.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Makes an UIDL request to the server.
 *
 * @param reqInvocations
 *            Data containing RPC invocations and all related information.
 * @param extraJson
 *            Parameters that are added to the payload
 */
protected void send(final JsonArray reqInvocations,
        final JsonObject extraJson) {
    registry.getRequestResponseTracker().startRequest();

    JsonObject payload = Json.createObject();
    String csrfToken = registry.getMessageHandler().getCsrfToken();
    if (!csrfToken.equals(ApplicationConstants.CSRF_TOKEN_DEFAULT_VALUE)) {
        payload.put(ApplicationConstants.CSRF_TOKEN, csrfToken);
    }
    payload.put(ApplicationConstants.RPC_INVOCATIONS, reqInvocations);
    payload.put(ApplicationConstants.SERVER_SYNC_ID,
            registry.getMessageHandler().getLastSeenServerSyncId());
    payload.put(ApplicationConstants.CLIENT_TO_SERVER_ID,
            clientToServerMessageId++);

    if (extraJson != null) {
        for (String key : extraJson.keys()) {
            JsonValue value = extraJson.get(key);
            payload.put(key, value);
        }
    }

    send(payload);

}
 
Example #14
Source File: ListChangeTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicJson() {
    StateNode child1 = StateNodeTest.createEmptyNode("child1");
    StateNode child2 = StateNodeTest.createEmptyNode("child2");
    ListAddChange<StateNode> change = new ListAddChange<>(feature, true, 0,
            Arrays.asList(child1, child2));

    JsonObject json = change.toJson(null);

    Assert.assertEquals(change.getNode().getId(),
            (int) json.getNumber(JsonConstants.CHANGE_NODE));
    Assert.assertEquals(NodeFeatureRegistry.getId(feature.getClass()),
            (int) json.getNumber(JsonConstants.CHANGE_FEATURE));
    Assert.assertEquals(JsonConstants.CHANGE_TYPE_SPLICE,
            json.getString(JsonConstants.CHANGE_TYPE));
    Assert.assertEquals(0,
            (int) json.getNumber(JsonConstants.CHANGE_SPLICE_INDEX));

    JsonArray addNodes = json
            .getArray(JsonConstants.CHANGE_SPLICE_ADD_NODES);
    Assert.assertEquals(2, addNodes.length());

    Assert.assertEquals(child1.getId(), (int) addNodes.getNumber(0));
    Assert.assertEquals(child2.getId(), (int) addNodes.getNumber(1));
}
 
Example #15
Source File: RootImpl.java    From serverside-elements with Apache License 2.0 6 votes vote down vote up
public JsonArray flushPendingCommands() {
    for (Entry<Integer, Component[]> entry : fetchDomComponents
            .entrySet()) {
        JsonArray connectorsJson = Json.createArray();
        for (Component component : entry.getValue()) {
            connectorsJson.set(connectorsJson.length(),
                    component.getConnectorId());
        }

        addCommand("fetchDom", null, Json.create(entry.getKey().intValue()),
                connectorsJson);
    }
    fetchDomComponents.clear();

    JsonArray payload = pendingCommands;
    pendingCommands = Json.createArray();
    return payload;
}
 
Example #16
Source File: ClientJsonCodec.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Decodes a value as a {@link StateNode} encoded on the server using
 * {@link JsonCodec#encodeWithTypeInfo(Object)} if it's possible. Otherwise
 * returns {@code null}.
 * <p>
 * It does the same as {@link #decodeWithTypeInfo(StateTree, JsonValue)} for
 * the encoded json value if the encoded object is a {@link StateNode}
 * except it returns the node itself instead of a DOM element associated
 * with it.
 *
 * @see #decodeWithTypeInfo(StateTree, JsonValue)
 * @param tree
 *            the state tree to use for resolving nodes and elements
 * @param json
 *            the JSON value to decode
 * @return the decoded state node if any
 */
public static StateNode decodeStateNode(StateTree tree, JsonValue json) {
    if (json.getType() == JsonType.ARRAY) {
        JsonArray array = (JsonArray) json;
        int typeId = (int) array.getNumber(0);
        switch (typeId) {
        case JsonCodec.NODE_TYPE: {
            int nodeId = (int) array.getNumber(1);
            return tree.getNode(nodeId);
        }
        case JsonCodec.ARRAY_TYPE:
        case JsonCodec.RETURN_CHANNEL_TYPE:
            return null;
        default:
            throw new IllegalArgumentException(
                    "Unsupported complex type in " + array.toJson());
        }
    } else {
        return null;
    }
}
 
Example #17
Source File: ListAddChange.java    From flow with Apache License 2.0 6 votes vote down vote up
@Override
protected void populateJson(JsonObject json, ConstantPool constantPool) {
    json.put(JsonConstants.CHANGE_TYPE, JsonConstants.CHANGE_TYPE_SPLICE);

    super.populateJson(json, constantPool);

    json.put(JsonConstants.CHANGE_SPLICE_INDEX, getIndex());

    Function<Object, JsonValue> mapper;
    String addKey;
    if (nodeValues) {
        addKey = JsonConstants.CHANGE_SPLICE_ADD_NODES;
        mapper = item -> Json.create(((StateNode) item).getId());
    } else {
        addKey = JsonConstants.CHANGE_SPLICE_ADD;
        mapper = item -> JsonCodec.encodeWithConstantPool(item,
                constantPool);
    }

    JsonArray newItemsJson = newItems.stream().map(mapper)
            .collect(JsonUtils.asArray());
    json.put(addKey, newItemsJson);
}
 
Example #18
Source File: PublishedServerEventHandlerRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void methodWithJsonValueIsInvoked() {
    JsonArray array = Json.createArray();

    JsonObject json = Json.createObject();
    json.put("foo", "bar");
    array.set(0, json);

    MethodWithParameters component = new MethodWithParameters();
    PublishedServerEventHandlerRpcHandler.invokeMethod(component,
            component.getClass(), "method4", array, -1);

    Assert.assertEquals(component.jsonValue, json);
}
 
Example #19
Source File: RootTest.java    From serverside-elements with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveChild() {
    root.appendChild(child);
    root.flushPendingCommands();

    child.remove();

    JsonArray pendingCommands = root.flushPendingCommands();

    Assert.assertEquals("[[\"remove\",2]]", pendingCommands.toJson());
}
 
Example #20
Source File: GwtBasicElementBinderTest.java    From flow with Apache License 2.0 5 votes vote down vote up
public void testBindVirtualChild_noCorrespondingElementInShadowRoot_searchByIndicesPath() {
    Element shadowRootElement = addShadowRootElement(element);

    String childTagName = "span";

    StateNode child = createChildNode(null, childTagName);

    Binder.bind(node, element);

    JsonArray path = Json.createArray();
    path.set(0, 1);
    addVirtualChild(node, child, NodeProperties.TEMPLATE_IN_TEMPLATE, path);

    Element elementWithDifferentTag = createAndAppendElementToShadowRoot(
            shadowRootElement, null, childTagName);
    assertNotSame(
            "Element added to shadow root should not have same tag name as virtual child node",
            childTagName, elementWithDifferentTag.getTagName());

    Reactive.flush();

    assertEquals(
            "Unexpected 'sendExistingElementWithIdAttachToServer' method call number",
            4, tree.existingElementRpcArgs.size());
    assertEquals(
            "Unexpected requested node id value argument in the 'sendExistingElementWithIdAttachToServer' method call",
            node, tree.existingElementRpcArgs.get(0));
    assertEquals(
            "Unexpected requested node id value argument in the 'sendExistingElementWithIdAttachToServer' method call",
            child.getId(), tree.existingElementRpcArgs.get(1));
    assertEquals(
            "Unexpected attached node id value argument in the 'sendExistingElementWithIdAttachToServer' method call",
            -1, tree.existingElementRpcArgs.get(2));
    assertEquals(
            "Unexpected identifier value argument in the 'sendExistingElementWithIdAttachToServer' method call",
            null, tree.existingElementRpcArgs.get(3));
}
 
Example #21
Source File: JsonUtilsTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void beanWithListAndMap() {
    ListAndMapBean bean = new ListAndMapBean();

    JsonObject json = JsonUtils.beanToJson(bean);

    JsonObject integerMap = json.getObject("integerMap");
    Assert.assertEquals(1, integerMap.getNumber("one"), 0);
    Assert.assertEquals(2, integerMap.getNumber("two"), 0);

    JsonObject childBeanMap = json.getObject("childBeanMap");
    JsonObject firstChild = childBeanMap.getObject("First");
    Assert.assertEquals("firstChildValue",
            firstChild.getString("childValue"));
    JsonObject secondChild = childBeanMap.getObject("Second");
    Assert.assertEquals("secondChildValue",
            secondChild.getString("childValue"));

    JsonArray integerList = json.getArray("integerList");
    Assert.assertEquals(3, integerList.get(0).asNumber(), 0);
    Assert.assertEquals(2, integerList.get(1).asNumber(), 0);
    Assert.assertEquals(1, integerList.get(2).asNumber(), 0);

    JsonArray childBeanList = json.getArray("childBeanList");
    Assert.assertEquals("firstChildValue",
            ((JsonObject) childBeanList.get(0)).getString("childValue"));
    Assert.assertEquals("secondChildValue",
            ((JsonObject) childBeanList.get(1)).getString("childValue"));
}
 
Example #22
Source File: JsonUtils.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the given list to JSON.
 *
 * @param list
 *                 the list to convert, not {@code null}
 * @return a JSON representation of the bean
 */
public static JsonArray listToJson(List<?> list) {
    Objects.requireNonNull(list, CANNOT_CONVERT_NULL_TO_A_JSON_OBJECT);
    try {
        return Json.instance().parse(objectMapper.writeValueAsString(list));
    } catch (JsonProcessingException e) {
        throw new RuntimeException("Error converting list to JSON", e);
    }
}
 
Example #23
Source File: BootstrapHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
private Map<LoadMode, JsonArray> popDependenciesToProcessOnServer(
        JsonObject initialUIDL) {
    Map<LoadMode, JsonArray> result = new EnumMap<>(LoadMode.class);
    Stream.of(LoadMode.EAGER, LoadMode.INLINE).forEach(mode -> {
        if (initialUIDL.hasKey(mode.name())) {
            result.put(mode, initialUIDL.getArray(mode.name()));
            initialUIDL.remove(mode.name());
        }
    });
    return result;
}
 
Example #24
Source File: SimpleElementBindingStrategy.java    From flow with Apache License 2.0 5 votes vote down vote up
private static boolean resolveFilters(Node element, String eventType,
        JsonObject expressionSettings, JsonObject eventData,
        Consumer<String> sendCommand) {

    boolean noFilters = true;
    boolean atLeastOneFilterMatched = false;

    for (String expression : expressionSettings.keys()) {
        JsonValue settings = expressionSettings.get(expression);

        boolean hasDebounce = settings.getType() == JsonType.ARRAY;

        if (!hasDebounce && !settings.asBoolean()) {
            continue;
        }
        noFilters = false;

        boolean filterMatched = eventData != null
                && eventData.getBoolean(expression);
        if (hasDebounce && filterMatched) {
            String debouncerId = "on-" + eventType + ":" + expression;

            // Count as a match only if at least one debounce is eager
            filterMatched = resolveDebounces(element, debouncerId,
                    (JsonArray) settings, sendCommand);
        }

        atLeastOneFilterMatched |= filterMatched;
    }

    return noFilters || atLeastOneFilterMatched;
}
 
Example #25
Source File: PublishedServerEventHandlerRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void methodWithParameterInvokedWithProperParameter() {
    JsonArray array = Json.createArray();
    array.set(0, 65);
    MethodWithParameters component = new MethodWithParameters();
    PublishedServerEventHandlerRpcHandler.invokeMethod(component,
            component.getClass(), "intMethod", array, -1);

    Assert.assertEquals(65, component.intArg);
}
 
Example #26
Source File: PublishedServerEventHandlerRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void methodWithDecoderParameters_nonConvertableValues_methodIsInvoked() {
    JsonArray params = Json.createArray();
    params.set(0, "264.1");
    params.set(1, "MR");

    DecoderParameters component = new DecoderParameters();
    PublishedServerEventHandlerRpcHandler.invokeMethod(component,
            component.getClass(), "method", params, -1);
}
 
Example #27
Source File: UidlWriter.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the performance timing data (used by TestBench 3) to the UIDL
 * response.
 */
private JsonValue createPerformanceData(UI ui) {
    JsonArray timings = Json.createArray();
    timings.set(0, ui.getSession().getCumulativeRequestDuration());
    timings.set(1, ui.getSession().getLastRequestDuration());
    return timings;
}
 
Example #28
Source File: PolymerTemplateTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private void doParseTemplate_hasTextNodesInTemplate_correctRequestIndicesPath(
        TextNodesInHtmlTemplate template) {

    VirtualChildrenList feature = template.getStateNode()
            .getFeature(VirtualChildrenList.class);
    JsonObject object = (JsonObject) feature.get(0)
            .getFeature(ElementData.class).getPayload();
    JsonArray path = object.getArray(NodeProperties.PAYLOAD);

    // check arrays of indices
    assertEquals(1, path.length());
    assertEquals(1, (int) path.get(0).asNumber());
}
 
Example #29
Source File: PublishedServerEventHandlerRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void methodWithoutArgs_argsProvided() {
    JsonArray args = Json.createArray();
    args.set(0, true);
    ComponentWithMethod component = new ComponentWithMethod();
    PublishedServerEventHandlerRpcHandler.invokeMethod(component,
            component.getClass(), "method", args, -1);
}
 
Example #30
Source File: ClientJsonCodec.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a JSON array to a JS array. This is a no-op in compiled
 * JavaScript, but needs special handling for tests running in the JVM.
 *
 * @param jsonArray
 *            the JSON array to convert
 * @return the converted JS array
 */
public static JsArray<Object> jsonArrayAsJsArray(JsonArray jsonArray) {
    JsArray<Object> jsArray;
    if (GWT.isScript()) {
        jsArray = WidgetUtil.crazyJsCast(jsonArray);
    } else {
        jsArray = JsCollections.array();
        for (int i = 0; i < jsonArray.length(); i++) {
            jsArray.push(decodeWithoutTypeInfo(jsonArray.get(i)));
        }
    }
    return jsArray;
}