com.vaadin.flow.server.VaadinServlet Java Examples

The following examples show how to use com.vaadin.flow.server.VaadinServlet. 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: VaadinAppShellInitializer.java    From flow with Apache License 2.0 6 votes vote down vote up
@Override
public void process(Set<Class<?>> classes, ServletContext context)
        throws ServletException {

    Collection<? extends ServletRegistration> registrations = context
            .getServletRegistrations().values();
    if (registrations.isEmpty()) {
        return;
    }

    DeploymentConfiguration config = StubServletConfig
            .createDeploymentConfiguration(context,
                    registrations.iterator().next(), VaadinServlet.class);

    init(classes, context, config);
}
 
Example #2
Source File: Jsr303Test.java    From flow with Apache License 2.0 6 votes vote down vote up
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
    String vaadinPackagePrefix = VaadinServlet.class.getPackage()
            .getName();
    vaadinPackagePrefix = vaadinPackagePrefix.substring(0,
            vaadinPackagePrefix.lastIndexOf('.'));
    if (name.equals(UnitTest.class.getName())) {
        super.loadClass(name);
    } else if (name
            .startsWith(Validation.class.getPackage().getName())) {
        throw new ClassNotFoundException();
    } else if (name.startsWith(vaadinPackagePrefix)) {
        String path = name.replace('.', '/').concat(".class");
        URL resource = Thread.currentThread().getContextClassLoader()
                .getResource(path);
        InputStream stream;
        try {
            stream = resource.openStream();
            byte[] bytes = IOUtils.toByteArray(stream);
            return defineClass(name, bytes, 0, bytes.length);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return super.loadClass(name);
}
 
Example #3
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 #4
Source File: JSR356WebsocketInitializer.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Tries to determine if the given servlet registration refers to a Vaadin
 * servlet.
 *
 * @param servletRegistration
 *            The servlet registration info for the servlet
 * @param servletContext
 *            the context of the servlet
 * @return false if the servlet is definitely not a Vaadin servlet, true
 *         otherwise
 */
protected boolean isVaadinServlet(ServletRegistration servletRegistration,
        ServletContext servletContext) {
    try {
        String servletClassName = servletRegistration.getClassName();
        if (servletClassName.equals("com.ibm.ws.wsoc.WsocServlet")) {
            // Websphere servlet which implements websocket endpoints,
            // dynamically added
            return false;
        }
        // Must use servletContext class loader to load servlet class to
        // work correctly in an OSGi environment (#20024)
        Class<?> servletClass = servletContext.getClassLoader()
                .loadClass(servletClassName);
        return VaadinServlet.class.isAssignableFrom(servletClass);
    } catch (Exception e) {
        // This will fail in OSGi environments, assume everything is a
        // VaadinServlet
        return true;
    }
}
 
Example #5
Source File: StreamRequestHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws ServletException {
    ServletConfig servletConfig = new MockServletConfig();
    VaadinServlet servlet = new VaadinServlet();
    servlet.init(servletConfig);
    VaadinService service = servlet.getService();

    session = new AlwaysLockedVaadinSession(service) {
        @Override
        public StreamResourceRegistry getResourceRegistry() {
            return streamResourceRegistry;
        }
    };
    streamResourceRegistry = new StreamResourceRegistry(session);
    request = Mockito.mock(VaadinServletRequest.class);
    ServletContext servletContext = Mockito.mock(ServletContext.class);
    Mockito.when(servletContext.getMimeType(Mockito.anyString()))
            .thenReturn(null);
    Mockito.when(request.getServletContext()).thenReturn(servletContext);
    response = Mockito.mock(VaadinResponse.class);
    ui = new MockUI();
    UI.setCurrent(ui);
}
 
Example #6
Source File: MockVaadinServletService.java    From flow with Apache License 2.0 5 votes vote down vote up
public MockVaadinServletService(VaadinServlet servlet,
        DeploymentConfiguration deploymentConfiguration) {
    super(servlet, deploymentConfiguration);

    try {
        servlet.init(new MockServletConfig());
    } catch (ServletException e) {
        throw new RuntimeException(e);
    }
}
 
Example #7
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 #8
Source File: Launcher.java    From electron-java-app with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    log.info("Server starting...");

    var server = new Server(8080);

    var context = new WebAppContext();
    context.setBaseResource(findWebRoot());
    context.addServlet(VaadinServlet.class, "/*");
    context.setContextPath("/");
    context.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
            ".*vaadin/.*\\.jar|.*/classes/.*");
    context.setConfigurationDiscovered(true);
    context.getServletContext().setExtendedListenerTypes(true);
    context.addEventListener(new ServletContextListeners());
    server.setHandler(context);

    var sessions = new SessionHandler();
    context.setSessionHandler(sessions);

    var classList = Configuration.ClassList.setServerDefault(server);
    classList.addBefore(JettyWebXmlConfiguration.class.getName(), AnnotationConfiguration.class.getName());
    WebSocketServerContainerInitializer.initialize(context); // fixes IllegalStateException: Unable to configure jsr356 at that stage. ServerContainer is null

    try {
        server.start();
        server.join();
    } catch (Exception e) {
        log.error("Server error:\n", e);
    }

    log.info("Server stopped");
}
 
