Java Code Examples for elemental.json.JsonObject#put()

The following examples show how to use elemental.json.JsonObject#put() . 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: GwtBasicElementBinderTest.java    From flow with Apache License 2.0 6 votes vote down vote up
public void testVirtualChild() {
    Binder.bind(node, element);

    StateNode childNode = createChildNode("child");

    NodeMap elementData = childNode.getMap(NodeFeatures.ELEMENT_DATA);
    JsonObject object = Json.createObject();
    object.put(NodeProperties.TYPE, NodeProperties.IN_MEMORY_CHILD);
    elementData.getProperty(NodeProperties.PAYLOAD).setValue(object);

    NodeList virtialChildren = node.getList(NodeFeatures.VIRTUAL_CHILDREN);
    virtialChildren.add(0, childNode);

    Reactive.flush();

    assertEquals(element.getChildElementCount(), 0);

    Element childElement = (Element) childNode.getDomNode();
    assertEquals("SPAN", childElement.getTagName());
    assertEquals("child", childElement.getId());
}
 
Example 2
Source File: InlineTargets.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Inline contents from classpath file to head of initial page.
 *
 * @param inline
 *            inline dependency to add to bootstrap page
 * @param request
 *            the request that is handled
 */
public void addInlineDependency(Inline inline, VaadinRequest request) {
    Inline.Wrapping type;
    // Determine the type as given or try to automatically decide
    if (inline.wrapping().equals(Inline.Wrapping.AUTOMATIC)) {
        type = determineDependencyType(inline);
    } else {
        type = inline.wrapping();
    }

    JsonObject dependency = Json.createObject();
    dependency.put(Dependency.KEY_TYPE, type.toString());
    dependency.put("LoadMode", LoadMode.INLINE.toString());

    dependency.put(Dependency.KEY_CONTENTS,
            BootstrapUtils.getDependencyContents(request, inline.value()));

    // Add to correct element target
    if (inline.target() == TargetElement.BODY) {
        getInlineBody(inline.position()).add(dependency);
    } else {
        getInlineHead(inline.position()).add(dependency);

    }
}
 
Example 3
Source File: DependencyLoaderTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private JsonObject createInlineDependency(Dependency.Type dependencyType,
        String contents) {
    JsonObject json = new Dependency(dependencyType, "", LoadMode.INLINE)
            .toJson();
    json.remove(Dependency.KEY_URL);
    json.put(Dependency.KEY_CONTENTS, contents);
    return json;
}
 
Example 4
Source File: EventRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private static JsonObject createElementEventInvocation(Element element,
        String eventType, JsonObject eventData) {
    StateNode node = element.getNode();
    // Copied from ServerConnector
    JsonObject message = Json.createObject();
    message.put(JsonConstants.RPC_NODE, node.getId());
    message.put(JsonConstants.RPC_EVENT_TYPE, eventType);

    if (eventData != null) {
        message.put(JsonConstants.RPC_EVENT_DATA, eventData);
    }

    return message;
}
 
Example 5
Source File: JavaScriptBootstrapHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
protected BootstrapContext createAndInitUI(Class<? extends UI> uiClass,
        VaadinRequest request, VaadinResponse response,
        VaadinSession session) {

    BootstrapContext context = super.createAndInitUI(
            JavaScriptBootstrapUI.class, request, response, session);
    JsonObject config = context.getApplicationParameters();

    String requestURL = getRequestUrl(request);
    String serviceUrl = getServiceUrl(request);

    String pushURL = context.getSession().getConfiguration().getPushURL();
    if (pushURL == null) {
        pushURL = serviceUrl;
    } else {
        try {
            URI uri = new URI(serviceUrl);
            pushURL = uri.resolve(new URI(pushURL)).toASCIIString();
        } catch (URISyntaxException exception) {
            throw new IllegalStateException(String.format(
                    "Can't resolve pushURL '%s' based on the service URL '%s'",
                    pushURL, serviceUrl), exception);
        }
    }
    PushConfiguration pushConfiguration = context.getUI()
            .getPushConfiguration();
    pushConfiguration.setPushUrl(pushURL);

    AppShellRegistry registry = AppShellRegistry
            .getInstance(session.getService().getContext());
    registry.modifyPushConfiguration(pushConfiguration);

    config.put("requestURL", requestURL);

    return context;
}
 
