Java源码示例:elemental.json.JsonValue
示例1
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;
}
示例2
/**
* 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);
}
示例3
/**
* 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());
}
}
示例4
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);
}
示例5
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;
}
示例6
@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;
}
示例7
@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;
}
示例8
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);
}
示例9
@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();
}
}
示例10
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());
}
}
示例11
/**
* 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);
}
}
示例12
@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;
}
示例13
/**
* 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());
}
}
示例14
@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;
});
}
示例15
/**
* 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");
}
示例16
/**
* 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;
}
}
示例17
@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;
});
}
示例18
@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);
}
示例19
@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);
}
示例20
public void handleCallback(JsonArray arguments) {
JsonArray attributeChanges = arguments.getArray(1);
for (int i = 0; i < attributeChanges.length(); i++) {
JsonArray attributeChange = attributeChanges.getArray(i);
int id = (int) attributeChange.getNumber(0);
String attribute = attributeChange.getString(1);
JsonValue value = attributeChange.get(2);
NodeImpl target = idToNode.get(Integer.valueOf(id));
if (value.getType() == JsonType.NULL) {
target.node.removeAttr(attribute);
} else {
target.node.attr(attribute, value.asString());
}
}
JsonArray callbacks = arguments.getArray(0);
for (int i = 0; i < callbacks.length(); i++) {
JsonArray call = callbacks.getArray(i);
int elementId = (int) call.getNumber(0);
int cid = (int) call.getNumber(1);
JsonArray params = call.getArray(2);
ElementImpl element = (ElementImpl) idToNode
.get(Integer.valueOf(elementId));
if (element == null) {
System.out.println(cid + " detached?");
return;
}
JavaScriptFunction callback = element.getCallback(cid);
callback.call(params);
}
}
示例21
@Before
public void init() {
MockitoAnnotations.initMocks(this);
ui = new MockUI();
element = new Element("div");
ui.getElement().appendChild(element);
lastClear = null;
lastSet = null;
lastUpdateId = -1;
update = new ArrayUpdater.Update() {
@Override
public void clear(int start, int length) {
lastClear = Range.withLength(start, length);
}
@Override
public void set(int start, List<JsonValue> items) {
lastSet = Range.withLength(start, items.size());
}
@Override
public void commit(int updateId) {
lastUpdateId = updateId;
}
};
Mockito.when(arrayUpdater.startUpdate(Mockito.anyInt()))
.thenReturn(update);
dataCommunicator = new DataCommunicator<>(dataGenerator, arrayUpdater,
data -> {
}, element.getNode());
pageSize = 50;
dataCommunicator.setPageSize(pageSize);
}
示例22
/**
* 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);
}
}
示例23
@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()));
}
示例24
@Test
public void testAsArray() {
Stream<JsonValue> stream = JsonUtils.stream(createTestArray1());
JsonArray array = stream.collect(JsonUtils.asArray());
Assert.assertTrue(JsonUtils.jsonEquals(createTestArray1(), array));
}
示例25
@Test
public void serializeEmptyObjectWithBasicCollections_returnJsonObjectWithNullProperties() {
ObjectWithBasicCollections bean = new ObjectWithBasicCollections();
/*
* private List<String> listOfStrings; private Set<Integer>
* setOfIntegers; private LinkedList<Boolean> linkedListOfBooleans;
* private ArrayList<Double> arrayListOfDoubles;
*
*/
JsonValue json = JsonSerializer.toJson(bean);
Assert.assertTrue("The JsonValue should be instanceof JsonObject",
json instanceof JsonObject);
JsonObject jsonObject = (JsonObject) json;
Assert.assertTrue(jsonObject.hasKey("listOfStrings"));
Assert.assertTrue(jsonObject.get("listOfStrings") instanceof JsonNull);
Assert.assertTrue(jsonObject.hasKey("setOfIntegers"));
Assert.assertTrue(jsonObject.get("setOfIntegers") instanceof JsonNull);
Assert.assertTrue(jsonObject.hasKey("linkedListOfBooleans"));
Assert.assertTrue(
jsonObject.get("linkedListOfBooleans") instanceof JsonNull);
Assert.assertTrue(jsonObject.hasKey("arrayListOfDoubles"));
Assert.assertTrue(
jsonObject.get("arrayListOfDoubles") instanceof JsonNull);
bean = JsonSerializer.toObject(ObjectWithBasicCollections.class, json);
Assert.assertNotNull("The deserialized object should not be null",
bean);
Assert.assertNull(bean.getListOfStrings());
Assert.assertNull(bean.getSetOfIntegers());
Assert.assertNull(bean.getLinkedListOfBooleans());
Assert.assertNull(bean.getArrayListOfDoubles());
}
示例26
private static void doHandleListChange(ListSpliceEvent event,
JsonValue value) {
JsArray<?> add = event.getAdd();
int index = event.getIndex();
int remove = event.getRemove().length();
StateNode node = event.getSource().getNode();
StateNode root = getFirstParentWithDomNode(node);
if (root == null) {
Console.warn("Root node for node " + node.getId()
+ " could not be found");
return;
}
JsArray<Object> array = JsCollections.array();
add.forEach(item -> array.push(createModelTree(item)));
if (isPolymerElement((Element) root.getDomNode())) {
String path = getNotificationPath(root, node, null);
if (path != null) {
splice((Element) root.getDomNode(), path, index, remove,
WidgetUtil.crazyJsoCast(array));
return;
}
}
@SuppressWarnings("unchecked")
JsArray<Object> payload = (JsArray<Object>) value;
payload.spliceArray(index, remove, array);
}
示例27
private void collectDeps(JsonObject target, JsonObject dep) {
if (!dep.hasKey(DEPENDENCIES)) {
return;
}
JsonObject deps = dep.get(DEPENDENCIES);
for (String key : deps.keys()) {
JsonValue value = deps.get(key);
if (value instanceof JsonObject) {
addDependency(target, key, (JsonObject) value);
collectDeps(target, (JsonObject) value);
}
}
}
示例28
private static <P extends JsonValue> TypeHandler<P> getHandler(
Class<P> type) {
ElementGetter<P> getter = (element, property, defaultValue) -> {
Serializable value = element.getPropertyRaw(property);
// JsonValue is passed straight through, other primitive
// values are jsonified
return type.cast(JsonCodec.encodeWithoutTypeInfo(value));
};
ElementSetter<P> setter = (element, property, value) -> element
.setPropertyJson(property, value);
return new TypeHandler<P>(setter, getter, null);
}
示例29
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;
}
示例30
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();
}