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

The following examples show how to use elemental.json.Json#createObject() . 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: GwtApplicationConnectionTest.java    From flow with Apache License 2.0 6 votes vote down vote up
public void test_should_not_addNavigationEvents_forWebComponents() {
    mockFlowBootstrapScript(true);

    JsonObject windowEvents = Json.createObject();
    addEventsObserver(Browser.getWindow(), windowEvents);

    JsonObject bodyEvents = Json.createObject();
    addEventsObserver(Browser.getDocument().getBody(), bodyEvents);

    new Bootstrapper().onModuleLoad();

    delayTestFinish(500);
    new Timer() {
        @Override
        public void run() {
            assertFalse(windowEvents.hasKey("popstate"));
            assertFalse(bodyEvents.hasKey("click"));
            finishTest();
        }
    }.schedule(100);
}
 
Example 3
Source File: BaseScale.java    From vaadin-chartjs with MIT License 6 votes vote down vote up
@Override
public JsonObject buildJson() {
    JsonObject map = Json.createObject();
    JUtils.putNotNull(map, "type", type);
    JUtils.putNotNull(map, "display", display);
    JUtils.putNotNull(map, "id", id);
    JUtils.putNotNull(map, "stacked", stacked);
    JUtils.putNotNull(map, "barThickness", barThickness);
    JUtils.putNotNull(map, "maxBarThickness", maxBarThickness);
    JUtils.putNotNull(map, "categoryPercentage", categoryPercentage);
    JUtils.putNotNull(map, "barPercentage", barPercentage);
    if (position != null) {
        JUtils.putNotNull(map, "position", position.name().toLowerCase());
    }
    JUtils.putNotNull(map, "gridLines", gridLines);
    JUtils.putNotNull(map, "scaleLabel", scaleLabel);
    JUtils.putNotNull(map, "ticks", ticks);
    return map;
}
 
Example 4
Source File: LegendLabel.java    From vaadin-chartjs with MIT License 5 votes vote down vote up
@Override
public JsonObject buildJson() {
    JsonObject map = Json.createObject();
    JUtils.putNotNull(map, "boxWidth", boxWidth);
    JUtils.putNotNull(map, "fontSize", fontSize);
    JUtils.putNotNull(map, "fontStyle", fontStyle);
    JUtils.putNotNull(map, "fontColor", fontColor);
    JUtils.putNotNull(map, "fontFamily", fontFamily);
    JUtils.putNotNull(map, "padding", padding);
    JUtils.putNotNull(map, "usePointStyle", usePointStyle);
    return map;
}
 
Example 5
Source File: MapSyncRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void syncJSON_jsonIsNotListItemAndNotPropertyValue_propertySetToJSON()
        throws Exception {
    // Let's use element's ElementPropertyMap for testing.
    TestComponent component = new TestComponent();
    Element element = component.getElement();
    UI ui = new UI();
    ui.add(component);

    StateNode node = element.getNode();

    TestComponent anotherComonent = new TestComponent();
    StateNode anotherNode = anotherComonent.getElement().getNode();

    ElementPropertyMap.getModel(node)
            .setUpdateFromClientFilter(name -> true);

    // Use the model node id for JSON object which represents a value to
    // update
    JsonObject json = Json.createObject();
    json.put("nodeId", anotherNode.getId());

    // send sync request
    sendSynchronizePropertyEvent(element, ui, "foo", json);

    Serializable testPropertyValue = node
            .getFeature(ElementPropertyMap.class).getProperty("foo");

    Assert.assertNotSame(anotherNode, testPropertyValue);
    Assert.assertTrue(testPropertyValue instanceof JsonValue);
}
 
Example 6
Source File: ElementDataTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void collectChanges_setPayloadOnly_onlyOneChanges() {
    JsonObject object = Json.createObject();
    elementData.setPayload(object);
    List<NodeChange> changes = new ArrayList<>();
    elementData.collectChanges(changes::add);

    Assert.assertEquals(1, changes.size());
    Assert.assertTrue(changes.get(0) instanceof MapPutChange);
    MapPutChange change = (MapPutChange) changes.get(0);

    Assert.assertEquals(NodeProperties.PAYLOAD, change.getKey());
    Assert.assertEquals(elementData.getNode(), change.getNode());
    Assert.assertEquals(object, change.getValue());
}
 
Example 7
Source File: ConstantPoolTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void sameValue_sameId() {
    ConstantPoolKey reference = new ConstantPoolKey(Json.createObject());

    String constantId = constantPool.getConstantId(reference);
    constantPool.dumpConstants();

    String otherId = constantPool
            .getConstantId(new ConstantPoolKey(Json.createObject()));

    Assert.assertEquals(constantId, otherId);
    Assert.assertFalse(constantPool.hasNewConstants());
}
 
