001/*
002 * Copyright 2002-2016 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.web.socket.client;
018
019import java.net.URI;
020import java.util.Collections;
021import java.util.HashSet;
022import java.util.List;
023import java.util.Map;
024import java.util.Set;
025
026import org.apache.commons.logging.Log;
027import org.apache.commons.logging.LogFactory;
028
029import org.springframework.http.HttpHeaders;
030import org.springframework.util.Assert;
031import org.springframework.util.concurrent.ListenableFuture;
032import org.springframework.web.socket.WebSocketExtension;
033import org.springframework.web.socket.WebSocketHandler;
034import org.springframework.web.socket.WebSocketHttpHeaders;
035import org.springframework.web.socket.WebSocketSession;
036import org.springframework.web.util.UriComponentsBuilder;
037
038/**
039 * Abstract base class for {@link WebSocketClient} implementations.
040 *
041 * @author Rossen Stoyanchev
042 * @since 4.0
043 */
044public abstract class AbstractWebSocketClient implements WebSocketClient {
045
046        private static final Set<String> specialHeaders = new HashSet<String>();
047
048        static {
049                specialHeaders.add("cache-control");
050                specialHeaders.add("connection");
051                specialHeaders.add("host");
052                specialHeaders.add("sec-websocket-extensions");
053                specialHeaders.add("sec-websocket-key");
054                specialHeaders.add("sec-websocket-protocol");
055                specialHeaders.add("sec-websocket-version");
056                specialHeaders.add("pragma");
057                specialHeaders.add("upgrade");
058        }
059
060
061        protected final Log logger = LogFactory.getLog(getClass());
062
063
064        @Override
065        public ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler,
066                        String uriTemplate, Object... uriVars) {
067
068                Assert.notNull(uriTemplate, "'uriTemplate' must not be null");
069                URI uri = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(uriVars).encode().toUri();
070                return doHandshake(webSocketHandler, null, uri);
071        }
072
073        @Override
074        public final ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler,
075                        WebSocketHttpHeaders headers, URI uri) {
076
077                Assert.notNull(webSocketHandler, "WebSocketHandler must not be null");
078                assertUri(uri);
079
080                if (logger.isDebugEnabled()) {
081                        logger.debug("Connecting to " + uri);
082                }
083
084                HttpHeaders headersToUse = new HttpHeaders();
085                if (headers != null) {
086                        for (String header : headers.keySet()) {
087                                if (!specialHeaders.contains(header.toLowerCase())) {
088                                        headersToUse.put(header, headers.get(header));
089                                }
090                        }
091                }
092
093                List<String> subProtocols = (headers != null && headers.getSecWebSocketProtocol() != null ?
094                                headers.getSecWebSocketProtocol() : Collections.<String>emptyList());
095
096                List<WebSocketExtension> extensions = (headers != null && headers.getSecWebSocketExtensions() != null ?
097                                headers.getSecWebSocketExtensions() : Collections.<WebSocketExtension>emptyList());
098
099                return doHandshakeInternal(webSocketHandler, headersToUse, uri, subProtocols, extensions,
100                                Collections.<String, Object>emptyMap());
101        }
102
103        protected void assertUri(URI uri) {
104                Assert.notNull(uri, "URI must not be null");
105                String scheme = uri.getScheme();
106                if (!"ws".equals(scheme) && !"wss".equals(scheme)) {
107                        throw new IllegalArgumentException("Invalid scheme: " + scheme);
108                }
109        }
110
111        /**
112         * Perform the actual handshake to establish a connection to the server.
113         * @param webSocketHandler the client-side handler for WebSocket messages
114         * @param headers HTTP headers to use for the handshake, with unwanted (forbidden)
115         * headers filtered out, never {@code null}
116         * @param uri the target URI for the handshake, never {@code null}
117         * @param subProtocols requested sub-protocols, or an empty list
118         * @param extensions requested WebSocket extensions, or an empty list
119         * @param attributes attributes to associate with the WebSocketSession, i.e. via
120         * {@link WebSocketSession#getAttributes()}; currently always an empty map.
121         * @return the established WebSocket session wrapped in a ListenableFuture.
122         */
123        protected abstract ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandler webSocketHandler,
124                        HttpHeaders headers, URI uri, List<String> subProtocols, List<WebSocketExtension> extensions,
125                        Map<String, Object> attributes);
126
127}