com.vaadin.flow.internal.StateNode Java Examples

The following examples show how to use com.vaadin.flow.internal.StateNode. 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: TemplateModelTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void beanModelType_emptyBeanAsInitialValue() {
    BeanModelTemplate template = new BeanModelTemplate();

    // Check that even before calling any model method the properties are
    // available via features
    Serializable bean = template.getElement().getNode()
            .getFeature(ElementPropertyMap.class).getProperty("bean");

    Assert.assertNotNull(bean);
    StateNode node = (StateNode) bean;
    Assert.assertEquals(0, node.getFeature(ElementPropertyMap.class)
            .getProperty("intValue"));

    // Now check properties via API
    Assert.assertNotNull(template.getModel().getBean());

    Assert.assertEquals(0, template.getModel().getBean().getIntValue());
}
 
Example #2
Source File: ElementPropertyMapTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void childPropertyUpdateFilter_renameProperty() {
    ElementPropertyMap map = createSimplePropertyMap();
    StateNode child = new StateNode(ElementPropertyMap.class);
    ElementPropertyMap childModel = ElementPropertyMap.getModel(child);

    map.put("foo", child);
    map.setUpdateFromClientFilter("foo.bar"::equals);

    Assert.assertTrue(childModel.mayUpdateFromClient("bar", "a"));

    map.remove("foo");
    Assert.assertFalse(childModel.mayUpdateFromClient("bar", "a"));

    map.put("bar", child);
    Assert.assertFalse(childModel.mayUpdateFromClient("bar", "a"));
}
 
Example #3
Source File: ListChangeTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicJson() {
    StateNode child1 = StateNodeTest.createEmptyNode("child1");
    StateNode child2 = StateNodeTest.createEmptyNode("child2");
    ListAddChange<StateNode> change = new ListAddChange<>(feature, true, 0,
            Arrays.asList(child1, child2));

    JsonObject json = change.toJson(null);

    Assert.assertEquals(change.getNode().getId(),
            (int) json.getNumber(JsonConstants.CHANGE_NODE));
    Assert.assertEquals(NodeFeatureRegistry.getId(feature.getClass()),
            (int) json.getNumber(JsonConstants.CHANGE_FEATURE));
    Assert.assertEquals(JsonConstants.CHANGE_TYPE_SPLICE,
            json.getString(JsonConstants.CHANGE_TYPE));
    Assert.assertEquals(0,
            (int) json.getNumber(JsonConstants.CHANGE_SPLICE_INDEX));

    JsonArray addNodes = json
            .getArray(JsonConstants.CHANGE_SPLICE_ADD_NODES);
    Assert.assertEquals(2, addNodes.length());

    Assert.assertEquals(child1.getId(), (int) addNodes.getNumber(0));
    Assert.assertEquals(child2.getId(), (int) addNodes.getNumber(1));
}
 
Example #4
Source File: AttachExistingElementFeatureTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void unregister_dataIsNotAvailaleByNode() {
    StateNode node = new StateNode();
    AttachExistingElementFeature feature = new AttachExistingElementFeature(
            node);

    Element element = Mockito.mock(Element.class);
    StateNode child = Mockito.mock(StateNode.class);
    ChildElementConsumer callback = Mockito
            .mock(ChildElementConsumer.class);
    Node<?> parent = Mockito.mock(Node.class);
    feature.register(parent, element, child, callback);

    feature.unregister(child);

    Assert.assertNull(feature.getCallback(child));
    Assert.assertNull(feature.getParent(child));
    Assert.assertNull(feature.getPreviousSibling(child));
}
 
Example #5
Source File: MapSyncRpcHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void propertyIsNotExplicitlyAllowed_subproperty_throwsWithComponentInfo() {
    exception.expect(IllegalArgumentException.class);
    exception.expectMessage(CoreMatchers.allOf(
            CoreMatchers.containsString(
                    "Component " + TestComponent.class.getName()),
            CoreMatchers.containsString("'" + TEST_PROPERTY + "'")));
    TestComponent component = new TestComponent();
    Element element = component.getElement();

    StateNode node = element.getNode();
    ElementPropertyMap propertyMap = node
            .getFeature(ElementPropertyMap.class)
            .resolveModelMap("foo.bar");

    new MapSyncRpcHandler().handleNode(propertyMap.getNode(),
            createSyncPropertyInvocation(propertyMap.getNode(),
                    TEST_PROPERTY, NEW_VALUE));
}
 
