com.vaadin.flow.component.Component Java Examples

The following examples show how to use com.vaadin.flow.component.Component. 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: ViewClassLocator.java    From flow with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Class<? extends Component> findViewClass(String fullOrSimpleName)
        throws ClassNotFoundException {
    if (fullOrSimpleName == null) {
        return null;
    }
    String baseName = fullOrSimpleName;
    try {
        return (Class<? extends Component>) getClass().getClassLoader()
                .loadClass(baseName);
    } catch (Exception e) {
    }
    if (views.containsKey(fullOrSimpleName)) {
        return views.get(fullOrSimpleName);
    }

    throw new ClassNotFoundException(baseName);
}
 
Example #2
Source File: RouteNotFoundError.java    From flow with Apache License 2.0 6 votes vote down vote up
private Element routeToHtml(RouteData route) {
    String text = route.getTemplate();
    if (text == null || text.isEmpty()) {
        text = "<root>";
    }

    if (!route.getTemplate().contains(":")) {
        return elementAsLink(route.getTemplate(), text);
    } else {
        Class<? extends Component> target = route.getNavigationTarget();
        if (ParameterDeserializer.isAnnotatedParameter(target,
                OptionalParameter.class)) {
            text += " (supports optional parameter)";
        } else {
            text += " (requires parameter)";
        }

        return new Element(Tag.LI).text(text);
    }
}
 
Example #3
Source File: RouteUtilTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void newRouteAnnotatedClass_updateRouteRegistry_routeIsAddedToRegistry() {
    // given
    @Route("a")
    class A extends Component {
    }
    ApplicationRouteRegistry registry = ApplicationRouteRegistry
            .getInstance(new MockVaadinServletService().getContext());

    // when
    RouteUtil.updateRouteRegistry(registry, Collections.singleton(A.class),
            Collections.emptySet(), Collections.emptySet());

    // then
    Assert.assertTrue(registry.getConfiguration().hasRoute("a"));
}
 
Example #4
Source File: RouteUtilTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void deletedRouteAnnotatedClass_updateRouteRegistry_routeIsRemovedFromRegistry() {
    // given
    @Route("a")
    class A extends Component {
    }
    ApplicationRouteRegistry registry = ApplicationRouteRegistry
            .getInstance(new MockVaadinServletService().getContext());
    registry.setRoute("a", A.class, Collections.emptyList());
    Assert.assertTrue(registry.getConfiguration().hasRoute("a"));

    // when
    RouteUtil.updateRouteRegistry(registry, Collections.emptySet(),
            Collections.emptySet(), Collections.singleton(A.class));

    // then
    Assert.assertFalse(registry.getConfiguration().hasRoute("a"));
}
 
Example #5
Source File: ConfigureRoutes.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Set a new {@link RouteTarget} for the given template.
 * <p>
 * Note! this will override any previous value.
 *
 * @param template
 *            template for which to set route target for
 * @param navigationTarget
 *            navigation target to add
 * @param parentChain
 *            chain of parent layouts that should be used with this target
 */
public void setRoute(String template,
        Class<? extends Component> navigationTarget,
        List<Class<? extends RouterLayout>> parentChain) {

    template = PathUtil.trimPath(template);

    final RouteTarget target = new RouteTarget(navigationTarget,
            parentChain);

    getRouteModel().addRoute(template, target);

    if (!hasRouteTarget(navigationTarget)) {
        setTargetRoute(navigationTarget, template);
    }

    getTargetRouteModelMap().computeIfAbsent(navigationTarget,
            aClass -> RouteModel.create(true));
    getTargetRouteModelMap().get(navigationTarget).addRoute(template,
            target);

    getRoutesMap().put(template, target);
}
 
Example #6
Source File: WebComponentTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void setProperty_throwsWhenGivenWrongPropertyTypeAsParameter() {
    exception.expect(IllegalArgumentException.class);
    exception.expectMessage("Property 'property' of type " +
            "'java.lang.Integer' cannot be assigned value of type " +
            "'java.lang.String'!");

    PropertyConfigurationImpl<Component, Integer> intConfiguration =
    new PropertyConfigurationImpl<>(
            Component.class, "property", Integer.class, 0);

    WebComponentBinding<Component> binding =
            new WebComponentBinding<>(mock(Component.class));
    binding.bindProperty(intConfiguration, false, null);

    WebComponent<Component> webComponent =
            new WebComponent<>(binding, new Element("tag"));

    PropertyConfigurationImpl<Component, String> stringConfiguration =
            new PropertyConfigurationImpl<>(
                    Component.class, "property", String.class, "value");

    webComponent.setProperty(stringConfiguration, "newValue");
}
 
