com.vaadin.flow.server.VaadinService Java Examples

The following examples show how to use com.vaadin.flow.server.VaadinService. 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: FrontendUtils.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the content of the <code>stats.json</code> file produced by webpack.
 *
 * @param service
 *            the vaadin service.
 * @return the content of the file as a string, null if not found.
 * @throws IOException
 *             on error reading stats file.
 */
public static String getStatsContent(VaadinService service)
        throws IOException {
    DeploymentConfiguration config = service.getDeploymentConfiguration();
    InputStream content = null;

    if (!config.isProductionMode() && config.enableDevServer()) {
        content = getStatsFromWebpack();
    }

    if (config.isStatsExternal()) {
        content = getStatsFromExternalUrl(config.getExternalStatsUrl(),
                service.getContext());
    }

    if (content == null) {
        content = getStatsFromClassPath(service);
    }
    return content != null
            ? IOUtils.toString(content, StandardCharsets.UTF_8)
            : null;
}
 
Example #2
Source File: UidlRequestHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void writeSessionExpired() throws Exception {

    VaadinService service = new VaadinServletService(null,
            new DefaultDeploymentConfiguration(getClass(),
                    new Properties()));
    when(request.getService()).thenReturn(service);

    when(request
            .getParameter(ApplicationConstants.REQUEST_TYPE_PARAMETER))
            .thenReturn(RequestType.UIDL.getIdentifier());

    boolean result = handler.handleSessionExpired(request, response);
    Assert.assertTrue("Result should be true", result);

    String responseContent = CommunicationUtil
            .getStringWhenWriteBytesOffsetLength(outputStream);

    // response shouldn't contain async
    Assert.assertEquals("Invalid response",
            "for(;;);[{\"meta\":{\"sessionExpired\":true}}]",
            responseContent);
}
 
Example #3
Source File: RouterConfigurationUrlResolvingTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Before
public void init() throws NoSuchFieldException, IllegalAccessException {
    super.init();
    ui = new RouterTestUI(router);
    ui.getSession().lock();
    ui.getSession().setConfiguration(configuration);

    VaadinService.setCurrent(service);

    Mockito.when(service.getDeploymentConfiguration())
            .thenReturn(configuration);
    Mockito.when(service.getRouter()).thenReturn(router);

    Mockito.when(configuration.isProductionMode()).thenReturn(true);
    routeConfiguration = RouteConfiguration
            .forRegistry(router.getRegistry());
}
 
Example #4
Source File: BrowserLiveReloadAccess.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * 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 6 votes vote down vote up
/**
 * Reload UI in browser.
 */
public void reload() {
    VaadinService vaadinService = vaadinServlet.getService();
    try {
        // TODO: Remove reflection when public flow release with
        // com.vaadin.flow.internal.BrowserLiveReload* is published
        Class<?> browserLiveReloadAccessClass = Class.forName("com.vaadin.flow.internal.BrowserLiveReloadAccess");
        Method getLiveReloadMethod = browserLiveReloadAccessClass.getMethod("getLiveReload", VaadinService.class);
        Class<?> browserLiveReloadClass = Class.forName("com.vaadin.flow.internal.BrowserLiveReload");
        Method reloadMethod = browserLiveReloadClass.getMethod("reload");
        Object browserLiveReloadAccess = vaadinService.getInstantiator()
                .getOrCreate(browserLiveReloadAccessClass);
        Object browserLiveReload = getLiveReloadMethod.invoke(browserLiveReloadAccess, vaadinService);
        reloadMethod.invoke(browserLiveReload);
        LOGGER.info("Live reload triggered");
    } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
        LOGGER.info("No live reload connection established");
        LOGGER.debug("Encountered the following exception invoking BrowserLiveReload::reload",
                ex);
    }
}
 
Example #6
Source File: FrontendUtils.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Get the latest has for the stats file in development mode. This is
 * requested from the webpack-dev-server.
 * <p>
 * In production mode and disabled dev server mode an empty string is
 * returned.
 *
 * @param service
 *            the Vaadin service.
 * @return hash string for the stats.json file, empty string if none found
 * @throws IOException
 *             if an I/O error occurs while creating the input stream.
 */
