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

The following examples show how to use elemental.json.Json#parse() . 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: JavaScriptBootstrapHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void should_respondPushScript_when_annotatedInAppShell()
        throws Exception {
    AppShellRegistry registry = new AppShellRegistry();
    registry.setShell(PushAppShell.class);
    mocks.setAppShellRegistry(registry);

    VaadinRequest request = mocks.createRequest(mocks, "/foo/?v-r=init&foo");
    jsInitHandler.handleRequest(session, request, response);

    Assert.assertEquals(200, response.getErrorCode());
    Assert.assertEquals("application/json", response.getContentType());
    JsonObject json = Json.parse(response.getPayload());

    // Using regex, because version depends on the build
    Assert.assertTrue(json.getString("pushScript").matches(
            "^\\./VAADIN/static/push/vaadinPush\\.js\\?v=[\\w\\.\\-]+$"));
}
 
Example 2
Source File: JavaScriptBootstrapHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void should_respondPushScript_when_enabledInDeploymentConfiguration()
        throws Exception {
    mocks.getDeploymentConfiguration().setPushMode(PushMode.AUTOMATIC);

    VaadinRequest request = mocks.createRequest(mocks,
            "/foo/?v-r=init&foo");
    jsInitHandler.handleRequest(session, request, response);

    Assert.assertEquals(200, response.getErrorCode());
    Assert.assertEquals("application/json", response.getContentType());
    JsonObject json = Json.parse(response.getPayload());

    // Using regex, because version depends on the build
    Assert.assertTrue(json.getString("pushScript").matches(
            "^\\./VAADIN/static/push/vaadinPush\\.js\\?v=[\\w\\.\\-]+$"));
}
 
Example 3
Source File: TaskRunNpmInstall.java    From flow with Apache License 2.0 6 votes vote down vote up
private boolean isVaadinHashUpdated() {
    final File localHashFile = getLocalHashFile();
    if (localHashFile.exists()) {
        try {
            String fileContent = FileUtils.readFileToString(localHashFile,
                    UTF_8.name());
            JsonObject content = Json.parse(fileContent);
            if (content.hasKey(HASH_KEY)) {
                final JsonObject packageJson = packageUpdater
                        .getPackageJson();
                return !content.getString(HASH_KEY).equals(packageJson
                        .getObject(VAADIN_DEP_KEY).getString(HASH_KEY));
            }
        } catch (IOException e) {
            packageUpdater.log()
                    .warn("Failed to load hashes forcing npm execution", e);
        }
    }
    return true;
}
 
Example 4
Source File: VersionsJsonFilterTest.java    From flow with Apache License 2.0 6 votes vote down vote up
private void assertMissingVaadinDependencies_allDependenciesSholdBeUserHandled(
        String depKey) throws IOException {
    String versions = IOUtils
            .toString(
                    getClass().getClassLoader()
                            .getResourceAsStream("versions/versions.json"),
                    StandardCharsets.UTF_8);
    String pkgJson = IOUtils.toString(
            getClass().getClassLoader()
                    .getResourceAsStream("versions/no_vaadin_package.json"),
            StandardCharsets.UTF_8);

    VersionsJsonFilter filter = new VersionsJsonFilter(Json.parse(pkgJson),
            depKey);
    JsonObject filteredJson = filter
            .getFilteredVersions(Json.parse(versions));
    Assert.assertTrue(filteredJson.hasKey("@vaadin/vaadin-progress-bar"));
    Assert.assertTrue(filteredJson.hasKey("@vaadin/vaadin-upload"));
    Assert.assertTrue(filteredJson.hasKey("@polymer/iron-list"));

    Assert.assertEquals("1.1.2",
            filteredJson.getString("@vaadin/vaadin-progress-bar"));
}
 