Example #9
Source File: StreamResourceHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws ServletException {
    ServletConfig servletConfig = new MockServletConfig();
    VaadinServlet servlet = new VaadinServlet();
    servlet.init(servletConfig);
    VaadinService service = servlet.getService();

    session = new AlwaysLockedVaadinSession(service);
    request = Mockito.mock(VaadinServletRequest.class);
    ServletContext context = Mockito.mock(ServletContext.class);
    Mockito.when(request.getServletContext()).thenReturn(context);
    response = Mockito.mock(VaadinServletResponse.class);
}
 
Example #10
Source File: StreamReceiverHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    contentLength = "6";
    inputStream = createInputStream("foobar");
    outputStream = mock(OutputStream.class);
    contentType = "foobar";
    parts = Collections.emptyList();
    MockitoAnnotations.initMocks(this);

    handler = new StreamReceiverHandler();

    VaadinServlet mockServlet = new VaadinServlet();
    mockServlet.init(new MockServletConfig());
    mockService = mockServlet.getService();

    mockRequest();
    mockReceiverAndRegistry();
    mockUi();

    when(streamReceiver.getNode()).thenReturn(stateNode);
    when(stateNode.isAttached()).thenReturn(true);
    when(streamVariable.getOutputStream())
            .thenAnswer(invocationOnMock -> outputStream);
    when(response.getOutputStream()).thenReturn(responseOutput);

    Mockito.when(session.getErrorHandler())
            .thenReturn(Mockito.mock(ErrorHandler.class));
}
 
Example #11
Source File: ServletDeployer.java    From flow with Apache License 2.0 5 votes vote down vote up
private VaadinServletCreation createAppServlet(
        ServletContext servletContext) {
    VaadinServletContext context = new VaadinServletContext(servletContext);
    boolean createServlet = ApplicationRouteRegistry.getInstance(context)
            .hasNavigationTargets();

    createServlet = createServlet || WebComponentConfigurationRegistry
            .getInstance(context).hasConfigurations();

    if (!createServlet) {
        servletCreationMessage = String.format(
                "%s there are no navigation targets registered to the "
                        + "route registry and there are no web component exporters.",
                SKIPPING_AUTOMATIC_SERVLET_REGISTRATION_BECAUSE);
        return VaadinServletCreation.NO_CREATION;
    }

    ServletRegistration vaadinServlet = findVaadinServlet(servletContext);
    if (vaadinServlet != null) {
        servletCreationMessage = String.format(
                "%s there is already a Vaadin servlet with the name %s",
                SKIPPING_AUTOMATIC_SERVLET_REGISTRATION_BECAUSE,
                vaadinServlet.getName());
        return VaadinServletCreation.SERVLET_EXISTS;
    }

    return createServletIfNotExists(servletContext, getClass().getName(),
            VaadinServlet.class, "/*");
}
 
Example #12
Source File: DevModeInitializer.java    From flow with Apache License 2.0 5 votes vote down vote up
private boolean isVaadinServletSubClass(String className) {
    try {
        return VaadinServlet.class
                .isAssignableFrom(Class.forName(className));
    } catch (ClassNotFoundException exception) {// NOSONAR
        log().debug(String.format("Servlet class name (%s) can't be found!",
                className));
        return false;

    }
}
 