Example #7
Source File: EventUtilTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void getImplementingComponents() throws Exception {
    Element node = new Element("root");
    node.appendChild(new Element("main"), new Element("menu"));
    Element nested = new Element("nested");
    nested.appendChild(new Element("nested-child"),
            new Element("nested-child-2"));

    node.appendChild(nested);
    Component.from(nested, EnterObserver.class);

    List<Element> elements = new ArrayList<>();

    EventUtil.inspectHierarchy(node, elements, element -> true);

    List<BeforeEnterObserver> listenerComponents = EventUtil
            .getImplementingComponents(elements.stream(),
                    BeforeEnterObserver.class)
            .collect(Collectors.toList());

    Assert.assertEquals("Wrong amount of listener instances found", 1,
            listenerComponents.size());
}
 
Example #8
Source File: AbstractNavigationStateRenderer.java    From flow with Apache License 2.0 5 votes vote down vote up
private static void checkForDuplicates(
        Class<? extends Component> routeTargetType,
        Collection<Class<? extends RouterLayout>> routeLayoutTypes) {
    Set<Class<?>> duplicateCheck = new HashSet<>();
    duplicateCheck.add(routeTargetType);
    for (Class<?> parentType : routeLayoutTypes) {
        if (!duplicateCheck.add(parentType)) {
            throw new IllegalArgumentException(
                    parentType + " is used in multiple locations");
        }
    }
}
 
Example #9
Source File: AttachExistingElementView.java    From flow with Apache License 2.0 5 votes vote down vote up
private void handleLabel(Element label) {
    attachedLabel = Component.from(label, Label.class);
    attachedLabel.setText("Client side label");
    attachedLabel.setId("label");

    add(AbstractDivView.createButton("Attach the already attached label",
            "attach-populated-label",
            event -> getElement().getStateProvider().attachExistingElement(
                    getElement().getNode(), "label", null,
                    this::handleAttachedLabel)));

    add(createButton("Remove myself on the server side", "remove-self",
            event -> event.getSource().getElement().removeFromParent()));
}
 
Example #10
Source File: WebComponentConfigurationRegistry.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Get an unmodifiable set containing all registered web component
 * configurations.
 *
 * @return unmodifiable set of web component configurations in registry or
 *         an empty set
 */
public Set<WebComponentConfiguration<? extends Component>> getConfigurations() {
    lock();
    try {
        return Collections
                .unmodifiableSet(new HashSet<>(configurationMap.values()));
    } finally {
        unlock();
    }
}
 
Example #11
Source File: WindowBasedCrudLayout.java    From crudui with Apache License 2.0 5 votes vote down vote up
@Override
public void addToolbarComponent(Component component) {
    if (!headerLayout.isVisible()) {
        headerLayout.setVisible(true);
        mainLayout.getElement().insertChild(mainLayout.getComponentCount() - 1, headerLayout.getElement());
    }

    toolbarLayout.setVisible(true);
    toolbarLayout.add(component);
}
 
Example #12
Source File: UIInternals.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the dependencies defined using {@link StyleSheet} or
 * {@link JavaScript} on the given Component class.
 *
 * @param componentClass
 *            the component class to read annotations from
 */
public void addComponentDependencies(
        Class<? extends Component> componentClass) {
    Page page = ui.getPage();
    DependencyInfo dependencies = ComponentUtil
            .getDependencies(session.getService(), componentClass);
    // In npm mode, add external JavaScripts directly to the page.
    addExternalDependencies(dependencies);
    addFallbackDependencies(dependencies);

    dependencies.getStyleSheets().forEach(styleSheet -> page
            .addStyleSheet(styleSheet.value(), styleSheet.loadMode()));
}
 
Example #13
Source File: SessionRouteRegistry.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<String> getTargetUrl(
        Class<? extends Component> navigationTarget,
        RouteParameters parameters) {
    Optional<String> targetUrl = super.getTargetUrl(navigationTarget,
            parameters);
    if (targetUrl.isPresent()) {
        return targetUrl;
    }

    return getParentRegistry().getTargetUrl(navigationTarget, parameters);
}
 
Example #14
Source File: ConfiguredRoutes.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Get the target class matching the given url.
 *
 * @param url
 *            string to get the route for
 * @return {@link Optional} containing the navigationTarget class if found
 */