Example 5
Source File: LockDevDepVersionsMojo.java    From flow with Apache License 2.0 5 votes vote down vote up
private void setPackageVersion(JsonObject versions, String key,
        File pkgJson) {
    try {
        JsonObject pkg = Json.parse(FileUtils.readFileToString(pkgJson,
                StandardCharsets.UTF_8));
        if (pkg.hasKey(VERSION)
                && pkg.get(VERSION).getType().equals(JsonType.STRING)) {
            versions.put(key, pkg.getString(VERSION));
        }
    } catch (IOException exception) {
        getLog().warn("Couldn't read " + Constants.PACKAGE_JSON + " for '"
                + key + "' module", exception);
    }
}
 
Example 6
Source File: DevDepsFileTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void devDepsFilePresent_hasContent() throws IOException {
    InputStream stream = DevDepsFileTest.class
            .getResourceAsStream("/devDependencies.json");
    Assert.assertNotNull(stream);

    JsonObject object = Json
            .parse(IOUtils.toString(stream, StandardCharsets.UTF_8));
    // locked versions has to contain webpack version at least
    Assert.assertTrue("Generated dev deps json doesn't contain webpack",
            object.hasKey("webpack"));
}
 
Example 7
Source File: AbstractNodeUpdatePackagesTest.java    From flow with Apache License 2.0 5 votes vote down vote up
JsonObject getPackageJson(File packageFile) throws IOException {
    JsonObject packageJson = null;
    if (packageFile.exists()) {
        String fileContent = FileUtils.readFileToString(packageFile,
                UTF_8.name());
        packageJson = Json.parse(fileContent);
    }
    return packageJson;
}
 
Example 8
Source File: VersionsJsonFilterTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private void assertFilterPlatformVersions(String depKey)
        throws IOException {
    String versions = IOUtils
            .toString(
                    getClass().getClassLoader()
                            .getResourceAsStream("versions/versions.json"),
                    StandardCharsets.UTF_8);
    String pkgJson = IOUtils
            .toString(
                    getClass().getClassLoader()
                            .getResourceAsStream("versions/package.json"),
                    StandardCharsets.UTF_8);

    VersionsJsonFilter filter = new VersionsJsonFilter(Json.parse(pkgJson),
            depKey);
    JsonObject filteredJson = filter
            .getFilteredVersions(Json.parse(versions));
    Assert.assertTrue(filteredJson.hasKey("@vaadin/vaadin-progress-bar"));
    Assert.assertTrue(filteredJson.hasKey("@vaadin/vaadin-upload"));
    Assert.assertTrue(filteredJson.hasKey("@polymer/iron-list"));

    Assert.assertEquals("1.1.2",
            filteredJson.getString("@vaadin/vaadin-progress-bar"));
    Assert.assertEquals("4.2.2",
            filteredJson.getString("@vaadin/vaadin-upload"));
    Assert.assertEquals("2.0.19",
            filteredJson.getString("@polymer/iron-list"));
}
 
Example 9
Source File: TaskRunNpmInstallTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void runNpmInstall_externalUpdateOfPackages_npmInstallIsRerun()
        throws ExecutionFailedException, IOException {
    nodeUpdater.modified = true;

    // manually fake TaskUpdatePackages.
    JsonObject packageJson = getNodeUpdater().getPackageJson();
    updatePackageHash(packageJson);
    getNodeUpdater().writePackageFile(packageJson);

    task.execute();

    final File localHashFile = new File(getNodeUpdater().nodeModulesFolder,
            ".vaadin/vaadin.json");
    Assert.assertTrue("Local has file was not created after install.",
            localHashFile.exists());

    String fileContent = FileUtils
            .readFileToString(localHashFile, UTF_8.name());
    JsonObject localHash = Json.parse(fileContent);
    Assert.assertNotEquals("We should have a non empty hash key", "",
            localHash.getString(HASH_KEY));

    // Update package json and hash as if someone had pushed to code repo.
    packageJson = getNodeUpdater().getPackageJson();
    packageJson.getObject(VAADIN_DEP_KEY).getObject(DEPENDENCIES)
            .put("a-avataaar", "^1.2.5");
    String hash = packageJson.getObject(VAADIN_DEP_KEY).getString(HASH_KEY);
    updatePackageHash(packageJson);

    Assert.assertNotEquals("Hash should have been updated", hash,
            packageJson.getObject(VAADIN_DEP_KEY).getString(HASH_KEY));

    getNodeUpdater().writePackageFile(packageJson);
    logger = Mockito.mock(Logger.class);

    task.execute();

    Mockito.verify(logger).info(getRunningMsg());
}
 