Example 8
Source File: PieAnimation.java    From vaadin-chartjs with MIT License 5 votes vote down vote up
@Override
public JsonObject buildJson() {
    JsonObject obj = Json.createObject();
    JUtils.putNotNull(obj, "duration", duration);
    if (easing != null) {
        JUtils.putNotNull(obj, "easing", easing.name());
    }
    JUtils.putNotNull(obj, "animateRotate", animateRotate);
    JUtils.putNotNull(obj, "animateScale", animateScale);
    return obj;
}
 
Example 9
Source File: GwtEventHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
public void testPolymerMockedEventHandlerWithEventData() {
    String methodName = "eventHandler";
    String methodId = "handlerId";
    String eventData = "event.button";

    node.getList(NodeFeatures.POLYMER_SERVER_EVENT_HANDLERS).add(0,
            methodName);
    node.getMap(NodeFeatures.POLYMER_EVENT_LISTENERS)
            .getProperty(methodName).setValue(methodId);

    JsonObject json = Json.createObject();
    JsonArray array = Json.createArray();
    array.set(0, eventData);
    json.put(methodId, array);

    node.getTree().getRegistry().getConstantPool().importFromJson(json);
    Binder.bind(node, element);
    Reactive.flush();

    NativeFunction mockedFunction = new NativeFunction("this." + methodName
            + "({button: 2, altKey: false, clientX: 50, clientY: 100})");
    mockedFunction.apply(element, JsCollections.array());

    assertEquals("The amount of server methods was not as expected", 1,
            serverMethods.size());
    assertEquals("Expected method did not match", methodName,
            serverMethods.keySet().iterator().next());
    assertEquals("Wrong amount of method arguments", 1,
            serverMethods.get(methodName).length());
    assertEquals("Gotten argument wasn't as expected", "2",
            serverMethods.get(methodName).get(0).toString());
    assertEquals("Method node did not match the expected node.", node,
            serverRpcNodes.get(methodName));
}
 
Example 10
Source File: UsageStatisticsExporter.java    From flow with Apache License 2.0 5 votes vote down vote up
private static String createUsageStatisticsJson(UsageStatistics.UsageEntry entry) {
    JsonObject json = Json.createObject();

    json.put("is", entry.getName());
    json.put("version", entry.getVersion());

    return json.toJson();
}
 
Example 11
Source File: TimeScaleOptions.java    From vaadin-chartjs with MIT License 5 votes vote down vote up
@Override
public JsonObject buildJson() {
    JsonObject map = Json.createObject();
    JUtils.putNotNull(map, "format", format);
    JUtils.putNotNull(map, "displayFormats", displayFormats);
    JUtils.putNotNull(map, "isoWeekday", isoWeekday);
    JUtils.putNotNull(map, "min", min);
    JUtils.putNotNull(map, "max", max);
    JUtils.putNotNull(map, "round", unitToString(round));    
    JUtils.putNotNull(map, "tooltipFormat", tooltipFormat);
    JUtils.putNotNull(map, "unit", unitToString(unit));    
    JUtils.putNotNull(map, "stepSize", stepSize);
    JUtils.putNotNull(map, "minUnit", unitToString(minUnit));    
    return map;
}
 
Example 12
Source File: RadialPointLabel.java    From vaadin-chartjs with MIT License 5 votes vote down vote up
@Override
public JsonObject buildJson() {
    JsonObject map = Json.createObject();
    JUtils.putNotNull(map, "display", display);
    JUtils.putNotNullList(map, "fontColor", fontColor);
    JUtils.putNotNull(map, "fontFamily", fontFamily);
    JUtils.putNotNull(map, "fontSize", fontSize);
    JUtils.putNotNull(map, "fontStyle", fontStyle);
    return map;
}
 
Example 13
Source File: JsonUtilsTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private static JsonObject createTestObject2() {
    JsonObject object = Json.createObject();

    object.put("foo", "oof");
    object.put("bar", createTestArray2());
    object.put("baz", Json.createArray());

    return object;
}
 
Example 14
Source File: ServerEventObject.java    From flow with Apache License 2.0 5 votes vote down vote up
private JsonObject createPolymerPropertyObject(Event event,
        String expression) {
    ServerEventDataExpression dataExpression = getOrCreateExpression(
            expression);
    JsonObject expressionValue = dataExpression.evaluate(event, this);
    JsonObject object = Json.createObject();
    object.put(NODE_ID, expressionValue.getNumber(NODE_ID));
    return object;
}
 
