Search in sources :

Example 11 with VaadinServletService

use of com.vaadin.flow.server.VaadinServletService in project flow by vaadin.

the class UidlRequestHandlerTest method writeSessionExpired.

@Test
public void writeSessionExpired() throws Exception {
    ApplicationConfiguration config = Mockito.mock(ApplicationConfiguration.class);
    Mockito.when(config.getPropertyNames()).thenReturn(Collections.emptyEnumeration());
    Mockito.when(config.getBuildFolder()).thenReturn(".");
    VaadinContext context = new MockVaadinContext();
    Mockito.when(config.getContext()).thenReturn(context);
    VaadinService service = new VaadinServletService(null, new DefaultDeploymentConfiguration(config, 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);
}
Also used : MockVaadinContext(com.vaadin.flow.server.MockVaadinContext) MockVaadinContext(com.vaadin.flow.server.MockVaadinContext) VaadinContext(com.vaadin.flow.server.VaadinContext) VaadinService(com.vaadin.flow.server.VaadinService) VaadinServletService(com.vaadin.flow.server.VaadinServletService) DefaultDeploymentConfiguration(com.vaadin.flow.server.DefaultDeploymentConfiguration) Properties(java.util.Properties) ApplicationConfiguration(com.vaadin.flow.server.startup.ApplicationConfiguration) Test(org.junit.Test)

Example 12 with VaadinServletService

use of com.vaadin.flow.server.VaadinServletService in project flow by vaadin.

the class BundleFilterInitializerTest method init.

@Before
public void init() throws MalformedURLException {
    event = Mockito.mock(ServiceInitEvent.class);
    VaadinServletService service = Mockito.mock(VaadinServletService.class);
    VaadinServlet servlet = Mockito.mock(VaadinServlet.class);
    Mockito.when(event.getSource()).thenReturn(service);
    Mockito.when(service.getServlet()).thenReturn(servlet);
    Mockito.when(service.getDeploymentConfiguration()).thenReturn(new DefaultDeploymentConfiguration(BundleFilterInitializerTest.class, new Properties(), (base, consumer) -> {
    }) {

        @Override
        public boolean isProductionMode() {
            return true;
        }
    });
    Mockito.doAnswer(invocation -> {
        dependencyFilterAddHandler.accept(invocation.getArgumentAt(0, DependencyFilter.class));
        return null;
    }).when(event).addDependencyFilter(Mockito.any(DependencyFilter.class));
    Mockito.doAnswer(invocation -> {
        return inputStreamProducer.apply(invocation.getArgumentAt(0, String.class));
    }).when(service).getResourceAsStream("/frontend-es6/vaadin-flow-bundle-manifest.json");
    Mockito.doAnswer(invocation -> {
        return resourceProducer.apply(invocation.getArgumentAt(0, String.class));
    }).when(service).getResource(Mockito.anyString());
}
Also used : ServiceInitEvent(com.vaadin.flow.server.ServiceInitEvent) IntStream(java.util.stream.IntStream) URL(java.net.URL) Dependency(com.vaadin.flow.shared.ui.Dependency) ByteArrayInputStream(java.io.ByteArrayInputStream) DefaultDeploymentConfiguration(com.vaadin.flow.server.DefaultDeploymentConfiguration) DependencyFilter(com.vaadin.flow.server.DependencyFilter) Before(org.junit.Before) JsonException(elemental.json.JsonException) ServiceInitEvent(com.vaadin.flow.server.ServiceInitEvent) Properties(java.util.Properties) MalformedURLException(java.net.MalformedURLException) VaadinServlet(com.vaadin.flow.server.VaadinServlet) IOException(java.io.IOException) Test(org.junit.Test) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) UncheckedIOException(java.io.UncheckedIOException) Consumer(java.util.function.Consumer) Mockito(org.mockito.Mockito) List(java.util.List) Stream(java.util.stream.Stream) LoadMode(com.vaadin.flow.shared.ui.LoadMode) ServletContext(javax.servlet.ServletContext) Assert(org.junit.Assert) UnsupportedEncodingException(java.io.UnsupportedEncodingException) VaadinServletService(com.vaadin.flow.server.VaadinServletService) InputStream(java.io.InputStream) VaadinServlet(com.vaadin.flow.server.VaadinServlet) VaadinServletService(com.vaadin.flow.server.VaadinServletService) DefaultDeploymentConfiguration(com.vaadin.flow.server.DefaultDeploymentConfiguration) DependencyFilter(com.vaadin.flow.server.DependencyFilter) Properties(java.util.Properties) Before(org.junit.Before)

