elemental.json.JsonValue Java Examples
The following examples show how to use
elemental.json.JsonValue.
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: JsonCodec.java From flow with Apache License 2.0 | 6 votes |
/** * Helper for encoding any "primitive" value that is directly supported in * JSON. Supported values types are {@link String}, {@link Number}, * {@link Boolean}, {@link JsonValue}. <code>null</code> is also supported. * * @param value * the value to encode * @return the value encoded as JSON */ public static JsonValue encodeWithoutTypeInfo(Object value) { if (value == null) { return Json.createNull(); } assert canEncodeWithoutTypeInfo(value.getClass()); Class<?> type = value.getClass(); if (String.class.equals(value.getClass())) { return Json.create((String) value); } else if (Integer.class.equals(type) || Double.class.equals(type)) { return Json.create(((Number) value).doubleValue()); } else if (Boolean.class.equals(type)) { return Json.create(((Boolean) value).booleanValue()); } else if (JsonValue.class.isAssignableFrom(type)) { return (JsonValue) value; } assert !canEncodeWithoutTypeInfo(type); throw new IllegalArgumentException( "Can't encode " + value.getClass() + " to json"); }
Example #2
Source File: ListAddChange.java From flow with Apache License 2.0 | 6 votes |
@Override protected void populateJson(JsonObject json, ConstantPool constantPool) { json.put(JsonConstants.CHANGE_TYPE, JsonConstants.CHANGE_TYPE_SPLICE); super.populateJson(json, constantPool); json.put(JsonConstants.CHANGE_SPLICE_INDEX, getIndex()); Function<Object, JsonValue> mapper; String addKey; if (nodeValues) { addKey = JsonConstants.CHANGE_SPLICE_ADD_NODES; mapper = item -> Json.create(((StateNode) item).getId()); } else { addKey = JsonConstants.CHANGE_SPLICE_ADD; mapper = item -> JsonCodec.encodeWithConstantPool(item, constantPool); } JsonArray newItemsJson = newItems.stream().map(mapper) .collect(JsonUtils.asArray()); json.put(addKey, newItemsJson); }
Example #3
Source File: MapPutChangeTest.java From flow with Apache License 2.0 | 6 votes |
@Test public void testJsonValueTypes() { JsonValue stringValue = getValue("string"); Assert.assertSame(JsonType.STRING, stringValue.getType()); Assert.assertEquals("string", stringValue.asString()); JsonValue numberValue = getValue(Integer.valueOf(1)); Assert.assertSame(JsonType.NUMBER, numberValue.getType()); Assert.assertEquals(1, numberValue.asNumber(), 0); JsonValue booleanValue = getValue(Boolean.TRUE); Assert.assertSame(JsonType.BOOLEAN, booleanValue.getType()); Assert.assertTrue(booleanValue.asBoolean()); JsonObject jsonInput = Json.createObject(); JsonValue jsonValue = getValue(jsonInput); Assert.assertSame(JsonType.OBJECT, jsonValue.getType()); Assert.assertSame(jsonInput, jsonValue); }
Example #4
Source File: WebComponentBinding.java From flow with Apache License 2.0 | 6 votes |
/** * Adds a property to {@code this} web component binding based on the {@code * propertyConfiguration}. If a property with an existing name is bound, the * previous binding is removed. * * @param propertyConfiguration * property configuration, not {@code null} * @param overrideDefault * set to {@code true} if the property should be initialized * with {@code startingValue} instead of default value found * in {@link PropertyData} * @param startingValue * starting value for the property. Can be {@code null}. * {@code overrideDefault} must be {@code true} for this value to * have any effect * @throws NullPointerException * if {@code propertyConfiguration} is {@code null} */ public void bindProperty( PropertyConfigurationImpl<C, ? extends Serializable> propertyConfiguration, boolean overrideDefault, JsonValue startingValue) { Objects.requireNonNull(propertyConfiguration, "Parameter 'propertyConfiguration' cannot be null!"); final SerializableBiConsumer<C, Serializable> consumer = propertyConfiguration .getOnChangeHandler(); final Serializable selectedStartingValue = !overrideDefault ? propertyConfiguration.getPropertyData().getDefaultValue() : jsonValueToConcreteType(startingValue, propertyConfiguration.getPropertyData().getType()); final PropertyBinding<? extends Serializable> binding = new PropertyBinding<>( propertyConfiguration.getPropertyData(), consumer == null ? null : value -> consumer.accept(component, value), selectedStartingValue); properties.put(propertyConfiguration.getPropertyData().getName(), binding); }
Example #5
Source File: WebComponentGenerator.java From flow with Apache License 2.0 | 6 votes |
/** * Gets JavaScript type name for * {@link com.vaadin.flow.server.webcomponent.PropertyData} for usage in * generated JavaScript code. * * @return the type for JS */ private static String getJSTypeName(PropertyData<?> propertyData) { if (propertyData.getType() == Boolean.class) { return "Boolean"; } else if (propertyData.getType() == Double.class || propertyData.getType() == Integer.class) { return "Number"; } else if (propertyData.getType() == String.class) { return "String"; } else if (JsonArray.class.isAssignableFrom(propertyData.getType())) { return "Array"; } else if (JsonValue.class.isAssignableFrom(propertyData.getType())) { return "Object"; } else { throw new IllegalStateException( "Unsupported type: " + propertyData.getType()); } }
Example #6
Source File: GwtPolymerModelTest.java From flow with Apache License 2.0 | 6 votes |
public void testPolymerUtilsStoreNodeIdNotAvailableAsListItem() { nextId = 98; List<String> serverList = Arrays.asList("one", "two"); StateNode andAttachNodeWithList = createAndAttachNodeWithList(modelNode, serverList); JsonValue jsonValue = PolymerUtils .createModelTree(andAttachNodeWithList); assertTrue( "Expected instance of JsonObject from converter, but was not.", jsonValue instanceof JsonObject); double nodeId = ((JsonObject) jsonValue).getNumber("nodeId"); assertFalse( "JsonValue array contained nodeId even though it shouldn't be visible", jsonValue.toJson().contains(Double.toString(nodeId))); assertEquals("Found nodeId didn't match the set nodeId", 98.0, nodeId); }
Example #7
Source File: PublishedServerEventHandlerRpcHandler.java From flow with Apache License 2.0 | 6 votes |
private static JsonArray unwrapVarArgs(JsonArray argsFromClient, Method method) { int paramCount = method.getParameterCount(); if (argsFromClient.length() == paramCount) { if (argsFromClient.get(paramCount - 1).getType() .equals(JsonType.ARRAY)) { return argsFromClient; } } JsonArray result = Json.createArray(); JsonArray rest = Json.createArray(); int newIndex = 0; for (int i = 0; i < argsFromClient.length(); i++) { JsonValue value = argsFromClient.get(i); if (i < paramCount - 1) { result.set(i, value); } else { rest.set(newIndex, value); newIndex++; } } result.set(paramCount - 1, rest); return result; }
Example #8
Source File: PendingJavaScriptInvocationTest.java From flow with Apache License 2.0 | 6 votes |
@Test public void blockFromSessionThreadAfterCompleting_doesNotThrow() throws Exception { MockVaadinSession session = new MockVaadinSession(); session.runWithLock(() -> { CompletableFuture<JsonValue> completableFuture = invocation .toCompletableFuture(); JsonObject value = Json.createObject(); invocation.complete(value); for (Callable<JsonValue> action : createBlockingActions( completableFuture)) { JsonValue actionValue = action.call(); Assert.assertSame(value, actionValue); } return null; }); }
Example #9
Source File: AbstractSinglePropertyField.java From flow with Apache License 2.0 | 6 votes |
@SuppressWarnings({ "unchecked", "rawtypes" }) private <P> TypeHandler<P> findHandler(Class<P> clazz) { TypeHandler<P> typeHandler = (TypeHandler<P>) typeHandlers.get(clazz); if (typeHandler == null && JsonValue.class.isAssignableFrom(clazz)) { typeHandler = getHandler((Class) clazz); } if (typeHandler == null) { throw new IllegalArgumentException( "Unsupported element property type: " + clazz.getName() + ". Supported types are: " + typeHandlers.keySet().parallelStream() .map(Class::getName) .collect(Collectors.joining(", "))); } return typeHandler; }
Example #10
Source File: NodeMap.java From flow with Apache License 2.0 | 6 votes |
@Override public JsonValue getDebugJson() { JsonObject json = WidgetUtil.createJsonObject(); properties.forEach((p, n) -> { if (p.hasValue()) { json.put(n, getAsDebugJson(p.getValue())); } }); if (json.keys().length == 0) { return null; } return json; }
Example #11
Source File: JsonSerializerTest.java From flow with Apache License 2.0 | 6 votes |
@Test public void serializePopulatedRecursiveObject_returnJsonObjectWithPopulatedProperties() { final int recursions = 10; RecursiveObject bean = createRecusiveObject(recursions, 0); JsonValue json = JsonSerializer.toJson(bean); Assert.assertTrue("The JsonValue should be instanceof JsonObject", json instanceof JsonObject); JsonObject object = ((JsonObject) json); for (int i = 0; i < recursions; i++) { Assert.assertEquals(i, object.getNumber("index"), PRECISION); if (i < recursions - 1) { object = object.getObject("recursive"); } else { Assert.assertTrue(object.get("recursive") instanceof JsonNull); } } bean = JsonSerializer.toObject(RecursiveObject.class, json); for (int i = 0; i < recursions; i++) { Assert.assertEquals(i, bean.getIndex()); bean = bean.getRecursive(); } }
Example #12
Source File: JsonCodec.java From flow with Apache License 2.0 | 6 votes |
/** * Helper for decoding any "primitive" value that is directly supported in * JSON. Supported values types are {@link String}, {@link Number}, * {@link Boolean}, {@link JsonValue}. <code>null</code> is also supported. * * @param json * the JSON value to decode * @return the decoded value */ public static Serializable decodeWithoutTypeInfo(JsonValue json) { assert json != null; switch (json.getType()) { case BOOLEAN: return decodeAs(json, Boolean.class); case STRING: return decodeAs(json, String.class); case NUMBER: return decodeAs(json, Double.class); case NULL: return null; default: return json; } }
Example #13
Source File: ElementListenerMap.java From flow with Apache License 2.0 | 6 votes |
public JsonValue toJson() { if (debounceSettings.isEmpty()) { return Json.create(false); } else if (debounceSettings.size() == 1 && debounceSettings.containsKey(Integer.valueOf(0))) { // Shorthand if only debounce is a dummy filter debounce return Json.create(true); } else { // [[timeout1, phase1, phase2, ...], [timeout2, phase1, ...]] return debounceSettings.entrySet().stream() .map(entry -> Stream .concat(Stream.of( Json.create(entry.getKey().intValue())), entry.getValue().stream() .map(DebouncePhase::getIdentifier) .map(Json::create)) .collect(JsonUtils.asArray())) .collect(JsonUtils.asArray()); } }
Example #14
Source File: ClientJsonCodec.java From flow with Apache License 2.0 | 6 votes |
/** * Decodes a value encoded on the server using * {@link JsonCodec#encodeWithTypeInfo(Object)}. * * @param tree * the state tree to use for resolving nodes and elements * @param json * the JSON value to decode * @return the decoded value */ public static Object decodeWithTypeInfo(StateTree tree, JsonValue json) { if (json.getType() == JsonType.ARRAY) { JsonArray array = (JsonArray) json; int typeId = (int) array.getNumber(0); switch (typeId) { case JsonCodec.NODE_TYPE: { int nodeId = (int) array.getNumber(1); Node domNode = tree.getNode(nodeId).getDomNode(); return domNode; } case JsonCodec.ARRAY_TYPE: return jsonArrayAsJsArray(array.getArray(1)); case JsonCodec.RETURN_CHANNEL_TYPE: return createReturnChannelCallback((int) array.getNumber(1), (int) array.getNumber(2), tree.getRegistry().getServerConnector()); default: throw new IllegalArgumentException( "Unsupported complex type in " + array.toJson()); } } else { return decodeWithoutTypeInfo(json); } }
Example #15
Source File: NodeMap.java From flow with Apache License 2.0 | 6 votes |
@Override public JsonValue convert(Function<Object, JsonValue> converter) { JsonObject json = WidgetUtil.createJsonObject(); properties.forEach((property, name) -> { if (property.hasValue()) { // Crazy cast since otherwise SDM fails for string values since // String is not a JSO JsonValue jsonValue = WidgetUtil .crazyJsoCast(converter.apply(property.getValue())); json.put(name, jsonValue); } }); return json; }
Example #16
Source File: JavaScriptSemantics.java From flow with Apache License 2.0 | 6 votes |
/** * Gets the boolean value of the provided value: * <ul> * <li><code>null</code> is <code>false</code>. * <li>String values are <code>true</code>, except for the empty string. * <li>Numerical values are <code>true</code>, except for 0 and * <code>NaN</code>. * <li>JSON object and JSON array values are always <code>true</code>. * </ul> * * @param value * the value to check for truthness * @return <code>true</code> if the provided value is trueish according to * JavaScript semantics, otherwise <code>false</code> */ public static boolean isTrueish(Object value) { if (value == null) { return false; } else if (value instanceof Boolean) { return ((Boolean) value).booleanValue(); } else if (value instanceof JsonValue) { return ((JsonValue) value).asBoolean(); } else if (value instanceof Number) { double number = ((Number) value).doubleValue(); // Special comparison to keep sonarqube happy return !Double.isNaN(number) && Double.doubleToLongBits(number) != 0; } else if (value instanceof String) { return !((String) value).isEmpty(); } else { throw new IllegalStateException( "Unsupported type: " + value.getClass()); } }
Example #17
Source File: PendingJavaScriptInvocationTest.java From flow with Apache License 2.0 | 6 votes |
@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 #18
Source File: PolymerUtils.java From flow with Apache License 2.0 | 6 votes |
private static void doHandlePropertyChange(MapProperty property, JsonValue value) { String propertyName = property.getName(); StateNode node = property.getMap().getNode(); StateNode root = getFirstParentWithDomNode(node); if (root == null) { Console.warn("Root node for node " + node.getId() + " could not be found"); return; } JsonValue modelTree = createModelTree(property.getValue()); if (isPolymerElement((Element) root.getDomNode())) { String path = getNotificationPath(root, node, propertyName); if (path != null) { setProperty((Element) root.getDomNode(), path, modelTree); } return; } WidgetUtil.setJsProperty(value, propertyName, modelTree); }
Example #19
Source File: ElementTest.java From flow with Apache License 2.0 | 6 votes |
private static Element createPropertyAssertElement(Object value) { Element element = ElementFactory.createDiv(); if (value instanceof Number && !(value instanceof Double)) { throw new IllegalArgumentException( "Double is the only accepted numeric type"); } if (value instanceof JsonValue) { element.setPropertyJson("property", (JsonValue) value); } else if (value instanceof Serializable) { BasicElementStateProvider.get().setProperty(element.getNode(), "property", (Serializable) value, true); } else if (value == null) { element.setProperty("property", null); } else { throw new IllegalArgumentException( "Invalid value type: " + value.getClass()); } return element; }
Example #20
Source File: JavaScriptBootstrapHandler.java From flow with Apache License 2.0 | 5 votes |
private JsonValue getErrors() { JsonObject errors = Json.createObject(); DevModeHandler devMode = DevModeHandler.getDevModeHandler(); if (devMode != null) { String errorMsg = devMode.getFailedOutput(); if (errorMsg != null) { errors.put("webpack-dev-server", errorMsg); } } return errors.keys().length > 0 ? errors : Json.createNull(); }
Example #21
Source File: PolymerUtils.java From flow with Apache License 2.0 | 5 votes |
private static void registerPropertyAddHandler(JsonValue value, JsArray<EventRemover> registrations, NodeMap map) { registrations.push(map.addPropertyAddListener(event -> { MapProperty property = event.getProperty(); registrations.push(property.addChangeListener( change -> handlePropertyChange(property, value))); handlePropertyChange(property, value); })); }
Example #22
Source File: WidgetUtil.java From flow with Apache License 2.0 | 5 votes |
private static native String toPrettyJsonJsni(JsonValue value) /*-{ // skip hashCode field return $wnd.JSON.stringify(value, function(keyName, value) { if (keyName == "$H") { return undefined; // skip hashCode property } return value; }, 4); }-*/;
Example #23
Source File: JsonUtilsTest.java From flow with Apache License 2.0 | 5 votes |
@Test public void testStream() { JsonArray array = createTestArray1(); List<JsonValue> list = JsonUtils.stream(array) .collect(Collectors.toList()); Assert.assertEquals(2, list.size()); Assert.assertEquals("foo", list.get(0).asString()); Assert.assertTrue( JsonUtils.jsonEquals(list.get(1), Json.createObject())); }
Example #24
Source File: NodeFeature.java From flow with Apache License 2.0 | 5 votes |
/** * Helper for getting a JSON representation of a child value. * * @param value * the child value * @return the JSON representation */ protected JsonValue getAsDebugJson(Object value) { if (value instanceof StateNode) { StateNode child = (StateNode) value; return child.getDebugJson(); } else { return WidgetUtil.crazyJsoCast(value); } }
Example #25
Source File: TreeChangeProcessorTest.java From flow with Apache License 2.0 | 5 votes |
private static JsonObject spliceChange(int node, int ns, int index, int remove, JsonValue... add) { JsonObject json = spliceBaseChange(node, ns, index, remove); if (add != null && add.length != 0) { json.put(JsonConstants.CHANGE_SPLICE_ADD, toArray(add)); } return json; }
Example #26
Source File: JsonUtils.java From flow with Apache License 2.0 | 5 votes |
@Override public BinaryOperator<JsonArray> combiner() { return (left, right) -> { for (int i = 0; i < right.length(); i++) { left.set(left.length(), right.<JsonValue> get(i)); } return left; }; }
Example #27
Source File: JsonUtilsTest.java From flow with Apache License 2.0 | 5 votes |
@Test public void testAsArray() { Stream<JsonValue> stream = JsonUtils.stream(createTestArray1()); JsonArray array = stream.collect(JsonUtils.asArray()); Assert.assertTrue(JsonUtils.jsonEquals(createTestArray1(), array)); }
Example #28
Source File: JsonCodecTest.java From flow with Apache License 2.0 | 5 votes |
@Test public void decodeAs_stringJson() { JsonString json = Json.create("Test123 String\n !%"); Assert.assertTrue(JsonCodec.decodeAs(json, Boolean.class)); Assert.assertEquals("Test123 String\n !%", JsonCodec.decodeAs(json, String.class)); Assert.assertEquals(Integer.valueOf(0), JsonCodec.decodeAs(json, Integer.class)); Assert.assertTrue(JsonCodec.decodeAs(json, Double.class).isNaN()); Assert.assertEquals(json, JsonCodec.decodeAs(json, JsonValue.class)); }
Example #29
Source File: DomEvent.java From flow with Apache License 2.0 | 5 votes |
private static DebouncePhase extractPhase(JsonObject eventData) { JsonValue jsonValue = eventData.get(JsonConstants.EVENT_DATA_PHASE); if (jsonValue == null) { return DebouncePhase.LEADING; } else { return DebouncePhase.forIdentifier(jsonValue.asString()); } }
Example #30
Source File: MapSyncRpcHandlerTest.java From flow with Apache License 2.0 | 5 votes |
@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); }