Java Code Examples for elemental.json.JsonObject#keys()

The following examples show how to use elemental.json.JsonObject#keys() . 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: VersionsJsonFilter.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Collect all dependencies that the user has changed that do not match the
 * flow managed dependency versions.
 *
 * @param packageJson
 *            package.json Json object
 * @return collection of user managed dependencies
 */
private JsonObject collectUserManagedDependencies(JsonObject packageJson) {
    JsonObject json = Json.createObject();
    JsonObject vaadinDep;
    if (packageJson.hasKey(VAADIN_DEP_KEY) && packageJson
            .getObject(VAADIN_DEP_KEY).hasKey(dependenciesKey)) {
        vaadinDep = packageJson.getObject(VAADIN_DEP_KEY)
                .getObject(dependenciesKey);
    } else {
        vaadinDep = Json.createObject();
    }

    if (packageJson.hasKey(dependenciesKey)) {
        JsonObject dependencies = packageJson.getObject(dependenciesKey);

        for (String key : dependencies.keys()) {
            if (isUserChanged(key, vaadinDep, dependencies)) {
                json.put(key, dependencies.getString(key));
            }
        }
    }

    return json;
}
 
Example 2
Source File: NodeMap.java    From flow with Apache License 2.0 6 votes vote down vote up
@Override
public JsonValue getDebugJson() {
    JsonObject json = WidgetUtil.createJsonObject();

    properties.forEach((p, n) -> {
        if (p.hasValue()) {
            json.put(n, getAsDebugJson(p.getValue()));
        }
    });

    if (json.keys().length == 0) {
        return null;
    }

    return json;
}
 
Example 3
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 4
Source File: VersionsJsonConverter.java    From flow with Apache License 2.0 5 votes vote down vote up
private void collectDependencies(JsonObject obj) {
    for (String key : obj.keys()) {
        JsonValue value = obj.get(key);
        if (!(value instanceof JsonObject)) {
            continue;
        }
        JsonObject json = (JsonObject) value;
        if (json.hasKey(NPM_NAME)) {
            addDependency(json);
        } else {
            collectDependencies(json);
        }
    }
}
 
Example 5
Source File: VersionsJsonFilter.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Collect framework managed versions to enforce that the user hasn't
 * changed.
 *
 * @return filtered versions json
 */
JsonObject getFilteredVersions(JsonObject versions) {
    JsonObject json = Json.createObject();
    for (String key : versions.keys()) {
        if (!userManagedDependencies.hasKey(key)) {
            json.put(key, versions.getString(key));
        } else {
            json.put(key, userManagedDependencies.getString(key));
        }
    }
    return json;
}
 
Example 6
Source File: TaskRunNpmInstall.java    From flow with Apache License 2.0 5 votes vote down vote up
private JsonObject getVersions(InputStream platformVersions)
        throws IOException {
    JsonObject versionsJson = null;
    if (platformVersions != null) {
        VersionsJsonConverter convert = new VersionsJsonConverter(
                Json.parse(IOUtils.toString(platformVersions,
                        StandardCharsets.UTF_8)));
        versionsJson = convert.getConvertedJson();
        versionsJson = new VersionsJsonFilter(
                packageUpdater.getPackageJson(), NodeUpdater.DEPENDENCIES)
                        .getFilteredVersions(versionsJson);
    }

    String genDevDependenciesPath = getDevDependenciesFilePath();
    if (genDevDependenciesPath == null) {
        packageUpdater.log().error(
                "Couldn't find dev dependencies file path from proeprties file. "
                        + "Dev dependencies won't be locked");
        return versionsJson;
    }
    JsonObject devDeps = readGeneratedDevDependencies(
            genDevDependenciesPath);
    if (devDeps == null) {
        return versionsJson;
    }
    devDeps = new VersionsJsonFilter(packageUpdater.getPackageJson(),
            NodeUpdater.DEV_DEPENDENCIES).getFilteredVersions(devDeps);
    if (versionsJson == null) {
        return devDeps;
    }
    for (String key : versionsJson.keys()) {
        devDeps.put(key, versionsJson.getString(key));
    }
    return devDeps;
}
 
Example 7
Source File: JavaScriptBootstrapHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
private JsonValue getErrors() {
    JsonObject errors = Json.createObject();
    DevModeHandler devMode = DevModeHandler.getDevModeHandler();
    if (devMode != null) {
        String errorMsg = devMode.getFailedOutput();
        if (errorMsg != null) {
            errors.put("webpack-dev-server", errorMsg);
        }
    }
    return errors.keys().length > 0 ? errors : Json.createNull();
}
 