Example #13
Source File: DevModeInitializer.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void process(Set<Class<?>> classes, ServletContext context)
        throws ServletException {
    Collection<? extends ServletRegistration> registrations = context
            .getServletRegistrations().values();

    ServletRegistration vaadinServletRegistration = null;
    for (ServletRegistration registration : registrations) {
        if (registration.getClassName() != null
                && isVaadinServletSubClass(registration.getClassName())) {
            vaadinServletRegistration = registration;
            break;
        }
    }

    DeploymentConfiguration config;
    if (vaadinServletRegistration != null) {
        config = StubServletConfig.createDeploymentConfiguration(context,
                vaadinServletRegistration, VaadinServlet.class);
    } else {
        config = StubServletConfig.createDeploymentConfiguration(context,
                VaadinServlet.class);
    }

    initDevModeHandler(classes, context, config);

    setDevModeStarted(context);
}
 
Example #14
Source File: MockVaadinServletService.java    From flow with Apache License 2.0 4 votes vote down vote up
public MockVaadinServletService(
        DeploymentConfiguration deploymentConfiguration) {
    this(new VaadinServlet(), deploymentConfiguration);
}
 
Example #15
Source File: ServletDeployer.java    From flow with Apache License 2.0 4 votes vote down vote up
private boolean isVaadinServlet(ClassLoader classLoader, String className) {
    return loadClass(classLoader, className)
            .map(VaadinServlet.class::isAssignableFrom).orElse(false);
}
 
Example #16
Source File: UITest.java    From flow with Apache License 2.0 4 votes vote down vote up
private static void initUI(UI ui, String initialLocation,
                           ArgumentCaptor<Integer> statusCodeCaptor)
        throws InvalidRouteConfigurationException {
    try {
        VaadinServletRequest request = Mockito
                .mock(VaadinServletRequest.class);
        VaadinResponse response = Mockito.mock(VaadinResponse.class);

        String pathInfo;
        if (initialLocation.isEmpty()) {
            pathInfo = null;
        } else {
            Assert.assertFalse(initialLocation.startsWith("/"));
            pathInfo = "/" + initialLocation;
        }
        Mockito.when(request.getPathInfo()).thenReturn(pathInfo);

        ServletConfig servletConfig = new MockServletConfig();
        VaadinServlet servlet = new VaadinServlet();
        servlet.init(servletConfig);
        VaadinService service = servlet.getService();
        service.setCurrentInstances(request, response);

        MockVaadinSession session = new AlwaysLockedVaadinSession(service);

        DeploymentConfiguration config = Mockito
                .mock(DeploymentConfiguration.class);
        Mockito.when(config.isProductionMode()).thenReturn(false);

        session.lock();
        session.setConfiguration(config);

        ui.getInternals().setSession(session);

        RouteConfiguration routeConfiguration = RouteConfiguration
                .forRegistry(ui.getRouter().getRegistry());

        routeConfiguration.update(() -> {
            routeConfiguration.getHandledRegistry().clean();
            Arrays.asList(RootNavigationTarget.class,
                    FooBarNavigationTarget.class, Parameterized.class,
                    FooBarParamNavigationTarget.class)
                    .forEach(routeConfiguration::setAnnotatedRoute);
        });

        ui.doInit(request, 0);
        ui.getRouter().initializeUI(ui, request);

        session.unlock();

        if (statusCodeCaptor != null) {
            Mockito.verify(response).setStatus(statusCodeCaptor.capture());
        }
    } catch (ServletException e) {
        throw new RuntimeException(e);
    }
}
 
Example #17
Source File: InvalidUrlTest.java    From flow with Apache License 2.0 4 votes vote down vote up
private static void initUI(UI ui, String initialLocation,
                           ArgumentCaptor<Integer> statusCodeCaptor)
        throws InvalidRouteConfigurationException {
    try {
        VaadinServletRequest request = Mockito
                .mock(VaadinServletRequest.class);
        VaadinResponse response = Mockito.mock(VaadinResponse.class);

        String pathInfo;
        if (initialLocation.isEmpty()) {
            pathInfo = null;
        } else {
            Assert.assertFalse(initialLocation.startsWith("/"));
            pathInfo = "/" + initialLocation;
        }
        Mockito.when(request.getPathInfo()).thenReturn(pathInfo);

        ServletConfig servletConfig = new MockServletConfig();
        VaadinServlet servlet = new VaadinServlet();
        servlet.init(servletConfig);
        VaadinService service = servlet.getService();
        service.setCurrentInstances(request, response);

        MockVaadinSession session = new AlwaysLockedVaadinSession(service);

        DeploymentConfiguration config = Mockito
                .mock(DeploymentConfiguration.class);
        Mockito.when(config.isProductionMode()).thenReturn(false);

        session.lock();
        session.setConfiguration(config);

        ui.getInternals().setSession(session);

        RouteConfiguration routeConfiguration = RouteConfiguration
                .forRegistry(ui.getRouter().getRegistry());
        routeConfiguration.update(() -> {
            routeConfiguration.getHandledRegistry().clean();
            Arrays.asList(UITest.RootNavigationTarget.class,
                    UITest.FooBarNavigationTarget.class).forEach(routeConfiguration::setAnnotatedRoute);
        });

        ui.doInit(request, 0);
        ui.getRouter().initializeUI(ui, request);

        session.unlock();

        if (statusCodeCaptor != null) {
            Mockito.verify(response).setStatus(statusCodeCaptor.capture());
        }
    } catch (ServletException e) {
        throw new RuntimeException(e);
    }
}
 
