com.vaadin.flow.server.VaadinContext Java Examples
The following examples show how to use
com.vaadin.flow.server.VaadinContext.
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: WebComponentConfigurationRegistry.java From flow with Apache License 2.0 | 6 votes |
/** * Get WebComponentRegistry instance for given servlet context. * * @param context * {@link VaadinService} to keep the instance in * @return WebComponentRegistry instance */ public static WebComponentConfigurationRegistry getInstance( VaadinContext context) { assert context != null; WebComponentConfigurationRegistry attribute = context.getAttribute( WebComponentConfigurationRegistry.class, WebComponentConfigurationRegistry::createRegistry); if (attribute == null) { throw new IllegalStateException( "Null WebComponentConfigurationRegistry obtained from VaadinContext of type " + context.getClass().getName()); } return attribute; }
Example #2
Source File: ApplicationRouteRegistry.java From flow with Apache License 2.0 | 6 votes |
/** * Gets the route registry for the given Vaadin context. If the Vaadin * context has no route registry, a new instance is created and assigned to * the context. * * @param context * the vaadin context for which to get a route registry, not * <code>null</code> * @return a registry instance for the given servlet context, not * <code>null</code> */ public static ApplicationRouteRegistry getInstance(VaadinContext context) { assert context != null; ApplicationRouteRegistryWrapper attribute; synchronized (context) { attribute = context .getAttribute(ApplicationRouteRegistryWrapper.class); if (attribute == null) { attribute = new ApplicationRouteRegistryWrapper( createRegistry(context)); context.setAttribute(attribute); } } return attribute.getRegistry(); }
Example #3
Source File: BrowserLiveReloadAccessTest.java From flow with Apache License 2.0 | 6 votes |
@Test public void getLiveReload_devMode_contextHasReloadInstance_instanceIsReturned() { VaadinService service = Mockito.mock(VaadinService.class); DeploymentConfiguration config = Mockito .mock(DeploymentConfiguration.class); Mockito.when(service.getDeploymentConfiguration()).thenReturn(config); Mockito.when(config.isProductionMode()).thenReturn(false); Mockito.when(config.isDevModeLiveReloadEnabled()).thenReturn(true); VaadinContext context = Mockito.mock(VaadinContext.class); Mockito.when(service.getContext()).thenReturn(context); BrowserLiveReloadImpl reload = Mockito .mock(BrowserLiveReloadImpl.class); Mockito.when(context.getAttribute(BrowserLiveReloadImpl.class)) .thenReturn(reload); Assert.assertSame(reload, access.getLiveReload(service)); }
Example #4
Source File: BrowserLiveReloadAccess.java From flow with Apache License 2.0 | 6 votes |
/** * Returns a {@link BrowserLiveReload} instance for the given * {@code service}. * <p> * Returns {@code null} if production mode is enabled for the service. * * @param service * a service * @return a BrowserLiveReload instance or null for production mode */ public BrowserLiveReload getLiveReload(VaadinService service) { if (service.getDeploymentConfiguration().isProductionMode()) { LoggerFactory.getLogger(BrowserLiveReloadAccess.class) .debug("BrowserLiveReloadAccess::getLiveReload is called in production mode."); return null; } if (!service.getDeploymentConfiguration().isDevModeLiveReloadEnabled()) { LoggerFactory.getLogger(BrowserLiveReloadAccess.class) .debug("BrowserLiveReloadAccess::getLiveReload is called when live reload is disabled."); return null; } VaadinContext context = service.getContext(); BrowserLiveReloadImpl liveReload; synchronized (this) { liveReload = context.getAttribute(BrowserLiveReloadImpl.class); if (liveReload == null) { liveReload = new BrowserLiveReloadImpl(); context.setAttribute(BrowserLiveReloadImpl.class, liveReload); } } return liveReload; }
Example #5
Source File: VaadinIntegration.java From HotswapAgent with GNU General Public License v2.0 | 5 votes |
/** * Update Flow route registry and push refresh to UIs (concrete parameter * types as {@link org.hotswap.agent.command.ReflectionCommand} determines * the method from actual argument types). * * @param addedClasses * returns classes that have been added or modified * @param modifiedClasses * returns classes that have been deleted */ public void updateRoutes(HashSet<Class<?>> addedClasses, HashSet<Class<?>> modifiedClasses) { assert (vaadinServlet != null); LOGGER.debug("The following classes were added:"); addedClasses.forEach(clazz -> LOGGER.debug("+ {}", clazz)); LOGGER.debug("The following classes were modified:"); modifiedClasses.forEach(clazz -> LOGGER.debug("# {}", clazz)); Method getInstanceMethod = null; Object getInstanceMethodParam = null; try { // Vaadin 14.2+ getInstanceMethod = ApplicationRouteRegistry.class.getMethod("getInstance", VaadinContext.class); getInstanceMethodParam = vaadinServlet.getService().getContext(); } catch (NoSuchMethodException ex1) { // In Vaadin 14.1, this method instead takes a ServletContext parameter LOGGER.debug("ApplicationRouteRegistry::getInstance(VaadinContext) not found"); try { getInstanceMethod = ApplicationRouteRegistry.class.getMethod("getInstance", ServletContext.class); getInstanceMethodParam = vaadinServlet.getServletContext(); } catch (NoSuchMethodException ex2) { // In Vaadin 14.1, this method takes a ServletContext parameter LOGGER.warning("Unable to obtain ApplicationRouteRegistry instance; routes are not updated "); return; } } try { ApplicationRouteRegistry registry = (ApplicationRouteRegistry) getInstanceMethod.invoke(null, getInstanceMethodParam); updateRouteRegistry(registry, addedClasses, modifiedClasses, Collections.emptySet()); } catch (IllegalAccessException | InvocationTargetException ex) { LOGGER.warning("Unable to obtain ApplicationRouteRegistry instance; routes are not updated:", ex); } }
Example #6
Source File: BrowserLiveReloadAccessTest.java From flow with Apache License 2.0 | 5 votes |
public static BrowserLiveReload mockBrowserLiveReloadImpl( VaadinContext context) { BrowserLiveReloadImpl liveReload = Mockito .mock(BrowserLiveReloadImpl.class); context.setAttribute(BrowserLiveReloadImpl.class, liveReload); return liveReload; }
Example #7
Source File: BrowserLiveReloadAccessTest.java From flow with Apache License 2.0 | 5 votes |
@Test public void getLiveReload_devMode_contextHasNoReloadInstance_instanceIsCreated() { VaadinService service = Mockito.mock(VaadinService.class); DeploymentConfiguration config = Mockito .mock(DeploymentConfiguration.class); Mockito.when(service.getDeploymentConfiguration()).thenReturn(config); Mockito.when(config.isProductionMode()).thenReturn(false); Mockito.when(config.isDevModeLiveReloadEnabled()).thenReturn(true); VaadinContext context = Mockito.mock(VaadinContext.class); Mockito.when(service.getContext()).thenReturn(context); Assert.assertNotNull(access.getLiveReload(service)); }
Example #8
Source File: PushHandlerTest.java From flow with Apache License 2.0 | 5 votes |
@Test public void onMessage_devMode_websocket_refreshConnection_callWithUIIsNotCalled() throws ServiceException { MockVaadinServletService service = Mockito .spy(MockVaadinServletService.class); MockDeploymentConfiguration deploymentConfiguration = (MockDeploymentConfiguration) service .getDeploymentConfiguration(); deploymentConfiguration.setProductionMode(false); deploymentConfiguration.setDevModeLiveReloadEnabled(true); VaadinContext context = service.getContext(); BrowserLiveReload liveReload = BrowserLiveReloadAccessTest .mockBrowserLiveReloadImpl(context); AtomicReference<AtmosphereResource> res = new AtomicReference<>(); runTest(service, (handler, resource) -> { AtmosphereRequest request = resource.getRequest(); Mockito.when(request .getParameter(ApplicationConstants.LIVE_RELOAD_CONNECTION)) .thenReturn(""); Mockito.when(resource.transport()).thenReturn(TRANSPORT.WEBSOCKET); handler.onMessage(resource); res.set(resource); }); Mockito.verify(service, Mockito.times(0)).requestStart(Mockito.any(), Mockito.any()); }
Example #9
Source File: WebComponentConfigurationRegistryTest.java From flow with Apache License 2.0 | 5 votes |
@Before public void init() { VaadinService service = mock(VaadinService.class); context = mock(VaadinContext.class); VaadinService.setCurrent(service); Mockito.when(service.getContext()).thenReturn(context); WebComponentConfigurationRegistry instance = createRegistry(); Mockito.when( context.getAttribute(WebComponentConfigurationRegistry.class)) .thenReturn(instance); Mockito.when(context.getAttribute( eq(WebComponentConfigurationRegistry.class), anyObject())) .thenReturn(instance); registry = WebComponentConfigurationRegistry.getInstance(context); }
Example #10
Source File: WebComponentBootstrapHandlerTest.java From flow with Apache License 2.0 | 5 votes |
private VaadinResponse getMockResponse(ByteArrayOutputStream stream) throws IOException { VaadinResponse response = Mockito.mock(VaadinResponse.class); VaadinService service = Mockito.mock(VaadinService.class); VaadinContext context = Mockito.mock(VaadinContext.class); Mockito.when(response.getOutputStream()).thenReturn(stream); Mockito.when(response.getService()).thenReturn(service); Mockito.when(service.getContext()).thenReturn(context); Mockito.when(context.getAttribute( eq(WebComponentConfigurationRegistry.class), any())).thenReturn( Mockito.mock(WebComponentConfigurationRegistry.class)); return response; }
Example #11
Source File: PushHandlerTest.java From flow with Apache License 2.0 | 5 votes |
@Test public void onConnect_devMode_websocket_refreshConnection_onConnectIsCalled_callWithUIIsNotCalled() throws ServiceException { MockVaadinServletService service = Mockito .spy(MockVaadinServletService.class); MockDeploymentConfiguration deploymentConfiguration = (MockDeploymentConfiguration) service .getDeploymentConfiguration(); deploymentConfiguration.setProductionMode(false); deploymentConfiguration.setDevModeLiveReloadEnabled(true); VaadinContext context = service.getContext(); BrowserLiveReload liveReload = BrowserLiveReloadAccessTest .mockBrowserLiveReloadImpl(context); AtomicReference<AtmosphereResource> res = new AtomicReference<>(); runTest(service, (handler, resource) -> { AtmosphereRequest request = resource.getRequest(); Mockito.when(request .getParameter(ApplicationConstants.LIVE_RELOAD_CONNECTION)) .thenReturn(""); Mockito.when(resource.transport()).thenReturn(TRANSPORT.WEBSOCKET); handler.onConnect(resource); res.set(resource); }); Mockito.verify(service, Mockito.times(0)).requestStart(Mockito.any(), Mockito.any()); Mockito.verify(liveReload).onConnect(res.get()); }
Example #12
Source File: UIInternals.java From flow with Apache License 2.0 | 4 votes |
private void addFallbackDependencies(DependencyInfo dependency) { if (isFallbackChunkLoaded) { return; } VaadinContext context = ui.getSession().getService().getContext(); FallbackChunk chunk = context.getAttribute(FallbackChunk.class); if (chunk == null) { if (getLogger().isDebugEnabled()) { getLogger().debug( "Fallback chunk is not available, skipping fallback dependencies load"); } return; } Set<String> modules = chunk.getModules(); Set<CssImportData> cssImportsData = chunk.getCssImports(); if (modules.isEmpty() && cssImportsData.isEmpty()) { getLogger().debug( "Fallback chunk is empty, skipping fallback dependencies load"); return; } List<CssImport> cssImports = dependency.getCssImports(); List<JavaScript> javaScripts = dependency.getJavaScripts(); List<JsModule> jsModules = dependency.getJsModules(); if (jsModules.stream().map(JsModule::value) .anyMatch(modules::contains)) { loadFallbackChunk(); return; } if (javaScripts.stream().map(JavaScript::value) .anyMatch(modules::contains)) { loadFallbackChunk(); return; } if (cssImports.stream().map(this::buildData) .anyMatch(cssImportsData::contains)) { loadFallbackChunk(); return; } }
Example #13
Source File: VertxVaadinService.java From vertx-vaadin with MIT License | 4 votes |
@Override protected VaadinContext constructVaadinContext() { return new VertxVaadinContext(getVertx()); }
Example #14
Source File: IndexHtmlRequestHandler.java From flow with Apache License 2.0 | 4 votes |
@Override public boolean synchronizedHandleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException { Document indexDocument = getIndexHtmlDocument(request); prependBaseHref(request, indexDocument); JsonObject initialJson = Json.createObject(); if (request.getService().getBootstrapInitialPredicate() .includeInitialUidl(request)) { includeInitialUidl(initialJson, session, request, response); indexHtmlResponse = new IndexHtmlResponse(request, response, indexDocument, UI.getCurrent()); // App might be using classic server-routing, which is true // unless we detect a call to JavaScriptBootstrapUI.connectClient session.setAttribute(SERVER_ROUTING, Boolean.TRUE); } else { indexHtmlResponse = new IndexHtmlResponse(request, response, indexDocument); } addInitialFlow(initialJson, indexDocument, session); configureErrorDialogStyles(indexDocument); showWebpackErrors(indexDocument); response.setContentType(CONTENT_TYPE_TEXT_HTML_UTF_8); VaadinContext context = session.getService().getContext(); AppShellRegistry registry = AppShellRegistry.getInstance(context); DeploymentConfiguration config = session.getConfiguration(); if (!config.isProductionMode()) { UsageStatisticsExporter.exportUsageStatisticsToDocument(indexDocument); } // modify the page based on the @PWA annotation setupPwa(indexDocument, session.getService()); // modify the page based on the @Meta, @ViewPort, @BodySize and @Inline annotations // and on the AppShellConfigurator registry.modifyIndexHtml(indexDocument, request); // modify the page based on registered IndexHtmlRequestListener:s request.getService().modifyIndexHtmlResponse(indexHtmlResponse); try { response.getOutputStream() .write(indexDocument.html().getBytes(UTF_8)); } catch (IOException e) { getLogger().error("Error writing 'index.html' to response", e); return false; } return true; }
Example #15
Source File: ServletDeployer.java From flow with Apache License 2.0 | 4 votes |
@Override public VaadinContext getVaadinContext() { ensureServletContext(); return new VaadinServletContext(servletContext); }
Example #16
Source File: ApplicationRouteRegistry.java From flow with Apache License 2.0 | 4 votes |
private static ApplicationRouteRegistry createRegistry( VaadinContext context) { return new ApplicationRouteRegistry(); }
Example #17
Source File: FrontendUtils.java From flow with Apache License 2.0 | 4 votes |
private static InputStream getStatsFromExternalUrl(String externalStatsUrl, VaadinContext context) { String url; // If url is relative try to get host from request // else fallback on 127.0.0.1:8080 if (externalStatsUrl.startsWith("/")) { VaadinRequest request = VaadinRequest.getCurrent(); url = getHostString(request) + externalStatsUrl; } else { url = externalStatsUrl; } try { URL uri = new URL(url); HttpURLConnection connection = (HttpURLConnection) uri .openConnection(); connection.setRequestMethod("GET"); // one minute timeout should be enough connection.setReadTimeout(60000); connection.setConnectTimeout(60000); String lastModified = connection.getHeaderField("last-modified"); if (lastModified != null) { LocalDateTime modified = ZonedDateTime .parse(lastModified, DateTimeFormatter.RFC_1123_DATE_TIME) .toLocalDateTime(); Stats statistics = context.getAttribute(Stats.class); if (statistics == null || modified.isAfter(statistics.getLastModified())) { statistics = new Stats( streamToString(connection.getInputStream()), lastModified); context.setAttribute(statistics); } return new ByteArrayInputStream( statistics.statsJson.getBytes(StandardCharsets.UTF_8)); } return connection.getInputStream(); } catch (IOException e) { getLogger().error("Failed to retrieve stats.json from the url {}.", url, e); } return null; }