Search in sources :

Example 11 with VaadinSession

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

the class UI method push.

/**
 * Pushes the pending changes and client RPC invocations of this UI to the
 * client-side.
 * <p>
 * If push is enabled, but the push connection is not currently open, the
 * push will be done when the connection is established.
 * <p>
 * As with all UI methods, the session must be locked when calling this
 * method. It is also recommended that {@link UI#getCurrent()} is set up to
 * return this UI since writing the response may invoke logic in any
 * attached component or extension. The recommended way of fulfilling these
 * conditions is to use {@link #access(Command)}.
 *
 * @throws IllegalStateException
 *             if push is disabled.
 * @throws UIDetachedException
 *             if this UI is not attached to a session.
 *
 * @see #getPushConfiguration()
 *
 * @since 7.1
 */
public void push() {
    VaadinSession session = getSession();
    if (session == null) {
        throw new UIDetachedException("Cannot push a detached UI");
    }
    assert session.hasLock();
    if (!getPushConfiguration().getPushMode().isEnabled()) {
        throw new IllegalStateException("Push not enabled");
    }
    PushConnection pushConnection = getInternals().getPushConnection();
    assert pushConnection != null;
    /*
         * Purge the pending access queue as it might mark a connector as dirty
         * when the push would otherwise be ignored because there are no changes
         * to push.
         */
    session.getService().runPendingAccessTasks(session);
    if (!getInternals().getStateTree().hasDirtyNodes()) {
        // Do not push if there is nothing to push
        return;
    }
    pushConnection.push();
}
Also used : VaadinSession(com.vaadin.flow.server.VaadinSession) PushConnection(com.vaadin.flow.server.communication.PushConnection)

Example 12 with VaadinSession

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

the class CurrentInstance method setCurrent.

/**
 * Sets current instances for the {@link VaadinSession} and all related
 * classes. The previously defined values can be restored by passing the
 * returned map to {@link #restoreInstances(Map)}.
 *
 * @since 7.1
 *
 * @param session
 *            The VaadinSession
 * @return A map containing the old values of the instances this method
 *         updated.
 */
public static Map<Class<?>, CurrentInstance> setCurrent(VaadinSession session) {
    Map<Class<?>, CurrentInstance> old = new HashMap<>();
    old.put(VaadinSession.class, doSet(VaadinSession.class, session));
    VaadinService service = null;
    if (session != null) {
        service = session.getService();
    }
    old.put(VaadinService.class, doSet(VaadinService.class, service));
    return old;
}
Also used : VaadinSession(com.vaadin.flow.server.VaadinSession) HashMap(java.util.HashMap) VaadinService(com.vaadin.flow.server.VaadinService)

Example 13 with VaadinSession

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

the class CurrentInstanceTest method testRestoreWithGarbageCollectedValue.

@Test
public void testRestoreWithGarbageCollectedValue() throws InterruptedException {
    VaadinSession session1 = new VaadinSession(null) {

        @Override
        public String toString() {
            return "First session";
        }
    };
    VaadinSession session2 = new VaadinSession(null) {

        @Override
        public String toString() {
            return "Second session";
        }
    };
    VaadinSession.setCurrent(session1);
    Map<Class<?>, CurrentInstance> previous = CurrentInstance.setCurrent(session2);
    // Use weak ref to verify object is collected
    WeakReference<VaadinSession> ref = new WeakReference<>(session1);
    session1 = null;
    Assert.assertTrue(TestUtil.isGarbageCollected(ref));
    CurrentInstance.restoreInstances(previous);
    Assert.assertNull(VaadinSession.getCurrent());
}
Also used : VaadinSession(com.vaadin.flow.server.VaadinSession) WeakReference(java.lang.ref.WeakReference) Test(org.junit.Test)

Example 14 with VaadinSession

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

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

the class VaadinSessionScopeTest method destroySession_sessionAttributeIsCleanedAndDestructionCallbackIsCalled.

@SuppressWarnings("rawtypes")
@Test
public void destroySession_sessionAttributeIsCleanedAndDestructionCallbackIsCalled() {
    VaadinSession session = mockSession();
    SpringVaadinSession springSession = (SpringVaadinSession) session;
    doCallRealMethod().when(springSession).addDestroyListener(Mockito.any());
    doCallRealMethod().when(springSession).fireSessionDestroy();
    VaadinSessionScope scope = new VaadinSessionScope();
    AtomicInteger count = new AtomicInteger();
    scope.registerDestructionCallback("foo", () -> count.getAndIncrement());
    Object object = new Object();
    ObjectFactory factory = Mockito.mock(ObjectFactory.class);
    when(factory.getObject()).thenReturn(object);
    scope.get("foo", factory);
    springSession.fireSessionDestroy();
    Assert.assertEquals(1, count.get());
    Assert.assertNull(session.getAttribute(BeanStore.class));
    // Destruction callbacks are not called anymore (they are removed)
    scope.getBeanStore().destroy();
    Assert.assertEquals(1, count.get());
    // object has been removed from the storage, so object factory is called
    // once again to create the bean
    scope.get("foo", factory);
    verify(factory, times(2)).getObject();
}
Also used : SpringVaadinSession(com.vaadin.flow.spring.SpringVaadinSession) VaadinSession(com.vaadin.flow.server.VaadinSession) SpringVaadinSession(com.vaadin.flow.spring.SpringVaadinSession) ObjectFactory(org.springframework.beans.factory.ObjectFactory) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test)

Aggregations

VaadinSession (com.vaadin.flow.server.VaadinSession)26 UI (com.vaadin.flow.component.UI)9 VaadinService (com.vaadin.flow.server.VaadinService)9 Before (org.junit.Before)6 DefaultInstantiator (com.vaadin.flow.di.DefaultInstantiator)4 VaadinServletRequest (com.vaadin.flow.server.VaadinServletRequest)4 SpringVaadinSession (com.vaadin.flow.spring.SpringVaadinSession)4 Test (org.junit.Test)4 CurrentInstance (com.vaadin.flow.internal.CurrentInstance)3 DeploymentConfiguration (com.vaadin.flow.function.DeploymentConfiguration)2 SessionExpiredException (com.vaadin.flow.server.SessionExpiredException)2 SystemMessages (com.vaadin.flow.server.SystemMessages)2 VaadinServlet (com.vaadin.flow.server.VaadinServlet)2 VaadinServletService (com.vaadin.flow.server.VaadinServletService)2 InvalidUIDLSecurityKeyException (com.vaadin.flow.server.communication.ServerRpcHandler.InvalidUIDLSecurityKeyException)2 PushMode (com.vaadin.flow.shared.communication.PushMode)2 JsonException (elemental.json.JsonException)2 IOException (java.io.IOException)2 Serializable (java.io.Serializable)2 Field (java.lang.reflect.Field)2