Example #6
Source File: NodeMapTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void put_sameValue_hasNoEffect() {
    StateTree tree = new StateTree(new UI().getInternals(),
            ElementChildrenList.class);
    StateNode child = new StateNode();

    AtomicBoolean listenerIsCalled = new AtomicBoolean();
    child.addAttachListener(() -> {
        Assert.assertFalse(listenerIsCalled.get());
        listenerIsCalled.set(true);
    });

    nodeMap.put("foo", child);

    tree.getRootNode().getFeature(ElementChildrenList.class)
            .add(child.getParent());

    Assert.assertTrue(listenerIsCalled.get());

    // The attach listener is not called one more time
    nodeMap.put("foo", child);
}
 
Example #7
Source File: BeanModelTypeTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void applicationToModel_filtered() {
    BeanModelType<Bean> beanType = new BeanModelType<>(Bean.class,
            new PropertyFilter(name -> !name.equals("intValue")), false);

    Bean bean = new Bean(3);

    StateNode applicationToModel = beanType.applicationToModel(bean,
            new PropertyFilter(name -> name.equals("string")
                    || name.equals("intValue")));

    ElementPropertyMap model = ElementPropertyMap
            .getModel(applicationToModel);

    Assert.assertEquals(Arrays.asList("string"),
            model.getPropertyNames().collect(Collectors.toList()));

    Assert.assertEquals("3", model.getProperty("string"));
}
 
Example #8
Source File: Element.java    From flow with Apache License 2.0 6 votes vote down vote up
private PendingJavaScriptResult scheduleJavaScriptInvocation(
        String expression, Stream<Serializable> parameters) {
    StateNode node = getNode();

    JavaScriptInvocation invocation = new JavaScriptInvocation(expression,
            parameters.toArray(Serializable[]::new));

    PendingJavaScriptInvocation pending = new PendingJavaScriptInvocation(
            node, invocation);

    node.runWhenAttached(ui -> ui.getInternals().getStateTree()
            .beforeClientResponse(node, context -> {
                if (!pending.isCanceled()) {
                    context.getUI().getInternals()
                            .addJavaScriptInvocation(pending);
                }
            }));

    return pending;
}
 
Example #9
Source File: MapSyncRpcHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
private Optional<Runnable> enqueuePropertyUpdate(StateNode node,
        JsonObject invocationJson, Class<? extends NodeFeature> feature,
        String property) {
    Serializable value = JsonCodec.decodeWithoutTypeInfo(
            invocationJson.get(JsonConstants.RPC_PROPERTY_VALUE));

    value = tryConvert(value, node);

    try {
        return Optional.of(node.getFeature(ElementPropertyMap.class)
                .deferredUpdateFromClient(property, value));
    } catch (PropertyChangeDeniedException exception) {
        throw new IllegalArgumentException(
                getVetoPropertyUpdateMessage(node, property), exception);
    }
}
 
Example #10
Source File: TemplateModelTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void listModelType_emptyListAsInitialValue() {
    ListBeanModelTemplate template = new ListBeanModelTemplate();

    // Check that even before calling any model method the properties are
    // available via features
    Serializable bean = template.getElement().getNode()
            .getFeature(ElementPropertyMap.class).getProperty("beans");
    Assert.assertNotNull(bean);

    StateNode node = (StateNode) bean;
    assertTrue(node.hasFeature(ModelList.class));

    // Now check properties via API
    List<Bean> list = template.getModel().getBeans();
    Assert.assertNotNull(list);
    Assert.assertEquals(0, list.size());
}
 
Example #11
Source File: StreamReceiverHandler.java    From vertx-vaadin with MIT License 5 votes vote down vote up
private void handleStream(VaadinSession session, FileSystem fileSystem,
                          StreamReceiver streamReceiver, StateNode owner, long contentLength,
                          FileUpload item) {
    String name = item.fileName();
    Buffer buffer = fileSystem.readFileBlocking(item.uploadedFileName());
    InputStream stream = new BufferInputStreamAdapter(buffer);
    try {
        handleFileUploadValidationAndData(session, stream, streamReceiver,
            name, item.contentType(), contentLength, owner);
    } catch (UploadException e) {
        session.getErrorHandler().error(new ErrorEvent(e));
    }
}
 
Example #12
Source File: BasicElementStateProvider.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void setAttribute(StateNode node, String attribute,
        AbstractStreamResource receiver) {
    assert node != null;
    assert attribute != null;
    assert receiver != null;
    getAttributeFeature(node).setResource(attribute, receiver);
}
 
Example #13
Source File: PolymerTemplateTest.java    From flow with 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 #14
Source File: StateNodeNodeListTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void testClear() {
    StateNode one = StateNodeTest.createEmptyNode("one");
    StateNode two = StateNodeTest.createEmptyNode("two");

    nodeList.add(one);
    nodeList.add(two);
    Assert.assertEquals(2, nodeList.size());
    nodeList.clear();
    Assert.assertEquals(0, nodeList.size());
}
 