public Optional<Class<? extends Component>> getTarget(String url) {
    final NavigationRouteTarget result = getNavigationRouteTarget(url);
    if (result.hasTarget()) {
        final RouteTarget routeTarget = result.getRouteTarget();
        return Optional.ofNullable(routeTarget.getTarget());
    } else {
        return Optional.empty();
    }
}
 
Example #15
Source File: LeftIconItem.java    From vaadin-app-layout with Apache License 2.0 5 votes vote down vote up
public void setIcon(Component icon) {
    if (this.icon != null) {
        remove(caption);
    }
    this.icon = icon;
    if (icon != null) {
        getElement().insertChild(0, this.icon.getElement());
    }
}
 
Example #16
Source File: AbstractCrud.java    From crudui with Apache License 2.0 5 votes vote down vote up
public AbstractCrud(Class<T> domainType, CrudLayout crudLayout, CrudFormFactory<T> crudFormFactory, CrudListener<T> crudListener) {
    this.domainType = domainType;
    this.crudLayout = crudLayout;
    this.crudFormFactory = crudFormFactory;

    if (crudListener != null) {
        setCrudListener(crudListener);
    }
    getContent().add((Component) crudLayout);

    getContent().setPadding(false);
    getContent().setMargin(false);
    setSizeFull();
}
 
Example #17
Source File: SessionRouteRegistry.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<Class<? extends Component>> getNavigationTarget(
        String url) {
    Objects.requireNonNull(url, "pathString must not be null.");
    final Optional<Class<? extends Component>> target = getConfiguration()
            .getTarget(url);
    if (target.isPresent()) {
        return target;
    }

    return getParentRegistry().getNavigationTarget(url);
}
 
Example #18
Source File: ApplicationRouteRegistry.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Set error handler navigation targets.
 * <p>
 * This can also be used to add error navigation targets that override
 * existing targets. Note! The overriding targets need to be extending the
 * existing target or they will throw.
 *
 * @param errorNavigationTargets
 *            error handler navigation targets
 */
public void setErrorNavigationTargets(
        Set<Class<? extends Component>> errorNavigationTargets) {
    Map<Class<? extends Exception>, Class<? extends Component>> exceptionTargetsMap = new HashMap<>();

    exceptionTargetsMap.putAll(getConfiguration().getExceptionHandlers());

    errorNavigationTargets.stream()
            .filter(target -> !defaultErrorHandlers.contains(target))
            .filter(this::allErrorFiltersMatch)
            .filter(handler -> !Modifier.isAbstract(handler.getModifiers()))
            .forEach(target -> addErrorTarget(target, exceptionTargetsMap));

    initErrorTargets(exceptionTargetsMap);
}
 
Example #19
Source File: RouteModelTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private void assertTarget(Class<? extends Component> target,
        RouteTarget routeTarget) {
    Assert.assertTrue("Weird expected target [" + target + "], actual ["
            + routeTarget + "]", (target == null) == (routeTarget == null));

    if (target != null) {
        Assert.assertTrue(
                "Invalid expected target [" + target + "], actual "
                        + routeTarget.getTarget(),
                routeTarget.getTarget().equals(target));
    }
}
 
Example #20
Source File: ApplicationRouteRegistry.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void setRoute(String path,
        Class<? extends Component> navigationTarget,
        List<Class<? extends RouterLayout>> parentChain) {
    if (routeFilters.stream().allMatch(
            filter -> filter.testNavigationTarget(navigationTarget))) {
        super.setRoute(path, navigationTarget, parentChain);
    } else {
        LoggerFactory.getLogger(ApplicationRouteRegistry.class).info(
                "Not registering route {} because it's not valid for all registered routeFilters.",
                navigationTarget.getName());
    }
}
 
Example #21
Source File: ElementUtilTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void attachTwoComponents() {
    Element e = ElementFactory.createDiv();
    Component c = Mockito.mock(Component.class);
    Component c2 = Mockito.mock(Component.class);
    ElementUtil.setComponent(e, c);
    ElementUtil.setComponent(e, c2);
}
 
Example #22
Source File: ElementUtilTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void attachToComponent() {
    Element e = ElementFactory.createDiv();
    Component c = Mockito.mock(Component.class);
    ElementUtil.setComponent(e, c);
    Assert.assertEquals(c, e.getComponent().get());
}
 
