elemental.json.Json Java Examples

The following examples show how to use elemental.json.Json. 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: AbstractOptions.java    From vaadin-chartjs with MIT License 6 votes vote down vote up
@Override
public JsonObject buildJson() {
    JsonObject map = Json.createObject();
    JUtils.putNotNull(map, "responsive", responsive);
    JUtils.putNotNull(map, "maintainAspectRatio", maintainAspectRatio);
    JUtils.putNotNull(map, "responsiveAnimationDuration", responsiveAnimationDuration);
    JUtils.putNotNull(map, "devicePixelRatio", devicePixelRatio);
    JUtils.putNotNull(map, "events", events);
    JUtils.putNotNull(map, "title", title);
    JUtils.putNotNull(map, "hover", hover);
    JUtils.putNotNull(map, "tooltips", tooltips);
    JUtils.putNotNull(map, "animation", animation);
    JUtils.putNotNull(map, "legend", legend);
    JUtils.putNotNull(map, "elements", elements);
    JUtils.putNotNull(map, "pan", pan);
    JUtils.putNotNull(map, "zoom", zoom);
    return map;
}
 
Example #2
Source File: GwtStateTreeTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testSendTemplateEventToServer_delegateToServerConnector() {
    StateNode node = new StateNode(0, tree);
    tree.registerNode(node);
    JsArray array = getArgArray();
    tree.sendTemplateEventToServer(node, "foo", array, -1);

    JsonObject object = Json.createObject();
    object.put("key", "value");
    array.set(array.length(), WidgetUtil.crazyJsCast(object));
    array.set(array.length(), getNativeArray());

    TestServerConnector serverConnector = (TestServerConnector) registry
            .getServerConnector();
    assertEquals(node, serverConnector.node);
    assertEquals("foo", serverConnector.methodName);
    JsonArray args = serverConnector.args;
    assertEquals(true, args.getBoolean(0));
    assertEquals("bar", args.getString(1));
    assertEquals(46.2, args.getNumber(2));
    assertEquals(object, args.getObject(3));

    assertEquals("item", ((JsonArray) args.getObject(4)).getString(0));
}
 
Example #3
Source File: ElementTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropertyBooleanConversions() {
    assertPropertyBoolean(true, Boolean.TRUE);
    assertPropertyBoolean(false, Boolean.FALSE);

    assertPropertyBoolean(true, "true");
    assertPropertyBoolean(true, "false");
    assertPropertyBoolean(false, "");

    assertPropertyBoolean(true, Double.valueOf(1));
    assertPropertyBoolean(true, Double.valueOf(3.14));
    assertPropertyBoolean(false, Double.valueOf(0));
    assertPropertyBoolean(false, Double.valueOf(Double.NaN));

    assertPropertyBoolean(false, Json.createNull());
    assertPropertyBoolean(false, Json.create(false));
    assertPropertyBoolean(true, Json.create(true));
    assertPropertyBoolean(true, Json.createObject());
}
 
Example #4
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 #5
Source File: ElementTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropertyIntConversions() {
    assertPropertyInt(1, Double.valueOf(1));
    assertPropertyInt(1, Double.valueOf(1.9));
    assertPropertyInt(0, Double.valueOf(Double.NaN));
    assertPropertyInt(Integer.MAX_VALUE, Double.valueOf(12.34e56));

    assertPropertyInt(1, "1");
    assertPropertyInt(1, "1.9");
    assertPropertyInt(Integer.MAX_VALUE, "12.34e56");
    assertPropertyInt(0, "foo");

    assertPropertyInt(1, Boolean.TRUE);
    assertPropertyInt(0, Boolean.FALSE);

    assertPropertyInt(1, Json.create(1));
    assertPropertyInt(1, Json.create(1.9));
    assertPropertyInt(1, Json.create(true));
    assertPropertyInt(0, Json.create(false));
    assertPropertyInt(1, Json.create("1"));
    assertPropertyInt(0, Json.create("foo"));
    assertPropertyInt(0, Json.createObject());
}
 
