Package com.vaadin.server

Examples of com.vaadin.server.VaadinSession


                    + checkFromBeforeClientResponse.isDone());
            checkFromBeforeClientResponse = null;
        }
        if (checkCurrentInstancesBeforeResponse) {
            UI currentUI = UI.getCurrent();
            VaadinSession currentSession = VaadinSession.getCurrent();

            log("Current UI matches in beforeResponse? " + (currentUI == this));
            log("Current session matches in beforeResponse? "
                    + (currentSession == getSession()));
            checkCurrentInstancesBeforeResponse = false;
View Full Code Here


    private static ConcurrentHashMap<VaadinSession, AtomicInteger> numberOfUIsOpened = new ConcurrentHashMap<VaadinSession, AtomicInteger>();

    public static class TabUI extends UI {
        @Override
        protected void init(VaadinRequest request) {
            VaadinSession application = VaadinSession.getCurrent();
            AtomicInteger count = numberOfUIsOpened.get(application);
            if (count == null) {
                numberOfUIsOpened.putIfAbsent(application, new AtomicInteger());
                // Get our added instance or another instance that was added by
                // another thread between previous get and putIfAbsent
View Full Code Here

    public static void removeFromParent(Component content)
            throws IllegalArgumentException {
        // Verify the appropriate session is locked
        UI parentUI = content.getUI();
        if (parentUI != null) {
            VaadinSession parentSession = parentUI.getSession();
            if (parentSession != null && !parentSession.hasLock()) {
                String message = "Cannot remove from parent when the session is not locked.";
                if (VaadinService.isOtherSessionLocked(parentSession)) {
                    message += " Furthermore, there is another locked session, indicating that the component might be about to be moved from one session to another.";
                }
                throw new IllegalStateException(message);
View Full Code Here

     * @throws IOException
     *             If the writing fails.
     */
    public void write(UI ui, Writer writer, boolean repaintAll, boolean async)
            throws IOException {
        VaadinSession session = ui.getSession();
        VaadinService service = session.getService();

        // Purge pending access calls as they might produce additional changes
        // to write out
        service.runPendingAccessTasks(session);

        ArrayList<ClientConnector> dirtyVisibleConnectors = ui
                .getConnectorTracker().getDirtyVisibleConnectors();
        LegacyCommunicationManager manager = session.getCommunicationManager();
        // Paints components
        ConnectorTracker uiConnectorTracker = ui.getConnectorTracker();
        getLogger().log(Level.FINE, "* Creating response to client");

        getLogger().log(
                Level.FINE,
                "Found " + dirtyVisibleConnectors.size()
                        + " dirty connectors to paint");
        for (ClientConnector connector : dirtyVisibleConnectors) {
            boolean initialized = uiConnectorTracker
                    .isClientSideInitialized(connector);
            connector.beforeClientResponse(!initialized);
        }

        uiConnectorTracker.setWritingResponse(true);
        try {

            int syncId = service.getDeploymentConfiguration()
                    .isSyncIdCheckEnabled() ? uiConnectorTracker
                    .getCurrentSyncId() : -1;
            writer.write("\"" + ApplicationConstants.SERVER_SYNC_ID + "\": "
                    + syncId + ", ");

            writer.write("\"changes\" : ");

            JsonPaintTarget paintTarget = new JsonPaintTarget(manager, writer,
                    !repaintAll);

            new LegacyUidlWriter().write(ui, writer, paintTarget);

            paintTarget.close();
            writer.write(", "); // close changes

            // send shared state to client

            // for now, send the complete state of all modified and new
            // components

            // Ideally, all this would be sent before "changes", but that causes
            // complications with legacy components that create sub-components
            // in their paint phase. Nevertheless, this will be processed on the
            // client after component creation but before legacy UIDL
            // processing.

            writer.write("\"state\":");
            new SharedStateWriter().write(ui, writer);
            writer.write(", "); // close states

            // TODO This should be optimized. The type only needs to be
            // sent once for each connector id + on refresh. Use the same cache
            // as
            // widget mapping

            writer.write("\"types\":");
            new ConnectorTypeWriter().write(ui, writer, paintTarget);
            writer.write(", "); // close states

            // Send update hierarchy information to the client.

            // This could be optimized aswell to send only info if hierarchy has
            // actually changed. Much like with the shared state. Note though
            // that an empty hierarchy is information aswell (e.g. change from 1
            // child to 0 children)

            writer.write("\"hierarchy\":");
            new ConnectorHierarchyWriter().write(ui, writer);
            writer.write(", "); // close hierarchy

            // send server to client RPC calls for components in the UI, in call
            // order

            // collect RPC calls from components in the UI in the order in
            // which they were performed, remove the calls from components

            writer.write("\"rpc\" : ");
            new ClientRpcWriter().write(ui, writer);
            writer.write(", "); // close rpc

            uiConnectorTracker.markAllConnectorsClean();

            writer.write("\"meta\" : ");

            SystemMessages messages = ui.getSession().getService()
                    .getSystemMessages(ui.getLocale(), null);
            // TODO hilightedConnector
            new MetadataWriter().write(ui, writer, repaintAll, async, messages);
            writer.write(", ");

            writer.write("\"resources\" : ");
            new ResourceWriter().write(ui, writer, paintTarget);

            Collection<Class<? extends ClientConnector>> usedClientConnectors = paintTarget
                    .getUsedClientConnectors();
            boolean typeMappingsOpen = false;
            ClientCache clientCache = manager.getClientCache(ui);

            List<Class<? extends ClientConnector>> newConnectorTypes = new ArrayList<Class<? extends ClientConnector>>();

            for (Class<? extends ClientConnector> class1 : usedClientConnectors) {
                if (clientCache.cache(class1)) {
                    // client does not know the mapping key for this type, send
                    // mapping to client
                    newConnectorTypes.add(class1);

                    if (!typeMappingsOpen) {
                        typeMappingsOpen = true;
                        writer.write(", \"typeMappings\" : { ");
                    } else {
                        writer.write(" , ");
                    }
                    String canonicalName = class1.getCanonicalName();
                    writer.write("\"");
                    writer.write(canonicalName);
                    writer.write("\" : ");
                    writer.write(manager.getTagForType(class1));
                }
            }
            if (typeMappingsOpen) {
                writer.write(" }");
            }

            // TODO PUSH Refactor to TypeInheritanceWriter or something
            boolean typeInheritanceMapOpen = false;
            if (typeMappingsOpen) {
                // send the whole type inheritance map if any new mappings
                for (Class<? extends ClientConnector> class1 : usedClientConnectors) {
                    if (!ClientConnector.class.isAssignableFrom(class1
                            .getSuperclass())) {
                        continue;
                    }
                    if (!typeInheritanceMapOpen) {
                        typeInheritanceMapOpen = true;
                        writer.write(", \"typeInheritanceMap\" : { ");
                    } else {
                        writer.write(" , ");
                    }
                    writer.write("\"");
                    writer.write(manager.getTagForType(class1));
                    writer.write("\" : ");
                    writer.write(manager
                            .getTagForType((Class<? extends ClientConnector>) class1
                                    .getSuperclass()));
                }
                if (typeInheritanceMapOpen) {
                    writer.write(" }");
                }
            }

            // TODO Refactor to DependencyWriter or something
            /*
             * Ensure super classes come before sub classes to get script
             * dependency order right. Sub class @JavaScript might assume that
             *
             * @JavaScript defined by super class is already loaded.
             */
            Collections.sort(newConnectorTypes, new Comparator<Class<?>>() {
                @Override
                public int compare(Class<?> o1, Class<?> o2) {
                    // TODO optimize using Class.isAssignableFrom?
                    return hierarchyDepth(o1) - hierarchyDepth(o2);
                }

                private int hierarchyDepth(Class<?> type) {
                    if (type == Object.class) {
                        return 0;
                    } else {
                        return hierarchyDepth(type.getSuperclass()) + 1;
                    }
                }
            });

            List<String> scriptDependencies = new ArrayList<String>();
            List<String> styleDependencies = new ArrayList<String>();

            for (Class<? extends ClientConnector> class1 : newConnectorTypes) {
                JavaScript jsAnnotation = class1
                        .getAnnotation(JavaScript.class);
                if (jsAnnotation != null) {
                    for (String uri : jsAnnotation.value()) {
                        scriptDependencies.add(manager.registerDependency(uri,
                                class1));
                    }
                }

                StyleSheet styleAnnotation = class1
                        .getAnnotation(StyleSheet.class);
                if (styleAnnotation != null) {
                    for (String uri : styleAnnotation.value()) {
                        styleDependencies.add(manager.registerDependency(uri,
                                class1));
                    }
                }
            }

            // Include script dependencies in output if there are any
            if (!scriptDependencies.isEmpty()) {
                writer.write(", \"scriptDependencies\": "
                        + JsonUtil.stringify(toJsonArray(scriptDependencies)));
            }

            // Include style dependencies in output if there are any
            if (!styleDependencies.isEmpty()) {
                writer.write(", \"styleDependencies\": "
                        + JsonUtil.stringify(toJsonArray(styleDependencies)));
            }

            session.getDragAndDropService().printJSONResponse(writer);

            for (ClientConnector connector : dirtyVisibleConnectors) {
                uiConnectorTracker.markClientSideInitialized(connector);
            }

View Full Code Here

        }
    }

    public void testApplicationConverterFactoryInBackgroundThread() {
        VaadinSession.setCurrent(null);
        final VaadinSession appWithCustomIntegerConverter = new AlwaysLockedVaadinSession(
                null);
        appWithCustomIntegerConverter
                .setConverterFactory(new ConverterFactory42());

        TextField tf = new TextField("", "123") {
            @Override
            public VaadinSession getSession() {
View Full Code Here

        // null
        assertEquals(42, tf.getConvertedValue());
    }

    public void testApplicationConverterFactoryForDetachedComponent() {
        final VaadinSession appWithCustomIntegerConverter = new AlwaysLockedVaadinSession(
                null);
        appWithCustomIntegerConverter
                .setConverterFactory(new ConverterFactory42());
        VaadinSession.setCurrent(appWithCustomIntegerConverter);

        TextField tf = new TextField("", "123");
        tf.setConverter(Integer.class);
View Full Code Here

        // null
        assertEquals(42, tf.getConvertedValue());
    }

    public void testApplicationConverterFactoryForDifferentThanCurrentApplication() {
        final VaadinSession fieldAppWithCustomIntegerConverter = new AlwaysLockedVaadinSession(
                null);
        fieldAppWithCustomIntegerConverter
                .setConverterFactory(new ConverterFactory42());
        VaadinSession.setCurrent(new AlwaysLockedVaadinSession(null));

        TextField tf = new TextField("", "123") {
            @Override
View Full Code Here

            return super.handleConnectorRequest(request, response, path);
        }

        DownloadStream stream;

        VaadinSession session = getSession();
        session.lock();
        try {
            List<URLReference> sources = getState().sources;

            int sourceIndex = Integer.parseInt(matcher.group(1));

            if (sourceIndex < 0 || sourceIndex >= sources.size()) {
                getLogger().log(Level.WARNING,
                        "Requested source index {0} is out of bounds",
                        sourceIndex);
                return false;
            }

            URLReference reference = sources.get(sourceIndex);
            ConnectorResource resource = (ConnectorResource) ResourceReference
                    .getResource(reference);
            stream = resource.getStream();
        } finally {
            session.unlock();
        }

        stream.writeResponse(request, response);
        return true;
    }
View Full Code Here

    private void callWithUi(final AtmosphereResource resource,
            final PushEventCallback callback, boolean websocket) {
        AtmosphereRequest req = resource.getRequest();
        VaadinServletRequest vaadinRequest = new VaadinServletRequest(req,
                service);
        VaadinSession session = null;

        if (websocket) {
            // For any HTTP request we have already started the request in the
            // servlet
            service.requestStart(vaadinRequest, null);
        }
        try {
            try {
                session = service.findVaadinSession(vaadinRequest);
                assert VaadinSession.getCurrent() == session;

            } catch (ServiceException e) {
                getLogger().log(Level.SEVERE,
                        "Could not get session. This should never happen", e);
                return;
            } catch (SessionExpiredException e) {
                SystemMessages msg = service.getSystemMessages(
                        ServletPortletHelper.findLocale(null, null,
                                vaadinRequest), vaadinRequest);
                sendNotificationAndDisconnect(
                        resource,
                        VaadinService.createCriticalNotificationJSON(
                                msg.getSessionExpiredCaption(),
                                msg.getSessionExpiredMessage(), null,
                                msg.getSessionExpiredURL()));
                return;
            }

            UI ui = null;
            session.lock();
            try {
                ui = service.findUI(vaadinRequest);
                assert UI.getCurrent() == ui;

                if (ui == null) {
                    sendNotificationAndDisconnect(resource,
                            UidlRequestHandler.getUINotFoundErrorJSON(service,
                                    vaadinRequest));
                } else {
                    callback.run(resource, ui);
                }
            } catch (final IOException e) {
                callErrorHandler(session, e);
            } catch (final Exception e) {
                SystemMessages msg = service.getSystemMessages(
                        ServletPortletHelper.findLocale(null, null,
                                vaadinRequest), vaadinRequest);

                AtmosphereResource errorResource = resource;
                if (ui != null && ui.getPushConnection() != null) {
                    // We MUST use the opened push connection if there is one.
                    // Otherwise we will write the response to the wrong request
                    // when using streaming (the client -> server request
                    // instead of the opened push channel)
                    errorResource = ((AtmospherePushConnection) ui
                            .getPushConnection()).getResource();
                }

                sendNotificationAndDisconnect(
                        errorResource,
                        VaadinService.createCriticalNotificationJSON(
                                msg.getInternalErrorCaption(),
                                msg.getInternalErrorMessage(), null,
                                msg.getInternalErrorURL()));
                callErrorHandler(session, e);
            } finally {
                try {
                    session.unlock();
                } catch (Exception e) {
                    getLogger().log(Level.WARNING,
                            "Error while unlocking session", e);
                    // can't call ErrorHandler, we (hopefully) don't have a lock
                }
View Full Code Here

        // things.

        AtmosphereResource resource = event.getResource();
        VaadinServletRequest vaadinRequest = new VaadinServletRequest(
                resource.getRequest(), service);
        VaadinSession session = null;

        try {
            session = service.findVaadinSession(vaadinRequest);
        } catch (ServiceException e) {
            getLogger().log(Level.SEVERE,
                    "Could not get session. This should never happen", e);
            return;
        } catch (SessionExpiredException e) {
            getLogger()
                    .log(Level.SEVERE,
                            "Session expired before push was disconnected. This should never happen",
                            e);
            return;
        }

        UI ui = null;
        session.lock();
        try {
            VaadinSession.setCurrent(session);
            // Sets UI.currentInstance
            ui = service.findUI(vaadinRequest);
            if (ui == null) {
                /*
                 * UI not found, could be because FF has asynchronously closed
                 * the websocket connection and Atmosphere has already done
                 * cleanup of the request attributes.
                 *
                 * In that case, we still have a chance of finding the right UI
                 * by iterating through the UIs in the session looking for one
                 * using the same AtmosphereResource.
                 */
                ui = findUiUsingResource(resource, session.getUIs());

                if (ui == null) {
                    getLogger()
                            .log(Level.SEVERE,
                                    "Could not get UI. This should never happen,"
                                            + " except when reloading in Firefox -"
                                            + " see http://dev.vaadin.com/ticket/14251.");
                    return;
                } else {
                    getLogger()
                            .log(Level.INFO,
                                    "No UI was found based on data in the request,"
                                            + " but a slower lookup based on the AtmosphereResource succeeded."
                                            + " See http://dev.vaadin.com/ticket/14251 for more details.");
                }
            }

            PushMode pushMode = ui.getPushConfiguration().getPushMode();
            AtmospherePushConnection pushConnection = getConnectionForUI(ui);

            String id = resource.uuid();

            if (pushConnection == null) {
                getLogger()
                        .log(Level.WARNING,
                                "Could not find push connection to close: {0} with transport {1}",
                                new Object[] { id, resource.transport() });
            } else {
                if (!pushMode.isEnabled()) {
                    /*
                     * The client is expected to close the connection after push
                     * mode has been set to disabled.
                     */
                    getLogger().log(Level.FINER,
                            "Connection closed for resource {0}", id);
                } else {
                    /*
                     * Unexpected cancel, e.g. if the user closes the browser
                     * tab.
                     */
                    getLogger()
                            .log(Level.FINER,
                                    "Connection unexpectedly closed for resource {0} with transport {1}",
                                    new Object[] { id, resource.transport() });
                }
                if (pushConnection.isConnected()) {
                    // disconnect() assumes the push connection is connected but
                    // this method can currently be called more than once during
                    // disconnect, depending on the situation
                    pushConnection.disconnect();
                }
            }

        } catch (final Exception e) {
            callErrorHandler(session, e);
        } finally {
            try {
                session.unlock();
            } catch (Exception e) {
                getLogger().log(Level.WARNING, "Error while unlocking session",
                        e);
                // can't call ErrorHandler, we (hopefully) don't have a lock
            }
View Full Code Here

TOP

Related Classes of com.vaadin.server.VaadinSession

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.