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

The following examples show how to use elemental.json.JsonArray#length() . 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: MessageSender.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Sends all pending method invocations (server RPC and legacy variable
 * changes) to the server.
 *
 */
private void doSendInvocationsToServer() {

    ServerRpcQueue serverRpcQueue = registry.getServerRpcQueue();
    if (serverRpcQueue.isEmpty()) {
        return;
    }

    boolean showLoadingIndicator = serverRpcQueue.showLoadingIndicator();
    JsonArray reqJson = serverRpcQueue.toJson();
    serverRpcQueue.clear();

    if (reqJson.length() == 0) {
        // Nothing to send, all invocations were filtered out (for
        // non-existing connectors)
        Console.warn(
                "All RPCs filtered out, not sending anything to the server");
        return;
    }

    JsonObject extraJson = Json.createObject();
    if (showLoadingIndicator) {
        registry.getLoadingIndicator().trigger();
    }
    send(reqJson, extraJson);
}
 
Example 2
Source File: FrontendUtils.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Read fallback chunk data from a json object.
 *
 * @param object
 *            json object to read fallback chunk data
 * @return a fallback chunk data
 */
public static FallbackChunk readFallbackChunk(JsonObject object) {
    if (!object.hasKey(CHUNKS)) {
        return null;
    }
    JsonObject obj = object.getObject(CHUNKS);
    if (!obj.hasKey(FALLBACK)) {
        return null;
    }
    obj = obj.getObject(FALLBACK);
    List<String> fallbackModles = new ArrayList<>();
    JsonArray modules = obj.getArray(JS_MODULES);
    for (int i = 0; i < modules.length(); i++) {
        fallbackModles.add(modules.getString(i));
    }
    List<CssImportData> fallbackCss = new ArrayList<>();
    JsonArray css = obj.getArray(CSS_IMPORTS);
    for (int i = 0; i < css.length(); i++) {
        fallbackCss.add(createCssData(css.getObject(i)));
    }
    return new FallbackChunk(fallbackModles, fallbackCss);
}
 
Example 3
Source File: UidlRequestHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
private String removeHashInChange(JsonArray change) {
    if (change.length() < 3
            || !change.get(2).getType().equals(JsonType.ARRAY)) {
        return null;
    }
    JsonArray value = change.getArray(2);
    if (value.length() < 2
            || !value.get(1).getType().equals(JsonType.OBJECT)) {
        return null;
    }
    JsonObject location = value.getObject(1);
    if (!location.hasKey(LOCATION)) {
        return null;
    }
    String url = location.getString(LOCATION);
    Matcher match = URL_PATTERN.matcher(url);
    if (match.find()) {
        location.put(LOCATION, match.group(1));
    }
    return url;
}
 
Example 4
Source File: UidlRequestHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
private String removeHashInRpc(JsonArray rpc) {
    if (rpc.length() != 4 || !rpc.get(1).getType().equals(JsonType.STRING)
            || !rpc.get(2).getType().equals(JsonType.STRING)
            || !rpc.get(3).getType().equals(JsonType.ARRAY)
            || !"com.vaadin.shared.extension.javascriptmanager.ExecuteJavaScriptRpc"
                    .equals(rpc.getString(1))
            || !"executeJavaScript".equals(rpc.getString(2))) {
        return null;
    }
    JsonArray scripts = rpc.getArray(3);
    for (int j = 0; j < scripts.length(); j++) {
        String exec = scripts.getString(j);
        Matcher match = HASH_PATTERN.matcher(exec);
        if (match.find()) {
            // replace JS with a noop
            scripts.set(j, ";");
            return match.group(1);
        }
    }
    return null;
}
 
Example 5
Source File: PublishedServerEventHandlerRpcHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
private static JsonArray unwrapVarArgs(JsonArray argsFromClient,
        Method method) {
    int paramCount = method.getParameterCount();
    if (argsFromClient.length() == paramCount) {
        if (argsFromClient.get(paramCount - 1).getType()
                .equals(JsonType.ARRAY)) {
            return argsFromClient;
        }
    }
    JsonArray result = Json.createArray();
    JsonArray rest = Json.createArray();
    int newIndex = 0;
    for (int i = 0; i < argsFromClient.length(); i++) {
        JsonValue value = argsFromClient.get(i);
        if (i < paramCount - 1) {
            result.set(i, value);
        } else {
            rest.set(newIndex, value);
            newIndex++;
        }
    }
    result.set(paramCount - 1, rest);
    return result;
}
 