Example #6
Source File: CubaSuggestionField.java    From cuba with Apache License 2.0 6 votes vote down vote up
private JsonObject getJsonObject(T suggestion) {
    final JsonObject object = Json.createObject();

    //noinspection unchecked
    object.put(SUGGESTION_ID, Json.create(keyMapper.key(suggestion)));

    String caption = textViewConverter.apply(suggestion);
    object.put(SUGGESTION_CAPTION, Json.create(caption));

    if (optionsStyleProvider != null) {
        String styleName = optionsStyleProvider.apply(suggestion);
        object.put(SUGGESTION_STYLE_NAME, Json.create(styleName));
    }

    return object;
}
 
Example #7
Source File: PendingJavaScriptInvocationTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void blockFromSessionThreadAfterFailing_doesNotThrow()
        throws Exception {
    MockVaadinSession session = new MockVaadinSession();
    session.runWithLock(() -> {
        CompletableFuture<JsonValue> completableFuture = invocation
                .toCompletableFuture();

        String errorMessage = "error message";
        invocation.completeExceptionally(Json.create(errorMessage));

        for (Callable<JsonValue> action : createBlockingActions(
                completableFuture)) {
            try {
                action.call();
                Assert.fail("Execution should have failed");
            } catch (ExecutionException | CompletionException e) {
                JavaScriptException cause = (JavaScriptException) e
                        .getCause();
                Assert.assertEquals(errorMessage, cause.getMessage());
            }
        }
        return null;
    });
}
 
Example #8
Source File: JUtils.java    From vaadin-chartjs with MIT License 5 votes vote down vote up
public static void putNotNullStringListOrSingle(JsonObject obj, String key, List<String> list) {
    if (list != null) {
        if (list.size() == 1) {
            putNotNull(obj, key, list.get(0));
        } else {
            JsonArray arr = Json.createArray();
            for (String entry : list) {
                arr.set(arr.length(), entry);
            }
            obj.put(key, arr);
        }
    }
}
 
Example #9
Source File: PolarAreaChartConfig.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", "polarArea");
    if (data != null) {
        JUtils.putNotNull(map, "data", data.buildJson());
    }
    if (options != null) {
        JUtils.putNotNull(map, "options", options.buildJson());
    }
    return map;
}
 
Example #10
Source File: JUtils.java    From vaadin-chartjs with MIT License 5 votes vote down vote up
public static void putNotNull(JsonObject obj, String key, List<String> list) {
    if (list != null) {
        JsonArray arr = Json.createArray();
        for (String entry : list) {
            arr.set(arr.length(), entry);
        }
        obj.put(key, arr);
    }
}
 
Example #11
Source File: JUtils.java    From vaadin-chartjs with MIT License 5 votes vote down vote up
public static void putNotNullNumberListOrSingle(JsonObject obj, String key, List<Double> listOfNumbers) {
    if (listOfNumbers != null) {
        if (listOfNumbers.size() == 1) {
            putNotNull(obj, key, listOfNumbers.get(0));
        } else {
            JsonArray arr = Json.createArray();
            for (Double n : listOfNumbers) {
                arr.set(arr.length(), n);
            }
            obj.put(key, arr);
        }
    }
}
 
Example #12
Source File: RendererUtilTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void registerEventHandlers_attachMultipleTimes_singleEventListenerRegistered() {
    UI ui = new TestUI();
    TestUIInternals internals = (TestUIInternals) ui.getInternals();

    Renderer<String> renderer = new Renderer<>();

    AtomicInteger eventCounter = new AtomicInteger(0);

    renderer.setEventHandler("foo", value -> {
        eventCounter.getAndIncrement();
    });

    Element contentTemplate = new Element(Tag.DIV);
    Element templateDataHost = new Element(Tag.SPAN);

    RendererUtil.registerEventHandlers(renderer, contentTemplate,
            templateDataHost, ValueProvider.identity());

    attachElements(ui, contentTemplate, templateDataHost);
    attachElements(ui, contentTemplate, templateDataHost);

    internals.getStateTree().runExecutionsBeforeClientResponse();

    JsonObject eventData = Json.createObject();
    eventData.put("key", "");
    templateDataHost.getNode().getFeature(ElementListenerMap.class)
            .fireEvent(new DomEvent(templateDataHost, "foo", eventData));

    Assert.assertEquals(1, eventCounter.get());
}
 