public static String getStatsHash(VaadinService service)
        throws IOException {
    DeploymentConfiguration config = service.getDeploymentConfiguration();
    if (!config.isProductionMode() && config.enableDevServer()) {
        DevModeHandler handler = DevModeHandler.getDevModeHandler();
        HttpURLConnection statsConnection = handler
                .prepareConnection("/stats.hash", "GET");
        if (statsConnection
                .getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new WebpackConnectionException(String.format(
                    NO_CONNECTION, "getting the stats content hash."));
        }
        return streamToString(statsConnection.getInputStream())
                .replaceAll("\"", "");
    }

    return "";
}
 
Example #7
Source File: WebComponentWrapperTest.java    From flow with Apache License 2.0 6 votes vote down vote up
private static WebComponentUI constructWebComponentUI(
        Element wrapperElement) {
    WebComponentUI ui = mock(WebComponentUI.class);
    when(ui.getUI()).thenReturn(Optional.of(ui));
    Element body = new Element("body");
    when(ui.getElement()).thenReturn(body);

    UIInternals internals = new UIInternals(ui);
    internals.setSession(
            new AlwaysLockedVaadinSession(mock(VaadinService.class)));
    when(ui.getInternals()).thenReturn(internals);

    Component parent = new Parent();
    parent.getElement().appendVirtualChild(wrapperElement);

    VaadinSession session = mock(VaadinSession.class);
    DeploymentConfiguration configuration = mock(
            DeploymentConfiguration.class);

    when(ui.getSession()).thenReturn(session);
    when(session.getConfiguration()).thenReturn(configuration);
    when(configuration.getWebComponentDisconnect()).thenReturn(1);

    return ui;
}
 
Example #8
Source File: InternalServerError.java    From flow with Apache License 2.0 6 votes vote down vote up
private void reportException(Exception exception, String path,
        String exceptionText) {
    getElement().appendChild(Element.createText(exceptionText));

    VaadinService vaadinService = VaadinService.getCurrent();
    // Check that we have a vaadinService as else we will fail on a NPE and
    // the stacktrace we actually got will disappear and getting a NPE is
    // confusing.
    boolean productionMode = vaadinService != null && vaadinService
            .getDeploymentConfiguration().isProductionMode();

    if (!productionMode) {
        checkLogBinding();
        printStacktrace(exception);
    }

    getLogger().error(
            "There was an exception while trying to navigate to '{}'", path,
            exception);
}
 
Example #9
Source File: WebComponentConfigurationRegistryInitializerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
    MockitoAnnotations.initMocks(this);
    Mockito.when(vaadinService.getContext()).thenReturn(context);
    Mockito.when(
            context.getAttribute(WebComponentConfigurationRegistry.class))
            .thenReturn(registry);
    Mockito.when(context.getAttribute(
            eq(WebComponentConfigurationRegistry.class), anyObject()))
            .thenReturn(registry);

    initializer = new WebComponentConfigurationRegistryInitializer();
    when(servletContext.getAttribute(
            WebComponentConfigurationRegistry.class.getName()))
                    .thenReturn(registry);

    VaadinService.setCurrent(vaadinService);
    when(vaadinService.getInstantiator())
            .thenReturn(new MockInstantiator());
}
 
Example #10
Source File: PolymerTemplateTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Override
public VaadinService createService() {
    configuration = Mockito.mock(DeploymentConfiguration.class);
    Mockito.when(configuration.isProductionMode()).thenReturn(false);

    VaadinService service = Mockito.mock(VaadinService.class);
    Mockito.when(service.getDeploymentConfiguration())
            .thenReturn(configuration);

    Instantiator instantiator = Mockito.mock(Instantiator.class);
    Mockito.when(instantiator.getTemplateParser())
            .thenReturn(NpmTemplateParser.getInstance());
    Mockito.when(service.getInstantiator())
            .thenReturn(instantiator);
    return service;
}
 
