Java Code Examples for elemental.json.JsonObject

The following examples show how to use elemental.json.JsonObject. 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: flow   Source File: MapSyncRpcHandler.java    License: 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 2
Source Project: flow   Source File: UidlRequestHandlerTest.java    License: 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 Project: flow   Source File: ListAddChange.java    License: 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 Project: flow   Source File: VersionsJsonFilter.java    License: 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 Project: flow   Source File: ComponentEventBusTest.java    License: 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 6
Source Project: flow   Source File: TaskRunPnpmInstallTest.java    License: 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 7
Source Project: flow   Source File: UidlWriter.java    License: 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 8
Source Project: flow   Source File: MapPutChangeTest.java    License: 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 9
Source Project: cuba   Source File: CubaMultiSelectionModelConnector.java    License: 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 10
Source Project: flow   Source File: BootstrapHandler.java    License: 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 11
Source Project: flow   Source File: ExecuteJavaScriptProcessor.java    License: 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 12
Source Project: flow   Source File: ScrollPositionHandler.java    License: 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 13
Source Project: vaadin-chartjs   Source File: BoxAnnotation.java    License: 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 14
Source Project: flow   Source File: ConstantPool.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Encodes all new constants to a JSON object and marks those constants as
 * non-new.
 *
 * @return a JSON object describing all new constants
 */
public JsonObject dumpConstants() {
    JsonObject json = Json.createObject();

    newKeys.forEach(key -> key.export(json));
    newKeys.clear();

    return json;
}
 
Example 15
Source Project: flow   Source File: TaskUpdatePackages.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Cleans up any previous version properties from the packageJson object if
 * present.
 *
 * @param packageJson
 *         JsonObject of current package.json contents
 * @return amount of removed properties
 * @throws IOException
 *         thrown if removal of package-lock.json fails
 */
private int removeLegacyProperties(JsonObject packageJson)
        throws IOException {
    int result = 0;
    /*
     * In modern Flow versions "@vaadin/flow-deps" should not exist.
     */
    if (packageJson.hasKey(DEPENDENCIES)) {
        JsonObject object = packageJson.getObject(DEPENDENCIES);
        if (object.hasKey(DEP_NAME_FLOW_DEPS)) {
            object.remove(DEP_NAME_FLOW_DEPS);
            log().debug("Removed \"{}\" as it's not generated anymore.",
                    DEP_NAME_FLOW_DEPS);
            result++;
        }
    }
    if (packageJson.hasKey(VAADIN_APP_PACKAGE_HASH)) {
        packageJson.remove(VAADIN_APP_PACKAGE_HASH);
        log().debug("Removed \"{}\" as it's not used.",
                VAADIN_APP_PACKAGE_HASH);
        result++;
    }
    if (!enablePnpm) {
        return result;
    }
    /*
     * In case of PNPM tool the package-lock should not be used at all.
     */
    File packageLockFile = getPackageLockFile();
    if (packageLockFile.exists()) {
        FileUtils.forceDelete(getPackageLockFile());
    }
    return result;
}
 
Example 16
Source Project: flow   Source File: PolymerTemplateTest.java    License: Apache License 2.0 5 votes vote down vote up
private void assertElementData(StateNode node, String type,
        String payload) {
    JsonObject object = (JsonObject) node.getFeature(ElementData.class)
            .getPayload();
    Assert.assertEquals(type, object.getString(NodeProperties.TYPE));
    Assert.assertEquals(payload, object.getString(NodeProperties.PAYLOAD));
}
 
Example 17
Source Project: flow   Source File: BuildFrontendMojo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Add the devMode token to build token file so we don't try to start the
 * dev server. Remove the abstract folder paths as they should not be used
 * for prebuilt bundles.
 */
private void updateBuildFile() {
    File tokenFile = getTokenFile();
    if (!tokenFile.exists()) {
        getLog().warn(
                "Couldn't update devMode token due to missing token file.");
        return;
    }
    try {
        String json = FileUtils.readFileToString(tokenFile,
                StandardCharsets.UTF_8.name());
        JsonObject buildInfo = JsonUtil.parse(json);

        buildInfo.remove(NPM_TOKEN);
        buildInfo.remove(GENERATED_TOKEN);
        buildInfo.remove(FRONTEND_TOKEN);
        buildInfo.remove(Constants.SERVLET_PARAMETER_ENABLE_PNPM);
        buildInfo.remove(Constants.REQUIRE_HOME_NODE_EXECUTABLE);
        buildInfo.remove(Constants.SERVLET_PARAMETER_DEVMODE_OPTIMIZE_BUNDLE);
        buildInfo.remove(Constants.CONNECT_JAVA_SOURCE_FOLDER_TOKEN);
        buildInfo.remove(Constants.CONNECT_APPLICATION_PROPERTIES_TOKEN);
        buildInfo.remove(Constants.CONNECT_JAVA_SOURCE_FOLDER_TOKEN);
        buildInfo.remove(Constants.CONNECT_OPEN_API_FILE_TOKEN);
        buildInfo.remove(Constants.CONNECT_GENERATED_TS_DIR_TOKEN);

        buildInfo.put(SERVLET_PARAMETER_ENABLE_DEV_SERVER, false);
        FileUtils.write(tokenFile, JsonUtil.stringify(buildInfo, 2) + "\n",
                StandardCharsets.UTF_8.name());
    } catch (IOException e) {
        getLog().warn("Unable to read token file", e);
    }
}
 