Example #13
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 #14
Source File: RadarChartConfig.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", "radar");
    // data
    if (data != null) {
        JUtils.putNotNull(map, "data", data.buildJson());
    }
    // options
    if (options != null) {
        JUtils.putNotNull(map, "options", options.buildJson());
    }
    return map;
}
 
Example #15
Source File: NodeList.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public JsonValue getDebugJson() {
    JsonArray json = Json.createArray();

    for (int i = 0; i < values.length(); i++) {
        Object value = values.get(i);
        JsonValue jsonValue = getAsDebugJson(value);

        json.set(json.length(), jsonValue);
    }

    return json;
}
 
Example #16
Source File: MessageSender.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Resynchronize the client side, i.e. reload all component hierarchy and
 * state from the server
 */
public void resynchronize() {
    Console.log("Resynchronizing from server");
    JsonObject resyncParam = Json.createObject();
    resyncParam.put(ApplicationConstants.RESYNCHRONIZE_ID, true);
    send(Json.createArray(), resyncParam);
}
 
Example #17
Source File: ExecuteJavaScriptProcessorTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void execute_nodeParametersAreCorrectlyPassed() {
    Registry registry = new Registry() {
        {
            StateTree tree = new StateTree(this);
            set(StateTree.class, tree);
            set(ExistingElementMap.class, new ExistingElementMap());
        }

    };
    CollectingExecuteJavaScriptProcessor processor = new CollectingExecuteJavaScriptProcessor(
            registry);

    StateNode node = new StateNode(10, registry.getStateTree());
    registry.getStateTree().registerNode(node);

    JsElement element = new JsElement() {

    };
    node.setDomNode(element);

    JsonArray json = JsonUtils.createArray(Json.create(JsonCodec.NODE_TYPE),
            Json.create(node.getId()));

    JsonArray invocation = Stream.of(json, Json.create("$0"))
            .collect(JsonUtils.asArray());

    // JRE impl of the array uses

    processor.execute(JsonUtils.createArray(invocation));

    Assert.assertEquals(1, processor.nodeParametersList.size());

    Assert.assertEquals(1, processor.nodeParametersList.get(0).size());

    JsMap<Object, StateNode> map = processor.nodeParametersList.get(0);

    StateNode stateNode = map.get(element);
    Assert.assertEquals(node, stateNode);
}
 
Example #18
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 #19
Source File: NodeUpdaterTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test // #6907 test when user has set newer versions
public void updateDefaultDependencies_newerVersionsAreNotChanged()
        throws IOException {
    JsonObject packageJson = nodeUpdater.getPackageJson();
    packageJson.put(NodeUpdater.DEPENDENCIES, Json.createObject());
    packageJson.put(NodeUpdater.DEV_DEPENDENCIES, Json.createObject());
    packageJson.getObject(NodeUpdater.DEV_DEPENDENCIES).put("webpack",
            "5.0.1");
    nodeUpdater.updateDefaultDependencies(packageJson);

    Assert.assertEquals("5.0.1", packageJson
            .getObject(NodeUpdater.DEV_DEPENDENCIES).getString("webpack"));
}
 
Example #20
Source File: GwtPropertyElementBinderTest.java    From flow with Apache License 2.0 5 votes vote down vote up
public void testDomListenerSynchronization() {
    // Must append for events to work in HTMLUnit
    Browser.getDocument().getBody().appendChild(element);
    Binder.bind(node, element);

    setSyncProperties("offsetHeight");

    String constantPoolKey = "expressionsKey";

    JsonObject expressions = Json.createObject();
    boolean isFilter = false;
    expressions.put(
            JsonConstants.SYNCHRONIZE_PROPERTY_TOKEN + "offsetWidth",
            isFilter);

    GwtBasicElementBinderTest.addToConstantPool(constantPool,
            constantPoolKey, expressions);
    node.getMap(NodeFeatures.ELEMENT_LISTENERS).getProperty("event1")
            .setValue(constantPoolKey);
    Reactive.flush();

    element.getStyle().setWidth("2px");
    element.getStyle().setHeight("2px");
    dispatchEvent("event1");
    /*
     * Only offsetWidth should be synchronized. offsetHeight is also marked
     * as a globally synchronized property, but it should not be sent since
     * there's no global synchronization configured for the event, only
     * synchronization of one specific property.
     */
    assertSynchronized("offsetWidth");
}
 
