Java Code Examples for elemental.json.impl.JsonUtil#parse()

The following examples show how to use elemental.json.impl.JsonUtil#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: TaskUpdateImports.java    From flow with Apache License 2.0 6 votes vote down vote up
private void updateBuildFile(AbstractUpdateImports updater) {
    boolean tokenFileExists = tokenFile != null && tokenFile.exists();
    if (!tokenFileExists) {
        log().warn(
                "Token file is not available. Fallback chunk data won't be written.");
    }
    try {
        if (tokenFileExists) {
            String json = FileUtils.readFileToString(tokenFile,
                    StandardCharsets.UTF_8);
            JsonObject buildInfo = json.isEmpty() ? Json.createObject()
                    : JsonUtil.parse(json);
            populateFallbackData(buildInfo, updater);
            FileUtils.write(tokenFile, JsonUtil.stringify(buildInfo, 2),
                    StandardCharsets.UTF_8);
        }

    } catch (IOException e) {
        log().warn("Unable to read token file", e);
    }
    if (tokenFileData != null) {
        populateFallbackData(tokenFileData, updater);
    }
}
 
Example 2
Source File: DeploymentConfigurationFactory.java    From flow with Apache License 2.0 6 votes vote down vote up
private static void readBuildInfo(Properties initParameters) {
    String json = getTokenFileContents(initParameters);

    // Read the json and set the appropriate system properties if not
    // already set.
    if (json != null) {
        JsonObject buildInfo = JsonUtil.parse(json);
        setInitParametersUsingTokenData(initParameters, buildInfo);

        FallbackChunk fallbackChunk = FrontendUtils
                .readFallbackChunk(buildInfo);
        if (fallbackChunk != null) {
            initParameters.put(FALLBACK_CHUNK, fallbackChunk);
        }
    }

    try {
        verifyMode(json != null, hasWebpackConfig(initParameters));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }

}
 
Example 3
Source File: UidlRequestHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void should_modifyUidl_when_MPR_JavaScriptBootstrapUI() throws Exception {
    JavaScriptBootstrapUI ui = mock(JavaScriptBootstrapUI.class);

    UidlRequestHandler handler = spy(new UidlRequestHandler());
    StringWriter writer = new StringWriter();

    JsonObject uidl = generateUidl(true, true);
    doReturn(uidl).when(handler).createUidl(ui, false);

    handler.writeUidl(ui, writer, false);

    String out = writer.toString();
    uidl = JsonUtil.parse(out.substring(9, out.length() - 1));

    String v7Uidl = uidl.getArray("execute").getArray(2).getString(1);
    assertFalse(v7Uidl.contains("http://localhost:9998/#!away"));
    assertTrue(v7Uidl.contains("http://localhost:9998/"));
    assertFalse(v7Uidl.contains("window.location.hash = '!away';"));
}
 
Example 4
Source File: UidlRequestHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void should_changeURL_when_v7LocationProvided() throws Exception {
    JavaScriptBootstrapUI ui = mock(JavaScriptBootstrapUI.class);

    UidlRequestHandler handler = spy(new UidlRequestHandler());
    StringWriter writer = new StringWriter();

    JsonObject uidl = generateUidl(true, true);
    doReturn(uidl).when(handler).createUidl(ui, false);

    handler.writeUidl(ui, writer, false);

    String out = writer.toString();
    uidl = JsonUtil.parse(out.substring(9, out.length() - 1));

    assertEquals(
            "setTimeout(() => history.pushState(null, null, 'http://localhost:9998/#!away'));",
            uidl.getArray("execute").getArray(1).getString(1));
}
 