Example 10
Source File: BuildFrontendMojoTest.java    From flow with Apache License 2.0 5 votes vote down vote up
static JsonObject getPackageJson(String packageJson) throws IOException {
    if (FileUtils.fileExists(packageJson)) {
        return Json.parse(FileUtils.fileRead(packageJson));

    } else {
        return Json.createObject();
    }
}
 
Example 11
Source File: Pojofy.java    From vertxui with GNU General Public License v3.0 5 votes vote down vote up
public static <O> boolean socketReceive(String url, Event e, ObjectMapper<O> outMapper, Consumer<O> handler) {
	Object me = ((MessageEvent) e).getData();
	String meString = me.toString();
	if (meString.equals("[object ArrayBuffer]")) { // websockets
		meString = socketToString((ArrayBuffer) me);
	}
	if (!meString.startsWith("{\"url\":\"" + url + "\"")) {
		return false;
	}
	JsonObject json = Json.parse(meString);
	handler.accept(out(json.getString("body"), outMapper));
	return true;
}
 
Example 12
Source File: JsonUtils.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the given bean to JSON.
 *
 * @param bean
 *                 the bean to convert, not {@code null}
 * @return a JSON representation of the bean
 */
public static JsonObject beanToJson(Object bean) {
    Objects.requireNonNull(bean, CANNOT_CONVERT_NULL_TO_A_JSON_OBJECT);

    try {
        return Json.parse(objectMapper.writeValueAsString(bean));
    } catch (JsonProcessingException e) {
        throw new RuntimeException("Error converting bean to JSON", e);
    }
}
 
Example 13
Source File: TaskRunNpmInstall.java    From flow with Apache License 2.0 5 votes vote down vote up
private JsonObject readGeneratedDevDependencies(String path)
        throws IOException {
    URL resource = classFinder.getResource(path);
    if (resource == null) {
        packageUpdater.log().warn("Couldn't find  dev dependencies file. "
                + "Dev dependencies won't be locked");
        return null;
    }
    try (InputStream content = resource.openStream()) {
        return Json
                .parse(IOUtils.toString(content, StandardCharsets.UTF_8));
    }
}
 
Example 14
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 15
Source File: NodeUpdater.java    From flow with Apache License 2.0 5 votes vote down vote up
static JsonObject getJsonFileContent(File packageFile) throws IOException {
    JsonObject jsonContent = null;
    if (packageFile.exists()) {
        String fileContent = FileUtils.readFileToString(packageFile,
                UTF_8.name());
        jsonContent = Json.parse(fileContent);
    }
    return jsonContent;
}
 
Example 16
Source File: CubaJavaScriptComponent.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeClientResponse(boolean initial) {
    super.beforeClientResponse(initial);

    if (initial || dirty) {
        if (stateData != null) {
            String json = getStateSerializer().toJson(stateData);
            getState().data = Json.parse(json);
        } else {
            getState().data = null;
        }

        dirty = false;
    }
}
 
Example 17
Source File: AbstractEndpointGeneratorBaseTest.java    From flow with Apache License 2.0 4 votes vote down vote up
protected JsonObject readJsonFile(Path file) {
    return Json.parse(readFile(file));
}
 