Example 15
Source File: DonutChartConfig.java    From vaadin-chartjs with MIT License 5 votes vote down vote up
@Override
public JsonObject buildJson() {
    JsonObject map = Json.createObject();
    JUtils.putNotNull(map, "type", "doughnut");
    if (data != null) {
        JUtils.putNotNull(map, "data", data.buildJson());
    }
    if (options != null) {
        JUtils.putNotNull(map, "options", options.buildJson());
    }
    return map;
}
 
Example 16
Source File: BubbleData.java    From vaadin-chartjs with MIT License 5 votes vote down vote up
@Override
public JsonObject buildJson() {
    JsonObject obj = Json.createObject();
    JUtils.putNotNull(obj, "x", x);
    JUtils.putNotNull(obj, "y", y);
    JUtils.putNotNull(obj, "r", r);
    return obj;
}
 
Example 17
Source File: MetadataWriter.java    From flow with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a JSON object containing metadata related to the given UI.
 *
 * @param ui
 *            The UI whose metadata to write.
 * @param repaintAll
 *            Whether the client should repaint everything.
 * @param async
 *            True if this message is sent by the server asynchronously,
 *            false if it is a response to a client message.
 * @param messages
 *            a {@link SystemMessages} containing client-side error
 *            messages.
 * @return JSON object with the metadata
 *
 */
public JsonObject createMetadata(UI ui, boolean repaintAll, boolean async,
        SystemMessages messages) {
    JsonObject meta = Json.createObject();

    if (repaintAll) {
        meta.put("repaintAll", true);
    }

    if (async) {
        meta.put(JsonConstants.META_ASYNC, true);
    }

    VaadinSessionState state = ui.getSession().getState();
    if (state != null && state.compareTo(VaadinSessionState.CLOSING) >= 0) {
        meta.put(JsonConstants.META_SESSION_EXPIRED, true);
    }

    // meta instruction for client to enable auto-forward to
    // sessionExpiredURL after timer expires.
    if (messages != null && messages.getSessionExpiredMessage() == null
            && messages.getSessionExpiredCaption() == null
            && messages.isSessionExpiredNotificationEnabled()
            && ui.getSession().getSession() != null) {
        int newTimeoutInterval = ui.getSession().getSession()
                .getMaxInactiveInterval();
        if (repaintAll || (timeoutInterval != newTimeoutInterval)) {
            String url = messages.getSessionExpiredURL();
            if (url == null) {
                url = "";
            }
            int redirectInterval = newTimeoutInterval + 15;

            JsonObject redirect = Json.createObject();
            redirect.put("interval", redirectInterval);
            redirect.put("url", url);

            meta.put("timedRedirect", redirect);
        }
        timeoutInterval = newTimeoutInterval;
    }

    return meta;
}
 
Example 18
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));
}
 
Example 19
Source File: GwtMessageHandlerTest.java    From flow with Apache License 2.0 4 votes vote down vote up
public void testMessageProcessing_moduleDependencyIsHandledBeforeApplyingChangesToTree() {
    resetInternalEvents();

    JavaScriptObject object = JavaScriptObject.createObject();
    JsonObject obj = object.cast();

    // make an empty changes list. It will initiate changes processing
    // anyway
    // Any changes processing should happen AFTER dependencies are loaded
    obj.put("changes", Json.createArray());

    JsonArray array = Json.createArray();

    // create a dependency
    JsonObject dep = Json.createObject();
    dep.put(Dependency.KEY_URL, "foo");
    dep.put(Dependency.KEY_TYPE, Dependency.Type.JS_MODULE.toString());
    array.set(0, dep);

    obj.put(LoadMode.EAGER.toString(), array);
    handler.handleJSON(object.cast());

    delayTestFinish(500);

    new Timer() {
        @Override
        public void run() {
            assertTrue(getResourceLoader().scriptUrls.contains("foo"));

            EventsOrder eventsOrder = registry.get(EventsOrder.class);
            assertTrue(eventsOrder.sources.size() >= 2);
            // the first one is resource loaded which means dependency
            // processing
            assertEquals(ResourceLoader.class.getName(),
                    eventsOrder.sources.get(0));
            // the second one is applying changes to StatTree
            assertEquals(StateTree.class.getName(),
                    eventsOrder.sources.get(1));
            finishTest();
        }
    }.schedule(100);
}
 
Example 20
Source File: JsonCodecTest.java    From flow with Apache License 2.0 4 votes vote down vote up
@Test(expected = ClassCastException.class)
public void decodeAs_jsonValueWrongType_classCastException() {
    JsonObject json = Json.createObject();
    json.put("foo", "bar");
    JsonCodec.decodeAs(json, JsonNumber.class);
}