Search in sources :

Example 16 with ResourceProvider

use of com.vaadin.flow.di.ResourceProvider in project flow by vaadin.

the class DevModeEndpointTest method setup.

@Before
@SuppressWarnings({ "unchecked", "rawtypes" })
public void setup() throws Exception {
    super.setup();
    assertFalse("No DevModeHandler should be available at test start", DevModeHandlerManager.getDevModeHandler(new VaadinServletContext(servletContext)).isPresent());
    createStubNode(false, true, baseDir);
    createStubWebpackServer("Compiled", 500, baseDir, true);
    // Prevent TaskRunNpmInstall#cleanUp from deleting node_modules
    new File(baseDir, "node_modules/.modules.yaml").createNewFile();
    ServletRegistration vaadinServletRegistration = Mockito.mock(ServletRegistration.class);
    Mockito.doReturn(new EndpointGeneratorTaskFactoryImpl()).when(lookup).lookup(EndpointGeneratorTaskFactory.class);
    ResourceProvider resourceProvider = Mockito.mock(ResourceProvider.class);
    Mockito.when(lookup.lookup(ResourceProvider.class)).thenReturn(resourceProvider);
    Mockito.when(vaadinServletRegistration.getClassName()).thenReturn(VaadinServletSubClass.class.getName());
    classes = new HashSet<>();
    classes.add(this.getClass());
    Map registry = new HashMap();
    // Adding extra registrations to make sure that
    // DevModeInitializer picks
    // the correct registration which is a VaadinServlet
    // registration.
    registry.put("extra1", Mockito.mock(ServletRegistration.class));
    registry.put("foo", vaadinServletRegistration);
    registry.put("extra2", Mockito.mock(ServletRegistration.class));
    Mockito.when(servletContext.getServletRegistrations()).thenReturn(registry);
    Mockito.when(servletContext.getInitParameterNames()).thenReturn(Collections.emptyEnumeration());
    Mockito.when(servletContext.getClassLoader()).thenReturn(this.getClass().getClassLoader());
    FileUtils.forceMkdir(new File(baseDir, DEFAULT_CONNECT_JAVA_SOURCE_FOLDER));
    devModeStartupListener = new DevModeStartupListener();
}
Also used : VaadinServletContext(com.vaadin.flow.server.VaadinServletContext) ServletRegistration(javax.servlet.ServletRegistration) EndpointGeneratorTaskFactoryImpl(dev.hilla.frontend.EndpointGeneratorTaskFactoryImpl) HashMap(java.util.HashMap) DevModeStartupListener(com.vaadin.base.devserver.startup.DevModeStartupListener) ResourceProvider(com.vaadin.flow.di.ResourceProvider) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) Before(org.junit.Before)

Example 17 with ResourceProvider

use of com.vaadin.flow.di.ResourceProvider in project flow by vaadin.

the class FrontendUtils method getStatsFromClassPath.

private static InputStream getStatsFromClassPath(VaadinService service) {
    Stats statistics = service.getContext().getAttribute(Stats.class);
    if (statistics != null) {
        return new ByteArrayInputStream(statistics.statsJson);
    }
    String stats = service.getDeploymentConfiguration().getStringProperty(SERVLET_PARAMETER_STATISTICS_JSON, VAADIN_SERVLET_RESOURCES + STATISTICS_JSON_DEFAULT).replaceFirst("^/", "");
    ResourceProvider resourceProvider = service.getContext().getAttribute(Lookup.class).lookup(ResourceProvider.class);
    URL statsUrl = resourceProvider.getApplicationResource(stats);
    InputStream stream = null;
    if (statsUrl != null) {
        try (InputStream statsStream = statsUrl.openStream()) {
            byte[] buffer = IOUtils.toByteArray(statsStream);
            statistics = new Stats(buffer, null);
            service.getContext().setAttribute(statistics);
            stream = new ByteArrayInputStream(buffer);
        } catch (IOException exception) {
            getLogger().warn("Couldn't read content of stats file {}", stats, exception);
            stream = null;
        }
    }
    if (stream == null) {
        getLogger().error("Cannot get the 'stats.json' from the classpath '{}'", stats);
    }
    return stream;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ResourceProvider(com.vaadin.flow.di.ResourceProvider) Lookup(com.vaadin.flow.di.Lookup) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) URL(java.net.URL)

