Java Code Examples for com.vaadin.flow.component.UI#getInternals()

The following examples show how to use com.vaadin.flow.component.UI#getInternals() . 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: UidlWriter.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Encodes the state tree changes of the given UI. The executions registered
 * at
 * {@link StateTree#beforeClientResponse(com.vaadin.flow.internal.StateNode, com.vaadin.flow.function.SerializableConsumer)}
 * at evaluated before the changes are encoded.
 *
 * @param ui
 *            the UI
 * @param stateChanges
 *            a JSON array to put state changes into
 * @see StateTree#runExecutionsBeforeClientResponse()
 */
private void encodeChanges(UI ui, JsonArray stateChanges) {
    UIInternals uiInternals = ui.getInternals();
    StateTree stateTree = uiInternals.getStateTree();

    stateTree.runExecutionsBeforeClientResponse();

    Set<Class<? extends Component>> componentsWithDependencies = new LinkedHashSet<>();
    stateTree.collectChanges(change -> {
        if (attachesComponent(change)) {
            ComponentMapping.getComponent(change.getNode())
                    .ifPresent(component -> addComponentHierarchy(ui,
                            componentsWithDependencies, component));
        }

        // Encode the actual change
        stateChanges.set(stateChanges.length(),
                change.toJson(uiInternals.getConstantPool()));
    });

    componentsWithDependencies
            .forEach(uiInternals::addComponentDependencies);
}
 
Example 2
Source File: RendererUtilTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void registerEventHandlers_elementsAreAlreadyAttached_setupEvenHandlers() {
    UI ui = new TestUI();

    Element contentTemplate = new Element(Tag.DIV);
    Element templateDataHost = new Element(Tag.SPAN);
    attachElements(ui, contentTemplate, templateDataHost);

    TestUIInternals internals = (TestUIInternals) ui.getInternals();

    Renderer<String> renderer = new Renderer<>();

    renderer.setEventHandler("foo", value -> {
    });

    RendererUtil.registerEventHandlers(renderer, contentTemplate,
            templateDataHost, ValueProvider.identity());

    assertJSExecutions(ui, internals, contentTemplate, templateDataHost);
}
 
Example 3
Source File: RendererUtilTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void registerEventHandlers_setupEvenHandlersOnAttach() {
    UI ui = new TestUI();
    TestUIInternals internals = (TestUIInternals) ui.getInternals();

    Renderer<String> renderer = new Renderer<>();

    renderer.setEventHandler("foo", value -> {
    });

    Element contentTemplate = new Element(Tag.DIV);
    Element templateDataHost = new Element(Tag.SPAN);

    RendererUtil.registerEventHandlers(renderer, contentTemplate,
            templateDataHost, ValueProvider.identity());

    attachElements(ui, contentTemplate, templateDataHost);
    assertJSExecutions(ui, internals, contentTemplate, templateDataHost);

    ui.getElement().removeAllChildren();
    internals.invocations.clear();

    attachElements(ui, contentTemplate, templateDataHost);
    assertJSExecutions(ui, internals, contentTemplate, templateDataHost);
}
 
Example 4
Source File: RendererUtilTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void registerEventHandlers_attachMultipleTimes_singleEventListenerRegistered() {
    UI ui = new TestUI();
    TestUIInternals internals = (TestUIInternals) ui.getInternals();

    Renderer<String> renderer = new Renderer<>();

    AtomicInteger eventCounter = new AtomicInteger(0);

    renderer.setEventHandler("foo", value -> {
        eventCounter.getAndIncrement();
    });

    Element contentTemplate = new Element(Tag.DIV);
    Element templateDataHost = new Element(Tag.SPAN);

    RendererUtil.registerEventHandlers(renderer, contentTemplate,
            templateDataHost, ValueProvider.identity());

    attachElements(ui, contentTemplate, templateDataHost);
    attachElements(ui, contentTemplate, templateDataHost);

    internals.getStateTree().runExecutionsBeforeClientResponse();

    JsonObject eventData = Json.createObject();
    eventData.put("key", "");
    templateDataHost.getNode().getFeature(ElementListenerMap.class)
            .fireEvent(new DomEvent(templateDataHost, "foo", eventData));

    Assert.assertEquals(1, eventCounter.get());
}
 
Example 5
Source File: ComponentRendererTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void templateRenderered_parentAttachedBeforeChild() {
    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);

    // simulate a call from the grid to refresh data - template is not setup
    containerParent.getNode().runWhenAttached(
            ui2 -> ui2.getInternals().getStateTree()
                    .beforeClientResponse(containerParent.getNode(),
                            context -> {
                                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 parent (ex: grid) before the child (ex: column)
    attachElement(ui, containerParent);
    attachElement(ui, container);

    internals.getStateTree().runExecutionsBeforeClientResponse();

}
 
Example 6
Source File: ComponentRendererTest.java    From flow with 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 7
Source File: UidlWriter.java    From flow with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a JSON object containing all pending changes to the given UI.
 *
 * @param ui
 *            The {@link UI} whose changes to write
 * @param async
 *            True if this message is sent by the server asynchronously,
 *            false if it is a response to a client message
 * @param resync
 *            True iff the client should be asked to resynchronize
 * @return JSON object containing the UIDL response
 */
public JsonObject createUidl(UI ui, boolean async, boolean resync) {
    JsonObject response = Json.createObject();

    UIInternals uiInternals = ui.getInternals();

    VaadinSession session = ui.getSession();
    VaadinService service = session.getService();

    // Purge pending access calls as they might produce additional changes
    // to write out
    service.runPendingAccessTasks(session);

    // Paints components
    getLogger().debug("* Creating response to client");

    int syncId = service.getDeploymentConfiguration().isSyncIdCheckEnabled()
            ? uiInternals.getServerSyncId()
            : -1;

    response.put(ApplicationConstants.SERVER_SYNC_ID, syncId);
    if (resync) {
        response.put(ApplicationConstants.RESYNCHRONIZE_ID, true);
    }
    int nextClientToServerMessageId = uiInternals
            .getLastProcessedClientToServerId() + 1;
    response.put(ApplicationConstants.CLIENT_TO_SERVER_ID,
            nextClientToServerMessageId);

    SystemMessages messages = ui.getSession().getService()
            .getSystemMessages(ui.getLocale(), null);

    JsonObject meta = new MetadataWriter().createMetadata(ui, false, async,
            messages);
    if (meta.keys().length > 0) {
        response.put("meta", meta);
    }

    JsonArray stateChanges = Json.createArray();

    encodeChanges(ui, stateChanges);

    populateDependencies(response, uiInternals.getDependencyList(),
            new ResolveContext(service, session.getBrowser()));

    if (uiInternals.getConstantPool().hasNewConstants()) {
        response.put("constants",
                uiInternals.getConstantPool().dumpConstants());
    }
    if (stateChanges.length() != 0) {
        response.put("changes", stateChanges);
    }

    List<PendingJavaScriptInvocation> executeJavaScriptList = uiInternals
            .dumpPendingJavaScriptInvocations();
    if (!executeJavaScriptList.isEmpty()) {
        response.put(JsonConstants.UIDL_KEY_EXECUTE,
                encodeExecuteJavaScriptList(executeJavaScriptList));
    }
    if (ui.getSession().getService().getDeploymentConfiguration()
            .isRequestTiming()) {
        response.put("timings", createPerformanceData(ui));
    }
    uiInternals.incrementServerId();
    return response;
}
 
Example 8
Source File: StateNodeTest.java    From flow with Apache License 2.0 4 votes vote down vote up
@Test
public void removeFromTree_closeUI_allowsToSetANewTree() {
    UI ui = new UI();

    AtomicBoolean isRootAttached = new AtomicBoolean();
    isRootAttached.set(true);

    StateNode root = new StateNode(ElementChildrenList.class) {
        @Override
        public boolean isAttached() {
            return isRootAttached.get();
        }

    };

    StateTree stateTree = new StateTree(ui.getInternals(),
            ElementChildrenList.class) {

        @Override
        public StateNode getRootNode() {
            return root;
        }

        @Override
        public boolean hasNode(StateNode node) {
            if (getRootNode().equals(node)) {
                return true;
            }
            return super.hasNode(node);
        }
    };

    root.setTree(stateTree);

    StateNode child = createEmptyNode("child");
    StateNode anotherChild = createEmptyNode("anotherChild");

    addChild(root, child);
    addChild(root, anotherChild);

    // remove the second child from its parent (don't remove it from the
    // tree!)
    removeFromParent(anotherChild);

    // Once a child is added to a tree its id is not negative
    Assert.assertNotEquals(-1, anotherChild.getId());

    // Remove the first child from the tree (as it's done on preserve on
    // refresh)
    child.removeFromTree();
    // emulate closed UI
    isRootAttached.set(false);

    // At this point the second child still refers to the stateTree and
    // normally it's not allowed to move nodes from one tree to another but
    // <code>stateTree</code> is "detached" and marked as replaced on
    // preserve on refresh via <code>removeFromTree</code> called on another
    // node
    anotherChild.setTree(new TestStateTree());

    // It's possible to set a new tree for the child whose owner is detached
    // as marked replaced via preserved on refresh, its id is reset to -1
    Assert.assertEquals(-1, anotherChild.getId());
}