Example 13 with VaadinServletService

use of com.vaadin.flow.server.VaadinServletService in project flow by vaadin.

the class BundleFilterInitializer method readBundleDependencies.

private Map<String, Set<String>> readBundleDependencies(ServiceInitEvent event, VaadinUriResolver es6ContextPathResolver) {
    VaadinServletService servlet = ((VaadinServletService) event.getSource());
    String es6Base = es6ContextPathResolver.resolveVaadinUri(ApplicationConstants.FRONTEND_PROTOCOL_PREFIX);
    if (!es6Base.endsWith("/")) {
        es6Base += '/';
    }
    String bundleManifestContextPath = es6Base + FLOW_BUNDLE_MANIFEST;
    try (InputStream bundleManifestStream = servlet.getResourceAsStream(bundleManifestContextPath)) {
        if (bundleManifestStream == null) {
            getLogger().info("Bundling disabled: Flow bundle manifest '{}' was not found in servlet context", bundleManifestContextPath);
            return Collections.emptyMap();
        }
        JsonObject bundlesToUrlsContained = Json.parse(IOUtils.toString(bundleManifestStream, StandardCharsets.UTF_8));
        Map<String, Set<String>> importToBundle = new HashMap<>();
        for (String bundlePath : bundlesToUrlsContained.keys()) {
            JsonArray bundledFiles = bundlesToUrlsContained.getArray(bundlePath);
            for (int i = 0; i < bundledFiles.length(); i++) {
                String bundledFile = bundledFiles.getString(i);
                if (servlet.getResource(es6ContextPathResolver.resolveVaadinUri(es6Base + bundlePath)) == null) {
                    throw new IllegalArgumentException(String.format("Failed to find bundle at context path '%s', specified in manifest '%s'. " + "Remove file reference from the manifest to disable bundle usage or add the bundle to the context path specified.", bundlePath, bundleManifestContextPath));
                }
                importToBundle.computeIfAbsent(bundledFile, key -> new HashSet<>()).add(bundlePath);
            }
        }
        return importToBundle;
    } catch (IOException e) {
        throw new UncheckedIOException(String.format("Failed to read bundle manifest file at context path '%s'", bundleManifestContextPath), e);
    }
}
Also used : ServiceInitEvent(com.vaadin.flow.server.ServiceInitEvent) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) Json(elemental.json.Json) Set(java.util.Set) JsonArray(elemental.json.JsonArray) IOException(java.io.IOException) HashMap(java.util.HashMap) VaadinUriResolver(com.vaadin.flow.shared.VaadinUriResolver) DeploymentConfiguration(com.vaadin.flow.function.DeploymentConfiguration) StandardCharsets(java.nio.charset.StandardCharsets) VaadinServiceInitListener(com.vaadin.flow.server.VaadinServiceInitListener) UncheckedIOException(java.io.UncheckedIOException) HashSet(java.util.HashSet) IOUtils(org.apache.commons.io.IOUtils) Map(java.util.Map) JsonObject(elemental.json.JsonObject) Collections(java.util.Collections) VaadinServletService(com.vaadin.flow.server.VaadinServletService) InputStream(java.io.InputStream) ApplicationConstants(com.vaadin.flow.shared.ApplicationConstants) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) InputStream(java.io.InputStream) VaadinServletService(com.vaadin.flow.server.VaadinServletService) JsonObject(elemental.json.JsonObject) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) JsonArray(elemental.json.JsonArray) HashSet(java.util.HashSet)

