Java Code Examples for elemental.json.Json

The following examples show how to use elemental.json.Json. These examples are extracted from open source projects. 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 Project: cuba   Source File: CubaSuggestionField.java    License: 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 2
Source Project: vaadin-chartjs   Source File: AbstractOptions.java    License: 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 3
Source Project: vaadin-chartjs   Source File: BaseScale.java    License: 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 Project: flow   Source File: PendingJavaScriptInvocationTest.java    License: 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 5
Source Project: flow   Source File: ElementTest.java    License: 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 Project: flow   Source File: GwtStateTreeTest.java    License: 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 7
Source Project: flow   Source File: ElementTest.java    License: 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 8
Source Project: flow   Source File: TreeChangeProcessorTest.java    License: Apache License 2.0 5 votes vote down vote up
private static JsonObject nodeSpliceChange(int node, int ns, int index,
        int remove, int... children) {
    JsonObject json = spliceBaseChange(node, ns, index, remove);

    if (children != null && children.length != 0) {
        JsonArray add = Arrays.stream(children).mapToObj(Json::create)
                .collect(JsonUtils.asArray());
        json.put(JsonConstants.CHANGE_SPLICE_ADD_NODES, add);
    }

    return json;
}
 
Example 9
Source Project: flow   Source File: NodeList.java    License: 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 10
Source Project: vertxui   Source File: Client.java    License: GNU General Public License v3.0 5 votes vote down vote up
public Client() {
	head.script(FigWheelyClient.urlJavascript);
	EventBus.importJs((Void) -> {

		String name = window.prompt("What is your name?", "");
		Fluent input = body.input(null, "text");
		Fluent messages = body.div();

		EventBus eventBus = EventBus.create(url, null);
		eventBus.onopen(event -> {
			eventBus.publish(freeway, name + ": Ola, I'm " + name + ".", null);
			eventBus.registerHandler(freeway, null, (error, in) -> { // onmessage
				messages.li(null, in.get("body").asString());
			});

			// extra example: pojo consume
			Pojofy.eventbusReceive(eventBus, addressPojo, null, AllExamplesClient.dto,
					a -> console.log("Received pojo: " + a.color));
		});

		input.keydown((fluent, event) -> {
			if (event.getKeyCode() == KeyboardEvent.KeyCode.ENTER) {
				eventBus.publish(freeway, name + ": " + input.domValue(), null);
				input.att(Att.value, null);

				// extra example: object publish
				Pojofy.eventbusPublish(eventBus, addressPojo, new Dto("blue by " + name),
						Json.parse("{\"action\":\"save\"}"), AllExamplesClient.dto);
			}
		});
		input.focus();
	});
}
 
Example 11
Source Project: vertxui   Source File: Client.java    License: GNU General Public License v3.0 5 votes vote down vote up
public Client() {
	head.script(FigWheelyClient.urlJavascript);
	SockJS.importJs((Void) -> {

		String name = window.prompt("What is your name?", "");
		Fluent input = body.input(null, "text");
		Fluent messages = body.div();

		SockJS socket = SockJS.create(url);
		socket.setOnopen(e -> {
			socket.send(name + ": Ola, I'm " + name + ".");
		});
		socket.setOnmessage(e -> {
			// extra: pojo example
			if (Pojofy.socketReceive(urlPojo, e, AllExamplesClient.dto,
					d -> console.log("Received pojo color=" + d.color))) {
				return;
			}

			messages.li(null, ((MessageEvent) e).getData().toString());
		});
		input.keydown((fluent, event) -> {
			if (event.getKeyCode() == KeyboardEvent.KeyCode.ENTER) {
				socket.send(name + ": " + input.domValue());
				input.att(Att.value, null);

				// extra: pojo example
				Pojofy.socketSend(socket, urlPojo, new Dto("violet"), AllExamplesClient.dto,
						Json.parse("{\"action\":\"save\"}"));
			}
		});
		input.focus();

	});
}
 
Example 12
Source Project: flow   Source File: NodeUpdater.java    License: Apache License 2.0 5 votes vote down vote up
JsonObject getResourcesPackageJson() throws IOException {
    JsonObject packageJson = getJsonFileContent(
            new File(flowResourcesFolder, PACKAGE_JSON));
    if (packageJson == null) {
        packageJson = Json.createObject();
        packageJson.put(DEP_NAME_KEY, DEP_NAME_FLOW_JARS);
        packageJson.put(DEP_LICENSE_KEY, DEP_LICENSE_DEFAULT);
        packageJson.put(DEP_MAIN_KEY, DEP_MAIN_FLOW_JARS);
        packageJson.put(DEP_VERSION_KEY, DEP_VERSION_DEFAULT);
    }
    return packageJson;
}
 
Example 13
Source Project: flow   Source File: LockDevDepVersionsMojo.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    File targetFile = new File(generatedDependenciesFolder,
            generatedDependencies);
    try {
        FileUtils.forceMkdirParent(targetFile);
    } catch (IOException exception) {
        throw new MojoExecutionException(
                "Can't make directories for the generated file", exception);
    }

    String content = listDevDependencies();

    JsonObject result = Json.createObject();
    JsonObject object = Json.parse(content);
    collectDeps(result, object);

    readVersionsFromPackageJson(result);

    try {
        FileUtils.write(targetFile, stringify(result, 2) + "\n",
                StandardCharsets.UTF_8);
    } catch (IOException e) {
        throw new MojoFailureException(
                "Couldn't write dependencies into the target file", e);
    }
}
 