Example 6
Source File: JsonCodecTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeAs_jsonValue() {
    JsonObject json = Json.createObject();
    json.put("foo", "bar");
    Assert.assertEquals("[object Object]",
            JsonCodec.decodeAs(json, String.class));
    Assert.assertEquals(json, JsonCodec.decodeAs(json, JsonValue.class));
    // boolean
    Assert.assertTrue(JsonCodec.decodeAs(json, Boolean.class));
    Assert.assertNull(JsonCodec.decodeAs(Json.createNull(), Boolean.class));
    Assert.assertTrue(JsonCodec.decodeAs(json, boolean.class));
    Assert.assertFalse(
            JsonCodec.decodeAs(Json.createNull(), boolean.class));
    // integer
    Assert.assertEquals(Integer.valueOf(0),
            JsonCodec.decodeAs(json, Integer.class));
    Assert.assertNull(JsonCodec.decodeAs(Json.createNull(), Integer.class));
    Assert.assertEquals(Integer.valueOf(0),
            JsonCodec.decodeAs(json, int.class));
    Assert.assertEquals(Integer.valueOf(0),
            JsonCodec.decodeAs(Json.createNull(), int.class));
    //double
    Assert.assertNull(JsonCodec.decodeAs(Json.createNull(), Double.class));
    Assert.assertTrue(JsonCodec.decodeAs(json, Double.class).isNaN());
    Assert.assertTrue(JsonCodec.decodeAs(json, double.class).isNaN());
    Assert.assertEquals(0.0d,
            JsonCodec.decodeAs(Json.createNull(), double.class),
            0.0001d);
}
 
Example 7
Source File: NodeUpdaterTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void updateDefaultDependencies_olderVersionsAreUpdated()
        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",
            "3.3.10");
    nodeUpdater.updateDefaultDependencies(packageJson);

    Assert.assertEquals("4.42.0", packageJson
            .getObject(NodeUpdater.DEV_DEPENDENCIES).getString("webpack"));
}
 
Example 8
Source File: UidlWriter.java    From flow with Apache License 2.0 5 votes vote down vote up
private static JsonObject dependencyToJson(Dependency dependency,
        ResolveContext context) {
    JsonObject dependencyJson = dependency.toJson();
    if (dependency.getLoadMode() == LoadMode.INLINE) {
        dependencyJson.put(Dependency.KEY_CONTENTS,
                getDependencyContents(dependency.getUrl(), context));
        dependencyJson.remove(Dependency.KEY_URL);
    }
    return dependencyJson;
}
 
Example 9
Source File: TreeChangeProcessorTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private static JsonObject mapBaseChange(int node, int ns, String type,
        String key) {
    JsonObject json = baseChange(node, type);
    json.put(JsonConstants.CHANGE_FEATURE, ns);
    json.put(JsonConstants.CHANGE_MAP_KEY, key);
    return json;
}
 
Example 10
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 11
Source File: EventRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void testElementEventData() throws Exception {
    TestComponent c = new TestComponent();
    Element element = c.getElement();
    UI ui = new UI();
    ui.add(c);
    AtomicInteger invocationData = new AtomicInteger(0);

    element.addEventListener("test-event", e -> invocationData
            .addAndGet((int) e.getEventData().getNumber("nr")));
    JsonObject eventData = Json.createObject();
    eventData.put("nr", 123);
    sendElementEvent(element, ui, "test-event", eventData);
    Assert.assertEquals(123, invocationData.get());
}
 
Example 12
Source File: TreeChangeProcessorTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private static JsonObject putChange(int node, int ns, String key,
        JsonValue value) {
    JsonObject json = mapBaseChange(node, ns, JsonConstants.CHANGE_TYPE_PUT,
            key);
    json.put(JsonConstants.CHANGE_PUT_VALUE, value);

    return json;
}
 
Example 13
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 14
Source File: TaskRunNpmInstall.java    From flow with Apache License 2.0 5 votes vote down vote up
private JsonObject getVersions(InputStream platformVersions)
        throws IOException {
    JsonObject versionsJson = null;
    if (platformVersions != null) {
        VersionsJsonConverter convert = new VersionsJsonConverter(
                Json.parse(IOUtils.toString(platformVersions,
                        StandardCharsets.UTF_8)));
        versionsJson = convert.getConvertedJson();
        versionsJson = new VersionsJsonFilter(
                packageUpdater.getPackageJson(), NodeUpdater.DEPENDENCIES)
                        .getFilteredVersions(versionsJson);
    }

    String genDevDependenciesPath = getDevDependenciesFilePath();
    if (genDevDependenciesPath == null) {
        packageUpdater.log().error(
                "Couldn't find dev dependencies file path from proeprties file. "
                        + "Dev dependencies won't be locked");
        return versionsJson;
    }
    JsonObject devDeps = readGeneratedDevDependencies(
            genDevDependenciesPath);
    if (devDeps == null) {
        return versionsJson;
    }
    devDeps = new VersionsJsonFilter(packageUpdater.getPackageJson(),
            NodeUpdater.DEV_DEPENDENCIES).getFilteredVersions(devDeps);
    if (versionsJson == null) {
        return devDeps;
    }
    for (String key : versionsJson.keys()) {
        devDeps.put(key, versionsJson.getString(key));
    }
    return devDeps;
}
 