Example 5
Source File: UidlRequestHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void should_updateHash_when_v7LocationNotProvided() throws Exception {
    JavaScriptBootstrapUI ui = mock(JavaScriptBootstrapUI.class);

    UidlRequestHandler handler = spy(new UidlRequestHandler());
    StringWriter writer = new StringWriter();

    JsonObject uidl = generateUidl(false, true);
    doReturn(uidl).when(handler).createUidl(ui, false);

    handler.writeUidl(ui, writer, false);

    String out = writer.toString();
    uidl = JsonUtil.parse(out.substring(9, out.length() - 1));

    assertEquals(
            "setTimeout(() => history.pushState(null, null, location.pathname + location.search + '#!away'));",
            uidl.getArray("execute").getArray(1).getString(1));
}
 
Example 6
Source File: PrepareFrontendMojoTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void tokenFileShouldExist_noDevModeTokenVisible()
        throws IOException, MojoExecutionException, MojoFailureException {
    mojo.execute();
    Assert.assertTrue("No token file could be found", tokenFile.exists());

    String json = org.apache.commons.io.FileUtils
            .readFileToString(tokenFile, "UTF-8");
    JsonObject buildInfo = JsonUtil.parse(json);
    Assert.assertNull("No devMode token should be available",
            buildInfo.get(SERVLET_PARAMETER_ENABLE_DEV_SERVER));
    Assert.assertNotNull("productionMode token should be available",
            buildInfo.get(SERVLET_PARAMETER_PRODUCTION_MODE));
    Assert.assertNotNull(
            "useDeprecatedV14Bootstrapping token should be available",
            buildInfo.get(SERVLET_PARAMETER_USE_V14_BOOTSTRAP));
}
 
Example 7
Source File: PrepareFrontendMojoTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void existingTokenFile_enableDevServerShouldBeRemoved()
        throws IOException, MojoExecutionException, MojoFailureException {

    JsonObject initialBuildInfo = Json.createObject();
    initialBuildInfo.put(SERVLET_PARAMETER_PRODUCTION_MODE, false);
    initialBuildInfo.put(SERVLET_PARAMETER_USE_V14_BOOTSTRAP, false);
    initialBuildInfo.put(SERVLET_PARAMETER_ENABLE_DEV_SERVER, false);
    org.apache.commons.io.FileUtils.forceMkdir(tokenFile.getParentFile());
    org.apache.commons.io.FileUtils.write(tokenFile,
            JsonUtil.stringify(initialBuildInfo, 2) + "\n", "UTF-8");

    mojo.execute();

    String json = org.apache.commons.io.FileUtils
            .readFileToString(tokenFile, "UTF-8");
    JsonObject buildInfo = JsonUtil.parse(json);
    Assert.assertNull("No devMode token should be available",
            buildInfo.get(SERVLET_PARAMETER_ENABLE_DEV_SERVER));
    Assert.assertNotNull("productionMode token should be available",
            buildInfo.get(SERVLET_PARAMETER_PRODUCTION_MODE));
    Assert.assertNotNull(
            "useDeprecatedV14Bootstrapping token should be available",
            buildInfo.get(SERVLET_PARAMETER_USE_V14_BOOTSTRAP));
}
 
Example 8
Source File: PrepareFrontendMojoTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void writeTokenFile_devModePropertiesAreWritten()
        throws IOException, MojoExecutionException, MojoFailureException {

    mojo.execute();

    String json = org.apache.commons.io.FileUtils
            .readFileToString(tokenFile, StandardCharsets.UTF_8);
    JsonObject buildInfo = JsonUtil.parse(json);

    Assert.assertTrue(
            Constants.SERVLET_PARAMETER_ENABLE_PNPM
                    + "should have been written",
            buildInfo.getBoolean(Constants.SERVLET_PARAMETER_ENABLE_PNPM));
    Assert.assertTrue(
            Constants.REQUIRE_HOME_NODE_EXECUTABLE
                    + "should have been written",
            buildInfo.getBoolean(Constants.REQUIRE_HOME_NODE_EXECUTABLE));

    Assert.assertFalse(buildInfo
            .hasKey(Constants.SERVLET_PARAMETER_DEVMODE_OPTIMIZE_BUNDLE));
}
 