Example 14
Source Project: flow   Source File: WebComponentExporterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void configuration_deliverPropertyUpdate() {
    exporter.addProperty("int", 0).onChange(MyComponent::update);

    WebComponentBinding<MyComponent> binding = config
            .createWebComponentBinding(new MockInstantiator(),
                    mock(Element.class), Json.createObject());

    Assert.assertNotNull(binding);

    binding.updateProperty("int", 1);

    Assert.assertEquals("Component should have been updated", 1,
            binding.getComponent().getValue());
}
 
Example 15
Source Project: flow   Source File: TaskUpdateImports.java    License: Apache License 2.0 5 votes vote down vote up
private JsonArray makeFallbackCssImports(AbstractUpdateImports updater) {
    JsonArray array = Json.createArray();
    Set<CssData> css = updater.getCss();
    Iterator<CssData> iterator = css.iterator();
    for (int i = 0; i < css.size(); i++) {
        array.set(i, makeCssJson(iterator.next()));
    }
    return array;
}
 
Example 16
Source Project: flow   Source File: ServerConnector.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sends a template event message to the server.
 *
 * @param node
 *            the node that listened to the event
 * @param methodName
 *            the event handler method name to execute on the server side
 * @param argsArray
 *            the arguments array for the method
 * @param promiseId
 *            the promise id to use for getting the result back, or -1 if no
 *            result is expected
 */
public void sendTemplateEventMessage(StateNode node, String methodName,
        JsonArray argsArray, int promiseId) {
    JsonObject message = Json.createObject();
    message.put(JsonConstants.RPC_TYPE,
            JsonConstants.RPC_PUBLISHED_SERVER_EVENT_HANDLER);
    message.put(JsonConstants.RPC_NODE, node.getId());
    message.put(JsonConstants.RPC_TEMPLATE_EVENT_METHOD_NAME, methodName);
    message.put(JsonConstants.RPC_TEMPLATE_EVENT_ARGS, argsArray);
    if (promiseId != -1) {
        message.put(JsonConstants.RPC_TEMPLATE_EVENT_PROMISE, promiseId);
    }
    sendMessage(message);
}
 
Example 17
Source Project: flow   Source File: TaskRunNpmInstallTest.java    License: 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 18
Source Project: vaadin-chartjs   Source File: LegendLabel.java    License: 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 19
Source Project: flow   Source File: MapSyncRpcHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
private static JsonObject createSyncPropertyInvocation(StateNode node,
        String property, Serializable value) {
    // Copied from ServerConnector
    JsonObject message = Json.createObject();
    message.put(JsonConstants.RPC_NODE, node.getId());
    message.put(JsonConstants.RPC_FEATURE,
            NodeFeatureRegistry.getId(ElementPropertyMap.class));
    message.put(JsonConstants.RPC_PROPERTY, property);
    message.put(JsonConstants.RPC_PROPERTY_VALUE,
            JsonCodec.encodeWithoutTypeInfo(value));

    return message;
}
 
Example 20
Source Project: flow   Source File: ServerEventObject.java    License: 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 21
Source Project: flow   Source File: PolymerServerEventHandlersTest.java    License: Apache License 2.0 5 votes vote down vote up
private JreJsonArray extractParametersData(Method method) {
    ConstantPoolKey parametersData = (ConstantPoolKey) stateNode
            .getFeature(PolymerEventListenerMap.class)
            .get(method.getName());
    assertNotNull(parametersData);

    JsonObject json = Json.createObject();
    parametersData.export(json);
    return json.get(parametersData.getId());
}
 
Example 22
Source Project: flow   Source File: JsonSerializer.java    License: Apache License 2.0 5 votes vote down vote up
private static JsonArray toJsonArray(Object javaArray) {
    int length = Array.getLength(javaArray);
    JsonArray array = Json.createArray();
    for (int i = 0; i < length; i++) {
        array.set(i, toJson(Array.get(javaArray, i)));
    }
    return array;
}
 
Example 23
Source Project: flow   Source File: GwtMessageHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testMessageProcessing_dynamicDependencyIsHandledBeforeApplyingChangesToTree() {
    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_TYPE, Dependency.Type.DYNAMIC_IMPORT.toString());
    dep.put(Dependency.KEY_URL, "return new Promise(function(resolve){ "
            + "window.testEvents.push('test-dependency'); resolve(); });");
    array.set(0, dep);

    obj.put(LoadMode.LAZY.toString(), array);

    handler.handleJSON(object.cast());

    delayTestFinish(500);

    new Timer() {
        @Override
        public void run() {
            assertEquals("test-dependency", getInternalEvent(0));
            assertEquals(StateTree.class.getName(), getInternalEvent(1));
            finishTest();
        }
    }.schedule(100);
}
 
Example 24
Source Project: flow   Source File: StringToNumberDecoderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void stringToLong_convertableString_valueIsConverted()
        throws RpcDecodeException {
    Long expected = 37l;
    Long value = decoder.decode(Json.create(String.valueOf(expected)),
            Long.class);
    Assert.assertEquals(expected, value);
}
 
Example 25
Source Project: flow   Source File: BuildFrontendMojoTest.java    License: 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 26
Source Project: vaadin-chartjs   Source File: TimeDisplayFormats.java    License: 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;
}
 
Example 27
Source Project: flow   Source File: JsonUtils.java    License: 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 28
Source Project: flow   Source File: ElementDataTest.java    License: 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 29
Source Project: flow   Source File: StringToNumberDecoderTest.java    License: 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 30
Source Project: flow   Source File: JsonUtilsTest.java    License: 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());
}