Search in sources :

Example 6 with VaadinServlet

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

the class DefaultTemplateParser method getTemplateContent.

@Override
public TemplateData getTemplateContent(Class<? extends PolymerTemplate<?>> clazz, String tag) {
    VaadinServlet servlet = VaadinServlet.getCurrent();
    boolean logEnabled = LOG_CACHE.get(clazz).compareAndSet(false, true);
    List<Dependency> dependencies = AnnotationReader.getAnnotationsFor(clazz, HtmlImport.class).stream().map(htmlImport -> new Dependency(Type.HTML_IMPORT, htmlImport.value(), htmlImport.loadMode())).collect(Collectors.toList());
    FilterContext filterContext = new FilterContext(VaadinSession.getCurrent());
    for (DependencyFilter filter : VaadinService.getCurrent().getDependencyFilters()) {
        dependencies = filter.filter(new ArrayList<>(dependencies), filterContext);
    }
    for (Dependency dependency : dependencies) {
        if (dependency.getType() != Type.HTML_IMPORT) {
            continue;
        }
        String url = dependency.getUrl();
        String path = servlet.resolveResource(url);
        if (logEnabled) {
            getLogger().debug("Html import path '{}' is resolved to '{}'", url, path);
        }
        try (InputStream content = servlet.getResourceAsStream(path)) {
            if (content == null) {
                throw new IllegalStateException(String.format("Can't find resource '%s' " + "via the servlet context", url));
            }
            Element templateElement = parseHtmlImport(content, url, tag);
            if (logEnabled && templateElement != null) {
                getLogger().debug("Found a template file containing template " + "definition for the tag '{}' by the path '{}'", tag, url);
            }
            if (templateElement != null) {
                return new TemplateData(url, templateElement);
            }
        } catch (IOException exception) {
            // ignore exception on close()
            if (logEnabled) {
                getLogger().warn("Couldn't close template input stream", exception);
            }
        }
    }
    throw new IllegalStateException(String.format("Couldn't find the " + "definition of the element with tag '%s' " + "in any template file declared using @'%s' annotations. " + "Check the availability of the template files in your WAR " + "file or provide alternative implementation of the " + "method getTemplateContent() which should return an element " + "representing the content of the template file", tag, HtmlImport.class.getSimpleName()));
}
Also used : LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Comment(org.jsoup.nodes.Comment) Dependency(com.vaadin.flow.shared.ui.Dependency) ArrayList(java.util.ArrayList) Type(com.vaadin.flow.shared.ui.Dependency.Type) Element(org.jsoup.nodes.Element) FilterContext(com.vaadin.flow.server.DependencyFilter.FilterContext) DependencyFilter(com.vaadin.flow.server.DependencyFilter) ReflectionCache(com.vaadin.flow.internal.ReflectionCache) VaadinSession(com.vaadin.flow.server.VaadinSession) Logger(org.slf4j.Logger) AnnotationReader(com.vaadin.flow.internal.AnnotationReader) VaadinServlet(com.vaadin.flow.server.VaadinServlet) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) HtmlImport(com.vaadin.flow.component.dependency.HtmlImport) Node(org.jsoup.nodes.Node) List(java.util.List) Document(org.jsoup.nodes.Document) VaadinService(com.vaadin.flow.server.VaadinService) Optional(java.util.Optional) Jsoup(org.jsoup.Jsoup) InputStream(java.io.InputStream) HtmlImport(com.vaadin.flow.component.dependency.HtmlImport) InputStream(java.io.InputStream) Element(org.jsoup.nodes.Element) VaadinServlet(com.vaadin.flow.server.VaadinServlet) ArrayList(java.util.ArrayList) DependencyFilter(com.vaadin.flow.server.DependencyFilter) Dependency(com.vaadin.flow.shared.ui.Dependency) IOException(java.io.IOException) FilterContext(com.vaadin.flow.server.DependencyFilter.FilterContext)

Example 7 with VaadinServlet

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

the class HtmlDependencyParser method parseDependencies.