Example 6
Source File: BootstrapHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
private List<Element> inlineDependenciesInHead(Element head,
        BootstrapUriResolver uriResolver, LoadMode loadMode,
        JsonArray dependencies) {
    List<Element> dependenciesToInlineInBody = new ArrayList<>();

    for (int i = 0; i < dependencies.length(); i++) {
        JsonObject dependencyJson = dependencies.getObject(i);
        Dependency.Type dependencyType = Dependency.Type
                .valueOf(dependencyJson.getString(Dependency.KEY_TYPE));
        Element dependencyElement = createDependencyElement(uriResolver,
                loadMode, dependencyJson, dependencyType);

        head.appendChild(dependencyElement);
    }
    return dependenciesToInlineInBody;
}
 
Example 7
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 8
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 9
Source File: PolymerUtils.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the custom element using {@code path} of indices starting from the
 * {@code root}.
 *
 * @param root
 *            the root element to start from
 * @param path
 *            the indices path identifying the custom element.
 * @return the element inside the {@code root} by the path of indices
 */
public static Element getCustomElement(Node root, JsonArray path) {
    Node current = root;
    for (int i = 0; i < path.length(); i++) {
        JsonValue value = path.get(i);
        current = getChildIgnoringStyles(current, (int) value.asNumber());
    }
    if (current instanceof Element) {
        return (Element) current;
    } else if (current == null) {
        Console.warn(
                "There is no element addressed by the path '" + path + "'");
    } else {
        Console.warn("The node addressed by path " + path
                + " is not an Element");
    }
    return null;
}
 
Example 10
Source File: RootImpl.java    From serverside-elements with Apache License 2.0 5 votes vote down vote up
public void handleCallback(JsonArray arguments) {
    JsonArray attributeChanges = arguments.getArray(1);
    for (int i = 0; i < attributeChanges.length(); i++) {
        JsonArray attributeChange = attributeChanges.getArray(i);
        int id = (int) attributeChange.getNumber(0);
        String attribute = attributeChange.getString(1);
        JsonValue value = attributeChange.get(2);

        NodeImpl target = idToNode.get(Integer.valueOf(id));
        if (value.getType() == JsonType.NULL) {
            target.node.removeAttr(attribute);
        } else {
            target.node.attr(attribute, value.asString());
        }
    }

    JsonArray callbacks = arguments.getArray(0);
    for (int i = 0; i < callbacks.length(); i++) {
        JsonArray call = callbacks.getArray(i);

        int elementId = (int) call.getNumber(0);
        int cid = (int) call.getNumber(1);
        JsonArray params = call.getArray(2);

        ElementImpl element = (ElementImpl) idToNode
                .get(Integer.valueOf(elementId));
        if (element == null) {
            System.out.println(cid + " detached?");
            return;
        }

        JavaScriptFunction callback = element.getCallback(cid);
        callback.call(params);
    }
}
 
Example 11
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;
}
 
Example 12
Source File: ExecuteJavaScriptProcessor.java    From flow with Apache License 2.0 5 votes vote down vote up
private void handleInvocation(JsonArray invocation) {
    StateTree tree = registry.getStateTree();

    // Last item is the script, the rest is parameters
    int parameterCount = invocation.length() - 1;

    String[] parameterNamesAndCode = new String[parameterCount + 1];
    JsArray<Object> parameters = JsCollections.array();

    JsMap<Object, StateNode> map = JsCollections.map();
    for (int i = 0; i < parameterCount; i++) {
        JsonValue parameterJson = invocation.get(i);
        Object parameter = ClientJsonCodec.decodeWithTypeInfo(tree,
                parameterJson);
        parameters.push(parameter);
        parameterNamesAndCode[i] = "$" + i;
        StateNode stateNode = ClientJsonCodec.decodeStateNode(tree,
                parameterJson);
        if (stateNode != null) {
            if (isVirtualChildAwaitingInitialization(stateNode)
                    || !isBound(stateNode)) {
                stateNode.addDomNodeSetListener(node -> {
                    Reactive.addPostFlushListener(
                            () -> handleInvocation(invocation));
                    return true;
                });
                return;
            }
            map.set(parameter, stateNode);
        }
    }

    // Set the script source as the last parameter
    String expression = invocation.getString(invocation.length() - 1);
    parameterNamesAndCode[parameterNamesAndCode.length - 1] = expression;

    invoke(parameterNamesAndCode, parameters, map);
}
 
Example 13
Source File: ExecuteJavaScriptProcessor.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Executes invocations received from the server.
 *
 * @param invocations
 *            a JSON containing invocation data
 */