Example 18 with ResourceProvider

use of com.vaadin.flow.di.ResourceProvider in project flow by vaadin.

the class BootstrapHandlerTest method getBootstrapPage_assetChunksIsAnARRAY_bootstrapParsesOk.

// #7158
@Test
public void getBootstrapPage_assetChunksIsAnARRAY_bootstrapParsesOk() throws ServiceException, IOException {
    initUI(testUI);
    String statsJson = "{\n" + " \"errors\": [],\n" + " \"warnings\": [],\n" + " \"assetsByChunkName\": {\n" + "  \"bundle\": [\n" + "    \"VAADIN/build/vaadin-bundle-e77008557c8d410bf0dc" + ".cache.js\",\n" + "    \"VAADIN/build/vaadin-bundle-e77008557c8d410bf0dc" + ".cache.js.map\"\n" + "  ],\n" + " }" + "}";
    File tmpFile = tmpDir.newFile();
    try (FileOutputStream stream = new FileOutputStream(tmpFile)) {
        IOUtils.write(statsJson, stream, StandardCharsets.UTF_8);
    }
    Lookup lookup = testUI.getSession().getService().getContext().getAttribute(Lookup.class);
    ResourceProvider provider = lookup.lookup(ResourceProvider.class);
    Mockito.when(provider.getApplicationResource(Mockito.anyString())).thenReturn(tmpFile.toURI().toURL());
    BootstrapContext bootstrapContext = new BootstrapContext(request, null, session, testUI, this::contextRootRelativePath);
    Document page = pageBuilder.getBootstrapPage(bootstrapContext);
    Elements scripts = page.head().getElementsByTag("script");
    Element bundle = scripts.stream().filter(el -> el.attr("src").equals("./VAADIN/build/vaadin-bundle-e77008557c8d410bf0dc.cache.js")).findFirst().get();
    Assert.assertFalse(bundle.hasAttr("defer"));
}
Also used : FileOutputStream(java.io.FileOutputStream) ResourceProvider(com.vaadin.flow.di.ResourceProvider) TargetElement(com.vaadin.flow.component.page.TargetElement) Element(org.jsoup.nodes.Element) Lookup(com.vaadin.flow.di.Lookup) BootstrapContext(com.vaadin.flow.server.BootstrapHandler.BootstrapContext) Document(org.jsoup.nodes.Document) Elements(org.jsoup.select.Elements) File(java.io.File) Test(org.junit.Test)

Example 19 with ResourceProvider

use of com.vaadin.flow.di.ResourceProvider in project flow by vaadin.

the class DeploymentConfigurationFactoryTest method createServletConfigMock.

private ServletConfig createServletConfigMock(Map<String, String> servletConfigParameters, Map<String, String> servletContextParameters) throws Exception {
    URLClassLoader classLoader = new URLClassLoader(new URL[] { temporaryFolder.getRoot().toURI().toURL() });
    Mockito.when(contextMock.getAttribute(ApplicationConfiguration.class.getName())).thenReturn(appConfiguration);
    Mockito.when(contextMock.getInitParameterNames()).thenReturn(Collections.enumeration(servletContextParameters.keySet()));
    Mockito.when(contextMock.getClassLoader()).thenReturn(classLoader);
    Mockito.when(contextMock.getInitParameter(Mockito.anyString())).thenAnswer(answer -> {
        String name = answer.getArgument(0);
        return servletContextParameters.get(name);
    });
    ResourceProvider provider = Mockito.mock(ResourceProvider.class);
    Lookup lookup = new Lookup() {

        @Override
        public <T> Collection<T> lookupAll(Class<T> serviceClass) {
            return null;
        }

        @Override
        public <T> T lookup(Class<T> serviceClass) {
            if (ResourceProvider.class.equals(serviceClass)) {
                return serviceClass.cast(provider);
            }
            return null;
        }
    };
    Mockito.when(provider.getApplicationResources(VAADIN_SERVLET_RESOURCES + TOKEN_FILE)).thenReturn(Collections.emptyList());
    Mockito.when(contextMock.getAttribute(Lookup.class.getName())).thenReturn(lookup);
    return new ServletConfig() {

        @Override
        public String getServletName() {
            return "whatever";
        }

        @Override
        public ServletContext getServletContext() {
            return contextMock;
        }

        @Override
        public String getInitParameter(String name) {
            return servletConfigParameters.get(name);
        }

        @Override
        public Enumeration<String> getInitParameterNames() {
            return Collections.enumeration(servletConfigParameters.keySet());
        }
    };
}
Also used : URLClassLoader(java.net.URLClassLoader) ResourceProvider(com.vaadin.flow.di.ResourceProvider) ServletConfig(javax.servlet.ServletConfig) Lookup(com.vaadin.flow.di.Lookup) BeforeClass(org.junit.BeforeClass) AfterClass(org.junit.AfterClass) ApplicationConfiguration(com.vaadin.flow.server.startup.ApplicationConfiguration)