Example 18
Source Project: vaadin-chartjs   Source File: RadarChartConfig.java    License: MIT License 5 votes vote down vote up
@Override
public JsonObject buildJson() {
    JsonObject map = Json.createObject();
    JUtils.putNotNull(map, "type", "radar");
    // data
    if (data != null) {
        JUtils.putNotNull(map, "data", data.buildJson());
    }
    // options
    if (options != null) {
        JUtils.putNotNull(map, "options", options.buildJson());
    }
    return map;
}
 
Example 19
Source Project: flow   Source File: BootstrapHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generates the initial UIDL message which is included in the initial
 * bootstrap page.
 *
 * @param ui
 *            the UI for which the UIDL should be generated
 * @return a JSON object with the initial UIDL message
 */
private JsonObject getInitialUidl(UI ui) {
    JsonObject json = new UidlWriter().createUidl(ui, false);

    VaadinSession session = ui.getSession();
    if (session.getConfiguration().isXsrfProtectionEnabled()) {
        writeSecurityKeyUIDL(json, ui);
    }
    writePushIdUIDL(json, session);
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Initial UIDL: {}", json.asString());
    }
    return json;
}
 
Example 20
Source Project: vertxui   Source File: Pojofy.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static <I> void socketSend(WebSocket socket, String url, I model, ObjectMapper<I> inMapper,
		JsonObject headers) {
	JsonObject object = Json.createObject();
	object.put("url", url);
	object.put("body", in(model, inMapper));
	object.put("headers", headers);
	socket.send(object.toJson());
}
 
Example 21
Source Project: flow   Source File: SimpleElementBindingStrategy.java    License: Apache License 2.0 5 votes vote down vote up
private void handleInjectId(BindingContext context, StateNode node,
        JsonObject object, boolean reactivePhase) {
    String id = object.getString(NodeProperties.PAYLOAD);
    String address = "id='" + id + "'";
    Supplier<Element> elementLookup = () -> ElementUtil
            .getElementById(context.htmlNode, id);

    doAppendVirtualChild(context, node, reactivePhase, elementLookup, id,
            address);
}
 
Example 22
Source Project: flow   Source File: ConstantPool.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Imports new constants into this pool.
 *
 * @param json
 *            a JSON object mapping constant keys to constant values, not
 *            <code>null</code>
 */
public void importFromJson(JsonObject json) {
    assert json != null;

    for (String key : json.keys()) {
        assert !constants.has(key);
        JsonValue value = json.get(key);

        assert value != null && value.getType() != JsonType.NULL;
        constants.set(key, value);
    }
}
 
Example 23
Source Project: flow   Source File: TreeChangeProcessorTest.java    License: Apache License 2.0 5 votes vote down vote up
private static JsonObject baseChange(int node, String type) {
    JsonObject json = Json.createObject();

    json.put(JsonConstants.CHANGE_TYPE, type);
    json.put(JsonConstants.CHANGE_NODE, node);
    return json;
}
 
Example 24
Source Project: flow   Source File: PrepareFrontendMojoTest.java    License: Apache License 2.0 5 votes vote down vote up
private void assertPackageJsonContent() throws IOException {
    JsonObject packageJsonObject = getPackageJson(packageJson);

    assertContainsPackage(packageJsonObject.getObject("dependencies"),
            "@polymer/polymer");

    assertContainsPackage(packageJsonObject.getObject("devDependencies"),
            "webpack", "webpack-cli", "webpack-dev-server",
            "copy-webpack-plugin", "html-webpack-plugin");
}
 
Example 25
Source Project: vaadin-chartjs   Source File: Scales.java    License: MIT License 5 votes vote down vote up
@Override
public JsonObject buildJson() {
    JsonObject map = Json.createObject();
    JUtils.putNotNullBuilders(map, "xAxes", xAxes);
    JUtils.putNotNullBuilders(map, "yAxes", yAxes);
    return map;
}
 