Example #18
Source File: RouteConfigurationTest.java    From flow with Apache License 2.0 4 votes vote down vote up
@Test
public void addListenerToApplicationScoped_noEventForSessionChange() {
    VaadinServlet servlet = Mockito.mock(VaadinServlet.class);
    Mockito.when(servlet.getServletContext()).thenReturn(servletContext);
    Mockito.when(vaadinService.getServlet()).thenReturn(servlet);

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

        List<RouteBaseData> added = new ArrayList<>();
        List<RouteBaseData> removed = new ArrayList<>();

        routeConfiguration.addRoutesChangeListener(event -> {
            added.clear();
            removed.clear();
            added.addAll(event.getAddedRoutes());
            removed.addAll(event.getRemovedRoutes());
        });

        routeConfiguration.setRoute("old", MyRoute.class);

        Assert.assertEquals(1, added.size());
        Assert.assertEquals(0, removed.size());

        added.clear();
        removed.clear();

        routeConfiguration = RouteConfiguration.forSessionScope();

        routeConfiguration.setRoute("new", MyRoute.class);

        Assert.assertEquals(0, added.size());
        Assert.assertEquals(0, removed.size());
    } finally {
        session.unlock();
        CurrentInstance.clearAll();
    }
}
 
Example #19
Source File: RouteConfigurationTest.java    From flow with Apache License 2.0 4 votes vote down vote up
@Test
public void addListenerToSessionScoped_alsoEventsForApplicationScope() {
    VaadinServlet servlet = Mockito.mock(VaadinServlet.class);
    Mockito.when(servlet.getServletContext()).thenReturn(servletContext);
    Mockito.when(vaadinService.getServlet()).thenReturn(servlet);

    try {
        CurrentInstance.set(VaadinService.class, vaadinService);
        VaadinSession.setCurrent(session);
        session.lock();

        List<RouteBaseData> added = new ArrayList<>();
        List<RouteBaseData> removed = new ArrayList<>();

        RouteConfiguration routeConfiguration = RouteConfiguration
                .forSessionScope();

        routeConfiguration.addRoutesChangeListener(event -> {
            added.clear();
            removed.clear();
            added.addAll(event.getAddedRoutes());
            removed.addAll(event.getRemovedRoutes());
        });

        routeConfiguration.setRoute("old", MyRoute.class);

        Assert.assertEquals(1, added.size());
        Assert.assertEquals(0, removed.size());

        added.clear();
        removed.clear();

        routeConfiguration = RouteConfiguration.forApplicationScope();

        routeConfiguration.setRoute("new", MyRoute.class);

        Assert.assertEquals(1, added.size());
        Assert.assertEquals(0, removed.size());
    } finally {
        session.unlock();
        CurrentInstance.clearAll();
    }
}
 
Example #20
Source File: RpcLoggerServlet.java    From flow with Apache License 2.0 4 votes vote down vote up
public RPCLoggerService(VaadinServlet servlet,
        DeploymentConfiguration deploymentConfiguration)
        throws ServiceException {
    super(servlet, deploymentConfiguration);
}
 
Example #21
Source File: MapSyncRpcHandlerTestServlet.java    From flow with Apache License 2.0 4 votes vote down vote up
public MapSyncServletService(VaadinServlet servlet,
        DeploymentConfiguration deploymentConfiguration) {
    super(servlet, deploymentConfiguration);
}
 
Example #22
Source File: VaadinIntegration.java    From HotswapAgent with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Sets the Vaadin servlet once instantiated.
 * 
 * @param servlet
 *            the Vaadin serlvet
 */
public void servletInitialized(VaadinServlet servlet) {
    vaadinServlet = servlet;
    LOGGER.info("{} initialized for servlet {}", getClass(), servlet);
}