Example #15
Source File: ClientCallableHandlersTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void attach_noComponent() {
    StateTree tree = new StateTree(new UI().getInternals(),
            ElementChildrenList.class);

    StateNode stateNode = new StateNode(ComponentMapping.class,
            ClientCallableHandlers.class);

    tree.getRootNode().getFeature(ElementChildrenList.class).add(stateNode);
    Assert.assertEquals(0,
            stateNode.getFeature(ClientCallableHandlers.class).size());
}
 
Example #16
Source File: AbstractNodeStateProvider.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public int getChildCount(StateNode node) {
    Optional<ElementChildrenList> maybeList = node
            .getFeatureIfInitialized(ElementChildrenList.class);
    // Lacking Optional.mapToInt
    if (maybeList.isPresent()) {
        return maybeList.get().size();
    } else {
        return 0;
    }

}
 
Example #17
Source File: StreamReceiverHandler.java    From vertx-vaadin with MIT License 5 votes vote down vote up
private void handleFileUploadValidationAndData(VaadinSession session,
                                               InputStream inputStream, StreamReceiver streamReceiver,
                                               String filename, String mimeType, long contentLength,
                                               StateNode node) throws UploadException {
    session.lock();
    try {
        if (node == null) {
            throw new UploadException(
                "File upload ignored because the node for the stream variable was not found");
        }
        if (!node.isAttached()) {
            throw new UploadException("Warning: file upload ignored for "
                + node.getId() + " because the component was disabled");
        }
    } finally {
        session.unlock();
    }
    try {
        // Store ui reference so we can do cleanup even if node is
        // detached in some event handler
        boolean forgetVariable = streamToReceiver(session, inputStream,
            streamReceiver, filename, mimeType, contentLength);
        if (forgetVariable) {
            cleanStreamVariable(session, streamReceiver);
        }
    } catch (Exception e) {
        session.lock();
        try {
            session.getErrorHandler().error(new ErrorEvent(e));
        } finally {
            session.unlock();
        }
    }
}
 
Example #18
Source File: AttachExistingElementRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void handleNode_error() {
    AttachExistingElementRpcHandler handler = new AttachExistingElementRpcHandler();

    int requestedId = 1;
    JsonObject object = Json.createObject();
    object.put(JsonConstants.RPC_ATTACH_REQUESTED_ID, requestedId);
    object.put(JsonConstants.RPC_ATTACH_ASSIGNED_ID, -1);
    object.put(JsonConstants.RPC_ATTACH_TAG_NAME, "div");
    object.put(JsonConstants.RPC_ATTACH_INDEX, -1);

    StateNode node = Mockito.mock(StateNode.class);
    StateNode requested = Mockito.mock(StateNode.class);
    StateTree tree = Mockito.mock(StateTree.class);
    Mockito.when(node.getOwner()).thenReturn(tree);
    Mockito.when(tree.getNodeById(requestedId)).thenReturn(requested);

    AttachExistingElementFeature feature = new AttachExistingElementFeature(
            node);
    Node<?> parentNode = Mockito.mock(Node.class);
    ChildElementConsumer consumer = Mockito
            .mock(ChildElementConsumer.class);
    Element sibling = Mockito.mock(Element.class);
    feature.register(parentNode, sibling, requested, consumer);
    Mockito.when(node.getFeature(AttachExistingElementFeature.class))
            .thenReturn(feature);

    handler.handleNode(node, object);

    Mockito.verify(consumer).onError(parentNode, "div", sibling);
    assertNodeIsUnregistered(node, requested, feature);
}
 
Example #19
Source File: ListModelType.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Imports beans into a model list based on the properties in the item type
 * of this model type.
 *
 * @param modelList
 *            the model list to import beans into
 * @param beans
 *            the list of beans to import
 * @param propertyFilter
 *            defines which properties from the item model type to import
 */
public void importBeans(ModelList modelList, List<T> beans,
        PropertyFilter propertyFilter) {
    // Collect all child nodes before clearing anything
    List<StateNode> childNodes = new ArrayList<>();
    for (Object bean : beans) {
        StateNode childNode = itemType.applicationToModel(bean,
                propertyFilter);
        childNodes.add(childNode);
    }

    modelList.clear();

    modelList.addAll(childNodes);
}
 
Example #20
Source File: MapSyncRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void handleNode_callsElementPropertyMapDeferredUpdateFromClient() {
    AtomicInteger deferredUpdateInvocations = new AtomicInteger();
    AtomicReference<String> deferredKey = new AtomicReference<>();
    StateNode node = new StateNode(ElementPropertyMap.class) {

        private ElementPropertyMap map = new ElementPropertyMap(this) {
            @Override
            public Runnable deferredUpdateFromClient(String key,
                    Serializable value) {
                deferredUpdateInvocations.incrementAndGet();
                deferredKey.set(key);
                return () -> {
                };
            }
        };

        @Override
        public <F extends NodeFeature> F getFeature(Class<F> featureType) {
            if (featureType.equals(ElementPropertyMap.class)) {
                return featureType.cast(map);
            }
            return super.getFeature(featureType);
        }

    };

    new MapSyncRpcHandler().handleNode(node,
            createSyncPropertyInvocation(node, TEST_PROPERTY, NEW_VALUE));

    Assert.assertEquals(1, deferredUpdateInvocations.get());
    Assert.assertEquals(TEST_PROPERTY, deferredKey.get());
}
 