Example #21
Source File: ComponentRendererTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void templateRenderered_parentAttachedBeforeChild() {
    UI ui = new TestUI();
    TestUIInternals internals = (TestUIInternals) ui.getInternals();

    ComponentRenderer<TestLabel, String> renderer = new ComponentRenderer<>(
            e -> (new TestLabel()));

    Element containerParent = new Element("div");
    Element container = new Element("div");

    KeyMapper<String> keyMapper = new KeyMapper<>();

    ComponentDataGenerator<String> rendering = (ComponentDataGenerator<String>) renderer
            .render(container, keyMapper);

    // simulate a call from the grid to refresh data - template is not setup
    containerParent.getNode().runWhenAttached(
            ui2 -> ui2.getInternals().getStateTree()
                    .beforeClientResponse(containerParent.getNode(),
                            context -> {
                                Assert.assertNotNull(
                                        "NodeIdPropertyName should not be null",
                                        rendering.getNodeIdPropertyName());
                                JsonObject value = Json.createObject();
                                rendering.generateData("item", value);
                                Assert.assertEquals(
                                        "generateData should add one element in the jsonobject",
                                        1, value.keys().length);
                            }));

    // attach the parent (ex: grid) before the child (ex: column)
    attachElement(ui, containerParent);
    attachElement(ui, container);

    internals.getStateTree().runExecutionsBeforeClientResponse();

}
 
Example #22
Source File: TemplateDataAnalyzer.java    From flow with Apache License 2.0 5 votes vote down vote up
private JsonArray getPath(org.jsoup.nodes.Element element,
        org.jsoup.nodes.Element templateRoot) {
    List<Integer> path = new ArrayList<>();
    org.jsoup.nodes.Element current = element;
    while (!current.equals(templateRoot)) {
        org.jsoup.nodes.Element parent = current.parent();
        path.add(indexOf(parent, current));
        current = parent;
    }
    JsonArray array = Json.createArray();
    for (int i = 0; i < path.size(); i++) {
        array.set(i, path.get(path.size() - i - 1));
    }
    return array;
}
 
Example #23
Source File: WebComponentBindingTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void updateValue() {
    binding.updateProperty("int", 5);
    Assert.assertEquals(5, component.integer);

    JsonObject obj = Json.createObject();
    obj.put("String", "Value");

    binding.updateProperty("json", obj);
    Assert.assertEquals("{\"String\":\"Value\"}",
            component.jsonValue.toJson());
}
 
Example #24
Source File: ZoomRange.java    From vaadin-chartjs with MIT License 5 votes vote down vote up
@Override
public JsonObject buildJson() {
    JsonObject obj = Json.createObject();
    setValue(obj, "x", x);
    setValue(obj, "y", y);
    return obj;
}
 
Example #25
Source File: JsonUtilsTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateArray() {
    JsonArray array = JsonUtils.createArray(Json.create("string"),
            Json.createNull());

    Assert.assertEquals(2, array.length());
    Assert.assertEquals("string", array.getString(0));
    Assert.assertSame(JreJsonNull.class, array.get(1).getClass());
}
 
Example #26
Source File: StringToNumberDecoderTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void stringToDouble_convertableString_valueIsConverted()
        throws RpcDecodeException {
    Double expected = 823.6349d;
    Double value = decoder.decode(Json.create(String.valueOf(expected)),
            Double.class);
    Assert.assertEquals(expected, value);
}
 
Example #27
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 #28
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 #29
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 #30
Source File: TimeDisplayFormats.java    From vaadin-chartjs with MIT License 5 votes vote down vote up
@Override
public JsonObject buildJson() {
    JsonObject map = Json.createObject();
    JUtils.putNotNull(map, "millisecond", millisecond);
    JUtils.putNotNull(map, "second", second);
    JUtils.putNotNull(map, "minute", minute);
    JUtils.putNotNull(map, "hour", hour);
    JUtils.putNotNull(map, "day", day);
    JUtils.putNotNull(map, "week", week);
    JUtils.putNotNull(map, "month", month);
    JUtils.putNotNull(map, "quarter", quarter);
    JUtils.putNotNull(map, "year", year);
    return map;
}