Example 15
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 16
Source File: MapSyncRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void syncJSON_jsonIsPropertyValueOfStateNode_propertySetToNode()
        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();

    // Set model value directly via ElementPropertyMap
    ElementPropertyMap propertyMap = node
            .getFeature(ElementPropertyMap.class);
    propertyMap.setUpdateFromClientFilter(name -> true);

    ElementPropertyMap modelMap = propertyMap.resolveModelMap("foo");
    // fake StateNode has been created for the model
    StateNode model = modelMap.getNode();
    modelMap.setProperty("bar", "baz");

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

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

    Serializable testPropertyValue = propertyMap.getProperty("foo");

    Assert.assertTrue(testPropertyValue instanceof StateNode);

    StateNode newNode = (StateNode) testPropertyValue;
    Assert.assertSame(model, newNode);
}
 
Example 17
Source File: WebComponent.java    From flow with Apache License 2.0 4 votes vote down vote up
/**
 * Fires a custom event on the client-side originating from the web
 * component with custom event data. Allows modifying the default event
 * behavior with {@link EventOptions}.
 *
 * @param eventName
 *         name of the event, not null
 * @param objectData
 *         data the event should carry. This data is placed as the {@code
 *         detail} property of the event, nullable
 * @param options
 *         event options for {@code bubbles}, {@code cancelable}, and {@code
 *         composed} flags, not null
 * @throws NullPointerException
 *         if either {@code eventName} or {@code options} is {@code null}
 */
public void fireEvent(String eventName, JsonValue objectData, EventOptions options) {
    Objects.requireNonNull(eventName, "Parameter 'eventName' must not be " +
            "null!");
    Objects.requireNonNull(options, "Parameter 'options' must not be null");

    JsonObject object = Json.createObject();
    object.put("bubbles", options.isBubbles());
    object.put("cancelable", options.isCancelable());
    object.put("composed", options.isComposed());
    object.put("detail", objectData == null ?
            Json.createNull() : objectData);

    componentHost.executeJs(String.format(CUSTOM_EVENT,
            object.toJson()), eventName);
}
 
Example 18
Source File: JsonSerializer.java    From flow with Apache License 2.0 4 votes vote down vote up
/**
 * Converts a Java bean, {@link JsonSerializable} instance, String, wrapper
 * of primitive type or enum to a {@link JsonValue}.
 * <p>
 * When a bean is used, a {@link JsonObject} is returned.
 * 
 * @param bean
 *            Java object to be converted
 * @return the json representation of the Java object
 */
public static JsonValue toJson(Object bean) {
    if (bean == null) {
        return Json.createNull();
    }
    if (bean instanceof Collection) {
        return toJson((Collection<?>) bean);
    }
    if (bean.getClass().isArray()) {
        return toJsonArray(bean);
    }
    if (bean instanceof JsonSerializable) {
        return ((JsonSerializable) bean).toJson();
    }

    Optional<JsonValue> simpleType = tryToConvertToSimpleType(bean);
    if (simpleType.isPresent()) {
        return simpleType.get();
    }

    try {
        JsonObject json = Json.createObject();
        BeanInfo info = Introspector.getBeanInfo(bean.getClass());
        for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
            if ("class".equals(pd.getName())) {
                continue;
            }
            Method reader = pd.getReadMethod();
            if (reader != null) {
                json.put(pd.getName(), toJson(reader.invoke(bean)));
            }
        }

        return json;
    } catch (Exception e) {
        throw new IllegalArgumentException(
                "Could not serialize object of type " + bean.getClass()
                        + " to JsonValue",
                e);
    }
}
 
Example 19
Source File: LockDevDepVersionsMojo.java    From flow with Apache License 2.0 4 votes vote down vote up
private void addDependency(JsonObject target, String name, JsonObject dep) {
    if (dep.hasKey(VERSION)) {
        String version = dep.getString(VERSION);
        target.put(name, version);
    }
}
 
Example 20
Source File: BootstrapHandler.java    From flow with Apache License 2.0 2 votes vote down vote up
/**
 * Writes the push id (and generates one if needed) to the given JSON
 * object.
 *
 * @param response
 *            the response JSON object to write security key into
 * @param session
 *            the vaadin session to which the security key belongs
 */
private static void writePushIdUIDL(JsonObject response,
        VaadinSession session) {
    String pushId = session.getPushId();
    response.put(ApplicationConstants.UIDL_PUSH_ID, pushId);
}