Java Code Examples for elemental.json.JsonArray#set()

The following examples show how to use elemental.json.JsonArray#set() . 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: AttributesTest.java    From serverside-elements with Apache License 2.0 6 votes vote down vote up
@Test
public void testArrayAttribute() {
    Element element = Elements.create("div");

    String[] items = {"A", "B", "C"};
    JsonArray jsonArray = Json.createArray();

    for (int i = 0; i < items.length; i++) {
        JsonObject object = Json.createObject();
        object.put("id", i);
        object.put("name", items[i]);

        jsonArray.set(i, object);
    }

    String jsonArrayString = jsonArray.toString();
    element.setAttribute("items", jsonArrayString);

    Assert.assertEquals(jsonArrayString, element.getAttribute("items"));
}
 
Example 2
Source File: PublishedServerEventHandlerRpcHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void methodWithArrayParamIsInvoked() {
    JsonArray array = Json.createArray();
    array.set(0, "foo");
    JsonArray secondArg = Json.createArray();
    secondArg.set(0, true);
    secondArg.set(1, false);
    array.set(1, secondArg);
    MethodWithParameters component = new MethodWithParameters();
    PublishedServerEventHandlerRpcHandler.invokeMethod(component,
            component.getClass(), "method1", array, -1);

    Assert.assertEquals("foo", component.strArg);
    Assert.assertArrayEquals(new boolean[] { true, false },
            component.arrayArg);
}
 
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: 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 5
Source File: RootImpl.java    From serverside-elements with Apache License 2.0 5 votes vote down vote up
void eval(ElementImpl element, String script, Object[] arguments) {
    // Param values
    JsonArray params = Json.createArray();

    // Array of param indices that should be treated as callbacks
    JsonArray callbacks = Json.createArray();

    for (int i = 0; i < arguments.length; i++) {
        Object value = arguments[i];
        Class<? extends Object> type = value.getClass();

        if (JavaScriptFunction.class.isAssignableFrom(type)) {
            // TODO keep sequence per element instead of "global"
            int cid = callbackIdSequence++;
            element.setCallback(cid, (JavaScriptFunction) value);

            value = Integer.valueOf(cid);
            type = Integer.class;

            callbacks.set(callbacks.length(), i);
        }

        EncodeResult encodeResult = JsonCodec.encode(value, null, type,
                null);
        params.set(i, encodeResult.getEncodedValue());
    }

    addCommand("eval", element, Json.create(script), params, callbacks);
}
 
Example 6
Source File: GwtMessageHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
public void testMessageProcessing_dynamicDependencyIsHandledBeforeApplyingChangesToTree() {
    resetInternalEvents();

    JavaScriptObject object = JavaScriptObject.createObject();
    JsonObject obj = object.cast();

    // make an empty changes list. It will initiate changes processing
    // anyway
    // Any changes processing should happen AFTER dependencies are loaded
    obj.put("changes", Json.createArray());

    JsonArray array = Json.createArray();

    // create a dependency
    JsonObject dep = Json.createObject();
    dep.put(Dependency.KEY_TYPE, Dependency.Type.DYNAMIC_IMPORT.toString());
    dep.put(Dependency.KEY_URL, "return new Promise(function(resolve){ "
            + "window.testEvents.push('test-dependency'); resolve(); });");
    array.set(0, dep);

    obj.put(LoadMode.LAZY.toString(), array);

    handler.handleJSON(object.cast());

    delayTestFinish(500);

    new Timer() {
        @Override
        public void run() {
            assertEquals("test-dependency", getInternalEvent(0));
            assertEquals(StateTree.class.getName(), getInternalEvent(1));
            finishTest();
        }
    }.schedule(100);
}
 
Example 7
Source File: PwaRegistry.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Creates manifest.webmanifest json object.
 *
 * @return manifest.webmanifest contents json object
 */