Example 26
Source Project: flow   Source File: ScrollPositionHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void readAndRestoreScrollPositionsFromHistoryAndSessionStorage(
        boolean delayAfterResponse) {
    // restore history index & token from state if applicable
    JsonObject state = (JsonObject) Browser.getWindow().getHistory()
            .getState();
    if (state != null && state.hasKey(HISTORY_INDEX)
            && state.hasKey(HISTORY_TOKEN)) {

        currentHistoryIndex = (int) state.getNumber(HISTORY_INDEX);
        historyResetToken = state.getNumber(HISTORY_TOKEN);

        String jsonString = null;
        try {
            jsonString = Browser.getWindow().getSessionStorage()
                    .getItem(createSessionStorageKey(historyResetToken));
        } catch (JavaScriptException e) {
            Console.error(
                    "Failed to get session storage: " + e.getMessage());
        }
        if (jsonString != null) {
            JsonObject jsonObject = Json.parse(jsonString);

            xPositions = convertJsonArrayToArray(
                    jsonObject.getArray(X_POSITIONS));
            yPositions = convertJsonArrayToArray(
                    jsonObject.getArray(Y_POSITIONS));
            // array lengths checked in restoreScrollPosition
            restoreScrollPosition(delayAfterResponse);
        } else {
            Console.warn(
                    "History.state has scroll history index, but no scroll positions found from session storage matching token <"
                            + historyResetToken
                            + ">. User has navigated out of site in an unrecognized way.");
            resetScrollPositionTracking();
        }
    } else {
        resetScrollPositionTracking();
    }
}
 
Example 27
Source Project: flow   Source File: ComponentRendererTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void templateRenderered_childAttachedBeforeParent() {
    UI ui = new TestUI();
    TestUIInternals internals = (TestUIInternals) ui.getInternals();

    ComponentRenderer<TestLabel, String> renderer = new ComponentRenderer<>(
            e -> (new TestLabel()));

    Element containerParent = new Element("div");
    Element container = new Element("div");
    KeyMapper<String> keyMapper = new KeyMapper<>();

    ComponentDataGenerator<String> rendering = (ComponentDataGenerator<String>) renderer
            .render(container, keyMapper);

    containerParent.getNode().runWhenAttached(
            ui2 -> ui2.getInternals().getStateTree()
                    .beforeClientResponse(containerParent.getNode(),
                            context -> {
                                // if nodeid is null then the component won't be rendered correctly
                                Assert.assertNotNull(
                                        "NodeIdPropertyName should not be null",
                                        rendering.getNodeIdPropertyName());
                                JsonObject value = Json.createObject();
                                rendering.generateData("item", value);
                                Assert.assertEquals(
                                        "generateData should add one element in the jsonobject",
                                        1, value.keys().length);
                            }));
    // attach the child (ex: container) before the parent (ex: grid)
    attachElement(ui, container);
    attachElement(ui, containerParent);

    internals.getStateTree().runExecutionsBeforeClientResponse();

}
 
Example 28
Source Project: flow   Source File: JsonUtilsTest.java    License: 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 29
Source Project: flow   Source File: ScrollPositionHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Store scroll positions and restore scroll positions depending on the
 * given pop state event.
 * <p>
 * This method behaves differently if there has been a
 * {@link #beforeClientNavigation(String)} before this, and if the pop state
 * event is caused by a fragment change that doesn't require a server side
 * round-trip.
 *
 * @param event
 *            the pop state event
 * @param triggersServerSideRoundtrip
 *            <code>true</code> if the pop state event triggers a server
 *            side request, <code>false</code> if not
 */
public void onPopStateEvent(PopStateEvent event,
        boolean triggersServerSideRoundtrip) {
    if (ignoreScrollRestorationOnNextPopStateEvent) {
        Browser.getWindow().getHistory().replaceState(
                createStateObjectWithHistoryIndexAndToken(), "",
                Browser.getDocument().getLocation().getHref());

        ignoreScrollRestorationOnNextPopStateEvent = false;
        return;
    }

    captureCurrentScrollPositions();

    JsonObject state = (JsonObject) event.getState();
    if (state == null || !state.hasKey(HISTORY_INDEX)
            || !state.hasKey(HISTORY_TOKEN)) {
        // state doesn't contain history index info, just log & reset
        Console.warn(MISSING_STATE_VARIABLES_MESSAGE);
        resetScrollPositionTracking();
        return;
    }

    double token = state.getNumber(HISTORY_TOKEN);
    if (!Objects.equals(token, historyResetToken)) {
        // current scroll positions are not for this history entry
        // try to restore arrays or reset
        readAndRestoreScrollPositionsFromHistoryAndSessionStorage(
                triggersServerSideRoundtrip);
        return;
    }

    currentHistoryIndex = (int) state.getNumber(HISTORY_INDEX);
    restoreScrollPosition(triggersServerSideRoundtrip);
}
 
Example 30
Source Project: vaadin-chartjs   Source File: JUtils.java    License: MIT License 5 votes vote down vote up
public static void putNotNullTimeDoublePairs(JsonObject obj, String key, List<Pair<LocalDateTime,Double>> listOfPairs) {
    if (listOfPairs != null) {
        JsonArray arr = Json.createArray();
        for (Pair<LocalDateTime,Double> n : listOfPairs) {
            if (n != null) {
                JsonObject map = Json.createObject();
                JUtils.putNotNull(map, "t",	n.getFirst());
                JUtils.putNotNull(map, "y", n.getSecond());
                arr.set(arr.length(), map);
            }
        }
        obj.put(key, arr);
    }
}