Example 14 with VaadinServletService

use of com.vaadin.flow.server.VaadinServletService in project flow by vaadin.

the class DefaultTemplateParserTest method setUp.

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    VaadinServletRequest request = Mockito.mock(VaadinServletRequest.class);
    VaadinSession session = Mockito.mock(VaadinSession.class);
    factory = (VaadinUriResolverFactory) vaadinRequest -> resolver;
    Mockito.when(session.getAttribute(VaadinUriResolverFactory.class)).thenReturn(factory);
    Mockito.when(service.getDependencyFilters()).thenReturn(Collections.emptyList());
    WrappedHttpSession wrappedSession = Mockito.mock(WrappedHttpSession.class);
    HttpSession httpSession = Mockito.mock(HttpSession.class);
    Mockito.when(wrappedSession.getHttpSession()).thenReturn(httpSession);
    servlet = new VaadinServlet() {

        @Override
        protected VaadinServletService createServletService() throws ServletException, ServiceException {
            return service;
        }

        @Override
        public ServletContext getServletContext() {
            return servletContext;
        }
    };
    Mockito.when(service.getServlet()).thenReturn(servlet);
    Mockito.when(resolver.resolveVaadinUri("/bar.html")).thenReturn("bar.html");
    Mockito.when(resolver.resolveVaadinUri("/bar1.html")).thenReturn("bar1.html");
    Mockito.when(resolver.resolveVaadinUri("/bundle.html")).thenReturn("bundle.html");
    Mockito.when(request.getWrappedSession()).thenReturn(wrappedSession);
    Mockito.when(request.getServletPath()).thenReturn("");
    Mockito.when(servletContext.getResourceAsStream("/bar.html")).thenReturn(new ByteArrayInputStream("<dom-module id='bar'></dom-module>".getBytes(StandardCharsets.UTF_8)));
    Mockito.when(servletContext.getResourceAsStream("/bar1.html")).thenReturn(new ByteArrayInputStream("<dom-module id='foo'></dom-module>".getBytes(StandardCharsets.UTF_8)));
    Mockito.when(servletContext.getResourceAsStream("/bundle.html")).thenReturn(getBundle(), getBundle(), getBundle());
    CurrentInstance.set(VaadinRequest.class, request);
    CurrentInstance.set(VaadinSession.class, session);
    CurrentInstance.set(VaadinService.class, service);
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) TemplateData(com.vaadin.flow.component.polymertemplate.TemplateParser.TemplateData) WrappedHttpSession(com.vaadin.flow.server.WrappedHttpSession) ServletException(javax.servlet.ServletException) Mock(org.mockito.Mock) CurrentInstance(com.vaadin.flow.internal.CurrentInstance) VaadinUriResolverFactory(com.vaadin.flow.server.VaadinUriResolverFactory) Comment(org.jsoup.nodes.Comment) VaadinUriResolver(com.vaadin.flow.shared.VaadinUriResolver) Dependency(com.vaadin.flow.shared.ui.Dependency) Type(com.vaadin.flow.shared.ui.Dependency.Type) Assert.assertThat(org.junit.Assert.assertThat) MockitoAnnotations(org.mockito.MockitoAnnotations) Tag(com.vaadin.flow.component.Tag) ByteArrayInputStream(java.io.ByteArrayInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Element(org.jsoup.nodes.Element) After(org.junit.After) DependencyFilter(com.vaadin.flow.server.DependencyFilter) VaadinServletRequest(com.vaadin.flow.server.VaadinServletRequest) Before(org.junit.Before) HttpSession(javax.servlet.http.HttpSession) VaadinSession(com.vaadin.flow.server.VaadinSession) Matchers.empty(org.hamcrest.Matchers.empty) VaadinServlet(com.vaadin.flow.server.VaadinServlet) Test(org.junit.Test) VaadinRequest(com.vaadin.flow.server.VaadinRequest) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) NotThreadSafe(net.jcip.annotations.NotThreadSafe) HtmlImport(com.vaadin.flow.component.dependency.HtmlImport) Node(org.jsoup.nodes.Node) Mockito(org.mockito.Mockito) List(java.util.List) Stream(java.util.stream.Stream) VaadinService(com.vaadin.flow.server.VaadinService) LoadMode(com.vaadin.flow.shared.ui.LoadMode) ServletContext(javax.servlet.ServletContext) ModelClass(com.vaadin.flow.component.polymertemplate.PolymerTemplateTest.ModelClass) ServiceException(com.vaadin.flow.server.ServiceException) Assert(org.junit.Assert) Collections(java.util.Collections) VaadinServletService(com.vaadin.flow.server.VaadinServletService) ServletException(javax.servlet.ServletException) VaadinSession(com.vaadin.flow.server.VaadinSession) ServiceException(com.vaadin.flow.server.ServiceException) ByteArrayInputStream(java.io.ByteArrayInputStream) WrappedHttpSession(com.vaadin.flow.server.WrappedHttpSession) HttpSession(javax.servlet.http.HttpSession) VaadinServletRequest(com.vaadin.flow.server.VaadinServletRequest) VaadinServlet(com.vaadin.flow.server.VaadinServlet) VaadinServletService(com.vaadin.flow.server.VaadinServletService) ServletContext(javax.servlet.ServletContext) WrappedHttpSession(com.vaadin.flow.server.WrappedHttpSession) Before(org.junit.Before)

