elemental.json.JsonObject Java Examples

The following examples show how to use elemental.json.JsonObject. 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: CubaMultiSelectionModelConnector.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public void onClick(GridClickEvent event) {
    SelectionModel<JsonObject> selectionModel = grid.getSelectionModel();
    if (!(selectionModel instanceof MultiSelectionModel)) {
        return;
    }

    //noinspection unchecked
    MultiSelectionModel model = (MultiSelectionModel) selectionModel;
    CellReference<JsonObject> cell = grid.getEventCell();

    if (!event.isShiftKeyDown() || previous < 0) {
        handleCtrlClick(model, cell, event);
        previous = cell.getRowIndex();
        return;
    }

    // This works on the premise that grid fires the data available event to
    // any newly added handlers.
    boolean ctrlOrMeta = event.isControlKeyDown() || event.isMetaKeyDown();
    handler = grid.addDataAvailableHandler(new ShiftSelector(cell, model, ctrlOrMeta));
}
 
Example #2
Source File: UidlRequestHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void should_modifyUidl_when_MPR_JavaScriptBootstrapUI() throws Exception {
    JavaScriptBootstrapUI ui = mock(JavaScriptBootstrapUI.class);

    UidlRequestHandler handler = spy(new UidlRequestHandler());
    StringWriter writer = new StringWriter();

    JsonObject uidl = generateUidl(true, true);
    doReturn(uidl).when(handler).createUidl(ui, false);

    handler.writeUidl(ui, writer, false);

    String out = writer.toString();
    uidl = JsonUtil.parse(out.substring(9, out.length() - 1));

    String v7Uidl = uidl.getArray("execute").getArray(2).getString(1);
    assertFalse(v7Uidl.contains("http://localhost:9998/#!away"));
    assertTrue(v7Uidl.contains("http://localhost:9998/"));
    assertFalse(v7Uidl.contains("window.location.hash = '!away';"));
}
 
Example #3
Source File: ListAddChange.java    From flow with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: VersionsJsonFilter.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Collect all dependencies that the user has changed that do not match the
 * flow managed dependency versions.
 *
 * @param packageJson
 *            package.json Json object
 * @return collection of user managed dependencies
 */
private JsonObject collectUserManagedDependencies(JsonObject packageJson) {
    JsonObject json = Json.createObject();
    JsonObject vaadinDep;
    if (packageJson.hasKey(VAADIN_DEP_KEY) && packageJson
            .getObject(VAADIN_DEP_KEY).hasKey(dependenciesKey)) {
        vaadinDep = packageJson.getObject(VAADIN_DEP_KEY)
                .getObject(dependenciesKey);
    } else {
        vaadinDep = Json.createObject();
    }

    if (packageJson.hasKey(dependenciesKey)) {
        JsonObject dependencies = packageJson.getObject(dependenciesKey);

        for (String key : dependencies.keys()) {
            if (isUserChanged(key, vaadinDep, dependencies)) {
                json.put(key, dependencies.getString(key));
            }
        }
    }

    return json;
}
 
Example #5
Source File: BoxAnnotation.java    From vaadin-chartjs with MIT License 6 votes vote down vote up
@Override
public JsonObject buildJson() {
    JsonObject map = super.buildJson();
    JUtils.putNotNull(map, "xScaleID", xScaleID);
    JUtils.putNotNull(map, "yScaleID", yScaleID);

    JUtils.putNotNullObj(map, "xMin", xMin);
    JUtils.putNotNullObj(map, "xMax", xMax);
    JUtils.putNotNullObj(map, "yMax", yMax);
    JUtils.putNotNullObj(map, "yMin", yMin);

    JUtils.putNotNull(map, "value", value);
    JUtils.putNotNull(map, "endValue", endValue);

    JUtils.putNotNull(map, "borderColor", borderColor);
    JUtils.putNotNull(map, "borderWidth", borderWidth);
    JUtils.putNotNull(map, "backgroundColor", backgroundColor);

    return map;
}
 
Example #6
Source File: ScrollPositionHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
private void onBeforeUnload(Event event) {
    captureCurrentScrollPositions();

    JsonObject stateObject = createStateObjectWithHistoryIndexAndToken();

    JsonObject sessionStorageObject = Json.createObject();
    sessionStorageObject.put(X_POSITIONS,
            convertArrayToJsonArray(xPositions));
    sessionStorageObject.put(Y_POSITIONS,
            convertArrayToJsonArray(yPositions));

    Browser.getWindow().getHistory().replaceState(stateObject, "",
            Browser.getWindow().getLocation().getHref());
    try {
        Browser.getWindow().getSessionStorage().setItem(
                createSessionStorageKey(historyResetToken),
                sessionStorageObject.toJson());
    } catch (JavaScriptException e) {
        Console.error("Failed to get session storage: " + e.getMessage());
    }
}
 