Example #11
Source File: RouteConfigurationTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
    servletContext = new MockServletContext();
    vaadinContext = new VaadinServletContext(servletContext);
    registry = ApplicationRouteRegistry
            .getInstance(vaadinContext);

    vaadinService = Mockito.mock(MockService.class);
    Mockito.when(vaadinService.getRouteRegistry()).thenReturn(registry);
    Mockito.when(vaadinService.getContext()).thenReturn(vaadinContext);

    VaadinService.setCurrent(vaadinService);

    session = new MockVaadinSession(vaadinService) {
        @Override
        public VaadinService getService() {
            return vaadinService;
        }
    };
}
 
Example #12
Source File: FrontendUtilsTest.java    From flow with Apache License 2.0 6 votes vote down vote up
private VaadinService getServiceWithResource(InputStream stats) {
    VaadinService service = Mockito.mock(VaadinService.class);
    ClassLoader classLoader = Mockito.mock(ClassLoader.class);
    DeploymentConfiguration deploymentConfiguration = Mockito
            .mock(DeploymentConfiguration.class);

    Mockito.when(service.getClassLoader()).thenReturn(classLoader);
    Mockito.when(service.getDeploymentConfiguration())
            .thenReturn(deploymentConfiguration);
    Mockito.when(deploymentConfiguration.getStringProperty(
            SERVLET_PARAMETER_STATISTICS_JSON,
            VAADIN_SERVLET_RESOURCES + STATISTICS_JSON_DEFAULT))
            .thenReturn(VAADIN_SERVLET_RESOURCES + STATISTICS_JSON_DEFAULT);
    Mockito.when(classLoader.getResourceAsStream(
            VAADIN_SERVLET_RESOURCES + STATISTICS_JSON_DEFAULT))
            .thenReturn(stats);
    return service;
}
 
Example #13
Source File: UidlRequestHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void writeSessionExpired_whenUINotFound() throws IOException {

    VaadinService service = mock(VaadinService.class);
    VaadinSession session = mock(VaadinSession.class);
    when(session.getService()).thenReturn(service);

    when(service.findUI(request)).thenReturn(null);

    boolean result = handler.synchronizedHandleRequest(session, request,
            response);
    Assert.assertTrue("Result should be true", result);

    String responseContent = CommunicationUtil
            .getStringWhenWriteString(outputStream);

    // response shouldn't contain async
    Assert.assertEquals("Invalid response",
            "for(;;);[{\"meta\":{\"sessionExpired\":true}}]",
            responseContent);
}
 
Example #14
Source File: RouteConfigurationTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void configurationForApplicationScope_buildsWithCorrectRegistry() {
    registry.update(() -> {
        registry.setRoute("", MyRoute.class, Collections.emptyList());
        registry.setRoute("path", Secondary.class, Collections.emptyList());
    });

    VaadinServlet servlet = Mockito.mock(VaadinServlet.class);
    Mockito.when(servlet.getServletContext()).thenReturn(servletContext);
    Mockito.when(vaadinService.getServlet()).thenReturn(servlet);

    try {
        CurrentInstance.set(VaadinService.class, vaadinService);
        session.lock();
        RouteConfiguration routeConfiguration = RouteConfiguration
                .forApplicationScope();

        Assert.assertEquals(
                "After unlock registry should be updated for others to configure with new data",
                2, routeConfiguration.getAvailableRoutes().size());
    } finally {
        session.unlock();
        CurrentInstance.clearAll();
    }
}
 
Example #15
Source File: ResponseWriterTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    MockDeploymentConfiguration deploymentConfiguration = new MockDeploymentConfiguration();
    deploymentConfiguration.setBrotli(true);

    responseWriter = new OverrideableResponseWriter(
            deploymentConfiguration);
    servletContext = Mockito.mock(ServletContext.class);
    request = Mockito.mock(HttpServletRequest.class);
    Mockito.when(request.getServletContext()).thenReturn(servletContext);
    // No header == getDateHeader returns -1 (Mockito default is 0)
    Mockito.when(request.getDateHeader(Matchers.anyString()))
            .thenReturn(-1L);

    response = Mockito.mock(HttpServletResponse.class);
    responseContentLength = new AtomicLong(-1L);
    Mockito.doAnswer(invocation -> {
        responseContentLength.set((long) invocation.getArguments()[0]);
        return null;
    }).when(response).setContentLengthLong(Matchers.anyLong());

    Assert.assertNull(VaadinService.getCurrent());
}
 
