Examples of FlexSession


Examples of flex.messaging.FlexSession

                    }
                }
            }
            else
            {
                FlexSession session = FlexContext.getFlexSession();

                // if this is being stopped during runtime config, we should have a session available to us
                // However, if this is being stopped on MessageBroker shutdown, we will not have a session
                // but do not need to worry about clean up in that case as the entire session will be cleaned up
                if (session == null)
                    return;

                // remove from Session if reference count is zero
                int refCount = mb.decrementAttributeIdRefCount(attributeId);
                if (refCount == 0)
                {
                    // remove assembler from servlet context
                    session.removeAttribute(attributeId);
                }
            }
        }
    }
View Full Code Here

Examples of flex.messaging.FlexSession

                        return System.currentTimeMillis();
                }
            }
           
            // And check for an associated session performing a long poll based on wait()/notify() for this FlexClient.
            FlexSession session = null;
            for (Iterator iter = sessions.iterator(); iter.hasNext();)
            {
                session = (FlexSession)iter.next();
                Object monitor = session.waitMonitor;
                if (monitor != null && monitor instanceof EndpointQueue)
View Full Code Here

Examples of flex.messaging.FlexSession

                    handler.asyncPollComplete(internalFlush(queue));
                }
                else // Set up an async long-poll.
                {
                    // Avoid monopolizing user agent connections.
                    FlexSession session = FlexContext.getFlexSession();
                    synchronized (session)
                    {                                              
                        if (session.asyncPoll != null)
                        {
                            // If the poll is from the same client, treat it as a no-op.
View Full Code Here

Examples of flex.messaging.FlexSession

        {
            asyncPoll.cancelTimeout();
            EndpointQueue queue = asyncPoll.getEndpointQueue();
            if (queue.asyncPoll.equals(asyncPoll))
                queue.asyncPoll = null;
            FlexSession session = asyncPoll.getFlexSession();
            synchronized (session)
            {
                if (session.asyncPoll.equals(asyncPoll))
                    session.asyncPoll = null;
            }
View Full Code Here

Examples of flex.messaging.FlexSession

        {
            newQueue = new EndpointQueue();
            newQueue.flexClient = this;
            newQueue.endpointId = endpointId;
            newQueue.messages = new ArrayList(); /* Default size of 10 is fine */
            FlexSession session = messageClient.getFlexSession();
            if (session.isPushSupported())
                newQueue.pushSession = session;
            newQueue.processor = flexClientManager.createOutboundQueueProcessor(this, endpointId);
            newQueue.messageClientRefCount = 1;
           
            outboundQueues.put(endpointId, newQueue);
        }
        else
        {
            newQueue = (EndpointQueue)outboundQueues.get(endpointId);
            newQueue.messageClientRefCount++;
            // Resubscribes as a result of network connectivity issues may arrive over the same
            // endpoint but use a new session.
            FlexSession session = messageClient.getFlexSession();
            if (session.isPushSupported())
                newQueue.pushSession = session;
        }
        return newQueue;
    }
View Full Code Here

Examples of flex.messaging.FlexSession

            }             

            // If our channel-endpoint combination supports small messages, and
            // if we know the current protocol version supports small messages,
            // try to replace the message...
            FlexSession session = FlexContext.getFlexSession();
            if (session != null && session.useSmallMessages()
                    && !context.isLegacy()
                    && context.getVersion() >= MessageIOConstants.AMF3
                    && outMessage instanceof Message)
            {
                outMessage = endpoint.convertToSmallMessage((Message)outMessage);
View Full Code Here

Examples of flex.messaging.FlexSession

     * has to be sent back.
     * @param flexClient FlexClient that requested the streaming connection.
     */
    protected void handleFlexClientStreamingOpenRequest(HttpServletRequest req, HttpServletResponse res, FlexClient flexClient)
    {      
        FlexSession session = FlexContext.getFlexSession()
        if (canStream && session.canStream)
        {
            // If canStream/session.canStream is true it means we currently have
            // less than the max number of allowed streaming threads, per endpoint/session.
           
            // We need to protect writes/reads to the stream count with the endpoint's lock.
            // Also, we have to be careful to handle the case where two threads get to this point when only
            // one streaming spot remains; one thread will win and the other needs to fault.
            boolean thisThreadCanStream = false;
            synchronized (lock)
            {
                ++streamingClientsCount;
                if (streamingClientsCount == maxStreamingClients)
                {                   
                    thisThreadCanStream = true; // This thread got the last spot.
                    canStream = false;
                }
                else if (streamingClientsCount > maxStreamingClients)
                {
                    thisThreadCanStream = false; // This thread was beaten out for the last spot.
                    --streamingClientsCount; // Decrement the count because we're not going to grant the streaming right to the client.
                }
                else
                {
                    // We haven't hit the limit yet, allow this thread to stream.
                    thisThreadCanStream = true;
                }
            }
                   
            // If the thread cannot wait due to endpoint streaming connection
            // limit, inform the client and return.
            if (!thisThreadCanStream)
            {
                if (Log.isError())
                    log.error("Endpoint with id '" + getId() + "' cannot grant streaming connection to FlexClient with id '"
                            + flexClient.getId() + "' because " + MAX_STREAMING_CLIENTS + " limit of '"
                            + maxStreamingClients + "' has been reached.");              
                try
                {
                    // Return an HTTP status code 400.
                    res.sendError(HttpServletResponse.SC_BAD_REQUEST);
                }
                catch (IOException ignore)
                {}                      
                return;
            }
           
            // Setup for specific user agents.
            byte[] kickStartBytesToStream = null;
            String userAgentValue = req.getHeader(USER_AGENT_HEADER_NAME);
            String userAgent = null;           
            if (userAgentValue != null)
            {
                // Search for the best match based upon length.
                int bestMatchLength = 0;
                for (Iterator iter = userAgentSettings.keySet().iterator(); iter.hasNext();)
                {
                    String userAgentMatch = (String)iter.next();
                    if (userAgentValue.indexOf(userAgentMatch) != -1)
                    {
                        int matchLength = userAgentMatch.length();
                        if (matchLength > bestMatchLength)
                        {
                            bestMatchLength = matchLength;
                            userAgent = userAgentMatch;
                        }
                    }                           
                }
               
                if (userAgent != null)
                {
                    UserAgentSettings ua = (UserAgentSettings)userAgentSettings.get(userAgent);
                    if (ua != null)
                    {
                        synchronized (session)
                        {
                            session.maxConnectionsPerSession = ua.getMaxStreamingConnectionsPerSession();
                        }
                        int kickStartBytes = ua.getKickstartBytes();
                        if (kickStartBytes > 0)              
                        {
                            // Determine the minimum number of actual bytes that need to be sent to
                            // kickstart, taking into account transfer-encoding overhead.
                            try
                            {
                                int chunkLengthHeaderSize = Integer.toHexString(kickStartBytes).getBytes("ASCII").length;
                                int chunkOverhead = chunkLengthHeaderSize + 4; // 4 for the 2 wrapping CRLF tokens.
                                int minimumKickstartBytes = kickStartBytes - chunkOverhead;
                                kickStartBytesToStream = new byte[(minimumKickstartBytes > 0) ? minimumKickstartBytes :
                                                                                                kickStartBytes];
                            }
                            catch (UnsupportedEncodingException ignore)
                            {
                                kickStartBytesToStream = new byte[kickStartBytes];
                            }
                            Arrays.fill(kickStartBytesToStream, NULL_BYTE);                       
                        }
                    }
                }                  
            }
           
            // Now, check with the session before granting the streaming connection.
            synchronized(session)
            {                 
                ++session.streamingConnectionsCount;
                if (session.streamingConnectionsCount == session.maxConnectionsPerSession)
                {
                    thisThreadCanStream = true; // This thread got the last spot in the session.
                    session.canStream = false;
                }
                else if (session.streamingConnectionsCount > session.maxConnectionsPerSession)
                {                
                    thisThreadCanStream = false; // This thread was beaten out for the last spot.
                    --session.streamingConnectionsCount;
                    synchronized(lock)
                    {
                        // Decrement the endpoint count because we're not going to grant the streaming right to the client.                   
                        --streamingClientsCount;                         
                    }
                }
                else
                {
                    // We haven't hit the limit yet, allow this thread to stream.
                    thisThreadCanStream = true;                       
                }
            }           
           
            // If the thread cannot wait due to session streaming connection
            // limit, inform the client and return.
            if (!thisThreadCanStream)
            {         
                if (Log.isError())
                    log.error("Endpoint with id '" + getId() + "' cannot grant streaming connection to FlexClient with id '"
                            + flexClient.getId() + "' because " + MAX_STREAMING_CONNECTIONS_PER_SESSION + " limit of '" + session.maxConnectionsPerSession
                            + "' for user-agent '" + userAgent + "' has been reached.");
                try
                {
                 // Return an HTTP status code 400.
                    res.sendError(HttpServletResponse.SC_BAD_REQUEST);
                }
                catch (IOException ignore)
                {
                    // NOWARN
                }  
                return;
            }

            Thread currentThread = Thread.currentThread();
            String threadName = currentThread.getName();
            EndpointPushNotifier notifier = null;               
            boolean suppressIOExceptionLogging = false; // Used to suppress logging for IO exception.               
            try
            {               
                currentThread.setName(threadName + STREAMING_THREAD_NAME_EXTENSION);
               
                // Open and commit response headers and get output stream.
                if (addNoCacheHeaders)
                    addNoCacheHeaders(req, res);
                res.setContentType(getResponseContentType());
                res.setHeader("Connection", "close");
                res.setHeader("Transfer-Encoding", "chunked");
                ServletOutputStream os = res.getOutputStream();
                res.flushBuffer()

                // If kickstart-bytes are specified, stream them.
                if (kickStartBytesToStream != null)
                {
                    if (Log.isDebug())
                        log.debug("Endpoint with id '" + getId() + "' is streaming " + kickStartBytesToStream.length
                                + " bytes (not counting chunk encoding overhead) to kick-start the streaming connection for FlexClient with id '"
                                + flexClient.getId() + "'.");
                       
                    streamChunk(kickStartBytesToStream, os, res);
                }
               
                // Setup serialization and type marshalling contexts
                setThreadLocals();
               
                // Activate streaming helper for this connection.
                // Watch out for duplicate stream issues.
                try
                {
                    notifier = new EndpointPushNotifier(this, flexClient);
                }
                catch (MessageException me)
                {
                    if (me.getNumber() == 10033) // It's a duplicate stream request from the same FlexClient. Leave the current stream in place and fault this.
                    {
                        if (Log.isWarn())                                       
                            log.warn("Endpoint with id '" + getId() + "' received a duplicate streaming connection request from, FlexClient with id '"
                                    + flexClient.getId() + "'. Faulting request.");

                        // Rollback counters and send an error response.
                        synchronized (lock)
                        {
                            --streamingClientsCount;
                            canStream = (streamingClientsCount < maxStreamingClients);                   
                            synchronized (session)
                            {
                                --session.streamingConnectionsCount;
                                session.canStream = (session.streamingConnectionsCount < session.maxConnectionsPerSession);
                            }
                        }
                        try
                        {
                            res.sendError(HttpServletResponse.SC_BAD_REQUEST);
                        }
                        catch (IOException ignore)
                        {
                            // NOWARN
                        }
                        return; // Exit early.
                    }                      
                }
                notifier.setIdleTimeoutMinutes(idleTimeoutMinutes);
                notifier.setLogCategory(getLogCategory());
                monitorTimeout(notifier);
                currentStreamingRequests.put(notifier.getNotifierId(), notifier);
               
                // Push down an acknowledgement for the 'connect' request containing the unique id for this specific stream.
                AcknowledgeMessage connectAck = new AcknowledgeMessage();
                connectAck.setBody(notifier.getNotifierId());
                connectAck.setCorrelationId(BaseStreamingHTTPEndpoint.OPEN_COMMAND);
                ArrayList toPush = new ArrayList(1);
                toPush.add(connectAck);
                streamMessages(toPush, os, res);
               
                // Output session level streaming count.
                if (Log.isDebug())
                    Log.getLogger(FlexSession.FLEX_SESSION_LOG_CATEGORY).info("Number of streaming clients for FlexSession with id '"+ session.getId() +"' is " + session.streamingConnectionsCount + ".");

                // Output endpoint level streaming count.
                if (Log.isDebug())
                    log.debug("Number of streaming clients for endpoint with id '"+ getId() +"' is " + streamingClientsCount + ".");                               

                // And cycle in a wait-notify loop with the aid of the helper until it
                // is closed, we're interrupted or the act of streaming data to the client fails.
                while (!notifier.isClosed())
                {                                       
                    // Synchronize on pushNeeded which is our condition variable.
                    synchronized (notifier.pushNeeded)
                    {
                        try
                        {                           
                            // Drain any messages that might have been accumulated
                            // while the previous drain was being processed.
                            streamMessages(notifier.drainMessages(), os, res);
                           
                            notifier.pushNeeded.wait(serverToClientHeartbeatMillis);
                           
                            List messages = notifier.drainMessages();                           
                            // If there are no messages to send to the client, send an null
                            // byte as a heartbeat to make sure the client is still valid.
                            if (messages == null && serverToClientHeartbeatMillis > 0)
                            {
                                try
                                {
                                    os.write(NULL_BYTE);
                                    res.flushBuffer();
                                }
                                catch (IOException e)
                                {
                                    if (Log.isWarn())                                       
                                        log.warn("Endpoint with id '" + getId() + "' is closing the streaming connection to FlexClient with id '"
                                                + flexClient.getId() + "' because endpoint encountered a socket write error" +
                                        ", possibly due to an unresponsive FlexClient.");                                       
                                    break; // Exit the wait loop.                                       
                                }                                   
                            }
                            // Otherwise stream the messages to the client.
                            else
                            {
                                // Update the last time notifier was used to drain messages.
                                // Important for idle timeout detection.                                
                                notifier.updateLastUse();                               
                               
                                streamMessages(messages, os, res);                               
                            }                          
                        }
                        catch (InterruptedException e)
                        {
                            if (Log.isWarn())
                                log.warn("Streaming thread '" + threadName + "' for endpoint with id '" + getId() + "' has been interrupted and the streaming connection will be closed.");
                            os.close();
                            break; // Exit the wait loop.
                        }
                    }
                    // Update the FlexClient last use time to prevent FlexClient from
                    // timing out when the client is still subscribed. It is important
                    // to do this outside synchronized(notifier.pushNeeded) to avoid
                    // thread deadlock!
                    flexClient.updateLastUse();
                }
                if (Log.isDebug())
                    log.debug("Streaming thread '" + threadName + "' for endpoint with id '" + getId() + "' is releasing connection and returning to the request handler pool.");
                suppressIOExceptionLogging = true;
                // Terminate the response.
                streamChunk(null, os, res);
            }
            catch (IOException e)
            {
                if (Log.isWarn() && !suppressIOExceptionLogging)
                    log.warn("Streaming thread '" + threadName + "' for endpoint with id '" + getId() + "' is closing connection due to an IO error.", e);
            }
            finally
            {
                currentThread.setName(threadName);
               
                // We're done so decrement the counts for streaming threads,
                // and update the canStream flag if necessary.
                synchronized (lock)
                {
                    --streamingClientsCount;
                    canStream = (streamingClientsCount < maxStreamingClients);                   
                    synchronized (session)
                    {
                        --session.streamingConnectionsCount;
                        session.canStream = (session.streamingConnectionsCount < session.maxConnectionsPerSession);
                    }
                }
               
                if (notifier != null)
                {
                    currentStreamingRequests.remove(notifier.getNotifierId());
                    notifier.close();
                }
                                   
                // Output session level streaming count.
                if (Log.isDebug())
                    Log.getLogger(FlexSession.FLEX_SESSION_LOG_CATEGORY).info("Number of streaming clients for FlexSession with id '"+ session.getId() +"' is " + session.streamingConnectionsCount + ".");

                // Output endpoint level streaming count.
                if (Log.isDebug())
                    log.debug("Number of streaming clients for endpoint with id '"+ getId() +"' is " + streamingClientsCount + ".");
            }      
View Full Code Here

Examples of flex.messaging.FlexSession

        if (version != null)
        {
            boolean clientSupportsSmallMessages = version.doubleValue() >= messagingVersion;
            if (clientSupportsSmallMessages && getSerializationContext().enableSmallMessages)
            {
                FlexSession session = FlexContext.getFlexSession();
                if (session != null)
                    session.setUseSmallMessages(true);
            }
        }
    }
View Full Code Here

Examples of flex.messaging.FlexSession

           if (id.equals("nil"))
               id = null;
          
           flexClient = getMessageBroker().getFlexClientManager().getFlexClient(id);
           // Make sure the FlexClient and FlexSession are associated.
           FlexSession session = FlexContext.getFlexSession();       
           flexClient.registerFlexSession(session);
           // And place the FlexClient in FlexContext for this request.
           FlexContext.setThreadLocalFlexClient(flexClient);
       }
       return flexClient;
View Full Code Here

Examples of flex.messaging.FlexSession

     */
    public static void cachePageableRowSet(PageableRowSet rowset)
    {
        if (rowset != null)
        {
            FlexSession session = FlexContext.getFlexSession();
            session.setAttribute(rowset.getID(), rowset);
        }
    }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. 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.