Example 15 with VaadinServletService

use of com.vaadin.flow.server.VaadinServletService in project flow by vaadin.

the class ApplicationRunnerServlet method findDeploymentConfiguration.

private DeploymentConfiguration findDeploymentConfiguration(DeploymentConfiguration originalConfiguration) throws Exception {
    // First level of cache
    DeploymentConfiguration configuration = CurrentInstance.get(DeploymentConfiguration.class);
    if (configuration == null) {
        // Not in cache, try to find a VaadinSession to get it from
        VaadinSession session = VaadinSession.getCurrent();
        if (session == null) {
            /*
                 * There's no current session, request or response when serving
                 * static resources, but there's still the current request
                 * maintained by ApplicationRunnerServlet, and there's most
                 * likely also a HttpSession containing a VaadinSession for that
                 * request.
                 */
            HttpServletRequest currentRequest = VaadinServletService.getCurrentServletRequest();
            if (currentRequest != null) {
                HttpSession httpSession = currentRequest.getSession(false);
                if (httpSession != null) {
                    Map<Class<?>, CurrentInstance> oldCurrent = CurrentInstance.setCurrent((VaadinSession) null);
                    try {
                        VaadinServletService service = (VaadinServletService) VaadinService.getCurrent();
                        session = service.findVaadinSession(new VaadinServletRequest(currentRequest, service));
                    } finally {
                        /*
                             * Clear some state set by findVaadinSession to
                             * avoid accidentally depending on it when coding on
                             * e.g. static request handling.
                             */
                        CurrentInstance.restoreInstances(oldCurrent);
                        currentRequest.removeAttribute(VaadinSession.class.getName());
                    }
                }
            }
        }
        if (session != null) {
            String name = ApplicationRunnerServlet.class.getName() + ".deploymentConfiguration";
            try {
                session.getLockInstance().lock();
                /*
                     * Read attribute using reflection to bypass
                     * VaadinSesison.getAttribute which would cause an infinite
                     * loop when checking the production mode setting for
                     * determining whether to check that the session is locked.
                     */
                Field attributesField = VaadinSession.class.getDeclaredField("attributes");
                attributesField.setAccessible(true);
                Attributes sessionAttributes = (Attributes) attributesField.get(session);
                configuration = (DeploymentConfiguration) sessionAttributes.getAttribute(name);
                if (configuration == null) {
                    ApplicationRunnerServlet servlet = (ApplicationRunnerServlet) VaadinServlet.getCurrent();
                    Class<?> classToRun;
                    try {
                        classToRun = servlet.getClassToRun();
                    } catch (ClassNotFoundException e) {
                        /*
                             * This happens e.g. if the UI class defined in the
                             * URL is not found or if this servlet just serves
                             * static resources while there's some other servlet
                             * that serves the UI (e.g. when using /run-push/).
                             */
                        return originalConfiguration;
                    }
                    CustomDeploymentConfiguration customDeploymentConfiguration = classToRun.getAnnotation(CustomDeploymentConfiguration.class);
                    if (customDeploymentConfiguration != null) {
                        Properties initParameters = new Properties(originalConfiguration.getInitParameters());
                        for (Conf entry : customDeploymentConfiguration.value()) {
                            initParameters.put(entry.name(), entry.value());
                        }
                        initParameters.put(VaadinSession.UI_PARAMETER, getApplicationRunnerApplicationClassName(request.get()));
                        configuration = new DefaultDeploymentConfiguration(ApplicationConfiguration.get(getService().getContext()), servlet.getClass(), initParameters);
                    } else {
                        configuration = originalConfiguration;
                    }
                    sessionAttributes.setAttribute(name, configuration);
                }
            } finally {
                session.getLockInstance().unlock();
            }
            CurrentInstance.set(DeploymentConfiguration.class, configuration);
        } else {
            configuration = originalConfiguration;
        }
    }
    return configuration;
}
Also used : VaadinSession(com.vaadin.flow.server.VaadinSession) Conf(com.vaadin.flow.uitest.servlet.CustomDeploymentConfiguration.Conf) HttpSession(javax.servlet.http.HttpSession) VaadinServletRequest(com.vaadin.flow.server.VaadinServletRequest) Attributes(com.vaadin.flow.server.Attributes) VaadinServletService(com.vaadin.flow.server.VaadinServletService) DefaultDeploymentConfiguration(com.vaadin.flow.server.DefaultDeploymentConfiguration) Properties(java.util.Properties) HttpServletRequest(javax.servlet.http.HttpServletRequest) Field(java.lang.reflect.Field) CurrentInstance(com.vaadin.flow.internal.CurrentInstance) DeploymentConfiguration(com.vaadin.flow.function.DeploymentConfiguration) DefaultDeploymentConfiguration(com.vaadin.flow.server.DefaultDeploymentConfiguration)

