Java Code Examples for elemental.json.Json#createArray()

The following examples show how to use elemental.json.Json#createArray() . 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: 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 2
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 3
Source File: ServerEventObject.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Collect extra data for element event if any has been sent from the
 * server. Note! Data is sent in the array in the same order as defined on
 * the server side.
 *
 * @param event
 *            The fired Event
 * @param methodName
 *            Method name that is called
 * @param node
 *            Target node
 * @return Array of extra event data
 */
private JsonArray getEventData(Event event, String methodName,
        StateNode node) {

    if (node.getMap(NodeFeatures.POLYMER_EVENT_LISTENERS)
            .hasPropertyValue(methodName)) {
        JsonArray dataArray = Json.createArray();
        ConstantPool constantPool = node.getTree().getRegistry()
                .getConstantPool();
        String expressionConstantKey = (String) node
                .getMap(NodeFeatures.POLYMER_EVENT_LISTENERS)
                .getProperty(methodName).getValue();

        JsArray<String> dataExpressions = constantPool
                .get(expressionConstantKey);

        for (int i = 0; i < dataExpressions.length(); i++) {
            String expression = dataExpressions.get(i);

            dataArray.set(i, getExpressionValue(event, node, expression));
        }
        return dataArray;
    }

    return null;
}
 
Example 4
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 5
Source File: NodeList.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public JsonValue getDebugJson() {
    JsonArray json = Json.createArray();

    for (int i = 0; i < values.length(); i++) {
        Object value = values.get(i);
        JsonValue jsonValue = getAsDebugJson(value);

        json.set(json.length(), jsonValue);
    }

    return json;
}
 
Example 6
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 7
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 8
Source File: NodeList.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public JsonValue convert(Function<Object, JsonValue> converter) {
    JsonArray json = Json.createArray();

    for (int i = 0; i < values.length(); i++) {
        Object value = values.get(i);
        // Crazy cast since otherwise SDM fails
        // for primitives values since primitives are not a JSO
        json.set(json.length(),
                WidgetUtil.crazyJsoCast(converter.apply(value)));
    }

    return json;

}
 
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: 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 11
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 12
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 13
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 14
Source File: GwtBasicElementBinderTest.java    From flow with Apache License 2.0 5 votes vote down vote up
public void testBindVirtualChild_existingShadowRootChildren_searchByIndicesPath() {
    addShadowRootElement(element);

    StateNode childNode = createChildNode(null, element.getTagName());
    StateNode virtualChild = createChildNode(null, element.getTagName());

    StateNode shadowRoot = createAndAttachShadowRootNode();

    shadowRoot.getList(NodeFeatures.ELEMENT_CHILDREN).add(0, childNode);

    Binder.bind(node, element);

    Reactive.flush();

    JsonArray path = Json.createArray();
    path.set(0, 0);

    addVirtualChild(node, virtualChild, NodeProperties.TEMPLATE_IN_TEMPLATE,
            path);

    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",
            virtualChild.getId(), tree.existingElementRpcArgs.get(1));
    assertEquals(
            "Unexpected attached node id value argument in the 'sendExistingElementWithIdAttachToServer' method call",
            childNode.getId(), tree.existingElementRpcArgs.get(2));
    assertEquals(
            "Unexpected identifier value argument in the 'sendExistingElementWithIdAttachToServer' method call",
            null, tree.existingElementRpcArgs.get(3));
}
 
Example 15
Source File: AbstractTemplate.java    From flow with Apache License 2.0 5 votes vote down vote up
private JsonArray filterUpdatableProperties(
        Map<String, Boolean> allowedProperties) {
    JsonArray array = Json.createArray();
    int i = 0;
    for (Entry<String, Boolean> entry : allowedProperties.entrySet()) {
        if (entry.getValue()) {
            array.set(i, entry.getKey());
            i++;
        }
    }
    return array;
}
 
Example 16
Source File: SizelessDataCommunicator.java    From viritin with Apache License 2.0 4 votes vote down vote up
@Override
protected void sendDataToClient(boolean initial) {
    if (getDataProvider() == null) {
        return;
    }

    if (initial) {
        rpc.reset(0);
    }

    Range requestedRows = getPushRows();
    if (!requestedRows.isEmpty()) {
        int offset = requestedRows.getStart();
        // Always fetch some extra rows.
        int limit = requestedRows.length() + getMinPushSize();
        List<T> rowsToPush = fetchItemsWithRange(offset, limit);
        int lastIndex = offset + rowsToPush.size();
        if (lastIndex > knownSize) {
            int rowsToAdd = lastIndex - knownSize;
            rpc.insertRows(knownSize,
                    rowsToAdd + (rowsToPush.size() == limit ? 1 : 0));
            knownSize = lastIndex;
        } else if (rowsToPush.size() < requestedRows.length()) {
            // Size decreased
            int rowsToRemove = Math.max(
                    requestedRows.length() - rowsToPush.size(),
                    knownSize - lastIndex);
            knownSize = lastIndex;
            rpc.removeRows(knownSize, rowsToRemove);
        }
        pushData(offset, rowsToPush);
    }

    if (!getUpdatedData().isEmpty()) {
        JsonArray dataArray = Json.createArray();
        int i = 0;
        for (T data : getUpdatedData()) {
            dataArray.set(i++, getDataObject(data));
        }
        rpc.updateData(dataArray);
    }

    setPushRows(Range.withLength(0, 0));
    getUpdatedData().clear();
}
 