private JsonObject initializeManifest() {
    JsonObject manifestData = Json.createObject();
    // Add basic properties
    manifestData.put("name", pwaConfiguration.getAppName());
    manifestData.put("short_name", pwaConfiguration.getShortName());
    if (!pwaConfiguration.getDescription().isEmpty()) {
        manifestData.put("description", pwaConfiguration.getDescription());
    }
    manifestData.put("display", pwaConfiguration.getDisplay());
    manifestData.put("background_color",
            pwaConfiguration.getBackgroundColor());
    manifestData.put("theme_color", pwaConfiguration.getThemeColor());
    manifestData.put("start_url", pwaConfiguration.getStartUrl());
    manifestData.put("scope", pwaConfiguration.getRootUrl());

    // Add icons
    JsonArray iconList = Json.createArray();
    int iconIndex = 0;
    for (PwaIcon icon : getManifestIcons()) {
        JsonObject iconData = Json.createObject();
        iconData.put("src", icon.getHref());
        iconData.put("sizes", icon.getSizes());
        iconData.put("type", icon.getType());
        iconList.set(iconIndex++, iconData);
    }
    manifestData.put("icons", iconList);
    return manifestData;
}
 
Example 8
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 9
Source File: JUtils.java    From vaadin-chartjs with MIT License 5 votes vote down vote up
public static void putNotNullIntListOrSingle(JsonObject obj, String key, List<Integer> listOfNumbers) {
    if (listOfNumbers != null) {
        if (listOfNumbers.size() == 1) {
            putNotNull(obj, key, listOfNumbers.get(0));
        } else {
            JsonArray arr = Json.createArray();
            for (Integer n : listOfNumbers) {
                arr.set(arr.length(), n.doubleValue());
            }
            obj.put(key, arr);
        }
    }
}
 
Example 10
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 11
Source File: JUtils.java    From vaadin-chartjs with MIT License 5 votes vote down vote up
public static void putNotNullStringListOrSingle(JsonObject obj, String key, List<String> list) {
    if (list != null) {
        if (list.size() == 1) {
            putNotNull(obj, key, list.get(0));
        } else {
            JsonArray arr = Json.createArray();
            for (String entry : list) {
                arr.set(arr.length(), entry);
            }
            obj.put(key, arr);
        }
    }
}
 
Example 12
Source File: PublishedServerEventHandlerRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void methodWithVarArg_acceptOneValue() {
    JsonArray array = Json.createArray();

    array.set(0, "foo");

    MethodWithVarArgParameter component = new MethodWithVarArgParameter();
    PublishedServerEventHandlerRpcHandler.invokeMethod(component,
            component.getClass(), "varArgMethod", array, -1);

    Assert.assertEquals(1, component.varArg.length);
    Assert.assertEquals("foo", component.varArg[0]);
}
 
Example 13
Source File: GwtEventHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
public void testPolymerMockedEventHandlerWithEventData() {
    String methodName = "eventHandler";
    String methodId = "handlerId";
    String eventData = "event.button";

    node.getList(NodeFeatures.POLYMER_SERVER_EVENT_HANDLERS).add(0,
            methodName);
    node.getMap(NodeFeatures.POLYMER_EVENT_LISTENERS)
            .getProperty(methodName).setValue(methodId);

    JsonObject json = Json.createObject();
    JsonArray array = Json.createArray();
    array.set(0, eventData);
    json.put(methodId, array);

    node.getTree().getRegistry().getConstantPool().importFromJson(json);
    Binder.bind(node, element);
    Reactive.flush();

    NativeFunction mockedFunction = new NativeFunction("this." + methodName
            + "({button: 2, altKey: false, clientX: 50, clientY: 100})");
    mockedFunction.apply(element, JsCollections.array());

    assertEquals("The amount of server methods was not as expected", 1,
            serverMethods.size());
    assertEquals("Expected method did not match", methodName,
            serverMethods.keySet().iterator().next());
    assertEquals("Wrong amount of method arguments", 1,
            serverMethods.get(methodName).length());
    assertEquals("Gotten argument wasn't as expected", "2",
            serverMethods.get(methodName).get(0).toString());
    assertEquals("Method node did not match the expected node.", node,
            serverRpcNodes.get(methodName));
}
 
Example 14
Source File: JUtils.java    From vaadin-chartjs with MIT License 5 votes vote down vote up
public static void putNotNullNumbers(JsonObject obj, String key, List<Double> listOfNumbers) {
    if (listOfNumbers != null) {
        JsonArray arr = Json.createArray();
        for (Double n : listOfNumbers) {
            if (n == null) {
                arr.set(arr.length(), new JreJsonNull());
            } else {
                arr.set(arr.length(), n);
            }
        }
        obj.put(key, arr);
    }
}
 
