com.vaadin.flow.router.RouteConfiguration Java Examples
The following examples show how to use
com.vaadin.flow.router.RouteConfiguration.
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: VaadinServiceTest.java From flow with Apache License 2.0 | 6 votes |
@Test public void should_reported_routing_hybrid() { VaadinServiceInitListener initListener = event -> { RouteConfiguration.forApplicationScope().setRoute("test", TestView.class); }; UsageStatistics.markAsUsed(Constants.STATISTIC_ROUTING_CLIENT, Version.getFullVersion()); MockInstantiator instantiator = new MockInstantiator(initListener); MockVaadinServletService service = new MockVaadinServletService(); service.init(instantiator); Assert.assertTrue(UsageStatistics.getEntries().anyMatch( e -> Constants.STATISTIC_ROUTING_HYBRID.equals(e.getName()))); Assert.assertFalse(UsageStatistics.getEntries().anyMatch( e -> Constants.STATISTIC_ROUTING_CLIENT.equals(e.getName()))); Assert.assertFalse(UsageStatistics.getEntries().anyMatch( e -> Constants.STATISTIC_ROUTING_SERVER.equals(e.getName()))); }
Example #2
Source File: TestingServiceInitListener.java From flow with Apache License 2.0 | 6 votes |
@Override public void serviceInit(ServiceInitEvent event) { event.getSource().addUIInitListener(this::handleUIInit); initCount.incrementAndGet(); RouteConfiguration configuration = RouteConfiguration .forApplicationScope(); if (!configuration .isPathAvailable(DYNAMICALLY_REGISTERED_ROUTE)) { configuration.setRoute(DYNAMICALLY_REGISTERED_ROUTE, DynamicallyRegisteredRoute.class); } event.addRequestHandler((session, request, response) -> { requestCount.incrementAndGet(); return false; }); }
Example #3
Source File: ErrorStateRendererTest.java From flow with Apache License 2.0 | 6 votes |
@Test public void handle_errorViewLayoutForwardsToAView_viewIsNavigated() { UI ui = configureMocks(); NavigationState state = new NavigationStateBuilder(ui.getRouter()) .withTarget(HappyPathErrorTarget.class).build(); ErrorStateRenderer renderer = new ErrorStateRenderer(state); RouteConfiguration.forRegistry(ui.getRouter().getRegistry()) .setAnnotatedRoute(HappyPathViewView.class); ErrorParameter<Exception> parameter = new ErrorParameter<>( Exception.class, new NullPointerException()); ErrorNavigationEvent event = new ErrorNavigationEvent(ui.getRouter(), new Location("error"), ui, NavigationTrigger.CLIENT_SIDE, parameter); Assert.assertEquals(200, renderer.handle(event)); List<HasElement> chain = ui.getInternals() .getActiveRouterTargetsChain(); Assert.assertEquals(1, chain.size()); Assert.assertEquals(HappyPathViewView.class, chain.get(0).getClass()); }
Example #4
Source File: ErrorStateRendererTest.java From flow with Apache License 2.0 | 6 votes |
@Test(expected = ExceptionsTrace.class) public void handle_openNPEErrorTarget_infiniteReroute_noStackOverflow_throws() { UI ui = configureMocks(); NavigationState state = new NavigationStateBuilder(ui.getRouter()) .withTarget(InfiniteLoopErrorTarget.class).build(); ErrorStateRenderer renderer = new ErrorStateRenderer(state); RouteConfiguration.forRegistry(ui.getRouter().getRegistry()) .setAnnotatedRoute(InfiniteLoopNPEView.class); ErrorParameter<Exception> parameter = new ErrorParameter<>( Exception.class, new NullPointerException()); ErrorNavigationEvent event = new ErrorNavigationEvent(ui.getRouter(), new Location("error"), ui, NavigationTrigger.CLIENT_SIDE, parameter); // event should route to ErrorTarget whose layout forwards to NPEView // which reroute to ErrorTarget and this is an infinite loop renderer.handle(event); }
Example #5
Source File: NavigationStateRendererTest.java From flow with Apache License 2.0 | 6 votes |
@Test public void getRouterLayoutForMulipleLayers() throws Exception { NavigationStateRenderer childRenderer = new NavigationStateRenderer( navigationStateFromTarget(ChildConfiguration.class)); RouteConfiguration.forRegistry(router.getRegistry()) .setAnnotatedRoute(ChildConfiguration.class); List<Class<? extends RouterLayout>> routerLayoutTypes = childRenderer .getRouterLayoutTypes(ChildConfiguration.class, router); Assert.assertEquals("Not all expected layouts were found", 2, routerLayoutTypes.size()); Assert.assertEquals("Wrong class found as first in array", MiddleLayout.class, routerLayoutTypes.get(0)); Assert.assertEquals("Wrong class found as second in array", RouteParentLayout.class, routerLayoutTypes.get(1)); }
Example #6
Source File: LocationObserverTest.java From flow with Apache License 2.0 | 6 votes |
@Test public void navigation_and_locale_change_should_fire_locale_change_observer() throws InvalidRouteConfigurationException { router = new Router(new TestRouteRegistry()); ui = new RouterTestUI(router); RouteConfiguration.forRegistry(router.getRegistry()).setAnnotatedRoute(Translations.class); ui.navigate(""); Assert.assertEquals("Expected event amount was wrong", 1, eventCollector.size()); Assert.assertEquals( "Received locale change event for locale: " + Locale.getDefault().getDisplayName(), eventCollector.get(0)); ui.setLocale(Locale.CANADA); Assert.assertEquals("Expected event amount was wrong", 2, eventCollector.size()); Assert.assertEquals( "Received locale change event for locale: " + Locale.CANADA.getDisplayName(), eventCollector.get(1)); }
Example #7
Source File: BootstrapHandlerPushConfigurationTest.java From flow with Apache License 2.0 | 6 votes |
private void assertPushConfigurationForComponent( Class<? extends Component> annotatedClazz, Class<? extends PushConnection> pushConnectionType) throws InvalidRouteConfigurationException { BootstrapHandler bootstrapHandler = new BootstrapHandler(); VaadinResponse response = mock(VaadinResponse.class); RouteConfiguration routeConfiguration = RouteConfiguration .forRegistry(service.getRouteRegistry()); routeConfiguration.update(() -> { routeConfiguration.getHandledRegistry().clean(); routeConfiguration.setAnnotatedRoute(annotatedClazz); }); final BootstrapHandler.BootstrapContext context = bootstrapHandler .createAndInitUI(UI.class, createVaadinRequest(), response, session); Push pushAnnotation = annotatedClazz.getAnnotation(Push.class); Assert.assertNotNull("Should have @Push annotated component", pushAnnotation); PushConfiguration pushConfiguration = context.getUI() .getPushConfiguration(); assertPushConfiguration(pushConfiguration, pushAnnotation); assertThat(context.getUI().getInternals().getPushConnection(), instanceOf(pushConnectionType)); }
Example #8
Source File: BootstrapHandlerTest.java From flow with Apache License 2.0 | 6 votes |
private void initUI(UI ui, VaadinRequest request, Set<Class<? extends Component>> navigationTargets) throws InvalidRouteConfigurationException { RouteConfiguration routeConfiguration = RouteConfiguration .forRegistry(service.getRouteRegistry()); routeConfiguration.update(() -> { routeConfiguration.getHandledRegistry().clean(); navigationTargets.forEach(routeConfiguration::setAnnotatedRoute); }); this.request = request; ui.doInit(request, 0); ui.getRouter().initializeUI(ui, request); context = new BootstrapContext(request, null, session, ui, this::contextRootRelativePath); ui.getInternals().setContextRoot(contextRootRelativePath(request)); }
Example #9
Source File: RouteRegistryInitializerTest.java From flow with Apache License 2.0 | 6 votes |
@Test public void routeRegistry_fails_for_multiple_registration_of_same_route() { expectedEx.expect(InvalidRouteConfigurationException.class); expectedEx.expectMessage( "Navigation targets must have unique routes, found navigation targets " + "'com.vaadin.flow.server.startup.RouteRegistryInitializerTest$NavigationTargetFoo' and " + "'com.vaadin.flow.server.startup.RouteRegistryInitializerTest$NavigationTargetFoo2' with the same route."); RouteConfiguration.forRegistry(registry) .setAnnotatedRoute(NavigationTargetFoo.class); Assert.assertTrue("RouteRegistry should be initialized", registry.hasNavigationTargets()); // Test should fail on this as there already exists a route for this // route RouteConfiguration.forRegistry(registry) .setAnnotatedRoute(NavigationTargetFoo2.class); }
Example #10
Source File: UpNavigationHelper.java From vaadin-app-layout with Apache License 2.0 | 6 votes |
public static Optional<RouteData> getClosestRoute(String url) { if (url.lastIndexOf("/") > 0) { Optional<RouteSimilarity> result = RouteConfiguration.forApplicationScope() .getAvailableRoutes() .stream() .filter(routeData -> !routeData.getUrl().equals(url) || routeData.getRouteAliases().stream().anyMatch(routeAliasData -> routeAliasData.getUrl().equals(url))) .map(routeData -> new RouteSimilarity(routeData, url)) .filter(routeSimilarity -> routeSimilarity.getSimilarity() > 0) .max(Comparator.comparingInt(RouteSimilarity::getSimilarity)); if (result.isPresent()) { return Optional.ofNullable(result.get().getRouteData()); } } return Optional.empty(); }
Example #11
Source File: UidlWriterTest.java From flow with Apache License 2.0 | 5 votes |
private UI initializeUIForDependenciesTest(UI ui) throws Exception { mocks = new MockServletServiceSessionSetup(); VaadinSession session = mocks.getSession(); session.lock(); ui.getInternals().setSession(session); RouteConfiguration routeConfiguration = RouteConfiguration .forRegistry(ui.getRouter().getRegistry()); routeConfiguration.update(() -> { routeConfiguration.getHandledRegistry().clean(); routeConfiguration.setAnnotatedRoute(BaseClass.class); }); for (String type : new String[] { "html", "js", "css" }) { mocks.getServlet().addServletContextResource("inline." + type, "inline." + type); } HttpServletRequest servletRequestMock = mock(HttpServletRequest.class); VaadinServletRequest vaadinRequestMock = mock( VaadinServletRequest.class); when(vaadinRequestMock.getHttpServletRequest()) .thenReturn(servletRequestMock); ui.doInit(vaadinRequestMock, 1); ui.getRouter().initializeUI(ui, vaadinRequestMock); return ui; }
Example #12
Source File: VaadinServiceTest.java From flow with Apache License 2.0 | 5 votes |
@Test public void should_reported_routing_server() { VaadinServiceInitListener initListener = event -> { RouteConfiguration.forApplicationScope().setRoute("test", TestView.class); }; MockInstantiator instantiator = new MockInstantiator(initListener); MockVaadinServletService service = new MockVaadinServletService(); service.init(instantiator); Assert.assertTrue(UsageStatistics.getEntries().anyMatch( e -> Constants.STATISTIC_ROUTING_SERVER.equals(e.getName()))); }
Example #13
Source File: VaadinServiceTest.java From flow with Apache License 2.0 | 5 votes |
@Test public void testServiceInitListener_accessApplicationRouteRegistry_registryAvailable() { VaadinServiceInitListener initListener = event -> { Assert.assertNotNull("service init should have set thread local", VaadinService.getCurrent()); Router router = event.getSource().getRouter(); Assert.assertNotEquals("Router should be initialized", router); Assert.assertNotEquals("registry should be initialized", router.getRegistry()); RouteConfiguration.forApplicationScope().setRoute("test", TestView.class); }; MockInstantiator instantiator = new MockInstantiator(initListener); MockVaadinServletService service = new MockVaadinServletService(); service.init(instantiator); // the following will allow the route configuration call to work VaadinService.setCurrent(service); List<RouteData> availableRoutes = RouteConfiguration .forApplicationScope().getAvailableRoutes(); VaadinService.setCurrent(null); Assert.assertEquals(1, availableRoutes.size()); Assert.assertEquals(availableRoutes.get(0).getUrl(), "test"); }
Example #14
Source File: ErrorStateRendererTest.java From flow with Apache License 2.0 | 5 votes |
@Test(expected = ExceptionsTrace.class) public void handle_openNPEView_infiniteReroute_noStackOverflow_throws() { UI ui = configureMocks(); NavigationState state = new NavigationStateBuilder(ui.getRouter()) .withTarget(InfiniteLoopNPEView.class).build(); NavigationStateRenderer renderer = new NavigationStateRenderer(state); RouteConfiguration.forRegistry(ui.getRouter().getRegistry()) .setAnnotatedRoute(InfiniteLoopNPEView.class); ((ApplicationRouteRegistry) ui.getRouter().getRegistry()) .setErrorNavigationTargets( Collections.singleton(InfiniteLoopErrorTarget.class)); NavigationEvent event = new NavigationEvent(ui.getRouter(), new Location("npe"), ui, NavigationTrigger.CLIENT_SIDE); // event should route to ErrorTarget whose layout forwards to NPEView // which reroute to ErrorTarget and this is an infinite loop renderer.handle(event); JsonObject routerLinkState = Json.createObject(); routerLinkState.put("href", "router_link"); routerLinkState.put("scrollPositionX", 0d); routerLinkState.put("scrollPositionY", 0d); event = new NavigationEvent(ui.getRouter(), new Location("npe"), ui, NavigationTrigger.ROUTER_LINK, routerLinkState, false); // event should route to ErrorTarget whose layout forwards to NPEView // which reroute to ErrorTarget and this is an infinite loop renderer.handle(event); }
Example #15
Source File: RouteRegistryInitializer.java From flow with Apache License 2.0 | 5 votes |
private boolean handleAmbiguousRoute(RouteConfiguration routeConfiguration, Class<? extends Component> configuredNavigationTarget, Class<? extends Component> navigationTarget) { if (GenericTypeReflector.isSuperType(navigationTarget, configuredNavigationTarget)) { return true; } else if (GenericTypeReflector.isSuperType(configuredNavigationTarget, navigationTarget)) { routeConfiguration.removeRoute(configuredNavigationTarget); routeConfiguration.setAnnotatedRoute(navigationTarget); return true; } return false; }
Example #16
Source File: RouteRegistryInitializer.java From flow with Apache License 2.0 | 5 votes |
private void setAnnotatedRoutes(RouteConfiguration routeConfiguration, Set<Class<? extends Component>> routes) { routeConfiguration.getHandledRegistry().clean(); for (Class<? extends Component> navigationTarget : routes) { try { routeConfiguration.setAnnotatedRoute(navigationTarget); } catch (AmbiguousRouteConfigurationException exception) { if (!handleAmbiguousRoute(routeConfiguration, exception.getConfiguredNavigationTarget(), navigationTarget)) { throw exception; } } } }
Example #17
Source File: NavigationStateRendererTest.java From flow with Apache License 2.0 | 5 votes |
@Test public void getRouterLayoutForSingleParent() throws Exception { NavigationStateRenderer childRenderer = new NavigationStateRenderer( navigationStateFromTarget(SingleView.class)); RouteConfiguration.forRegistry(router.getRegistry()) .setAnnotatedRoute(SingleView.class); List<Class<? extends RouterLayout>> routerLayoutTypes = childRenderer .getRouterLayoutTypes(SingleView.class, router); Assert.assertEquals("Not all expected layouts were found", 1, routerLayoutTypes.size()); Assert.assertEquals("Wrong class found", RouteParentLayout.class, routerLayoutTypes.get(0)); }
Example #18
Source File: UpNavigationHelper.java From vaadin-app-layout with Apache License 2.0 | 4 votes |
public static void performUpNavigation(Class<? extends Component> currentNavigation) { getClosestRoute(RouteConfiguration.forSessionScope().getUrl(currentNavigation)) .ifPresent(routeData -> UI.getCurrent().navigate(routeData.getUrl())); }
Example #19
Source File: ScannerTestComponents.java From flow with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") public static void registerUserRoute(RouteConfiguration config, String userId) { config.setRoute(userId, DynamicComponentClass.class, DynamicLayoutClass.class); }
Example #20
Source File: UpNavigationHelper.java From vaadin-app-layout with Apache License 2.0 | 4 votes |
public void register(Class<? extends Component> className) { getRoutesForClassName(className) .forEach(routeData -> { registeredRoutes.put(routeData, RouteConfiguration.forSessionScope().getUrl(className)); }); }
Example #21
Source File: InvalidUrlTest.java From flow with Apache License 2.0 | 4 votes |
private static void initUI(UI ui, String initialLocation, ArgumentCaptor<Integer> statusCodeCaptor) throws InvalidRouteConfigurationException { try { VaadinServletRequest request = Mockito .mock(VaadinServletRequest.class); VaadinResponse response = Mockito.mock(VaadinResponse.class); String pathInfo; if (initialLocation.isEmpty()) { pathInfo = null; } else { Assert.assertFalse(initialLocation.startsWith("/")); pathInfo = "/" + initialLocation; } Mockito.when(request.getPathInfo()).thenReturn(pathInfo); ServletConfig servletConfig = new MockServletConfig(); VaadinServlet servlet = new VaadinServlet(); servlet.init(servletConfig); VaadinService service = servlet.getService(); service.setCurrentInstances(request, response); MockVaadinSession session = new AlwaysLockedVaadinSession(service); DeploymentConfiguration config = Mockito .mock(DeploymentConfiguration.class); Mockito.when(config.isProductionMode()).thenReturn(false); session.lock(); session.setConfiguration(config); ui.getInternals().setSession(session); RouteConfiguration routeConfiguration = RouteConfiguration .forRegistry(ui.getRouter().getRegistry()); routeConfiguration.update(() -> { routeConfiguration.getHandledRegistry().clean(); Arrays.asList(UITest.RootNavigationTarget.class, UITest.FooBarNavigationTarget.class).forEach(routeConfiguration::setAnnotatedRoute); }); ui.doInit(request, 0); ui.getRouter().initializeUI(ui, request); session.unlock(); if (statusCodeCaptor != null) { Mockito.verify(response).setStatus(statusCodeCaptor.capture()); } } catch (ServletException e) { throw new RuntimeException(e); } }
Example #22
Source File: UITest.java From flow with Apache License 2.0 | 4 votes |
private static void initUI(UI ui, String initialLocation, ArgumentCaptor<Integer> statusCodeCaptor) throws InvalidRouteConfigurationException { try { VaadinServletRequest request = Mockito .mock(VaadinServletRequest.class); VaadinResponse response = Mockito.mock(VaadinResponse.class); String pathInfo; if (initialLocation.isEmpty()) { pathInfo = null; } else { Assert.assertFalse(initialLocation.startsWith("/")); pathInfo = "/" + initialLocation; } Mockito.when(request.getPathInfo()).thenReturn(pathInfo); ServletConfig servletConfig = new MockServletConfig(); VaadinServlet servlet = new VaadinServlet(); servlet.init(servletConfig); VaadinService service = servlet.getService(); service.setCurrentInstances(request, response); MockVaadinSession session = new AlwaysLockedVaadinSession(service); DeploymentConfiguration config = Mockito .mock(DeploymentConfiguration.class); Mockito.when(config.isProductionMode()).thenReturn(false); session.lock(); session.setConfiguration(config); ui.getInternals().setSession(session); RouteConfiguration routeConfiguration = RouteConfiguration .forRegistry(ui.getRouter().getRegistry()); routeConfiguration.update(() -> { routeConfiguration.getHandledRegistry().clean(); Arrays.asList(RootNavigationTarget.class, FooBarNavigationTarget.class, Parameterized.class, FooBarParamNavigationTarget.class) .forEach(routeConfiguration::setAnnotatedRoute); }); ui.doInit(request, 0); ui.getRouter().initializeUI(ui, request); session.unlock(); if (statusCodeCaptor != null) { Mockito.verify(response).setStatus(statusCodeCaptor.capture()); } } catch (ServletException e) { throw new RuntimeException(e); } }
Example #23
Source File: ScannerTestComponents.java From flow with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") private void registerRoute() { RouteConfiguration.forSessionScope().setRoute("foo", DynamicComponentClass.class, DynamicLayoutClass.class); }
Example #24
Source File: UpNavigationHelper.java From vaadin-app-layout with Apache License 2.0 | 4 votes |
private static Stream<RouteData> getRoutesForClassName(Class<? extends Component> className) { return RouteConfiguration.forSessionScope() .getAvailableRoutes() .stream() .filter(routeData -> routeData.getNavigationTarget() == className); }
Example #25
Source File: ScannerTestComponents.java From flow with Apache License 2.0 | 4 votes |
public RouteWithService() { UserRouteService.registerUserRoute(RouteConfiguration.forSessionScope(), "donald"); }
Example #26
Source File: UI.java From flow with Apache License 2.0 | 3 votes |
/** * Updates this UI to show the view corresponding to the given navigation * target with the specified parameters. The parameters needs to comply with * the ones defined in one of the {@link com.vaadin.flow.router.Route} or * {@link com.vaadin.flow.router.RouteAlias} annotating the navigationTarget * and with any {@link com.vaadin.flow.router.RoutePrefix} annotating the * parent layouts of the navigationTarget. * <p> * Besides the navigation to the {@code location} this method also updates * the browser location (and page history). * * @param navigationTarget * navigation target to navigate to. * @param parameters * parameters to pass to view. * @throws IllegalArgumentException * if navigationTarget is a {@link HasUrlParameter} with a * mandatory parameter, but parameters argument doesn't * provide {@link HasUrlParameterFormat#PARAMETER_NAME} * parameter. * @throws NotFoundException * in case there is no route defined for the given * navigationTarget matching the parameters. */ public void navigate(Class<? extends Component> navigationTarget, RouteParameters parameters) { RouteConfiguration configuration = RouteConfiguration .forRegistry(getRouter().getRegistry()); navigate(configuration.getUrl(navigationTarget, parameters)); }