com.vaadin.flow.router.BeforeEnterEvent Java Examples

The following examples show how to use com.vaadin.flow.router.BeforeEnterEvent. 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: AbstractNavigationStateRenderer.java    From flow with Apache License 2.0 6 votes vote down vote up
private Optional<Integer> sendBeforeEnterEventToExistingChain(
        BeforeEnterEvent beforeNavigation, NavigationEvent event,
        List<HasElement> chain) {
    // Reverse the chain so that the target is last.
    chain = new ArrayList<>(chain);
    Collections.reverse(chain);

    // Used when the chain already exists by being preserved on refresh.
    // See `isPreserveOnRefreshTarget` method implementation and usage.
    List<BeforeEnterHandler> chainEnterHandlers = new ArrayList<>(
            EventUtil.collectBeforeEnterObserversFromChain(chain, event
                    .getUI().getInternals().getActiveRouterTargetsChain()));

    Optional<Integer> result = sendBeforeEnterEvent(chainEnterHandlers,
            event, beforeNavigation, chain);

    if (result.isPresent()) {
        return result;
    }

    return Optional.empty();
}
 
Example #2
Source File: AbstractNavigationStateRenderer.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Inform any {@link BeforeEnterObserver}s in attaching element chain. The
 * event is sent first to the {@link BeforeEnterHandler}s registered within
 * the {@link UI}, then to any element in the chain and to any of it's child
 * components in the hierarchy which implements {@link BeforeEnterHandler}
 *
 * If the <code>chain</code> argument is empty <code>chainClasses</code> is
 * going to be used and populate <code>chain</code> with new created
 * instance.
 *
 * @param beforeNavigation
 *            before enter navigation event sent to observers
 * @param event
 *            original navigation event
 * @param chain
 *            the chain of {@link HasElement} instances which will be
 *            rendered. In case this is empty it'll be populated with
 *            instances according with the navigation event's location.
 * @return result of observer events
 */
private Optional<Integer> createChainIfEmptyAndExecuteBeforeEnterNavigation(
        BeforeEnterEvent beforeNavigation, NavigationEvent event,
        List<HasElement> chain) {

    // Always send the beforeNavigation event first to the registered
    // listeners
    List<BeforeEnterHandler> registeredEnterHandlers = new ArrayList<>(
            beforeNavigation.getUI()
                    .getNavigationListeners(BeforeEnterHandler.class));

    Optional<Integer> result = sendBeforeEnterEvent(registeredEnterHandlers,
            event, beforeNavigation, null);
    if (result.isPresent()) {
        return result;
    }

    if (chain.isEmpty()) {
        return sendBeforeEnterEventAndPopulateChain(beforeNavigation, event,
                chain);
    } else {
        return sendBeforeEnterEventToExistingChain(beforeNavigation, event,
                chain);
    }
}
 
Example #3
Source File: RouterTestServlet.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    Location location = event.getUI().getInternals()
            .getActiveViewLocation();
    if (!location.getPath().isEmpty()) {
        VaadinSession.getCurrent().getSession().invalidate();
    }
}
 
Example #4
Source File: LoadingIndicatorView.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {

    NativeButton disableButton = new NativeButton(
            "Disable default loading indicator theme and add custom");
    disableButton.setId("disable-theme");
    disableButton.addClickListener(clickEvent -> {
        clickEvent.getSource().getUI().get()
                .getLoadingIndicatorConfiguration()
                .setApplyDefaultTheme(false);
        clickEvent.getSource().getUI().get().getPage()
                .addStyleSheet("/loading-indicator.css");
    });
    add(disableButton);
    add(divWithText("First delay: "
            + getLoadingIndicatorConfiguration().getFirstDelay()));
    add(divWithText("Second delay: "
            + getLoadingIndicatorConfiguration().getSecondDelay()));
    add(divWithText("Third delay: "
            + getLoadingIndicatorConfiguration().getThirdDelay()));

    int[] delays = new int[] { 100, 200, 500, 1000, 2000, 5000, 10000 };
    for (int delay : delays) {
        add(createButton("Trigger event which takes " + delay + "ms",
                "wait" + delay, e -> delay(delay)));
    }
}
 