Example #16
Source File: HasCurrentService.java    From flow with Apache License 2.0 5 votes vote down vote up
@Before
public void setUpCurrentService() {
    clearCurrentService();
    assertNull(VaadinService.getCurrent());

    service = createService();
    VaadinService.setCurrent(service);
}
 
Example #17
Source File: LiveReloadView.java    From flow with Apache License 2.0 5 votes vote down vote up
private void handleClickLiveReload(ClickEvent event) {
    BrowserLiveReloadAccess liveReloadAccess = VaadinService.getCurrent()
            .getInstantiator().getOrCreate(BrowserLiveReloadAccess.class);
    BrowserLiveReload browserLiveReload = liveReloadAccess
            .getLiveReload(VaadinService.getCurrent());
    browserLiveReload.reload();
}
 
Example #18
Source File: VaadinConnectAccessCheckerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
    checker = new VaadinConnectAccessChecker();
    requestMock = mock(HttpServletRequest.class);
    sessionMock = mock(HttpSession.class);
    when(sessionMock.getAttribute(VaadinService.getCsrfTokenAttributeName()))
            .thenReturn("Vaadin CCDM");
    when(requestMock.getSession()).thenReturn(sessionMock);
    when(requestMock.getUserPrincipal()).thenReturn(mock(Principal.class));
    when(requestMock.getHeader("X-CSRF-Token"))
            .thenReturn("Vaadin CCDM");
    when(requestMock.isUserInRole("ROLE_USER")).thenReturn(true);
}
 
Example #19
Source File: VaadinConnectControllerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void should_bePossibeToGetPrincipalInEndpoint() {
    MockVaadinServletService service = new MockVaadinServletService();
    VaadinService.setCurrent(service);
    when(principal.getName()).thenReturn("foo");

    VaadinConnectController vaadinController = createVaadinController(
            TEST_ENDPOINT, new VaadinConnectAccessChecker());

    ResponseEntity<String> response = vaadinController.serveEndpoint(
            TEST_ENDPOINT_NAME, "getUserName",
            createRequestParameters("{}"), requestMock);

    assertEquals("\"foo\"", response.getBody());
}
 
Example #20
Source File: FrontendUtilsTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private VaadinService setupStatsAssetMocks(String statsFile)
        throws IOException {
    String stats = IOUtils.toString(FrontendUtilsTest.class.getClassLoader()
            .getResourceAsStream(statsFile), StandardCharsets.UTF_8);

    return getServiceWithResource(
            new ByteArrayInputStream(stats.getBytes()));
}
 
Example #21
Source File: KnownUnsupportedTypesTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
protected VaadinService createService() {
    VaadinService service = Mockito.mock(VaadinService.class);
    DeploymentConfiguration configuration = Mockito
            .mock(DeploymentConfiguration.class);
    Mockito.when(configuration.isProductionMode()).thenReturn(true);
    Mockito.when(service.getDeploymentConfiguration())
            .thenReturn(configuration);
    return service;
}
 
Example #22
Source File: TemplateModelTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
protected VaadinService createService() {
    VaadinService service = Mockito.mock(VaadinService.class);
    DeploymentConfiguration configuration = Mockito
            .mock(DeploymentConfiguration.class);
    Mockito.when(configuration.isProductionMode()).thenReturn(true);
    Mockito.when(service.getDeploymentConfiguration())
            .thenReturn(configuration);
    return service;
}
 
Example #23
Source File: AbstractDnDUnitTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    DefaultDeploymentConfiguration configuration = new DefaultDeploymentConfiguration(
            VaadinServlet.class, new Properties());

    VaadinService service = Mockito.mock(VaadinService.class);
    Mockito.when(service.resolveResource(Mockito.anyString()))
            .thenReturn("");

    VaadinSession session = Mockito.mock(VaadinSession.class);
    Mockito.when(session.getConfiguration()).thenReturn(configuration);
    Mockito.when(session.getService()).thenReturn(service);

    ui = new MockUI(session);
}
 
