Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You 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.apache.tomcat.websocket.server;
 
 import static org.jboss.web.WebsocketsMessages.MESSAGES;
 
 import  java.nio.charset.StandardCharsets;
 import java.util.List;
 import java.util.Map;
 
 
 
 public class UpgradeUtil {
 
     private static final byte[] WS_ACCEPT =
             "258EAFA5-E914-47DA-95CA-C5AB0DC85B11".getBytes(
                     StandardCharsets.ISO_8859_1);
 
     private UpgradeUtil() {
         // Utility class. Hide default constructor.
     }

    
Checks to see if this is an HTTP request that includes a valid upgrade request to web socket.

Note: RFC 2616 does not limit HTTP upgrade to GET requests but the Java WebSocket spec 1.0, section 8.2 implies such a limitation and RFC 6455 section 4.1 requires that a WebSocket Upgrade uses GET.

 
     public static boolean isWebSocketUpgradeRequest(ServletRequest request,
             ServletResponse response) {
 
         return ((request instanceof HttpServletRequest) &&
                 (response instanceof HttpServletResponse) &&
                 headerContainsToken((HttpServletRequestrequest,
                         .,
                         .) &&
                 "GET".equals(((HttpServletRequestrequest).getMethod()));
     }
 
 
     public static void doUpgrade(WsServerContainer scHttpServletRequest req,
             HttpServletResponse respServerEndpointConfig sec,
             Map<String,StringpathParams)
             throws ServletExceptionIOException {
 
         // Validate the rest of the headers and reject the request if that
         // validation fails
         String key;
         String subProtocol = null;
                 .)) {
             resp.sendError(.);
             return;
         }
                 .)) {
             resp.setStatus(426);
             resp.setHeader(.,
                    .);
            return;
        }
        key = req.getHeader(.);
        if (key == null) {
            resp.sendError(.);
            return;
        }
        // Origin check
        String origin = req.getHeader("Origin");
        if (!sec.getConfigurator().checkOrigin(origin)) {
            resp.sendError(.);
            return;
        }
        // Sub-protocols
        List<StringsubProtocols = getTokensFromHeader(req,
                .);
        subProtocol = sec.getConfigurator().getNegotiatedSubprotocol(
                sec.getSubprotocols(), subProtocols);
        // Extensions
        // Should normally only be one header but handle the case of multiple
        // headers
        List<ExtensionextensionsRequested = new ArrayList<Extension>();
        Enumeration<StringextHeaders = req.getHeaders(.);
        while (extHeaders.hasMoreElements()) {
            Util.parseExtensionHeader(extensionsRequestedextHeaders.nextElement());
        }
        // Negotiation phase 1. By default this simply filters out the
        // extensions that the server does not support but applications could
        // use a custom configurator to do more than this.
        List<ExtensionnegotiatedExtensionsPhase1 = sec.getConfigurator().getNegotiatedExtensions(
                .extensionsRequested);
        // Negotiation phase 2. Create the Transformations that will be applied
        // to this connection. Note than an extension may be dropped at this
        // point if the client has requested a configuration that the server is
        // unable to support.
        List<Transformationtransformations = createTransformations(negotiatedExtensionsPhase1);
        List<ExtensionnegotiatedExtensionsPhase2;
        if (transformations.isEmpty()) {
            negotiatedExtensionsPhase2 = Collections.emptyList();
        } else {
            negotiatedExtensionsPhase2 = new ArrayList<Extension>(transformations.size());
            for (Transformation t : transformations) {
                negotiatedExtensionsPhase2.add(t.getExtensionResponse());
            }
        }
        // Build the transformation pipeline
        Transformation transformation = null;
        StringBuilder responseHeaderExtensions = new StringBuilder();
        boolean first = true;
        for (Transformation t : transformations) {
            if (first) {
                first = false;
            } else {
                responseHeaderExtensions.append(',');
            }
            append(responseHeaderExtensionst.getExtensionResponse());
            if (transformation == null) {
                transformation = t;
            } else {
                transformation.setNext(t);
            }
        }
        // Now we have the full pipeline, validate the use of the RSV bits.
        if (transformation != null && !transformation.validateRsvBits(0)) {
            throw new ServletException(.incompatibleRsvBitUsage());
        }
        // If we got this far, all is good. Accept the connection.
                .);
                .);
                getWebSocketAccept(key));
        if (subProtocol != null && subProtocol.length() > 0) {
            // RFC6455 4.2.2 explicitly states "" is not valid here
            resp.setHeader(.subProtocol);
        }
        if (!transformations.isEmpty()) {
            resp.setHeader(.responseHeaderExtensions.toString());
        }
        WsHandshakeRequest wsRequest = new WsHandshakeRequest(req);
        WsHandshakeResponse wsResponse = new WsHandshakeResponse();
        WsPerSessionServerEndpointConfig perSessionServerEndpointConfig =
                new WsPerSessionServerEndpointConfig(sec);
        sec.getConfigurator().modifyHandshake(perSessionServerEndpointConfig,
                wsRequestwsResponse);
        wsRequest.finished();
        // Add any additional headers
        for (Entry<String,List<String>> entry :
                wsResponse.getHeaders().entrySet()) {
            for (String headerValueentry.getValue()) {
                resp.addHeader(entry.getKey(), headerValue);
            }
        }
        Endpoint ep;
        try {
            Class<?> clazz = sec.getEndpointClass();
            if (Endpoint.class.isAssignableFrom(clazz)) {
                ep = (Endpointsec.getConfigurator().getEndpointInstance(
                        clazz);
            } else {
                ep = new PojoEndpointServer();
            }
        } catch (InstantiationException e) {
            throw new ServletException(e);
        }
        // Small hack until the Servlet API provides a way to do this.
        ServletRequest inner = req;
        // Unwrap the request
        while (inner instanceof ServletRequestWrapper) {
            inner = ((ServletRequestWrapperinner).getRequest();
        }
        if (inner instanceof RequestFacade) {
            WsHttpUpgradeHandler wsHandler =
                    ((RequestFacadeinner).upgrade(WsHttpUpgradeHandler.class);
            wsHandler.preInit(epperSessionServerEndpointConfigscwsRequest,
                    negotiatedExtensionsPhase2subProtocoltransformationpathParams,
                    req.isSecure());
        } else {
            throw new ServletException(.upgradeFailed());
        }
    }
    private static List<TransformationcreateTransformations(
            List<ExtensionnegotiatedExtensions) {
        TransformationFactory factory = TransformationFactory.getInstance();
        LinkedHashMap<String,List<List<Extension.Parameter>>> extensionPreferences =
                new LinkedHashMap<String,List<List<Extension.Parameter>>>();
        // Result will likely be smaller than this
        List<Transformationresult = new ArrayList<Transformation>(negotiatedExtensions.size());
        for (Extension extension : negotiatedExtensions) {
            List<List<Extension.Parameter>> preferences =
                    extensionPreferences.get(extension.getName());
            if (preferences == null) {
                preferences = new ArrayList<List<Extension.Parameter>>();
                extensionPreferences.put(extension.getName(), preferences);
            }
            preferences.add(extension.getParameters());
        }
        for (Map.Entry<String,List<List<Extension.Parameter>>> entry :
            extensionPreferences.entrySet()) {
            Transformation transformation = factory.create(entry.getKey(), entry.getValue(), true);
            if (transformation != null) {
                result.add(transformation);
            }
        }
        return result;
    }
    private static void append(StringBuilder sbExtension extension) {
        if (extension == null || extension.getName() == null || extension.getName().length() == 0) {
            return;
        }
        sb.append(extension.getName());
        for (Extension.Parameter p : extension.getParameters()) {
            sb.append(';');
            sb.append(p.getName());
            if (p.getValue() != null) {
                sb.append('=');
                sb.append(p.getValue());
            }
        }
    }
    /*
     * This only works for tokens. Quoted strings need more sophisticated
     * parsing.
     */
    private static boolean headerContainsToken(HttpServletRequest req,
            String headerNameString target) {
        Enumeration<Stringheaders = req.getHeaders(headerName);
        while (headers.hasMoreElements()) {
            String header = headers.nextElement();
            String[] tokens = header.split(",");
            for (String token : tokens) {
                if (target.equalsIgnoreCase(token.trim())) {
                    return true;
                }
            }
        }
        return false;
    }
    /*
     * This only works for tokens. Quoted strings need more sophisticated
     * parsing.
     */
    private static List<StringgetTokensFromHeader(HttpServletRequest req,
            String headerName) {
        List<Stringresult = new ArrayList<String>();
        Enumeration<Stringheaders = req.getHeaders(headerName);
        while (headers.hasMoreElements()) {
            String header = headers.nextElement();
            String[] tokens = header.split(",");
            for (String token : tokens) {
                result.add(token.trim());
            }
        }
        return result;
    }
    private static String getWebSocketAccept(String key) {
        byte[] digest = ConcurrentMessageDigest.digestSHA1(
                key.getBytes(StandardCharsets.ISO_8859_1), );
        return Base64.encodeBase64String(digest);
    }
New to GrepCode? Check out our FAQ X