Example #7
Source File: ComponentEventBusTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void domEvent_fireServerEvent() {
    TestComponent component = new TestComponent();
    EventTracker<MappedToDomEvent> eventTracker = new EventTracker<>();
    component.addListener(MappedToDomEvent.class, eventTracker);

    JsonObject eventData = Json.createObject();
    eventData.put("event.someData", 42);
    eventData.put("event.moreData", 1);
    fireDomEvent(component, "dom-event", eventData);

    eventTracker.assertEventCalled(component, true);
    MappedToDomEvent event = eventTracker.getEvent();
    Assert.assertEquals(42, event.getSomeData());
    Assert.assertEquals("1", event.getMoreData());
}
 
Example #8
Source File: TaskRunPnpmInstallTest.java    From flow with Apache License 2.0 6 votes vote down vote up
private JsonObject getGeneratedVersionsContent(File versions, File devDeps)
        throws MalformedURLException, IOException {
    String devDepsPath = "foo";

    ClassFinder classFinder = getClassFinder();
    Mockito.when(classFinder.getResource(Constants.VAADIN_VERSIONS_JSON))
            .thenReturn(versions.toURI().toURL());
    Mockito.when(classFinder.getResource(devDepsPath))
            .thenReturn(devDeps.toURI().toURL());

    TaskRunNpmInstall task = createTaskWithDevDepsLocked(devDepsPath);

    String path = task.generateVersionsJson();

    File generatedVersionsFile = new File(path);
    return Json.parse(FileUtils.readFileToString(generatedVersionsFile,
            StandardCharsets.UTF_8));

}
 
Example #9
Source File: BootstrapHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
private void setupFrameworkLibraries(Element head,
        JsonObject initialUIDL, BootstrapContext context) {

    VaadinService service = context.getSession().getService();
    DeploymentConfiguration conf = service.getDeploymentConfiguration();

    conf.getPolyfills().forEach(
            polyfill -> head.appendChild(createJavaScriptElement(
                    "./" + VAADIN_MAPPING + polyfill, false)));
    try {
        appendNpmBundle(head, service, context);
    } catch (IOException e) {
        throw new BootstrapException(
                "Unable to read webpack stats file.", e);
    }

    if (context.getPushMode().isEnabled()) {
        head.appendChild(
                createJavaScriptElement(getPushScript(context)));
    }

    head.appendChild(getBootstrapScript(initialUIDL, context));
    head.appendChild(
            createJavaScriptElement(getClientEngineUrl(context)));
}
 
Example #10
Source File: ExecuteJavaScriptProcessor.java    From flow with Apache License 2.0 6 votes vote down vote up
private boolean isVirtualChildAwaitingInitialization(StateNode node) {
    if (node.getDomNode() != null
            || node.getTree().getNode(node.getId()) == null) {
        return false;
    }
    if (node.getMap(NodeFeatures.ELEMENT_DATA)
            .hasPropertyValue(NodeProperties.PAYLOAD)) {
        Object value = node.getMap(NodeFeatures.ELEMENT_DATA)
                .getProperty(NodeProperties.PAYLOAD).getValue();
        if (value instanceof JsonObject) {
            JsonObject object = (JsonObject) value;
            String type = object.getString(NodeProperties.TYPE);
            return NodeProperties.INJECT_BY_ID.equals(type)
                    || NodeProperties.TEMPLATE_IN_TEMPLATE.equals(type);
        }
    }
    return false;
}
 
Example #11
Source File: UidlWriter.java    From flow with Apache License 2.0 6 votes vote down vote up
private static void populateDependencies(JsonObject response,
        DependencyList dependencyList, ResolveContext context) {
    Collection<Dependency> pendingSendToClient = dependencyList
            .getPendingSendToClient();

    for (DependencyFilter filter : context.getService()
            .getDependencyFilters()) {
        pendingSendToClient = filter.filter(
                new ArrayList<>(pendingSendToClient), context.getService());
    }

    if (!pendingSendToClient.isEmpty()) {
        groupDependenciesByLoadMode(pendingSendToClient, context)
                .forEach((loadMode, dependencies) -> response
                        .put(loadMode.name(), dependencies));
    }
    dependencyList.clearPendingSendToClient();
}
 
Example #12
Source File: MapPutChangeTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@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 #13
Source File: MapSyncRpcHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
private Serializable tryCopyStateNode(StateNode node,
        JsonObject properties) {
    if (node == null) {
        return properties;
    }

    // Copy only if the request is for a node inside a list
    if (isInList(node)) {
        StateNode copy = new StateNode(node);
        ElementPropertyMap originalProperties = node
                .getFeature(ElementPropertyMap.class);
        ElementPropertyMap copyProperties = copy
                .getFeature(ElementPropertyMap.class);
        originalProperties.getPropertyNames()
                .forEach(property -> copyProperties.setProperty(property,
                        originalProperties.getProperty(property)));
        return copy;
    }
    if (isProperty(node)) {
        return node;
    }
    return properties;
}
 