Example #24
Source File: TemplateModelWithEncodersTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
protected VaadinService createService() {
    VaadinService service = Mockito.mock(VaadinService.class);
    DeploymentConfiguration configuration = Mockito
            .mock(DeploymentConfiguration.class);
    Mockito.when(configuration.isProductionMode()).thenReturn(true);
    Mockito.when(service.getDeploymentConfiguration())
            .thenReturn(configuration);
    return service;
}
 
Example #25
Source File: TestingServiceInitListener.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void serviceInit(ServiceInitEvent event) {
    // just set a fake backend to trigger live-reload client-side
    BrowserLiveReloadAccess liveReloadAccess = VaadinService.getCurrent()
            .getInstantiator().getOrCreate(BrowserLiveReloadAccess.class);
    BrowserLiveReload browserLiveReload = liveReloadAccess
            .getLiveReload(VaadinService.getCurrent());
    browserLiveReload.setBackend(BrowserLiveReload.Backend.HOTSWAP_AGENT);
}
 
Example #26
Source File: WebComponentConfigurationRegistryTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@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 #27
Source File: TemplateInitializer.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new initializer instance.
 *
 * @param template
 *            a template to initialize
 * @param parser
 *            a template parser instance
 * @param service
 *            the related service
 */
@SuppressWarnings("unchecked")
public TemplateInitializer(PolymerTemplate<?> template,
        TemplateParser parser, VaadinService service) {
    this.template = template;
    idMapper = new IdMapper(template);

    boolean productionMode = service.getDeploymentConfiguration()
            .isProductionMode();

    templateClass = (Class<? extends PolymerTemplate<?>>) template
            .getClass();

    ParserData data = null;
    if (productionMode) {
        ReflectionCache<PolymerTemplate<?>, ParserData> cache = CACHE
                .computeIfAbsent(parser, analyzer -> new ReflectionCache<>(
                        clazz -> new TemplateDataAnalyzer(clazz, analyzer,
                                service).parseTemplate()));
        data = cache.get(templateClass);
    }
    if (data == null) {
        data = new TemplateDataAnalyzer(templateClass, parser, service)
                .parseTemplate();
    }
    parserData = data;
}
 
Example #28
Source File: TemplateComponentTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public TemplateData getTemplateContent(
        Class<? extends PolymerTemplate<?>> clazz, String tag,
        VaadinService service) {
    Document doc = Jsoup.parse(TEMPLATE);
    return new TemplateData("",
            doc.getElementsByTag("template").get(0));
}
 
Example #29
Source File: TrackMessageSizeUI.java    From flow with Apache License 2.0 5 votes vote down vote up
private String findMethodImplementation() {
    String filename = "/VAADIN/static/push/vaadinPush.js";
    URL resourceURL = findResourceURL(filename,
            (VaadinServletService) VaadinService.getCurrent());
    if (resourceURL == null) {
        log("Can't find " + filename);
        return null;
    }

    try {
        String string = IOUtils.toString(resourceURL,
                StandardCharsets.UTF_8);

        // Find the function inside the script content
        int startIndex = string.indexOf("function _trackMessageSize");
        if (startIndex == -1) {
            log("function not found");
            return null;
        }

        // Assumes there's a /** comment before the next function
        int endIndex = string.indexOf("/**", startIndex);
        if (endIndex == -1) {
            log("End of function not found");
            return null;
        }

        return string.substring(startIndex, endIndex);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #30
Source File: DevModeConfigView.java    From flow with Apache License 2.0 5 votes vote down vote up
public DevModeConfigView() {
    Paragraph productionMode = new Paragraph(String.valueOf(VaadinService
            .getCurrent().getDeploymentConfiguration().isProductionMode()));
    productionMode.setId("productionMode");

    Paragraph devModeLiveReloadEnabled = new Paragraph(
            String.valueOf(VaadinService.getCurrent()
                    .getDeploymentConfiguration().isDevModeLiveReloadEnabled()));
    devModeLiveReloadEnabled.setId("devModeLiveReloadEnabled");

    add(productionMode, devModeLiveReloadEnabled);
}