Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (c) 2008-2014 the original author or authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package org.cometd.websocket.server;
 
 import java.util.List;
 
 
 {
     public WebSocketTransport(BayeuxServerImpl bayeux)
     {
         super(bayeux);
     }
 
     @Override
     protected void init()
     {
         super.init();
 
         final ServletContext context = (ServletContext)getOption(ServletContext.class.getName());
         if (context == null)
             throw new IllegalArgumentException("Missing ServletContext");
 
         String cometdURLMapping = (String)getOption();
         if (cometdURLMapping == null)
             throw new IllegalArgumentException("Missing URL Mapping");
 
         if (cometdURLMapping.endsWith("/*"))
             cometdURLMapping = cometdURLMapping.substring(0, cometdURLMapping.length() - 2);
 
         ServerContainer container = (ServerContainer)context.getAttribute(ServerContainer.class.getName());
         // JSR 356 does not support a input buffer size option
         int maxMessageSize = getOption(container.getDefaultMaxTextMessageBufferSize());
         container.setDefaultMaxTextMessageBufferSize(maxMessageSize);
         long idleTimeout = getOption(container.getDefaultMaxSessionIdleTimeout());
         container.setDefaultMaxSessionIdleTimeout(idleTimeout);
 
         String protocol = getProtocol();
         ServerEndpointConfig config = ServerEndpointConfig.Builder.create(WebSocketScheduler.classcometdURLMapping)
                 .subprotocols(protocol == null ? null : Collections.singletonList(protocol))
                 .configurator(new Configurator(context))
                 .build();
 
         try
         {
             container.addEndpoint(config);
         }
         catch (DeploymentException x)
         {
             throw new RuntimeException(x);
         }
     }
 
     @Override
     protected void destroy()
     {
         Executor threadPool = getExecutor();
         if (threadPool instanceof LifeCycle)
         {
             try
            {
                ((LifeCycle)threadPool).stop();
            }
            catch (Exception x)
            {
                .trace(""x);
            }
        }
        super.destroy();
    }
    protected boolean checkOrigin(HandshakeRequest requestString origin)
    {
        return true;
    }
    protected void send(final Session wsSessionfinal ServerSession sessionString datathrows IOException
    {
        // This method may be called concurrently.
        // The WebSocket specification specifically forbids concurrent calls in case of
        // blocking writes, so we rely on async writes.
        // In Jetty this is guaranteed to work, while for other implementation who knows.
        .debug("Sending {}"data);
        // Async write.
        wsSession.getAsyncRemote().sendText(datanew SendHandler()
        {
            @Override
            public void onResult(SendResult result)
            {
                Throwable failure = result.getException();
                if (failure != null)
                    handleException(wsSessionsessionfailure);
            }
        });
    }
    {
        private final AbstractWebSocketScheduler delegate;
        private volatile Session _wsSession;
        private WebSocketScheduler(WebSocketContext context)
        {
             = new AbstractWebSocketScheduler(context)
            {
                @Override
                protected void close(final int codeString reason)
                {
                    try
                    {
                        .close(new CloseReason(CloseReason.CloseCodes.getCloseCode(code), reason));
                    }
                    catch (IOException x)
                    {
                        .trace("Could not close WebSocket session " + x);
                    }
                }
                @Override
                protected void schedule(boolean timeoutServerMessage.Mutable expiredConnectReply)
                {
                    schedule(timeoutexpiredConnectReply);
                }
            };
        }
        @Override
        public void onOpen(Session wsSessionEndpointConfig config)
        {
             = wsSession;
            wsSession.addMessageHandler(this);
        }
        @Override
        public void onClose(Session wsSessionCloseReason closeReason)
        {
            .onClose(closeReason.getCloseCode().getCode(), closeReason.getReasonPhrase());
        }
        @Override
        public void onError(Session wsSessionThrowable failure)
        {
            .onError(failure);
            // TODO: more to do ?
        }
        @Override
        public void cancel()
        {
            .cancel();
        }
        @Override
        public void schedule()
        {
            .schedule();
        }
        @Override
        public void run()
        {
            .run();
        }
        @Override
        public void onMessage(String data)
        {
            .debug("WebSocket Text message on {}/{}"WebSocketTransport.this.hashCode(), hashCode());
            .onMessage(data);
        }
    }
    private class WebSocketContext implements BayeuxContext
    {
        private final ServletContext context;
        private final HandshakeRequest request;
        private WebSocketContext(ServletContext contextHandshakeRequest request)
        {
            this. = context;
            this. = request;
        }
        @Override
        public Principal getUserPrincipal()
        {
            return .getUserPrincipal();
        }
        @Override
        public boolean isUserInRole(String role)
        {
            return .isUserInRole(role);
        }
        @Override
        public InetSocketAddress getRemoteAddress()
        {
            // Not available in JSR 356
            return null;
        }
        @Override
        public InetSocketAddress getLocalAddress()
        {
            // Not available in JSR 356
            return null;
        }
        @Override
        public String getHeader(String name)
        {
            List<Stringheaders = .getHeaders().get(name);
            return headers != null && headers.size() > 0 ? headers.get(0) : null;
        }
        @Override
        public List<StringgetHeaderValues(String name)
        {
            return .getHeaders().get(name);
        }
        public String getParameter(String name)
        {
            List<Stringparams = .getParameterMap().get(name);
            return params != null && params.size() > 0 ? params.get(0) : null;
        }
        @Override
        public List<StringgetParameterValues(String name)
        {
            return .getParameterMap().get(name);
        }
        @Override
        public String getCookie(String name)
        {
            // TODO:
            return null;
        }
        @Override
        public String getHttpSessionId()
        {
            HttpSession session = (HttpSession).getHttpSession();
            return session == null ? null : session.getId();
        }
        @Override
        public Object getHttpSessionAttribute(String name)
        {
            HttpSession session = (HttpSession).getHttpSession();
            return session == null ? null : session.getAttribute(name);
        }
        @Override
        public void setHttpSessionAttribute(String nameObject value)
        {
            HttpSession session = (HttpSession).getHttpSession();
            if (session != null)
                session.setAttribute(namevalue);
        }
        @Override
        public void invalidateHttpSession()
        {
            HttpSession session = (HttpSession).getHttpSession();
            if (session != null)
                session.invalidate();
        }
        @Override
        public Object getRequestAttribute(String name)
        {
            // Not available in JSR 356
            return null;
        }
        @Override
        public Object getContextAttribute(String name)
        {
            return .getAttribute(name);
        }
        @Override
        public String getContextInitParameter(String name)
        {
            return .getInitParameter(name);
        }
        @Override
        public String getURL()
        {
            String url = .getRequestURI().toString();
            String query = .getQueryString();
            if (query != null)
                url += "?" + query;
            return url;
        }
    }
    private class Configurator extends ServerEndpointConfig.Configurator
    {
        private final ServletContext servletContext;
        private WebSocketContext bayeuxContext;
        private boolean protocolMatches;
        private Configurator(ServletContext servletContext)
        {
            this. = servletContext;
            // Use a sensible default in case getNegotiatedSubprotocol() is not invoked.
            this. = true;
        }
        @Override
        public void modifyHandshake(ServerEndpointConfig secHandshakeRequest requestHandshakeResponse response)
        {
            this. = new WebSocketContext(request);
        }
        @Override
        public boolean checkOrigin(String originHeaderValue)
        {
            HandshakeRequest request =  == null ? null : .;
            return WebSocketTransport.this.checkOrigin(requestoriginHeaderValue);
        }
        @Override
        public String getNegotiatedSubprotocol(List<StringsupportedList<Stringrequested)
        {
            if ( = checkProtocol(supportedrequested))
                return super.getNegotiatedSubprotocol(supportedrequested);
            .warn("Could not negotiate WebSocket SubProtocols: server{} != client{}"supportedrequested);
            return null;
        }
        @Override
        public List<ExtensiongetNegotiatedExtensions(List<ExtensioninstalledList<Extensionrequested)
        {
            return super.getNegotiatedExtensions(installedrequested);
        }
        @Override
        @SuppressWarnings("unchecked")
        public <T> T getEndpointInstance(Class<T> endpointClassthrows InstantiationException
        {
            if (!getBayeux().getAllowedTransports().contains(getName()))
                throw new InstantiationException("Transport not allowed");
            if (!)
                throw new InstantiationException("Could not negotiate WebSocket SubProtocols");
            return (T)new WebSocketScheduler();
        }
    }
New to GrepCode? Check out our FAQ X