Example 15
Source File: GwtBasicElementBinderTest.java    From flow with Apache License 2.0 5 votes vote down vote up
public void testVirtualBindChild_wrongTag_searchByIndicesPath() {
    Element shadowRootElement = addShadowRootElement(element);

    String childTagName = "span";

    StateNode child = createChildNode(null, childTagName);

    Binder.bind(node, element);

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

    Element elementWithDifferentTag = createAndAppendElementToShadowRoot(
            shadowRootElement, null, "div");
    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 16
Source File: PublishedServerEventHandlerRpcHandlerTest.java    From flow with Apache License 2.0 4 votes vote down vote up
@Test
public void promiseFailure() {
    int promiseId = 4;

    JsonArray args = Json.createArray();
    args.set(0, -36);

    ComponentWithMethod component = new ComponentWithMethod();
    MockUI ui = new MockUI();
    ui.add(component);

    // Get rid of attach invocations
    ui.getInternals().getStateTree().runExecutionsBeforeClientResponse();
    ui.getInternals().dumpPendingJavaScriptInvocations();

    try {
        PublishedServerEventHandlerRpcHandler.invokeMethod(component,
                component.getClass(), "compute", args, promiseId);
        Assert.fail("Exception should be thrown");
    } catch (RuntimeException e) {
        Assert.assertTrue(e.getCause() instanceof ArithmeticException);
    }

    List<PendingJavaScriptInvocation> pendingJavaScriptInvocations = ui
            .dumpPendingJsInvocations();
    Assert.assertEquals(1, pendingJavaScriptInvocations.size());

    JavaScriptInvocation invocation = pendingJavaScriptInvocations.get(0)
            .getInvocation();
    Assert.assertTrue("Invocation does not look like a promise callback",
            invocation.getExpression()
                    .contains(JsonConstants.RPC_PROMISE_CALLBACK_NAME));

    List<Object> parameters = invocation.getParameters();
    Assert.assertEquals("Expected two paramters: promiseId,  target", 2,
            parameters.size());
    Assert.assertEquals(
            "Promise id should match the value passed to invokeMethod",
            Integer.valueOf(promiseId), parameters.get(0));
    Assert.assertEquals("Target should be the component's element",
            component.getElement(), parameters.get(1));
}
 
Example 17
Source File: GwtMultipleBindingTest.java    From flow with Apache License 2.0 4 votes vote down vote up
public void testDomEventHandlerDoubleBind() {
    Binder.bind(node, element);

    String booleanExpression = "window.navigator.userAgent[0] === 'M'";

    String constantPoolKey = "expressionsKey";

    JsonArray expressionConstantValue = Json.createArray();
    expressionConstantValue.set(0, booleanExpression);

    addToConstantPool(constantPoolKey, expressionConstantValue);

    node.getMap(NodeFeatures.ELEMENT_LISTENERS).getProperty("click")
            .setValue(constantPoolKey);
    Reactive.flush();

    node.setBound();
    Binder.bind(node, element);
}
 
Example 18
Source File: GwtMessageHandlerTest.java    From flow with Apache License 2.0 4 votes vote down vote up
public void testMessageProcessing_moduleDependencyIsHandledBeforeApplyingChangesToTree() {
    resetInternalEvents();

    JavaScriptObject object = JavaScriptObject.createObject();
    JsonObject obj = object.cast();

    // make an empty changes list. It will initiate changes processing
    // anyway
    // Any changes processing should happen AFTER dependencies are loaded
    obj.put("changes", Json.createArray());

    JsonArray array = Json.createArray();

    // create a dependency
    JsonObject dep = Json.createObject();
    dep.put(Dependency.KEY_URL, "foo");
    dep.put(Dependency.KEY_TYPE, Dependency.Type.JS_MODULE.toString());
    array.set(0, dep);

    obj.put(LoadMode.EAGER.toString(), array);
    handler.handleJSON(object.cast());

    delayTestFinish(500);

    new Timer() {
        @Override
        public void run() {
            assertTrue(getResourceLoader().scriptUrls.contains("foo"));

            EventsOrder eventsOrder = registry.get(EventsOrder.class);
            assertTrue(eventsOrder.sources.size() >= 2);
            // the first one is resource loaded which means dependency
            // processing
            assertEquals(ResourceLoader.class.getName(),
                    eventsOrder.sources.get(0));
            // the second one is applying changes to StatTree
            assertEquals(StateTree.class.getName(),
                    eventsOrder.sources.get(1));
            finishTest();
        }
    }.schedule(100);
}
 
Example 19
Source File: GwtEventHandlerTest.java    From flow with Apache License 2.0 4 votes vote down vote up
public void testEventHandlerModelItemSingleItem() {
    String methodName = "eventHandlerSingleModelItem";
    String methodId = "handlerSingleModelId";
    String eventData = "item";

    node.getList(NodeFeatures.POLYMER_SERVER_EVENT_HANDLERS).add(0,
            methodName);
    node.getMap(NodeFeatures.POLYMER_EVENT_LISTENERS)
            .getProperty(methodName).setValue(methodId);

    JsonObject json = Json.createObject();
    JsonArray array = Json.createArray();
    array.set(0, eventData);
    json.put(methodId, array);

    node.getTree().getRegistry().getConstantPool().importFromJson(json);
    node.setDomNode(element);
    Binder.bind(node, element);
    // Add the node property for getPolymerPropertyObject functionality
    setNodeProperty(node.getDomNode(), eventData, "nodeId", "1");
    Reactive.flush();

    NativeFunction mockedFunction = new NativeFunction(
            "this." + methodName + "({button: 0})");
    mockedFunction.apply(element, JsCollections.array());

    assertEquals("The amount of server methods was not as expected", 1,
            serverMethods.size());
    assertEquals("Expected method did not match", methodName,
            serverMethods.keySet().iterator().next());
    assertEquals("Wrong amount of method arguments", 1,
            serverMethods.get(methodName).length());

    assertTrue("Received value was not a JsonObject",
            serverMethods.get(methodName).get(0) instanceof JsonObject);

    JsonObject expectedResult = Json.createObject();
    expectedResult.put("nodeId", 1);

    assertEquals("Gotten argument wasn't as expected",
            expectedResult.toJson(),
            ((JsonObject) serverMethods.get(methodName).get(0)).toJson());
    assertEquals("Method node did not match the expected node.", node,
            serverRpcNodes.get(methodName));
}
 
Example 20
Source File: CubaSideMenu.java    From cuba with Apache License 2.0 4 votes vote down vote up
protected JsonArray toJson(List<MenuItem> menuItems) {
    JsonArray array = Json.createArray();

    int i = 0;
    for (MenuItem menuItem : menuItems) {
        if (menuItem.isVisible()) {
            JsonObject item = Json.createObject();

            item.put(MENU_ITEM_ID, Json.create(menuItemIdMapper.key(menuItem)));

            if (menuItem.getCaption() != null) {
                item.put(MENU_ITEM_CAPTION, Json.create(menuItem.getCaption()));
            }
            if (menuItem.getDescription() != null) {
                item.put(MENU_ITEM_DESCRIPTION, Json.create(menuItem.getDescription()));
            }
            if (menuItem.getStyleName() != null) {
                item.put(MENU_ITEM_STYLE_NAME, Json.create(menuItem.getStyleName()));
            }
            item.put(MENU_ITEM_EXPANDED, Json.create(menuItem.isExpanded()));
            item.put(MENU_ITEM_CAPTION_AS_HTML, Json.create(menuItem.isCaptionAsHtml()));

            if (menuItem.getBadgeText() != null) {
                item.put(MENU_ITEM_BADGE_TEXT, Json.create(menuItem.getBadgeText()));
            }

            if (menuItem.getCubaId() != null) {
                item.put(MENU_ITEM_CUBA_ID, Json.create(menuItem.getCubaId()));
            }

            if (menuItem.getIcon() != null) {
                String resourceKey = menuIconsKeyMapper.key(menuItem.getIcon());

                menuIconResourceKeys.add(resourceKey);

                setResource(resourceKey, menuItem.getIcon());

                item.put(MENU_ITEM_ICON, Json.create(resourceKey));
            }

            if (!menuItem.getChildren().isEmpty()) {
                JsonArray childrenJsonArray = toJson(menuItem.getChildren());
                item.put(MENU_ITEM_CHILDREN, childrenJsonArray);
            }

            array.set(i, item);

            i++;
        }
    }

    return array;
}