public void execute(JsonArray invocations) {
    for (int i = 0; i < invocations.length(); i++) {
        JsonArray invocation = invocations.getArray(i);
        handleInvocation(invocation);
    }
}
 
Example 14
Source File: CubaSuggestionFieldWidget.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected void showSuggestions(JsonArray suggestions, boolean userOriginated) {
    this.suggestions.clear();

    for (int i = 0; i < suggestions.length(); i++) {
        JsonObject jsonSuggestion = suggestions.getObject(i);
        Suggestion suggestion = new Suggestion(
                jsonSuggestion.getString(SUGGESTION_ID),
                jsonSuggestion.getString(SUGGESTION_CAPTION),
                jsonSuggestion.getString(SUGGESTION_STYLE_NAME)
        );
        this.suggestions.add(suggestion);
    }

    showSuggestions(userOriginated);
}
 
Example 15
Source File: BootstrapHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
private String getArrayChunkName(JsonObject chunks, String key) {
    JsonArray chunkArray = chunks.getArray(key);

    for (int i = 0; i < chunkArray.length(); i++) {
        String chunkName = chunkArray.getString(0);
        if (chunkName.endsWith(".js")) {
            return chunkName;
        }
    }
    return "";
}
 
Example 16
Source File: DependencyLoader.java    From flow with Apache License 2.0 5 votes vote down vote up
private JsMap<String, BiConsumer<String, ResourceLoadListener>> extractLazyDependenciesAndLoadOthers(
        LoadMode loadMode, JsonArray dependencies) {
    JsMap<String, BiConsumer<String, ResourceLoadListener>> lazyDependencies = JsCollections
            .map();
    for (int i = 0; i < dependencies.length(); i++) {
        JsonObject dependencyJson = dependencies.getObject(i);
        Dependency.Type type = Dependency.Type
                .valueOf(dependencyJson.getString(Dependency.KEY_TYPE));
        BiConsumer<String, ResourceLoadListener> resourceLoader = getResourceLoader(
                type, loadMode);

        if (type == Dependency.Type.DYNAMIC_IMPORT) {
            loadDependencyEagerly(
                    dependencyJson.getString(Dependency.KEY_URL),
                    resourceLoader);
        } else {
            switch (loadMode) {
            case EAGER:
                loadDependencyEagerly(getDependencyUrl(dependencyJson),
                        resourceLoader);
                break;
            case LAZY:
                lazyDependencies.set(getDependencyUrl(dependencyJson),
                        resourceLoader);
                break;
            case INLINE:
                loadDependencyEagerly(
                        dependencyJson.getString(Dependency.KEY_CONTENTS),
                        resourceLoader);
                break;
            default:
                throw new IllegalArgumentException(
                        "Unknown load mode = " + loadMode);
            }
        }
    }
    return lazyDependencies;
}
 
Example 17
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 18
Source File: DependencyLoaderTest.java    From flow with Apache License 2.0 4 votes vote down vote up
private JsonArray mergeArrays(JsonArray jsonArray1, JsonArray jsonArray2) {
    for (int i = 0; i < jsonArray2.length(); i++) {
        jsonArray1.set(jsonArray1.length(), jsonArray2.getObject(i));
    }
    return jsonArray1;
}
 
Example 19
Source File: GwtDependencyLoaderTest.java    From flow with Apache License 2.0 4 votes vote down vote up
private JsonArray mergeArrays(JsonArray jsonArray1, JsonArray jsonArray2) {
    for (int i = 0; i < jsonArray2.length(); i++) {
        jsonArray1.set(jsonArray1.length(), jsonArray2.getObject(i));
    }
    return jsonArray1;
}
 
Example 20
Source File: JsonSerializer.java    From flow with Apache License 2.0 3 votes vote down vote up
/**
 * Converts a JsonArray into a collection of Java objects. The Java objects
 * can be Java beans, {@link JsonSerializable} instances, Strings, wrappers
 * of primitive types or enums.
 * 
 * @param type
 *            the type of the elements in the array
 * @param json
 *            the json representation of the objects
 * @param <T>
 *            the resulting objects types
 *
 * @return a modifiable list of converted objects. Returns an empty list if
 *         the input array is <code>null</code>
 */
public static <T> List<T> toObjects(Class<T> type, JsonArray json) {
    if (json == null) {
        return new ArrayList<>(0);
    }
    List<T> list = new ArrayList<>(json.length());
    for (int i = 0; i < json.length(); i++) {
        list.add(JsonSerializer.toObject(type, json.get(i)));
    }
    return list;
}