Example 9
Source File: UidlRequestHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void should_not_modifyUidl_when_MPR_nonJavaScriptBootstrapUI() throws Exception {
    JavaScriptBootstrapUI ui = null;

    UidlRequestHandler handler = spy(new UidlRequestHandler());
    StringWriter writer = new StringWriter();

    JsonObject uidl = generateUidl(true, true);
    doReturn(uidl).when(handler).createUidl(ui, false);

    handler.writeUidl(ui, writer, false);

    String out = writer.toString();

    assertTrue(out.startsWith("for(;;);[{"));
    assertTrue(out.endsWith("}]"));

    uidl = JsonUtil.parse(out.substring(9, out.length() - 1));
    String v7Uidl = uidl.getArray("execute").getArray(2).getString(1);

    assertTrue(v7Uidl.contains("http://localhost:9998/#!away"));
    assertTrue(v7Uidl.contains("window.location.hash = '!away';"));

    assertEquals(
            "setTimeout(() => window.history.pushState(null, '', $0))",
            uidl.getArray("execute").getArray(1).getString(1));
}
 
Example 10
Source File: BuildFrontendMojo.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Add the devMode token to build token file so we don't try to start the
 * dev server. Remove the abstract folder paths as they should not be used
 * for prebuilt bundles.
 */
private void updateBuildFile() {
    File tokenFile = getTokenFile();
    if (!tokenFile.exists()) {
        getLog().warn(
                "Couldn't update devMode token due to missing token file.");
        return;
    }
    try {
        String json = FileUtils.readFileToString(tokenFile,
                StandardCharsets.UTF_8.name());
        JsonObject buildInfo = JsonUtil.parse(json);

        buildInfo.remove(NPM_TOKEN);
        buildInfo.remove(GENERATED_TOKEN);
        buildInfo.remove(FRONTEND_TOKEN);
        buildInfo.remove(Constants.SERVLET_PARAMETER_ENABLE_PNPM);
        buildInfo.remove(Constants.REQUIRE_HOME_NODE_EXECUTABLE);
        buildInfo.remove(Constants.SERVLET_PARAMETER_DEVMODE_OPTIMIZE_BUNDLE);
        buildInfo.remove(Constants.CONNECT_JAVA_SOURCE_FOLDER_TOKEN);
        buildInfo.remove(Constants.CONNECT_APPLICATION_PROPERTIES_TOKEN);
        buildInfo.remove(Constants.CONNECT_JAVA_SOURCE_FOLDER_TOKEN);
        buildInfo.remove(Constants.CONNECT_OPEN_API_FILE_TOKEN);
        buildInfo.remove(Constants.CONNECT_GENERATED_TS_DIR_TOKEN);

        buildInfo.put(SERVLET_PARAMETER_ENABLE_DEV_SERVER, false);
        FileUtils.write(tokenFile, JsonUtil.stringify(buildInfo, 2) + "\n",
                StandardCharsets.UTF_8.name());
    } catch (IOException e) {
        getLog().warn("Unable to read token file", e);
    }
}
 