Example #5
Source File: RouterTestServlet.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    WrappedSession session = VaadinSession.getCurrent().getSession();
    if (session == null) {
        sessionId.setText("No session");
    } else {
        sessionId.setText("Session id: " + session.getId());
    }
}
 
Example #6
Source File: RequestParametersView.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    requestParamLabel.setText(event.getLocation().getQueryParameters()
            .getParameters()
            .getOrDefault(REQUEST_PARAM_NAME, Collections.emptyList())
            .stream().findFirst().orElse(NO_INPUT_TEXT));

}
 
Example #7
Source File: RerouteView.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    if (reroute) {
        event.rerouteToError(NotFoundException.class,
                "Rerouting to error view");
    }

    super.beforeEnter(event);
}
 
Example #8
Source File: PushRouteNotFoundView.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public int setErrorParameter(BeforeEnterEvent event,
        ErrorParameter<NotFoundException> parameter) {
    String path = event.getLocation().getPath();
    if (PUSH_NON_EXISTENT_PATH.equals(path)) {
        isPushPath = true;
        return HttpServletResponse.SC_NOT_FOUND;
    } else {
        return super.setErrorParameter(event, parameter);
    }
}
 
Example #9
Source File: AbstractNavigationStateRenderer.java    From flow with Apache License 2.0 5 votes vote down vote up
private Optional<Integer> notifyNavigationTarget(NavigationEvent event,
        BeforeEnterEvent beforeNavigation,
        LocationChangeEvent locationChangeEvent,
        Component componentInstance) {

    notifyNavigationTarget(componentInstance, event, beforeNavigation,
            locationChangeEvent);

    return handleTriggeredBeforeEvent(event, beforeNavigation);
}
 
Example #10
Source File: AbstractNavigationStateRenderer.java    From flow with Apache License 2.0 5 votes vote down vote up
private Optional<Integer> sendBeforeEnterEvent(NavigationEvent event,
        BeforeEnterEvent beforeNavigation,
        BeforeEnterHandler eventHandler) {
    eventHandler.beforeEnter(beforeNavigation);
    validateBeforeEvent(beforeNavigation);
    return handleTriggeredBeforeEvent(event, beforeNavigation);
}
 
Example #11
Source File: AbstractNavigationStateRenderer.java    From flow with Apache License 2.0 5 votes vote down vote up
private Optional<Integer> sendBeforeEnterEventAndPopulateChain(
        BeforeEnterEvent beforeNavigation, NavigationEvent event,
        List<HasElement> chain) {
    List<HasElement> oldChain = event.getUI().getInternals()
            .getActiveRouterTargetsChain();

    // Create the chain components if missing.
    List<Class<? extends HasElement>> typesChain = getTypesChain();

    try {
        for (Class<? extends HasElement> elementType : typesChain) {
            HasElement element = getRouteTarget(elementType, event);

            chain.add(element);

            List<BeforeEnterHandler> chainEnterHandlers = new ArrayList<>(
                    EventUtil.collectBeforeEnterObserversFromChainElement(
                            element, oldChain));

            final boolean lastElement = chain.size() == typesChain.size();
            Optional<Integer> result = sendBeforeEnterEvent(
                    chainEnterHandlers, event, beforeNavigation,
                    lastElement ? chain : null);
            if (result.isPresent()) {
                return result;
            }
        }

        return Optional.empty();

    } finally {

        // Reverse the chain to preserve backwards compatibility.
        // The events were sent starting from parent layout and ending with
        // the navigation target component.
        // The chain ought to be output starting with the navigation target
        // component as the first element.
        Collections.reverse(chain);
    }
}
 
Example #12
Source File: ErrorTarget.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public int setErrorParameter(BeforeEnterEvent event,
        ErrorParameter<NotFoundException> parameter) {
    getElement().appendChild(ElementFactory.createDiv(
            "This is the error view. Next element contains the error path "),
            ElementFactory.createDiv(event.getLocation().getPath())
                    .setAttribute("id", "error-path"));
    return HttpServletResponse.SC_NOT_FOUND;
}
 
Example #13
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);
}
 
Example #14
Source File: ErrorStateRenderer.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) {
    @SuppressWarnings({ "rawtypes", "unchecked" })
    int statusCode = ((HasErrorParameter) componentInstance)
            .setErrorParameter(beforeEnterEvent,
                    ((ErrorNavigationEvent) navigationEvent)
                            .getErrorParameter());

    locationChangeEvent.setStatusCode(statusCode);
}
 
