001/*
002 * Copyright 2002-2018 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.lang.Nullable;
031import org.springframework.util.Assert;
032import org.springframework.util.concurrent.ListenableFuture;
033import org.springframework.web.socket.WebSocketExtension;
034import org.springframework.web.socket.WebSocketHandler;
035import org.springframework.web.socket.WebSocketHttpHeaders;
036import org.springframework.web.socket.WebSocketSession;
037import org.springframework.web.util.UriComponentsBuilder;
038
039/**
040 * Abstract base class for {@link WebSocketClient} implementations.
041 *
042 * @author Rossen Stoyanchev
043 * @since 4.0
044 */
045public abstract class AbstractWebSocketClient implements WebSocketClient {
046
047        private static final Set<String> specialHeaders = new HashSet<>();
048
049        static {
050                specialHeaders.add("cache-control");
051                specialHeaders.add("connection");
052                specialHeaders.add("host");
053                specialHeaders.add("sec-websocket-extensions");
054                specialHeaders.add("sec-websocket-key");
055                specialHeaders.add("sec-websocket-protocol");
056                specialHeaders.add("sec-websocket-version");
057                specialHeaders.add("pragma");
058                specialHeaders.add("upgrade");
059        }
060
061
062        protected final Log logger = LogFactory.getLog(getClass());
063
064
065        @Override
066        public ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler,
067                        String uriTemplate, Object... uriVars) {
068
069                Assert.notNull(uriTemplate, "'uriTemplate' must not be null");
070                URI uri = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(uriVars).encode().toUri();
071                return doHandshake(webSocketHandler, null, uri);
072        }
073
074        @Override
075        public final ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler,
076                        @Nullable WebSocketHttpHeaders headers, URI uri) {
077
078                Assert.notNull(webSocketHandler, "WebSocketHandler must not be null");
079                assertUri(uri);
080
081                if (logger.isDebugEnabled()) {
082                        logger.debug("Connecting to " + uri);
083                }
084
085                HttpHeaders headersToUse = new HttpHeaders();
086                if (headers != null) {
087                        headers.forEach((header, values) -> {
088                                if (values != null && !specialHeaders.contains(header.toLowerCase())) {
089                                        headersToUse.put(header, values);
090                                }
091                        });
092                }
093
094                List<String> subProtocols =
095                                (headers != null ? headers.getSecWebSocketProtocol() : Collections.emptyList());
096                List<WebSocketExtension> extensions =
097                                (headers != null ? headers.getSecWebSocketExtensions() : Collections.emptyList());
098
099                return doHandshakeInternal(webSocketHandler, headersToUse, uri, subProtocols, extensions,
100                                Collections.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 the 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 the 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}