Java Code Examples for elemental.json.JsonObject#hasKey()
The following examples show how to use
elemental.json.JsonObject#hasKey() .
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: UidlRequestHandler.java From flow with Apache License 2.0 | 6 votes |
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 2
Source File: DeploymentConfigurationFactory.java From flow with Apache License 2.0 | 6 votes |
private static void setDevModePropertiesUsingTokenData( Properties initParameters, JsonObject buildInfo) { // read dev mode properties from the token and set init parameter only // if it's not yet set if (initParameters .getProperty(InitParameters.SERVLET_PARAMETER_ENABLE_PNPM) == null && buildInfo.hasKey(InitParameters.SERVLET_PARAMETER_ENABLE_PNPM)) { initParameters.setProperty(InitParameters.SERVLET_PARAMETER_ENABLE_PNPM, String.valueOf(buildInfo.getBoolean( InitParameters.SERVLET_PARAMETER_ENABLE_PNPM))); } if (initParameters .getProperty(InitParameters.REQUIRE_HOME_NODE_EXECUTABLE) == null && buildInfo.hasKey(InitParameters.REQUIRE_HOME_NODE_EXECUTABLE)) { initParameters.setProperty(InitParameters.REQUIRE_HOME_NODE_EXECUTABLE, String.valueOf(buildInfo.getBoolean( InitParameters.REQUIRE_HOME_NODE_EXECUTABLE))); } }
Example 3
Source File: FrontendUtils.java From flow with Apache License 2.0 | 6 votes |
/** * 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 4
Source File: VersionsJsonFilter.java From flow with Apache License 2.0 | 6 votes |
/** * 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 5
Source File: NavigationRpcHandler.java From flow with Apache License 2.0 | 6 votes |
@Override public Optional<Runnable> handle(UI ui, JsonObject invocationJson) { History history = ui.getPage().getHistory(); HistoryStateChangeHandler historyStateChangeHandler = history .getHistoryStateChangeHandler(); if (historyStateChangeHandler != null) { JsonValue state = invocationJson .get(JsonConstants.RPC_NAVIGATION_STATE); String location = invocationJson .getString(JsonConstants.RPC_NAVIGATION_LOCATION); boolean triggeredByLink = invocationJson .hasKey(JsonConstants.RPC_NAVIGATION_ROUTERLINK); NavigationTrigger trigger = triggeredByLink ? NavigationTrigger.ROUTER_LINK : NavigationTrigger.HISTORY; HistoryStateChangeEvent event = new HistoryStateChangeEvent(history, state, new Location(location), trigger); historyStateChangeHandler.onHistoryStateChange(event); } return Optional.empty(); }
Example 6
Source File: MessageHandler.java From flow with Apache License 2.0 | 5 votes |
private void handleDependencies(JsonObject inputJson) { Console.log("Handling dependencies"); JsMap<LoadMode, JsonArray> dependencies = JsCollections.map(); for (LoadMode loadMode : LoadMode.values()) { if (inputJson.hasKey(loadMode.name())) { dependencies.set(loadMode, inputJson.getArray(loadMode.name())); } } if (!dependencies.isEmpty()) { registry.getDependencyLoader().loadDependencies(dependencies); } }
Example 7
Source File: ScrollPositionHandler.java From flow with Apache License 2.0 | 5 votes |
/** * Store scroll positions and restore scroll positions depending on the * given pop state event. * <p> * This method behaves differently if there has been a * {@link #beforeClientNavigation(String)} before this, and if the pop state * event is caused by a fragment change that doesn't require a server side * round-trip. * * @param event * the pop state event * @param triggersServerSideRoundtrip * <code>true</code> if the pop state event triggers a server * side request, <code>false</code> if not */ public void onPopStateEvent(PopStateEvent event, boolean triggersServerSideRoundtrip) { if (ignoreScrollRestorationOnNextPopStateEvent) { Browser.getWindow().getHistory().replaceState( createStateObjectWithHistoryIndexAndToken(), "", Browser.getDocument().getLocation().getHref()); ignoreScrollRestorationOnNextPopStateEvent = false; return; } captureCurrentScrollPositions(); JsonObject state = (JsonObject) event.getState(); if (state == null || !state.hasKey(HISTORY_INDEX) || !state.hasKey(HISTORY_TOKEN)) { // state doesn't contain history index info, just log & reset Console.warn(MISSING_STATE_VARIABLES_MESSAGE); resetScrollPositionTracking(); return; } double token = state.getNumber(HISTORY_TOKEN); if (!Objects.equals(token, historyResetToken)) { // current scroll positions are not for this history entry // try to restore arrays or reset readAndRestoreScrollPositionsFromHistoryAndSessionStorage( triggersServerSideRoundtrip); return; } currentHistoryIndex = (int) state.getNumber(HISTORY_INDEX); restoreScrollPosition(triggersServerSideRoundtrip); }
Example 8
Source File: TaskUpdatePackages.java From flow with Apache License 2.0 | 5 votes |
/** * Generate hash for package dependencies. This will consider both * 'dependencies' and 'devDependencies' of the packageJson format * JsonObject. * <p> * Dependencies will be sorted by key so that different runs for same * dependencies in different order will not trigger npm install. * * @param packageJson * JsonObject built in the same format as package.json * @return has for dependencies and devDependencies */ static String generatePackageJsonHash(JsonObject packageJson) { StringBuilder hashContent = new StringBuilder(); if (packageJson.hasKey(DEPENDENCIES)) { JsonObject dependencies = packageJson.getObject(DEPENDENCIES); hashContent.append("\"dependencies\": {"); String sortedDependencies = Arrays.stream(dependencies.keys()) .sorted(String::compareToIgnoreCase) .map(key -> String.format("\"%s\": \"%s\"", key, dependencies.getString(key))) .collect(Collectors.joining(",\n ")); hashContent.append(sortedDependencies); hashContent.append("}"); } if (packageJson.hasKey(DEV_DEPENDENCIES)) { if (hashContent.length() > 0) { hashContent.append(",\n"); } JsonObject devDependencies = packageJson .getObject(DEV_DEPENDENCIES); hashContent.append("\"devDependencies\": {"); String sortedDevDependencies = Arrays.stream(devDependencies.keys()) .sorted(String::compareToIgnoreCase) .map(key -> String.format("\"%s\": \"%s\"", key, devDependencies.getString(key))) .collect(Collectors.joining(",\n ")); hashContent.append(sortedDevDependencies); hashContent.append("}"); } return getHash(hashContent.toString()); }
Example 9
Source File: TaskUpdatePackages.java From flow with Apache License 2.0 | 5 votes |
private String getShrinkWrapVersion(JsonObject packageJson) { if (packageJson == null) { return null; } if (packageJson.hasKey(DEPENDENCIES)) { JsonObject dependencies = packageJson.getObject(DEPENDENCIES); if (dependencies.hasKey(SHRINK_WRAP)) { JsonValue value = dependencies.get(SHRINK_WRAP); return value.asString(); } } return null; }
Example 10
Source File: TaskUpdatePackages.java From flow with Apache License 2.0 | 5 votes |
private JsonObject getPackageLockDependencies() throws IOException { File packageLock = getPackageLockFile(); if (!packageLock.exists()) { return null; } JsonObject packageLockJson = getJsonFileContent(packageLock); if (packageLockJson == null) { return null; } if (!packageLockJson.hasKey(DEPENDENCIES)) { return null; } JsonObject dependencies = packageLockJson.getObject(DEPENDENCIES); return dependencies; }
Example 11
Source File: ScrollPositionHandler.java From flow with Apache License 2.0 | 5 votes |
private void readAndRestoreScrollPositionsFromHistoryAndSessionStorage( boolean delayAfterResponse) { // restore history index & token from state if applicable JsonObject state = (JsonObject) Browser.getWindow().getHistory() .getState(); if (state != null && state.hasKey(HISTORY_INDEX) && state.hasKey(HISTORY_TOKEN)) { currentHistoryIndex = (int) state.getNumber(HISTORY_INDEX); historyResetToken = state.getNumber(HISTORY_TOKEN); String jsonString = null; try { jsonString = Browser.getWindow().getSessionStorage() .getItem(createSessionStorageKey(historyResetToken)); } catch (JavaScriptException e) { Console.error( "Failed to get session storage: " + e.getMessage()); } if (jsonString != null) { JsonObject jsonObject = Json.parse(jsonString); xPositions = convertJsonArrayToArray( jsonObject.getArray(X_POSITIONS)); yPositions = convertJsonArrayToArray( jsonObject.getArray(Y_POSITIONS)); // array lengths checked in restoreScrollPosition restoreScrollPosition(delayAfterResponse); } else { Console.warn( "History.state has scroll history index, but no scroll positions found from session storage matching token <" + historyResetToken + ">. User has navigated out of site in an unrecognized way."); resetScrollPositionTracking(); } } else { resetScrollPositionTracking(); } }
Example 12
Source File: LockDevDepVersionsMojo.java From flow with Apache License 2.0 | 5 votes |
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 13
Source File: VersionsJsonConverter.java From flow with Apache License 2.0 | 5 votes |
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 14
Source File: NodeUpdater.java From flow with Apache License 2.0 | 5 votes |
private int handleExistingVaadinDep(JsonObject json, String pkg, String version, JsonObject vaadinDeps) { boolean added = false; if (json.hasKey(pkg)) { FrontendVersion packageVersion = toVersion(json, pkg); FrontendVersion newVersion = new FrontendVersion(version); FrontendVersion vaadinVersion = toVersion(vaadinDeps, pkg); // Vaadin and package.json versions are the same, but dependency // updates (can be up or down) if (vaadinVersion.isEqualTo(packageVersion) && !vaadinVersion.isEqualTo(newVersion)) { json.put(pkg, version); added = true; // if vaadin and package not the same, but new version is newer // update package version. } else if (newVersion.isNewerThan(packageVersion)) { json.put(pkg, version); added = true; } } else { json.put(pkg, version); added = true; } // always update vaadin version to the latest set version vaadinDeps.put(pkg, version); if (added) { log().debug("Added \"{}\": \"{}\" line.", pkg, version); } return added ? 1 : 0; }
Example 15
Source File: NodeUpdater.java From flow with Apache License 2.0 | 5 votes |
int addDependency(JsonObject json, String key, String pkg, String version) { Objects.requireNonNull(json, "Json object need to be given"); Objects.requireNonNull(key, "Json sub object needs to be give."); Objects.requireNonNull(pkg, "dependency package needs to be defined"); JsonObject vaadinDeps = json.getObject(VAADIN_DEP_KEY); if (!json.hasKey(key)) { json.put(key, Json.createObject()); } json = json.get(key); vaadinDeps = vaadinDeps.getObject(key); if (vaadinDeps.hasKey(pkg)) { if (version == null) { version = vaadinDeps.getString(pkg); } return handleExistingVaadinDep(json, pkg, version, vaadinDeps); } else { vaadinDeps.put(pkg, version); if (!json.hasKey(pkg) || new FrontendVersion(version) .isNewerThan(toVersion(json, pkg))) { json.put(pkg, version); log().debug("Added \"{}\": \"{}\" line.", pkg, version); return 1; } } return 0; }
Example 16
Source File: BootstrapHandler.java From flow with Apache License 2.0 | 5 votes |
private Element createDependencyElement(BootstrapUriResolver resolver, LoadMode loadMode, JsonObject dependency, Dependency.Type type) { boolean inlineElement = loadMode == LoadMode.INLINE; String url = dependency.hasKey(Dependency.KEY_URL) ? resolver.resolveVaadinUri( dependency.getString(Dependency.KEY_URL)) : null; final Element dependencyElement; switch (type) { case STYLESHEET: dependencyElement = createStylesheetElement(url); break; case JAVASCRIPT: dependencyElement = createJavaScriptElement(url, !inlineElement); break; case JS_MODULE: dependencyElement = createJavaScriptElement(url, false, "module"); break; default: throw new IllegalStateException( "Unsupported dependency type: " + type); } if (inlineElement) { dependencyElement.appendChild(new DataNode( dependency.getString(Dependency.KEY_CONTENTS))); } return dependencyElement; }
Example 17
Source File: TaskUpdatePackages.java From flow with Apache License 2.0 | 4 votes |
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 18
Source File: DeploymentConfigurationFactory.java From flow with Apache License 2.0 | 4 votes |
private static void setInitParametersUsingTokenData( Properties initParameters, JsonObject buildInfo) { if (buildInfo.hasKey(SERVLET_PARAMETER_PRODUCTION_MODE)) { initParameters.setProperty(SERVLET_PARAMETER_PRODUCTION_MODE, String.valueOf(buildInfo .getBoolean(SERVLET_PARAMETER_PRODUCTION_MODE))); } if (buildInfo.hasKey(EXTERNAL_STATS_FILE_TOKEN) || buildInfo.hasKey(EXTERNAL_STATS_URL_TOKEN)) { // If external stats file is flagged then // dev server should be false - only variable that can // be configured, in addition to stats variables, is // production mode initParameters.setProperty(SERVLET_PARAMETER_ENABLE_DEV_SERVER, Boolean.toString(false)); initParameters.setProperty(EXTERNAL_STATS_FILE, Boolean.toString(true)); if (buildInfo.hasKey(EXTERNAL_STATS_URL_TOKEN)) { initParameters.setProperty(EXTERNAL_STATS_URL, buildInfo.getString(EXTERNAL_STATS_URL_TOKEN)); } // NO OTHER CONFIGURATION: return; } if (buildInfo.hasKey(SERVLET_PARAMETER_USE_V14_BOOTSTRAP)) { initParameters.setProperty(SERVLET_PARAMETER_USE_V14_BOOTSTRAP, String.valueOf(buildInfo .getBoolean(SERVLET_PARAMETER_USE_V14_BOOTSTRAP))); // Need to be sure that we remove the system property, // because it has priority in the configuration getter System.clearProperty( VAADIN_PREFIX + SERVLET_PARAMETER_USE_V14_BOOTSTRAP); } if (buildInfo.hasKey(SERVLET_PARAMETER_INITIAL_UIDL)) { initParameters.setProperty(SERVLET_PARAMETER_INITIAL_UIDL, String.valueOf(buildInfo .getBoolean(SERVLET_PARAMETER_INITIAL_UIDL))); // Need to be sure that we remove the system property, // because it has priority in the configuration getter System.clearProperty( VAADIN_PREFIX + SERVLET_PARAMETER_INITIAL_UIDL); } if (buildInfo.hasKey(NPM_TOKEN)) { initParameters.setProperty(PROJECT_BASEDIR, buildInfo.getString(NPM_TOKEN)); verifyFolderExists(initParameters, buildInfo.getString(NPM_TOKEN)); } if (buildInfo.hasKey(FRONTEND_TOKEN)) { initParameters.setProperty(FrontendUtils.PARAM_FRONTEND_DIR, buildInfo.getString(FRONTEND_TOKEN)); // Only verify frontend folder if it's not a subfolder of the // npm folder. if (!buildInfo.hasKey(NPM_TOKEN) || !buildInfo.getString(FRONTEND_TOKEN) .startsWith(buildInfo.getString(NPM_TOKEN))) { verifyFolderExists(initParameters, buildInfo.getString(FRONTEND_TOKEN)); } } // These should be internal only so if there is a System // property override then the user probably knows what // they are doing. if (buildInfo.hasKey(SERVLET_PARAMETER_ENABLE_DEV_SERVER)) { initParameters.setProperty(SERVLET_PARAMETER_ENABLE_DEV_SERVER, String.valueOf(buildInfo .getBoolean(SERVLET_PARAMETER_ENABLE_DEV_SERVER))); } if (buildInfo.hasKey(SERVLET_PARAMETER_REUSE_DEV_SERVER)) { initParameters.setProperty(SERVLET_PARAMETER_REUSE_DEV_SERVER, String.valueOf(buildInfo .getBoolean(SERVLET_PARAMETER_REUSE_DEV_SERVER))); } if (buildInfo.hasKey(CONNECT_JAVA_SOURCE_FOLDER_TOKEN)) { initParameters.setProperty(CONNECT_JAVA_SOURCE_FOLDER_TOKEN, buildInfo.getString(CONNECT_JAVA_SOURCE_FOLDER_TOKEN)); } if (buildInfo.hasKey(CONNECT_OPEN_API_FILE_TOKEN)) { initParameters.setProperty(CONNECT_OPEN_API_FILE_TOKEN, buildInfo.getString(CONNECT_OPEN_API_FILE_TOKEN)); } if (buildInfo.hasKey(CONNECT_APPLICATION_PROPERTIES_TOKEN)) { initParameters.setProperty(CONNECT_APPLICATION_PROPERTIES_TOKEN, buildInfo.getString(CONNECT_APPLICATION_PROPERTIES_TOKEN)); } if (buildInfo.hasKey(CONNECT_GENERATED_TS_DIR_TOKEN)) { initParameters.setProperty(CONNECT_GENERATED_TS_DIR_TOKEN, buildInfo.getString(CONNECT_GENERATED_TS_DIR_TOKEN)); } setDevModePropertiesUsingTokenData(initParameters, buildInfo); }
Example 19
Source File: CubaSideMenuWidget.java From cuba with Apache License 2.0 | 4 votes |
protected void addItems(JsonArray items, HasWidgets container) { for (int i = 0; i < items.length(); i++) { JsonObject itemJson = items.getObject(i); Icon icon = null; String iconId = itemJson.getString("icon"); if (menuItemIconSupplier != null && iconId != null) { icon = menuItemIconSupplier.apply(iconId); } boolean captionAsHtml = false; if (itemJson.hasKey("captionAsHtml")) { captionAsHtml = itemJson.getBoolean("captionAsHtml"); } MenuItemWidget menuItemWidget = new MenuItemWidget(this, itemJson.getString("id"), icon, itemJson.getString("styleName"), itemJson.getString("caption"), captionAsHtml); menuItemWidget.setDescription(itemJson.getString("description")); menuItemWidget.setCubaId(itemJson.getString("cubaId")); menuItemWidget.setBadgeText(itemJson.getString("badgeText")); container.add(menuItemWidget); JsonArray childrenItemsJson = itemJson.getArray("children"); if (childrenItemsJson != null) { MenuContainerWidget menuContainerWidget = new MenuContainerWidget(this, menuItemWidget); addItems(childrenItemsJson, menuContainerWidget); container.add(menuContainerWidget); menuItemWidget.setSubMenu(menuContainerWidget); if (itemJson.hasKey("expanded") && itemJson.getBoolean("expanded")) { menuContainerWidget.setExpanded(true); } } } }
Example 20
Source File: TaskUpdatePackages.java From flow with Apache License 2.0 | 3 votes |
/** * Compares vaadin-shrinkwrap dependency version from the * {@code dependencies} object with the current vaadin-shrinkwrap version * (retrieved from various sources like package.json, package-lock.json). * Removes package-lock.json file and node_modules, * target/frontend/node_modules folders in case the versions are different. * * @param dependencies * dependencies object with the vaadin-shrinkwrap version * @throws IOException */ private boolean ensureReleaseVersion(JsonObject dependencies) throws IOException { String shrinkWrapVersion = null; if (dependencies.hasKey(SHRINK_WRAP)) { shrinkWrapVersion = dependencies.getString(SHRINK_WRAP); } return Objects.equals(shrinkWrapVersion, getCurrentShrinkWrapVersion()); }