Example 17
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 18
Source File: GwtEventHandlerTest.java    From flow with Apache License 2.0 4 votes vote down vote up
public void testEventHandlerModelItem() {
    String methodName = "eventHandlerModelItem";
    String methodId = "handlerModelId";
    String eventData = "event.model.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);
    Binder.bind(node, element);
    Reactive.flush();

    NativeFunction mockedFunction = new NativeFunction("this." + methodName
            + "({button: 0, model:{item: {nodeId: 2, value: 'test value'}}})");
    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", 2);

    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 19
Source File: UidlWriter.java    From flow with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a JSON object containing all pending changes to the given UI.
 *
 * @param ui
 *            The {@link UI} whose changes to write
 * @param async
 *            True if this message is sent by the server asynchronously,
 *            false if it is a response to a client message
 * @param resync
 *            True iff the client should be asked to resynchronize
 * @return JSON object containing the UIDL response
 */
public JsonObject createUidl(UI ui, boolean async, boolean resync) {
    JsonObject response = Json.createObject();

    UIInternals uiInternals = ui.getInternals();

    VaadinSession session = ui.getSession();
    VaadinService service = session.getService();

    // Purge pending access calls as they might produce additional changes
    // to write out
    service.runPendingAccessTasks(session);

    // Paints components
    getLogger().debug("* Creating response to client");

    int syncId = service.getDeploymentConfiguration().isSyncIdCheckEnabled()
            ? uiInternals.getServerSyncId()
            : -1;

    response.put(ApplicationConstants.SERVER_SYNC_ID, syncId);
    if (resync) {
        response.put(ApplicationConstants.RESYNCHRONIZE_ID, true);
    }
    int nextClientToServerMessageId = uiInternals
            .getLastProcessedClientToServerId() + 1;
    response.put(ApplicationConstants.CLIENT_TO_SERVER_ID,
            nextClientToServerMessageId);

    SystemMessages messages = ui.getSession().getService()
            .getSystemMessages(ui.getLocale(), null);

    JsonObject meta = new MetadataWriter().createMetadata(ui, false, async,
            messages);
    if (meta.keys().length > 0) {
        response.put("meta", meta);
    }

    JsonArray stateChanges = Json.createArray();

    encodeChanges(ui, stateChanges);

    populateDependencies(response, uiInternals.getDependencyList(),
            new ResolveContext(service, session.getBrowser()));

    if (uiInternals.getConstantPool().hasNewConstants()) {
        response.put("constants",
                uiInternals.getConstantPool().dumpConstants());
    }
    if (stateChanges.length() != 0) {
        response.put("changes", stateChanges);
    }

    List<PendingJavaScriptInvocation> executeJavaScriptList = uiInternals
            .dumpPendingJavaScriptInvocations();
    if (!executeJavaScriptList.isEmpty()) {
        response.put(JsonConstants.UIDL_KEY_EXECUTE,
                encodeExecuteJavaScriptList(executeJavaScriptList));
    }
    if (ui.getSession().getService().getDeploymentConfiguration()
            .isRequestTiming()) {
        response.put("timings", createPerformanceData(ui));
    }
    uiInternals.incrementServerId();
    return response;
}
 
Example 20
Source File: GwtBasicElementBinderTest.java    From flow with Apache License 2.0 4 votes vote down vote up
public void testBindVirtualChild_withDeferredElementInShadowRoot_byIndicesPath() {
    String childId = "childElement";
    StateNode childNode = createChildNode(childId, element.getTagName());

    NodeMap properties = childNode.getMap(NodeFeatures.ELEMENT_PROPERTIES);
    MapProperty fooProperty = properties.getProperty("foo");
    fooProperty.setValue("bar");

    WidgetUtil.setJsProperty(element, "ready", NativeFunction.create(""));

    Binder.bind(node, element);

    JsonArray path = Json.createArray();
    path.set(0, 0);

    addVirtualChild(node, childNode, NodeProperties.TEMPLATE_IN_TEMPLATE,
            path);

    Element shadowRoot = Browser.getDocument().createElement("div");

    List<Integer> expectedAfterBindingFeatures = Arrays.asList(
            NodeFeatures.POLYMER_SERVER_EVENT_HANDLERS,
            NodeFeatures.ELEMENT_CHILDREN);

    Reactive.flush();

    expectedAfterBindingFeatures.forEach(notExpectedFeature -> assertFalse(
            "Child node should not have any features from list "
                    + expectedAfterBindingFeatures
                    + " before binding, but got feature "
                    + notExpectedFeature,
            childNode.hasFeature(notExpectedFeature)));

    WidgetUtil.setJsProperty(element, "root", shadowRoot);
    Element addressedElement = createAndAppendElementToShadowRoot(
            shadowRoot, childId, element.getTagName());

    // add flush listener which register the property to revert its initial
    // value back if it has been changed during binding "from the client
    // side" and do update the property emulating client side update
    // The property value should be reverted back in the end
    Reactive.addFlushListener(() -> {
        tree.getRegistry().getInitialPropertiesHandler()
                .handlePropertyUpdate(fooProperty);
        fooProperty.setValue("baz");
    });

    PolymerUtils.fireReadyEvent(element);

    // the property value should be the same as initially
    assertEquals("bar", fooProperty.getValue());

    expectedAfterBindingFeatures.forEach(expectedFeature -> assertTrue(
            "Child node should have all features from list "
                    + expectedAfterBindingFeatures
                    + " before binding, but missing feature "
                    + expectedFeature,
            childNode.hasFeature(expectedFeature)));

    // nothing has changed: no new child
    assertEquals("No new child should be added to the element after attach",
            0, element.getChildElementCount());
    assertEquals(
            "No new child should be added to the shadow root after attach",
            1, shadowRoot.getChildElementCount());

    Element childElement = shadowRoot.getFirstElementChild();

    assertSame(
            "Existing element should be the same as element in the StateNode object",
            addressedElement, childElement);
}