Example 11
Source File: VaadinVerticle.java    From vertx-vaadin with MIT License 4 votes vote down vote up
private void readBuildInfo(JsonObject config) { // NOSONAR
    try {
        String json = null;
        // token file location passed via init parameter property
        String tokenLocation = config.getString(PARAM_TOKEN_FILE);
        if (tokenLocation != null) {
            File tokenFile = new File(tokenLocation);
            if (tokenFile.canRead()) {
                json = FileUtils.readFileToString(tokenFile, "UTF-8");
            }
        }

        // token file is in the class-path of the application
        if (json == null) {
            URL resource = VaadinVerticle.class
                .getClassLoader()
                .getResource(VAADIN_SERVLET_RESOURCES + TOKEN_FILE);
            if (resource != null) {
                json = FrontendUtils.streamToString(resource.openStream());
            }
        }

        // Read the json and set the appropriate system properties if not
        // already set.
        if (json != null) {
            elemental.json.JsonObject buildInfo = JsonUtil.parse(json);
            if (buildInfo.hasKey(SERVLET_PARAMETER_PRODUCTION_MODE)) {
                config.put(
                    SERVLET_PARAMETER_PRODUCTION_MODE,
                    String.valueOf(buildInfo.getBoolean(
                        SERVLET_PARAMETER_PRODUCTION_MODE)));
                // Need to be sure that we remove the system property,
                // because
                // it has priority in the configuration getter
                System.clearProperty(
                    VAADIN_PREFIX + SERVLET_PARAMETER_PRODUCTION_MODE);
            }
            if (buildInfo.hasKey(SERVLET_PARAMETER_COMPATIBILITY_MODE)) {
                config.put(
                    SERVLET_PARAMETER_COMPATIBILITY_MODE,
                    String.valueOf(buildInfo.getBoolean(
                        SERVLET_PARAMETER_COMPATIBILITY_MODE)));
                // Need to be sure that we remove the system property,
                // because it has priority in the configuration getter
                System.clearProperty(VAADIN_PREFIX
                    + SERVLET_PARAMETER_COMPATIBILITY_MODE);
            }
            if (System.getProperty(PROJECT_BASEDIR) == null
                && buildInfo.hasKey("npmFolder")) {
                System.setProperty(PROJECT_BASEDIR,
                    buildInfo.getString("npmFolder"));
            }
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 12
Source File: UidlRequestHandlerTest.java    From flow with Apache License 2.0 4 votes vote down vote up
@Test
public void should_not_modify_non_MPR_Uidl() throws Exception {
    JavaScriptBootstrapUI ui = mock(JavaScriptBootstrapUI.class);

    UidlRequestHandler handler = spy(new UidlRequestHandler());
    StringWriter writer = new StringWriter();

    JsonObject uidl = generateUidl(true, true);
    uidl.getArray("execute").getArray(2).remove(1);

    doReturn(uidl).when(handler).createUidl(ui, false);

    handler.writeUidl(ui, writer, false);


    String expected = uidl.toJson();

    String out = writer.toString();
    uidl = JsonUtil.parse(out.substring(9, out.length() - 1));

    String actual = uidl.toJson();

    assertEquals(expected, actual);
}
 
Example 13
Source File: UidlRequestHandlerTest.java    From flow with Apache License 2.0 4 votes vote down vote up
private JsonObject generateUidl(boolean withLocation, boolean withHash) {
    JsonObject uidl = JsonUtil.parse(
        "{" +
        "  \"syncId\": 3," +
        "  \"clientId\": 3," +
        "  \"changes\": []," +
        "  \"execute\": [" +
        "   [\"\", \"document.title = $0\"]," +
        "   [\"\", \"setTimeout(() => window.history.pushState(null, '', $0))\"]," +
        "   [[0, 16], \"___PLACE_FOR_V7_UIDL___\", \"$0.firstElementChild.setResponse($1)\"]," +
        "   [1,null,[0, 16], \"return (function() { this.$server['}p']($0, true, $1)}).apply($2)\"]" +
        "  ]," +
        "  \"timings\": []" +
        "}");

    String v7String =
        "\"syncId\": 2," +
        "\"clientId\": 2," +
        "\"changes\": [" +
        "  [],[\"___PLACE_FOR_LOCATION_CHANGE___\"]" +
        "]," +
        "\"state\": {" +
        "}," +
        "\"types\": {" +
        "}," +
        "\"hierarchy\": {" +
        "}," +
        "\"rpc\": [" +
        " [],[" +
        "  \"11\"," +
        "  \"com.vaadin.shared.extension.javascriptmanager.ExecuteJavaScriptRpc\"," +
        "  \"executeJavaScript\", [ \"___PLACE_FOR_HASH_RPC___\" ]" +
        " ],[" +
        "  \"12\"," +
        "  \"com.example.FooRpc\"," +
        "  \"barMethod\", [{}, {}]" +
        " ],[]" +
        "]," +
        "\"meta\": {}, \"resources\": {},\"typeMappings\": {},\"typeInheritanceMap\": {}, \"timings\": []";

    String locationChange =
        "\"change\", {\"pid\": \"0\"}, [\"0\", {\"id\": \"0\", \"location\": \"http://localhost:9998/#!away\"}]";

    String hashRpc =
         "window.location.hash = '!away';";

    if (withLocation) {
        v7String = v7String.replace("\"___PLACE_FOR_LOCATION_CHANGE___\"", locationChange);
    }
    if (withHash) {
        v7String = v7String.replace("___PLACE_FOR_HASH_RPC___", hashRpc);
    }

    uidl.getArray("execute").getArray(2).set(1, v7String);
    return uidl;
}
 
Example 14
Source File: BuildFrontendMojoTest.java    From flow with Apache License 2.0 4 votes vote down vote up
@Test
public void existingTokenFile_enableDevServerShouldBeAdded()
        throws IOException, IllegalAccessException, MojoExecutionException,
        MojoFailureException {

    File projectBase = temporaryFolder.getRoot();
    File webpackOutputDirectory = new File(projectBase,
            VAADIN_SERVLET_RESOURCES);

    ReflectionUtils.setVariableValueInObject(mojo, "generatedFolder",
            projectBase);
    ReflectionUtils.setVariableValueInObject(mojo, "webpackOutputDirectory",
            webpackOutputDirectory);

    JsonObject initialBuildInfo = Json.createObject();
    initialBuildInfo.put(SERVLET_PARAMETER_PRODUCTION_MODE, false);
    initialBuildInfo.put(Constants.NPM_TOKEN, "npm");
    initialBuildInfo.put(Constants.GENERATED_TOKEN, "generated");
    initialBuildInfo.put(Constants.FRONTEND_TOKEN, "frontend");

    initialBuildInfo.put(Constants.SERVLET_PARAMETER_ENABLE_PNPM, true);
    initialBuildInfo.put(Constants.REQUIRE_HOME_NODE_EXECUTABLE, true);
    initialBuildInfo
            .put(Constants.SERVLET_PARAMETER_DEVMODE_OPTIMIZE_BUNDLE, true);

    org.apache.commons.io.FileUtils.forceMkdir(tokenFile.getParentFile());
    org.apache.commons.io.FileUtils.write(tokenFile,
            JsonUtil.stringify(initialBuildInfo, 2) + "\n", "UTF-8");

    mojo.execute();

    String json = org.apache.commons.io.FileUtils
            .readFileToString(tokenFile, "UTF-8");
    JsonObject buildInfo = JsonUtil.parse(json);
    Assert.assertNotNull("devMode token should be available",
            buildInfo.get(SERVLET_PARAMETER_ENABLE_DEV_SERVER));
    Assert.assertNotNull("productionMode token should be available",
            buildInfo.get(SERVLET_PARAMETER_PRODUCTION_MODE));
    Assert.assertNull("npmFolder should have been removed",
            buildInfo.get(Constants.NPM_TOKEN));
    Assert.assertNull("generatedFolder should have been removed",
            buildInfo.get(Constants.GENERATED_TOKEN));
    Assert.assertNull("frontendFolder should have been removed",
            buildInfo.get(Constants.FRONTEND_TOKEN));

    Assert.assertNull(
            Constants.SERVLET_PARAMETER_ENABLE_PNPM
                    + "should have been removed",
            buildInfo.get(Constants.SERVLET_PARAMETER_ENABLE_PNPM));
    Assert.assertNull(
            Constants.REQUIRE_HOME_NODE_EXECUTABLE
                    + "should have been removed",
            buildInfo.get(Constants.REQUIRE_HOME_NODE_EXECUTABLE));
    Assert.assertNull(
            Constants.SERVLET_PARAMETER_DEVMODE_OPTIMIZE_BUNDLE
                    + "should have been removed",
            buildInfo.get(
                    Constants.SERVLET_PARAMETER_DEVMODE_OPTIMIZE_BUNDLE));
}