Example #14
Source File: JsonSerializerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private void assertObjectHasFalseValueForKey(JsonObject object,
        String key) {
    Assert.assertTrue(key + " should be present in the JsonObject",
            object.hasKey(key));
    Assert.assertEquals(key + " should be false in the JsonObject", false,
            object.getBoolean(key));
}
 
Example #15
Source File: Element.java    From vaadin-chartjs with MIT License 5 votes vote down vote up
@Override
public JsonObject buildJson() {
    JsonObject obj = Json.createObject();
    JUtils.putNotNull(obj, "arc", arc);
    JUtils.putNotNull(obj, "line", line);
    JUtils.putNotNull(obj, "point", point);
    JUtils.putNotNull(obj, "rectangle", rectangle);
    return obj;
}
 
Example #16
Source File: GwtBasicElementBinderTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private void addVirtualChild(StateNode shadowRootNode, StateNode childNode,
        String type, JsonValue payload) {
    NodeList virtualChildren = shadowRootNode
            .getList(NodeFeatures.VIRTUAL_CHILDREN);
    JsonObject object = Json.createObject();
    childNode.getMap(NodeFeatures.ELEMENT_DATA)
            .getProperty(NodeProperties.PAYLOAD).setValue(object);
    object.put(NodeProperties.TYPE, type);
    object.put(NodeProperties.PAYLOAD, payload);
    virtualChildren.add(virtualChildren.length(), childNode);
}
 
Example #17
Source File: CubaTreeGridWidget.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
protected String getCustomHtmlAttributes(Column<?, JsonObject> column) {
    if (columnIds != null) {
        Object columnId = (columnIds.get(column));
        if (columnId != null) {
            return "cuba-id=\"" +
                    CUBA_ID_COLUMN_HIDING_TOGGLE_PREFIX +
                    CUBA_ID_COLUMN_PREFIX +
                    columnId + "\"";
        }
    }

    return super.getCustomHtmlAttributes(column);
}
 
Example #18
Source File: ComponentDataGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void generateData(T item, JsonObject jsonObject) {
    /*
     * If no nodeIdPropertyName set do nothing. It is supposed to be set up
     * by setupTemplateWhenAttached which is triggered through
     * setupTemplate.
     */
    if (nodeIdPropertyName == null) {
        return;
    }

    String itemKey = getItemKey(item);
    Component oldRenderedComponent = getRenderedComponent(itemKey);

    int nodeId;
    // If we have a component for the given item use that, else create new
    // component and register it.
    if (oldRenderedComponent != null) {
        nodeId = oldRenderedComponent.getElement().getNode().getId();
    } else {
        Component renderedComponent = createComponent(item);
        registerRenderedComponent(itemKey, renderedComponent);

        nodeId = renderedComponent.getElement().getNode().getId();
    }

    jsonObject.put(nodeIdPropertyName, nodeId);
}
 
Example #19
Source File: TreeChangeProcessor.java    From flow with Apache License 2.0 5 votes vote down vote up
private static void populateFeature(JsonObject change, StateNode node) {
    assert change.hasKey(
            JsonConstants.CHANGE_FEATURE_TYPE) : "Change doesn't contain feature type. Don't know how to populate feature";
    int featureId = (int) change.getNumber(JsonConstants.CHANGE_FEATURE);
    if (change.getBoolean(JsonConstants.CHANGE_FEATURE_TYPE)) {
        // list feature
        node.getList(featureId);
    } else {
        node.getMap(featureId);
    }
}
 