Example #23
Source File: TextRenderer.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public Component createComponent(ITEM item) {
    String text = itemLabelGenerator.apply(item);
    if (text == null) {
        throw new IllegalStateException(String.format(
                "Got 'null' as a label value for the item '%s'. "
                        + "'%s' instance may not return 'null' values",
                item, ItemLabelGenerator.class.getSimpleName()));
    }
    return new TextRendererComponent(createElement(text));
}
 
Example #24
Source File: AppBarBuilder.java    From vaadin-app-layout with Apache License 2.0 5 votes vote down vote up
@Override
public FlexLayout build() {
    FlexLayout layout = new FlexLayout(components.toArray(new Component[0]));
    layout.getStyle().set("flex-direction", "var(--app-layout-app-bar-flex-direction)");
    layout.setWidthFull();
    layout.setAlignItems(FlexComponent.Alignment.CENTER);
    return layout;
}
 
Example #25
Source File: SessionRouteRegistry.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<Class<? extends Component>> getNavigationTarget(
        String url, List<String> segments) {
    Objects.requireNonNull(url, "url must not be null.");
    final Optional<Class<? extends Component>> target = getConfiguration()
            .getTarget(PathUtil.getPath(url, segments));
    if (target.isPresent()) {
        return target;
    }

    return getParentRegistry().getNavigationTarget(url, segments);
}
 
Example #26
Source File: ApplicationRouteRegistry.java    From flow with Apache License 2.0 5 votes vote down vote up
private void initErrorTargets(
        Map<Class<? extends Exception>, Class<? extends Component>> map) {
    if (!map.containsKey(NotFoundException.class)) {
        map.put(NotFoundException.class, RouteNotFoundError.class);
    }
    if (!map.containsKey(Exception.class)) {
        map.put(Exception.class, InternalServerError.class);
    }
    configure(configuration -> map.forEach(configuration::setErrorRoute));
}
 
Example #27
Source File: AbstractListDataViewListenerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void addSizeChangeListener_sizeChanged_newSizeSuppliedInEvent() {
    String[] items = new String[] { "item1", "item2", "item3", "item4" };
    HasListDataView<String, ? extends AbstractListDataView<String>> component =
            getVerifiedComponent();
    AbstractListDataView<String> dataView = component
            .setItems(items);

    AtomicBoolean invocationChecker = new AtomicBoolean(false);

    UI ui = new MockUI();
    ui.add((Component) component);

    // Make initial size event
    fakeClientCall(ui);

    dataView.addSizeChangeListener(event -> {
        Assert.assertEquals("Unexpected data size", 1, event.getSize());
        invocationChecker.set(true);
    });

    dataView.setFilter("item1"::equals);

    // Size change should be sent as size has changed after filtering.
    fakeClientCall(ui);

    Assert.assertTrue("Size change never called", invocationChecker.get());
}
 
Example #28
Source File: AbstractRouteRegistry.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void setRoute(String path,
        Class<? extends Component> navigationTarget,
        List<Class<? extends RouterLayout>> parentChain) {
    configureWithFullTemplate(path, navigationTarget,
            (configuration, fullTemplate) -> configuration
                    .setRoute(fullTemplate, navigationTarget, parentChain));
}
 
Example #29
Source File: PublishedServerEventHandlerRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private void requestInvokeMethod(Component component, String method) {
    JsonObject json = Json.createObject();
    json.put(JsonConstants.RPC_TEMPLATE_EVENT_METHOD_NAME, method);

    new PublishedServerEventHandlerRpcHandler()
            .handleNode(component.getElement().getNode(), json);
}
 
Example #30
Source File: NavigationStateRenderer.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
protected void notifyNavigationTarget(Component componentInstance,
        NavigationEvent navigationEvent, BeforeEnterEvent beforeEnterEvent,
        LocationChangeEvent locationChangeEvent) {

    if (!(componentInstance instanceof HasUrlParameter)) {
        return;
    }

    NavigationState navigationState = getNavigationState();
    Class<? extends Component> routeTargetType = navigationState
            .getNavigationTarget();

    List<String> parameters = navigationState.getUrlParameters()
            .orElse(null);

    Object deserializedParameter = null;
    try {
        deserializedParameter = ParameterDeserializer
                .deserializeRouteParameters(routeTargetType, parameters);
    } catch (Exception e) {
        beforeEnterEvent.rerouteToError(NotFoundException.class, String
                .format("Failed to parse url parameter, exception: %s", e));
        return;
    }

    HasUrlParameter<Object> hasUrlParameter = (HasUrlParameter<Object>) componentInstance;
    hasUrlParameter.setParameter(beforeEnterEvent, deserializedParameter);
}