Aggregations

VaadinServletService (com.vaadin.flow.server.VaadinServletService)23 Test (org.junit.Test)14 MockVaadinServletService (com.vaadin.flow.server.MockVaadinServletService)10 VaadinServletRequest (com.vaadin.flow.server.VaadinServletRequest)9 VaadinSession (com.vaadin.flow.server.VaadinSession)8 Properties (java.util.Properties)7 DefaultDeploymentConfiguration (com.vaadin.flow.server.DefaultDeploymentConfiguration)6 VaadinServlet (com.vaadin.flow.server.VaadinServlet)6 DeploymentConfiguration (com.vaadin.flow.function.DeploymentConfiguration)5 VaadinService (com.vaadin.flow.server.VaadinService)5 Before (org.junit.Before)5 MockVaadinSession (com.vaadin.flow.server.MockVaadinSession)4 ApplicationConfiguration (com.vaadin.flow.server.startup.ApplicationConfiguration)4 URL (java.net.URL)4 Collections (java.util.Collections)4 ServletContext (javax.servlet.ServletContext)4 Lookup (com.vaadin.flow.di.Lookup)3 ResourceProvider (com.vaadin.flow.di.ResourceProvider)3 CurrentInstance (com.vaadin.flow.internal.CurrentInstance)3 VaadinResponse (com.vaadin.flow.server.VaadinResponse)3