Example #20
Source File: RadarDataset.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", type);
    JUtils.putNotNullNumbers(map, "data", getData());
    JUtils.putNotNull(map, "label", label);

    if (this.fillToPlus != null && this.fillToDatasetIndex != null) {
        JUtils.putNotNull(map, "fill", (this.fillToPlus ? "+":"-") + this.fillToDatasetIndex);
    } else if (this.fillToPlus == null && this.fillToDatasetIndex != null) {
        JUtils.putNotNull(map, "fill", this.fillToDatasetIndex);
    } else if (this.fillMode != null) {
        JUtils.putNotNull(map, "fill", fillMode.name().toLowerCase());
    } else {
        JUtils.putNotNull(map, "fill", fill);
    }

    JUtils.putNotNull(map, "hidden", hidden);
    JUtils.putNotNull(map, "lineTension", lineTension);
    JUtils.putNotNull(map, "backgroundColor", backgroundColor);
    JUtils.putNotNull(map, "borderWidth", borderWidth);
    JUtils.putNotNull(map, "borderColor", borderColor);
    JUtils.putNotNull(map, "borderCapStyle", borderCapStyle);
    JUtils.putNotNullIntList(map, "borderDash", borderDash);
    JUtils.putNotNull(map, "borderDashOffset", borderDashOffset);
    JUtils.putNotNull(map, "borderJoinStyle", borderJoinStyle);
    JUtils.putNotNullStringListOrSingle(map, "pointBorderColor", pointBorderColor);
    JUtils.putNotNullStringListOrSingle(map, "pointBackgroundColor", pointBackgroundColor);
    JUtils.putNotNullIntListOrSingle(map, "pointBorderWidth", pointBorderWidth);
    JUtils.putNotNullIntListOrSingle(map, "pointRadius", pointRadius);
    JUtils.putNotNullIntListOrSingle(map, "pointHoverRadius", pointHoverRadius);
    JUtils.putNotNullIntListOrSingle(map, "hitRadius", hitRadius);
    JUtils.putNotNullStringListOrSingle(map, "pointHoverBackgroundColor", pointHoverBackgroundColor);
    JUtils.putNotNullStringListOrSingle(map, "pointHoverBorderColor", pointHoverBorderColor);
    JUtils.putNotNullIntListOrSingle(map, "pointHoverBorderWidth", pointHoverBorderWidth);
    if (pointStyle != null) {
        JUtils.putNotNull(map, "pointStyle", pointStyle.name());
    }
    return map;
}
 
Example #21
Source File: Point.java    From vaadin-chartjs with MIT License 5 votes vote down vote up
@Override
public JsonObject buildJson() {
    JsonObject map = Json.createObject();
    JUtils.putNotNull(map, "radius", radius);
    if (pointStyle != null) {
        JUtils.putNotNull(map, "pointStyle", pointStyle.name());
    }
    JUtils.putNotNull(map, "backgroundColor", backgroundColor);
    JUtils.putNotNull(map, "borderColor", borderColor);
    JUtils.putNotNull(map, "borderWidth", borderWidth);
    JUtils.putNotNull(map, "hitRadius", hitRadius);
    JUtils.putNotNull(map, "hoverRadius", hoverRadius);
    JUtils.putNotNull(map, "hoverBorderWidth", hoverBorderWidth);
    return map;
}
 
Example #22
Source File: PanRange.java    From vaadin-chartjs with MIT License 5 votes vote down vote up
private void setValue(JsonObject obj, String key, Object value) {
    if (value instanceof String) {
        JUtils.putNotNull(obj, "x", (String) value);
    } else if (value instanceof Double) {
        JUtils.putNotNull(obj, "x", (Double) value);
    }
}
 
Example #23
Source File: CubaCheckBoxGroupWidget.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void buildOptions(List<JsonObject> items) {
    super.buildOptions(items);

    for (Widget widget : getWidget()) {
        if (widget instanceof VCheckBox) {
            ((VCheckBox) widget).addKeyDownHandler(this);
        }
    }
}
 
Example #24
Source File: LockDevDepVersionsMojo.java    From flow with 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 #25
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 #26
Source File: JUtils.java    From vaadin-chartjs with MIT License 5 votes vote down vote up
public static void putNotNullBuilders(JsonObject obj, String key, List<? extends JsonBuilder> listOfBuilder) {
    if (listOfBuilder != null) {
        JsonArray arr = Json.createArray();
        for (JsonBuilder tbb : listOfBuilder) {
            arr.set(arr.length(), tbb.buildJson());
        }
        obj.put(key, arr);
    }
}
 
Example #27
Source File: CubaMultiSelectionModelConnector.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected void handleCtrlClick(MultiSelectionModel model,
                               CellReference<JsonObject> cell, GridClickEvent event) {
    NativeEvent e = event.getNativeEvent();
    JsonObject row = cell.getRow();
    if (!e.getCtrlKey() && !e.getMetaKey()) {
        model.deselectAll();
    }

    if (model.isSelected(row)) {
        model.deselect(row);
    } else {
        model.select(row);
    }
}
 
Example #28
Source File: UsageStatisticsExporter.java    From flow with Apache License 2.0 5 votes vote down vote up
private static String createUsageStatisticsJson(UsageStatistics.UsageEntry entry) {
    JsonObject json = Json.createObject();

    json.put("is", entry.getName());
    json.put("version", entry.getVersion());

    return json.toJson();
}
 
Example #29
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 #30
Source File: AbstractNodeUpdatePackagesTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private void updateVersion() throws IOException {
    // Change the version
    JsonObject json = packageUpdater.getPackageJson();
    getDependencies(json).put(SHRINKWRAP, "1.1.1");
    Files.write(packageJson.toPath(),
            Collections.singletonList(stringify(json)));
}