private void parseDependencies(String path, Set<String> dependencies) {
    if (dependencies.contains(path)) {
        return;
    }
    dependencies.add(path);
    VaadinSession session = VaadinSession.getCurrent();
    VaadinServlet servlet = VaadinServlet.getCurrent();
    if (servlet == null || session == null) {
        /*
             * Cannot happen in runtime.
             *
             * But not all unit tests set it. Let's just don't proceed further.
             */
        return;
    }
    assert session.hasLock();
    HtmlDependenciesCache cache = session.getAttribute(HtmlDependenciesCache.class);
    if (cache == null) {
        cache = new HtmlDependenciesCache();
        session.setAttribute(HtmlDependenciesCache.class, cache);
    }
    String resolvedPath = servlet.resolveResource(path);
    if (cache.hasDependency(resolvedPath)) {
        return;
    }
    cache.addDependency(resolvedPath);
    try (InputStream content = servlet.getResourceAsStream(resolvedPath)) {
        if (content == null) {
            getLogger().trace("Can't find resource '{}' to parse for imports via the servlet context", path);
        } else {
            parseHtmlImports(content, resolvedPath).map(uri -> resolveUri(uri, path)).forEach(uri -> parseDependencies(uri, dependencies));
        }
    } catch (IOException exception) {
        // ignore exception on close()
        getLogger().debug("Couldn't close template input stream", exception);
    }
}
Also used : VaadinSession(com.vaadin.flow.server.VaadinSession) Logger(org.slf4j.Logger) URISyntaxException(java.net.URISyntaxException) Collection(java.util.Collection) VaadinServlet(com.vaadin.flow.server.VaadinServlet) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) IOException(java.io.IOException) StandardCharsets(java.nio.charset.StandardCharsets) Serializable(java.io.Serializable) HashSet(java.util.HashSet) Stream(java.util.stream.Stream) Document(org.jsoup.nodes.Document) URI(java.net.URI) Jsoup(org.jsoup.Jsoup) SharedUtil(com.vaadin.flow.shared.util.SharedUtil) InputStream(java.io.InputStream) ApplicationConstants(com.vaadin.flow.shared.ApplicationConstants) VaadinSession(com.vaadin.flow.server.VaadinSession) InputStream(java.io.InputStream) VaadinServlet(com.vaadin.flow.server.VaadinServlet) IOException(java.io.IOException)

Example 8 with VaadinServlet

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

the class ThemeUrlResolverTest method init.

@Before
public void init() throws Exception {
    assert VaadinSession.getCurrent() == null : "Required no current vaadin session.";
    assert VaadinRequest.getCurrent() == null : "Required no current vaadin request.";
    MockitoAnnotations.initMocks(this);
    servlet = new VaadinServlet() {

        @Override
        protected DeploymentConfiguration createDeploymentConfiguration() throws ServletException {
            return mockDeploymentConfiguration;
        }
    };
    Properties initParameters = new Properties();
    Mockito.when(servletConfig.getServletContext()).thenReturn(servletContext);
    Mockito.when(servletConfig.getInitParameterNames()).thenReturn((Enumeration<String>) initParameters.propertyNames());
    Mockito.when(servletContext.getInitParameterNames()).thenReturn((Enumeration<String>) initParameters.propertyNames());
    Mockito.when(servletContext.getResource(Mockito.anyString())).thenAnswer(i -> new URL("http://localhost" + i.getArguments()[0]));
    servlet.init(servletConfig);
    Mockito.when(session.getAttribute(VaadinUriResolverFactory.class)).thenReturn(uriResolverFactory);
    Mockito.when(uriResolverFactory.getUriResolver(Mockito.any())).thenReturn(vaadinUriResolver);
    Mockito.when(vaadinUriResolver.resolveVaadinUri(Mockito.anyString())).thenAnswer(i -> i.getArguments()[0]);
    VaadinSession.setCurrent(session);
    CurrentInstance.set(VaadinRequest.class, request);
}
Also used : ServletException(javax.servlet.ServletException) VaadinServlet(com.vaadin.flow.server.VaadinServlet) Properties(java.util.Properties) MockDeploymentConfiguration(com.vaadin.tests.util.MockDeploymentConfiguration) DeploymentConfiguration(com.vaadin.flow.function.DeploymentConfiguration) URL(java.net.URL) Before(org.junit.Before)

Example 9 with VaadinServlet

use of com.vaadin.flow.server.VaadinServlet 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 10 with VaadinServlet

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

the class VaadinServiceTest method serviceContainsStreamRequestHandler.

@Test
public void serviceContainsStreamRequestHandler() throws ServiceException, ServletException {
    ServletConfig servletConfig = new MockServletConfig();
    VaadinServlet servlet = new VaadinServlet();
    servlet.init(servletConfig);
    VaadinService service = servlet.getService();
    Assert.assertTrue(service.createRequestHandlers().stream().filter(StreamRequestHandler.class::isInstance).findAny().isPresent());
}
Also used : ServletConfig(javax.servlet.ServletConfig) VaadinServlet(com.vaadin.flow.server.VaadinServlet) VaadinService(com.vaadin.flow.server.VaadinService) Test(org.junit.Test)

Aggregations

VaadinServlet (com.vaadin.flow.server.VaadinServlet)14 VaadinService (com.vaadin.flow.server.VaadinService)6 ServletException (javax.servlet.ServletException)6 Before (org.junit.Before)6 ServletConfig (javax.servlet.ServletConfig)5 Test (org.junit.Test)5 DependencyFilter (com.vaadin.flow.server.DependencyFilter)4 MockServletConfig (com.vaadin.flow.server.MockServletConfig)4 VaadinServletService (com.vaadin.flow.server.VaadinServletService)4 StandardCharsets (java.nio.charset.StandardCharsets)4 Properties (java.util.Properties)4 ServletContext (javax.servlet.ServletContext)4 VaadinRequest (com.vaadin.flow.server.VaadinRequest)3 VaadinResponse (com.vaadin.flow.server.VaadinResponse)3 VaadinSession (com.vaadin.flow.server.VaadinSession)3 Dependency (com.vaadin.flow.shared.ui.Dependency)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 URL (java.net.URL)3