Example #15
Source File: ServerSideForwardView.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    if (Boolean.TRUE.equals(parameter)) {
        event.forwardTo("client-view");
    }

    parameter = null;
}
 
Example #16
Source File: NPEHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public int setErrorParameter(BeforeEnterEvent event,
        ErrorParameter<NullPointerException> parameter) {
    getElement().setText("NPE is thrown " + event.getLocation().getPath());

    Exception exception = parameter.getCaughtException();
    LoggerFactory.getLogger(NPEHandler.class).error(exception.getMessage(),
            exception);

    setId("no-route");
    return 500;
}
 
Example #17
Source File: LoginView.java    From radman with MIT License 5 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    securityService.initiateFallbackUser();
    if (event.getLocation().getQueryParameters().getParameters().containsKey("error")) {
        messageLabel.getClassList().add("visible");
    }
}
 
Example #18
Source File: ServerSideForwardView.java    From flow with Apache License 2.0 4 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    event.forwardTo("client-view");
}
 
Example #19
Source File: RerouteToWithBeforeEnter.java    From flow with Apache License 2.0 4 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    event.rerouteTo(ServerSideView.class);
}
 
Example #20
Source File: ViewWithAllEvents.java    From flow with Apache License 2.0 4 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    addLog("2 beforeEnter");
}
 
Example #21
Source File: ErrorStateRendererTest.java    From flow with Apache License 2.0 4 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    event.rerouteToError(NullPointerException.class);
}
 
Example #22
Source File: RouterTestServlet.java    From flow with Apache License 2.0 4 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    throw new RuntimeException(
            "Intentionally caused by " + getClass().getSimpleName());
}
 
Example #23
Source File: ForwardToWithBeforeEnter.java    From flow with Apache License 2.0 4 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    event.rerouteTo(ServerSideView.class);
}
 
Example #24
Source File: AbstractDivView.java    From flow with Apache License 2.0 4 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    onShow();
}
 
Example #25
Source File: RefreshCloseConnectionView.java    From flow with Apache License 2.0 4 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    /*
     * Workaround for "restartApplication" parameter usage: I wasn't able to
     * get it working properly.
     *
     * This code shows "init" of first load and it logs more messages on
     * view refresh (even though the view preserves its state in refresh).
     *
     * It's so complicated because IT should be able to completely "reset"
     * the state of the view between tests execution. To be able to do that
     * a parameter is used: if parameter is different then view is
     * recreated.
     */
    Set<String> params = event.getLocation().getQueryParameters()
            .getParameters().keySet();
    String newParam = null;
    if (!params.isEmpty()) {
        newParam = params.iterator().next();
    }
    boolean isInitial = false;
    if (Objects.equals(param, newParam)) {
        if (count == 0) {
            isInitial = true;
        }
        count++;
    } else {
        removeAll();
        param = newParam;
        count = 1;
        isInitial = true;
    }
    UI ui = event.getUI();
    if (isInitial) {
        log("Init");
    } else {
        if (ui.getInternals().getPushConnection().isConnected()) {
            log("Still connected");
        }
        log("Refresh");
        new Thread() {
            @Override
            public void run() {
                ui.accessSynchronously(() -> log("Push"));
            }
        }.start();
    }
}
 
Example #26
Source File: NPETargetView.java    From flow with Apache License 2.0 4 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    event.rerouteToError(NullPointerException.class);
}
 
Example #27
Source File: ISELayout.java    From flow with Apache License 2.0 4 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    event.forwardTo(ISETargetView.class);
}
 
Example #28
Source File: PushLayout.java    From flow with Apache License 2.0 4 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    if (FORWARD_PATH.equals(event.getLocation().getPath())) {
        event.forwardTo(ForwardPage.class);
    }
}
 
Example #29
Source File: ISEHandler.java    From flow with Apache License 2.0 4 votes vote down vote up
@Override
public int setErrorParameter(BeforeEnterEvent event,
        ErrorParameter<IllegalStateException> parameter) {
    return 500;
}
 
Example #30
Source File: ForwardToView.java    From flow with Apache License 2.0 4 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    event.forwardTo("com.vaadin.flow.uitest.ui.BasicComponentView");
}