Example 8
Source File: DomEventTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private <T extends ComponentEvent<Component>> JsonObject getEventSettings(
        Class<T> eventType) {
    Component component = new Component(new Element("element")) {
    };
    component.addListener(eventType, e -> {
    });

    ElementListenerMap elementListenerMap = component.getElement().getNode()
            .getFeature(ElementListenerMap.class);

    List<NodeChange> changes = new ArrayList<>();
    elementListenerMap.collectChanges(changes::add);

    Assert.assertEquals(1, changes.size());
    MapPutChange change = (MapPutChange) changes.get(0);
    Assert.assertEquals("event", change.getKey());

    ConstantPoolKey value = (ConstantPoolKey) change.getValue();
    JsonObject constantPoolUpdate = Json.createObject();
    value.export(constantPoolUpdate);

    String[] keys = constantPoolUpdate.keys();
    Assert.assertEquals(1, keys.length);
    JsonObject eventSettings = constantPoolUpdate.getObject(keys[0]);

    return eventSettings;
}
 
Example 9
Source File: BeanDataGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void generateData(T item, JsonObject data) {
    JsonValue value = JsonSerializer.toJson(item);
    if (value instanceof JsonObject) {
        JsonObject object = (JsonObject) value;
        for (String key : object.keys()) {
            data.put(key, (JsonValue) object.get(key));
        }
    } else {
        data.put("value", value);
    }
}
 
Example 10
Source File: LockDevDepVersionsMojo.java    From flow with Apache License 2.0 5 votes vote down vote up
private void readVersionsFromPackageJson(JsonObject versions) {
    File nodeModules = new File(npmFolder, NODE_MODULES);
    for (String key : versions.keys()) {
        File module = new File(nodeModules, key);
        File pkgJson = new File(module, Constants.PACKAGE_JSON);
        if (pkgJson.exists()) {
            setPackageVersion(versions, key, pkgJson);
        } else {
            getLog().warn("Couldn't find " + Constants.PACKAGE_JSON
                    + " for '" + key + "' module");
        }
    }
}
 
Example 11
Source File: LockDevDepVersionsMojo.java    From flow with Apache License 2.0 5 votes vote down vote up
private void collectDeps(JsonObject target, JsonObject dep) {
    if (!dep.hasKey(DEPENDENCIES)) {
        return;
    }
    JsonObject deps = dep.get(DEPENDENCIES);
    for (String key : deps.keys()) {
        JsonValue value = deps.get(key);
        if (value instanceof JsonObject) {
            addDependency(target, key, (JsonObject) value);
            collectDeps(target, (JsonObject) value);
        }
    }
}
 
Example 12
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 13
Source File: TaskUpdatePackages.java    From flow with Apache License 2.0 4 votes vote down vote up
private boolean updatePackageJsonDependencies(JsonObject packageJson,
        Map<String, String> deps) throws IOException {
    int added = 0;

    JsonObject dependencies = packageJson.getObject(DEPENDENCIES);
    // Update the dependency for the folder with resources
    updateFlowFrontendDependencies(dependencies);

    // Add application dependencies
    for (Entry<String, String> dep : deps.entrySet()) {
        added += addDependency(packageJson, DEPENDENCIES, dep.getKey(),
                dep.getValue());
    }

    if (added > 0) {
        log().info("Added {} dependencies to main package.json", added);
    }

    // Remove obsolete dependencies
    List<String> dependencyCollection = Stream
            .concat(deps.entrySet().stream(),
                    getDefaultDependencies().entrySet().stream())
            .map(Entry::getKey).collect(Collectors.toList());

    JsonObject vaadinDependencies = packageJson.getObject(VAADIN_DEP_KEY)
            .getObject(DEPENDENCIES);
    boolean doCleanUp = forceCleanUp;
    int removed = removeLegacyProperties(packageJson);
    if (dependencies != null) {
        for (String key : dependencies.keys()) {
            if (!dependencyCollection.contains(key)
                    && vaadinDependencies.hasKey(key)) {
                dependencies.remove(key);
                log().debug("Removed \"{}\".", key);
                removed++;
            }
        }
        doCleanUp = doCleanUp
                || !enablePnpm && !ensureReleaseVersion(dependencies);
    }

    if (removed > 0) {
        log().info("Removed {} dependencies", removed);
    }

    if (doCleanUp) {
        cleanUp();
    }

    String oldHash = packageJson.getObject(VAADIN_DEP_KEY)
            .getString(HASH_KEY);
    String newHash = generatePackageJsonHash(packageJson);
    // update packageJson hash value, if no changes it will not be written
    packageJson.getObject(VAADIN_DEP_KEY).put(HASH_KEY, newHash);

    return added > 0 || removed > 0 || !oldHash.equals(newHash);
}
 
Example 14
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;
}