Example #21
Source File: NodeMapTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void collectChanges_sameValue_neverCollect_noValueChanges() {
    StateNode node = new StateNode(ElementPropertyMap.class);
    NeverProduceChangeMap map = new NeverProduceChangeMap(node);

    assertChangeIsNotCollected(map, "bar");
    // change the same property one more time to another value: it still
    // should not be collected
    assertChangeIsNotCollected(map, "baz");
}
 
Example #22
Source File: MapSyncRpcHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
private Serializable tryConvert(Serializable value, StateNode context) {
    if (value instanceof JsonObject) {
        JsonObject json = (JsonObject) value;
        if (json.hasKey("nodeId")) {
            StateTree tree = (StateTree) context.getOwner();
            double id = json.getNumber("nodeId");
            StateNode stateNode = tree.getNodeById((int) id);
            return tryCopyStateNode(stateNode, json);
        }
    }
    return value;
}
 
Example #23
Source File: ListChangeTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmptyAddNotInJson() {
    ListAddChange<StateNode> change = new ListAddChange<>(feature, false, 1,
            Arrays.asList());

    JsonObject json = change.toJson(null);

    Assert.assertFalse(json.hasKey(JsonConstants.CHANGE_SPLICE_ADD_NODES));
}
 
Example #24
Source File: ElementPropertyMapTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void deferredUpdateFromClient_listChild_filterDisallowsUpdate()
        throws PropertyChangeDeniedException {
    ElementPropertyMap map = createSimplePropertyMap();
    ModelList list = map.resolveModelList("foo");
    StateNode child = new StateNode(ElementPropertyMap.class);

    map.setUpdateFromClientFilter(key -> false);
    list.add(child);

    ElementPropertyMap childModel = ElementPropertyMap.getModel(child);

    assertDeferredUpdate_noOp(childModel, "bar");
}
 
Example #25
Source File: MapSyncRpcHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
private boolean isInList(StateNode node) {
    StateNode parent = node.getParent();
    assert parent != null;
    if (parent.hasFeature(ModelList.class)
            && parent.getFeature(ModelList.class).contains(node)) {
        return true;
    }
    return false;
}
 
Example #26
Source File: ElementPropertyMapTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveModelList_modelListStateNodeHasReportedFeature() {
    ElementPropertyMap map = createSimplePropertyMap();
    map.resolveModelList("foo");

    StateNode stateNode = (StateNode) map.get("foo");
    Assert.assertTrue(stateNode.isReportedFeature(ModelList.class));
}
 
Example #27
Source File: VirtualChildrenList.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public StateNode remove(int index) {
    // removing the payload in case the element is reused
    get(index).getFeature(ElementData.class).remove(NodeProperties.PAYLOAD);

    // this should not omit a node change to client side.
    return super.remove(index);
}
 
Example #28
Source File: ShadowRoot.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the shadow root instance mapped to the given state node.
 *
 * @param node
 *            the state node, not <code>null</code>
 * @return the shadow root for the node, not <code>null</code>
 */
public static ShadowRoot get(StateNode node) {
    assert node != null;
    if (isShadowRoot(node)) {
        return new ShadowRoot(node);
    } else {
        throw new IllegalArgumentException(
                "Node is not valid as an element");
    }
}
 
Example #29
Source File: NodeMapTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void collectChanges_sameValue_alwaysCollect_allValueChangesCollected() {
    StateNode node = new StateNode(ElementPropertyMap.class);
    AlwaysProduceChangeMap map = new AlwaysProduceChangeMap(node);

    assertChangeCollected(map);
    // change the same property one more time: it still should be collected
    assertChangeCollected(map);
}
 
Example #30
Source File: Element.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the element mapped to the given state node.
 *
 * @param node
 *            the state node, not <code>null</code>
 * @return the element for the node, not <code>null</code>
 */
public static Element get(StateNode node) {
    assert node != null;

    if (node.hasFeature(TextNodeMap.class)) {
        return get(node, BasicTextElementStateProvider.get());
    } else if (node.hasFeature(ElementData.class)) {
        return get(node, BasicElementStateProvider.get());
    } else {
        throw new IllegalArgumentException(
                "Node is not valid as an element");
    }
}