Example 20 with ResourceProvider

use of com.vaadin.flow.di.ResourceProvider in project flow by vaadin.

the class BootstrapHandlerTest method enableViteFeature.

private void enableViteFeature(boolean productionMode) throws IOException {
    VaadinContext vaadinContext = Mockito.mock(VaadinContext.class);
    final Lookup lookup = Mockito.mock(Lookup.class);
    ResourceProvider resourceProvider = Mockito.mock(ResourceProvider.class);
    Mockito.when(lookup.lookup(ResourceProvider.class)).thenReturn(resourceProvider);
    Mockito.when(resourceProvider.getClientResourceAsStream("META-INF/resources/" + ApplicationConstants.CLIENT_ENGINE_PATH + "/compile.properties")).thenReturn(getClass().getClassLoader().getResourceAsStream("META-INF/resources/" + ApplicationConstants.CLIENT_ENGINE_PATH + "/compile.properties"));
    Mockito.when(vaadinContext.getAttribute(Lookup.class)).thenReturn(lookup);
    service.setContext(vaadinContext);
    ApplicationConfiguration configuration = Mockito.mock(ApplicationConfiguration.class);
    Mockito.when(configuration.isProductionMode()).thenReturn(false);
    Mockito.when(configuration.getJavaResourceFolder()).thenReturn(tmpDir.getRoot());
    Mockito.when(lookup.lookup(ApplicationConfiguration.class)).thenReturn(configuration);
    Mockito.when(vaadinContext.getAttribute(ApplicationConfiguration.class)).thenReturn(configuration);
    Mockito.when(vaadinContext.getAttribute(Mockito.eq(ApplicationConfiguration.class), Mockito.any())).thenReturn(configuration);
    final FeatureFlags featureFlags = FeatureFlags.get(testUI.getSession().getService().getContext());
    Mockito.when(vaadinContext.getAttribute(FeatureFlags.class)).thenReturn(featureFlags);
    featureFlags.setEnabled(FeatureFlags.VITE.getId(), true);
    Mockito.when(configuration.isProductionMode()).thenReturn(productionMode);
}
Also used : ResourceProvider(com.vaadin.flow.di.ResourceProvider) Lookup(com.vaadin.flow.di.Lookup) FeatureFlags(com.vaadin.experimental.FeatureFlags) ApplicationConfiguration(com.vaadin.flow.server.startup.ApplicationConfiguration)

Aggregations

ResourceProvider (com.vaadin.flow.di.ResourceProvider)30 Lookup (com.vaadin.flow.di.Lookup)22 Test (org.junit.Test)11 URL (java.net.URL)10 VaadinContext (com.vaadin.flow.server.VaadinContext)8 ApplicationConfiguration (com.vaadin.flow.server.startup.ApplicationConfiguration)5 File (java.io.File)5 IOException (java.io.IOException)5 Before (org.junit.Before)5 MockVaadinServletService (com.vaadin.flow.server.MockVaadinServletService)4 VaadinConfig (com.vaadin.flow.server.VaadinConfig)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 InputStream (java.io.InputStream)4 Properties (java.util.Properties)4 Instantiator (com.vaadin.flow.di.Instantiator)3 VaadinServletContext (com.vaadin.flow.server.VaadinServletContext)3 VaadinServletService (com.vaadin.flow.server.VaadinServletService)3 ServletContext (javax.servlet.ServletContext)3 DeploymentConfiguration (com.vaadin.flow.function.DeploymentConfiguration)2 StaticFileServer (com.vaadin.flow.server.StaticFileServer)2