Example 18
Source File: VersionsJsonConverterTest.java    From flow with Apache License 2.0 4 votes vote down vote up
@Test
public void convertPlatformVersions() throws IOException {
    // @formatter:off
    String json = "{\"core\": {"+
                        "\"flow\": { "
                        + " \"javaVersion\": \"3.0.0.alpha17\""
                        + "}, "
                    + " \"vaadin-progress-bar\": { "
                        + " \"npmName\": \"@vaadin/vaadin-progress-bar\", "
                        + "\"jsVersion\": \"1.1.2\" "
                      + "},"
                   + "},"  //core
            + "\"vaadin-upload\": { "
                + "\"npmName\": \"@vaadin/vaadin-upload\", "
                + "\"jsVersion\": \"4.2.2\""
              + "},"+
                "\"iron-list\": {\n" +
                "            \"npmName\": \"@polymer/iron-list\",\n" +
                "            \"npmVersion\": \"3.0.2\",\n" +
                "            \"javaVersion\": \"3.0.0.beta1\",\n" +
                "            \"jsVersion\": \"2.0.19\"\n" +
                "        },"
                +"\"platform\": \"foo\""
            + "}";
    // @formatter:on

    VersionsJsonConverter convert = new VersionsJsonConverter(
            Json.parse(json));
    JsonObject convertedJson = convert.getConvertedJson();
    Assert.assertTrue(convertedJson.hasKey("@vaadin/vaadin-progress-bar"));
    Assert.assertTrue(convertedJson.hasKey("@vaadin/vaadin-upload"));
    Assert.assertTrue(convertedJson.hasKey("@polymer/iron-list"));

    Assert.assertFalse(convertedJson.hasKey("flow"));
    Assert.assertFalse(convertedJson.hasKey("core"));
    Assert.assertFalse(convertedJson.hasKey("platform"));

    Assert.assertEquals("1.1.2",
            convertedJson.getString("@vaadin/vaadin-progress-bar"));
    Assert.assertEquals("4.2.2",
            convertedJson.getString("@vaadin/vaadin-upload"));
    Assert.assertEquals("3.0.2",
            convertedJson.getString("@polymer/iron-list"));
}
 
Example 19
Source File: BootstrapHandler.java    From flow with Apache License 2.0 4 votes vote down vote up
private void appendNpmBundle(Element head, VaadinService service,
        BootstrapContext context) throws IOException {
    String content = FrontendUtils.getStatsAssetsByChunkName(service);
    if (content == null) {
        StringBuilder message = new StringBuilder(
                "The stats file from webpack (stats.json) was not found.\n");
        if (service.getDeploymentConfiguration().isProductionMode()) {
            message.append(
                    "The application is running in production mode.");
            message.append(
                    "Verify that build-frontend task has executed successfully and that stats.json is on the classpath.");
            message.append(
                    "Or switch application to development mode.");
        } else if (!service.getDeploymentConfiguration()
                .enableDevServer()) {
            message.append(
                    "Dev server is disabled for the application.");
            message.append(
                    "Verify that build-frontend task has executed successfully and that stats.json is on the classpath.");
        } else {
            message.append(
                    "This typically mean that you have started the application without executing the 'prepare-frontend' Maven target.\n");
            message.append(
                    "If you are using Spring Boot and are launching the Application class directly, ");
            message.append(
                    "you need to run \"mvn install\" once first or launch the application using \"mvn spring-boot:run\"");
        }
        throw new IOException(message.toString());
    }
    JsonObject chunks = Json.parse(content);
    for (String key : getChunkKeys(chunks)) {
        String chunkName;
        if (chunks.get(key).getType().equals(JsonType.ARRAY)) {
            chunkName = getArrayChunkName(chunks, key);
        } else {
            chunkName = chunks.getString(key);
        }
        Element script = createJavaScriptElement(
                "./" + VAADIN_MAPPING + chunkName, false);
        head.appendChild(script.attr("type", "module")
                .attr("data-app-id",
                        context.getUI().getInternals().getAppId())
                // Fixes basic auth in Safari #6560
                .attr("crossorigin", true));
    }
}
 
Example 20
Source File: BundleParser.java    From flow with Apache License 2.0 2 votes vote down vote up
/**
 * Parses the content of the stats file to return a json object.
 *
 * @param fileContents
 *            the content of the stats file
 * @return a JsonObject with the stats
 */
public static JsonObject parseJsonStatistics(String fileContents) {
    return Json.parse(fileContents);
}