Upgrade to Jetty 12

This commit upgrades Spring Framework to Jetty 12.0.1, and Reactive HTTP
 Client 4.0.0.

Closes gh-30698
This commit is contained in:
Arjen Poutsma
2023-06-22 11:53:50 +02:00
parent 210b42b7d8
commit 6597727c86
32 changed files with 491 additions and 851 deletions

View File

@@ -20,13 +20,14 @@ import java.nio.ByteBuffer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jetty.websocket.api.Callback;
import org.eclipse.jetty.websocket.api.Frame;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketFrame;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketOpen;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
import org.eclipse.jetty.websocket.core.OpCode;
@@ -65,8 +66,8 @@ public class JettyWebSocketHandlerAdapter {
}
@OnWebSocketConnect
public void onWebSocketConnect(Session session) {
@OnWebSocketOpen
public void onWebSocketOpen(Session session) {
try {
this.wsSession.initializeNativeSession(session);
this.webSocketHandler.afterConnectionEstablished(this.wsSession);
@@ -88,8 +89,8 @@ public class JettyWebSocketHandlerAdapter {
}
@OnWebSocketMessage
public void onWebSocketBinary(byte[] payload, int offset, int length) {
BinaryMessage message = new BinaryMessage(payload, offset, length, true);
public void onWebSocketBinary(ByteBuffer payload, Callback callback) {
BinaryMessage message = new BinaryMessage(payload, true);
try {
this.webSocketHandler.handleMessage(this.wsSession, message);
}
@@ -99,7 +100,7 @@ public class JettyWebSocketHandlerAdapter {
}
@OnWebSocketFrame
public void onWebSocketFrame(Frame frame) {
public void onWebSocketFrame(Frame frame, Callback callback) {
if (OpCode.PONG == frame.getOpCode()) {
ByteBuffer payload = frame.getPayload() != null ? frame.getPayload() : EMPTY_PAYLOAD;
PongMessage message = new PongMessage(payload);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -17,6 +17,7 @@
package org.springframework.web.socket.adapter.jetty;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.security.Principal;
@@ -24,9 +25,10 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.eclipse.jetty.websocket.api.Callback;
import org.eclipse.jetty.websocket.api.ExtensionConfig;
import org.eclipse.jetty.websocket.api.RemoteEndpoint;
import org.eclipse.jetty.websocket.api.Session;
import org.springframework.http.HttpHeaders;
@@ -131,18 +133,17 @@ public class JettyWebSocketSession extends AbstractWebSocketSession<Session> {
@Override
public InetSocketAddress getLocalAddress() {
checkNativeSessionInitialized();
return (InetSocketAddress) getNativeSession().getLocalAddress();
return (InetSocketAddress) getNativeSession().getLocalSocketAddress();
}
@Override
public InetSocketAddress getRemoteAddress() {
checkNativeSessionInitialized();
return (InetSocketAddress) getNativeSession().getRemoteAddress();
return (InetSocketAddress) getNativeSession().getRemoteSocketAddress();
}
/**
* This method is a no-op for Jetty. As per {@link Session#getPolicy()}, the
* returned {@code WebSocketPolicy} is read-only and changing it has no effect.
* This method is a no-op for Jetty.
*/
@Override
public void setTextMessageSizeLimit(int messageSizeLimit) {
@@ -155,8 +156,7 @@ public class JettyWebSocketSession extends AbstractWebSocketSession<Session> {
}
/**
* This method is a no-op for Jetty. As per {@link Session#getPolicy()}, the
* returned {@code WebSocketPolicy} is read-only and changing it has no effect.
* This method is a no-op for Jetty.
*/
@Override
public void setBinaryMessageSizeLimit(int messageSizeLimit) {
@@ -210,31 +210,57 @@ public class JettyWebSocketSession extends AbstractWebSocketSession<Session> {
@Override
protected void sendTextMessage(TextMessage message) throws IOException {
getRemoteEndpoint().sendString(message.getPayload());
useSession((session, callback) -> session.sendText(message.getPayload(), callback));
}
@Override
protected void sendBinaryMessage(BinaryMessage message) throws IOException {
getRemoteEndpoint().sendBytes(message.getPayload());
useSession((session, callback) -> session.sendBinary(message.getPayload(), callback));
}
@Override
protected void sendPingMessage(PingMessage message) throws IOException {
getRemoteEndpoint().sendPing(message.getPayload());
useSession((session, callback) -> session.sendPing(message.getPayload(), callback));
}
@Override
protected void sendPongMessage(PongMessage message) throws IOException {
getRemoteEndpoint().sendPong(message.getPayload());
}
private RemoteEndpoint getRemoteEndpoint() {
return getNativeSession().getRemote();
useSession((session, callback) -> session.sendPong(message.getPayload(), callback));
}
@Override
protected void closeInternal(CloseStatus status) throws IOException {
getNativeSession().close(status.getCode(), status.getReason());
useSession((session, callback) -> session.close(status.getCode(), status.getReason(), callback));
}
private void useSession(SessionConsumer sessionConsumer) throws IOException {
try {
Callback.Completable completable = new Callback.Completable();
sessionConsumer.consume(getNativeSession(), completable);
completable.get();
}
catch (ExecutionException ex) {
Throwable cause = ex.getCause();
if (cause instanceof IOException ioEx) {
throw ioEx;
}
else if (cause instanceof UncheckedIOException uioEx) {
throw uioEx.getCause();
}
else {
throw new IOException(ex.getMessage(), cause);
}
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
@FunctionalInterface
private interface SessionConsumer {
void consume(Session session, Callback callback) throws IOException;
}
}

View File

@@ -1,174 +0,0 @@
/*
* Copyright 2002-2022 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
*
* https://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.springframework.web.socket.client.jetty;
import java.net.URI;
import java.security.Principal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.springframework.context.Lifecycle;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;
import org.springframework.util.concurrent.FutureUtils;
import org.springframework.web.socket.WebSocketExtension;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.adapter.jetty.JettyWebSocketHandlerAdapter;
import org.springframework.web.socket.adapter.jetty.JettyWebSocketSession;
import org.springframework.web.socket.adapter.jetty.WebSocketToJettyExtensionConfigAdapter;
import org.springframework.web.socket.client.AbstractWebSocketClient;
/**
* Initiates WebSocket requests to a WebSocket server programmatically
* through the Jetty WebSocket API. Only supported on Jetty 11, superseded by
* {@link org.springframework.web.socket.client.standard.StandardWebSocketClient}.
*
* <p>As of 4.1 this class implements {@link Lifecycle} rather than
* {@link org.springframework.context.SmartLifecycle}. Use
* {@link org.springframework.web.socket.client.WebSocketConnectionManager
* WebSocketConnectionManager} instead to auto-start a WebSocket connection.
*
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @since 4.0
* @deprecated as of 6.0.3, in favor of
* {@link org.springframework.web.socket.client.standard.StandardWebSocketClient}
*/
@Deprecated(since = "6.0.3", forRemoval = true)
public class JettyWebSocketClient extends AbstractWebSocketClient implements Lifecycle {
private final org.eclipse.jetty.websocket.client.WebSocketClient client;
@Nullable
private AsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
/**
* Default constructor that creates an instance of
* {@link org.eclipse.jetty.websocket.client.WebSocketClient}.
*/
public JettyWebSocketClient() {
this.client = new org.eclipse.jetty.websocket.client.WebSocketClient();
}
/**
* Constructor that accepts an existing
* {@link org.eclipse.jetty.websocket.client.WebSocketClient} instance.
*/
public JettyWebSocketClient(WebSocketClient client) {
this.client = client;
}
/**
* Set an {@link AsyncTaskExecutor} to use when opening connections.
* <p>If this property is set to {@code null}, calls to any of the
* {@code doHandshake} methods will block until the connection is established.
* <p>By default an instance of {@code SimpleAsyncTaskExecutor} is used.
*/
public void setTaskExecutor(@Nullable AsyncTaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
/**
* Return the configured {@link AsyncTaskExecutor}.
*/
@Nullable
public AsyncTaskExecutor getTaskExecutor() {
return this.taskExecutor;
}
@Override
public void start() {
try {
this.client.start();
}
catch (Exception ex) {
throw new IllegalStateException("Failed to start Jetty WebSocketClient", ex);
}
}
@Override
public void stop() {
try {
this.client.stop();
}
catch (Exception ex) {
logger.error("Failed to stop Jetty WebSocketClient", ex);
}
}
@Override
public boolean isRunning() {
return this.client.isStarted();
}
@Override
public CompletableFuture<WebSocketSession> executeInternal(WebSocketHandler wsHandler,
HttpHeaders headers, final URI uri, List<String> protocols,
List<WebSocketExtension> extensions, Map<String, Object> attributes) {
final ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setSubProtocols(protocols);
for (WebSocketExtension extension : extensions) {
request.addExtensions(new WebSocketToJettyExtensionConfigAdapter(extension));
}
request.setHeaders(headers);
Principal user = getUser();
JettyWebSocketSession wsSession = new JettyWebSocketSession(attributes, user);
Callable<WebSocketSession> connectTask = () -> {
JettyWebSocketHandlerAdapter adapter = new JettyWebSocketHandlerAdapter(wsHandler, wsSession);
Future<Session> future = this.client.connect(adapter, uri, request);
future.get(this.client.getConnectTimeout() + 2000, TimeUnit.MILLISECONDS);
return wsSession;
};
if (this.taskExecutor != null) {
return FutureUtils.callAsync(connectTask, this.taskExecutor);
}
else {
return FutureUtils.callAsync(connectTask);
}
}
/**
* Return the user to make available through {@link WebSocketSession#getPrincipal()}.
* By default, this method returns {@code null}
*/
@Nullable
protected Principal getUser() {
return null;
}
}

View File

@@ -1,9 +0,0 @@
/**
* Client-side support for the Jetty WebSocket API.
*/
@NonNullApi
@NonNullFields
package org.springframework.web.socket.client.jetty;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;

View File

@@ -25,8 +25,8 @@ import java.util.Map;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.eclipse.jetty.websocket.server.JettyWebSocketCreator;
import org.eclipse.jetty.websocket.server.JettyWebSocketServerContainer;
import org.eclipse.jetty.ee10.websocket.server.JettyWebSocketCreator;
import org.eclipse.jetty.ee10.websocket.server.JettyWebSocketServerContainer;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;

View File

@@ -23,11 +23,11 @@ import java.util.Enumeration;
import java.util.Iterator;
import java.util.concurrent.CompletableFuture;
import org.eclipse.jetty.client.ContentResponse;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.util.StringRequestContent;
import org.eclipse.jetty.client.Request;
import org.eclipse.jetty.client.Response;
import org.eclipse.jetty.client.StringRequestContent;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpMethod;
@@ -186,11 +186,11 @@ public class JettyXhrTransport extends AbstractXhrTransport implements Lifecycle
/**
* Jetty client {@link org.eclipse.jetty.client.api.Response.Listener Response
* Jetty client {@link org.eclipse.jetty.client.Response.Listener Response
* Listener} that splits the body of the response into SockJS frames and
* delegates them to the {@link XhrClientSockJsSession}.
*/
private class SockJsResponseListener extends Response.Listener.Adapter {
private class SockJsResponseListener implements Response.Listener {
private final URI transportUrl;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -63,7 +63,6 @@ public abstract class AbstractWebSocketIntegrationTests {
@SuppressWarnings("removal")
static Stream<Arguments> argumentsFactory() {
return Stream.of(
arguments(named("Jetty", new JettyWebSocketTestServer()), named("Jetty", new org.springframework.web.socket.client.jetty.JettyWebSocketClient())),
arguments(named("Tomcat", new TomcatWebSocketTestServer()), named("Standard", new StandardWebSocketClient())),
arguments(named("Undertow", new UndertowTestServer()), named("Standard", new StandardWebSocketClient())));
}

View File

@@ -21,13 +21,13 @@ import java.util.EnumSet;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.Filter;
import jakarta.servlet.ServletContext;
import org.eclipse.jetty.ee10.servlet.FilterHolder;
import org.eclipse.jetty.ee10.servlet.ServletContextHandler;
import org.eclipse.jetty.ee10.servlet.ServletHolder;
import org.eclipse.jetty.ee10.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.NetworkConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

View File

@@ -51,7 +51,7 @@ class JettyWebSocketHandlerAdapterTests {
@Test
void onOpen() throws Exception {
this.adapter.onWebSocketConnect(this.session);
this.adapter.onWebSocketOpen(this.session);
verify(this.webSocketHandler).afterConnectionEstablished(this.webSocketSession);
}

View File

@@ -1,125 +0,0 @@
/*
* Copyright 2002-2019 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
*
* https://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.springframework.web.socket.client.jetty;
/**
* Tests for {@link JettyWebSocketClient}.
*
* @author Rossen Stoyanchev
*/
public class JettyWebSocketClientTests {
/* TODO: complete upgrade to Jetty 11
private JettyWebSocketClient client;
private TestJettyWebSocketServer server;
private String wsUrl;
private WebSocketSession wsSession;
@BeforeEach
public void setup() throws Exception {
this.server = new TestJettyWebSocketServer(new TextWebSocketHandler());
this.server.start();
this.client = new JettyWebSocketClient();
this.client.start();
this.wsUrl = "ws://localhost:" + this.server.getPort() + "/test";
}
@AfterEach
public void teardown() throws Exception {
this.wsSession.close();
this.client.stop();
this.server.stop();
}
@Test
public void doHandshake() throws Exception {
WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
headers.setSecWebSocketProtocol(Arrays.asList("echo"));
this.wsSession = this.client.doHandshake(new TextWebSocketHandler(), headers, new URI(this.wsUrl)).get();
assertThat(this.wsSession.getUri().toString()).isEqualTo(this.wsUrl);
assertThat(this.wsSession.getAcceptedProtocol()).isEqualTo("echo");
}
@Test
public void doHandshakeWithTaskExecutor() throws Exception {
WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
headers.setSecWebSocketProtocol(Arrays.asList("echo"));
this.client.setTaskExecutor(new SimpleAsyncTaskExecutor());
this.wsSession = this.client.doHandshake(new TextWebSocketHandler(), headers, new URI(this.wsUrl)).get();
assertThat(this.wsSession.getUri().toString()).isEqualTo(this.wsUrl);
assertThat(this.wsSession.getAcceptedProtocol()).isEqualTo("echo");
}
private static class TestJettyWebSocketServer {
private final Server server;
public TestJettyWebSocketServer(final WebSocketHandler webSocketHandler) {
this.server = new Server();
ServerConnector connector = new ServerConnector(this.server);
connector.setPort(0);
this.server.addConnector(connector);
this.server.setHandler(new WebSocketUpgradeHandler() {
@Override
public void configure(JettyWebSocketServletFactory factory) {
factory.setCreator(new JettyWebSocketCreator() {
@Override
public Object createWebSocket(JettyServerUpgradeRequest req, JettyServerUpgradeResponse resp) {
if (!CollectionUtils.isEmpty(req.getSubProtocols())) {
resp.setAcceptedSubProtocol(req.getSubProtocols().get(0));
}
JettyWebSocketSession session = new JettyWebSocketSession(null, null);
return new JettyWebSocketHandlerAdapter(webSocketHandler, session);
}
});
}
});
}
public void start() throws Exception {
this.server.start();
}
public void stop() throws Exception {
this.server.stop();
}
public int getPort() {
return ((ServerConnector) this.server.getConnectors()[0]).getLocalPort();
}
}
*/
}

View File

@@ -1,64 +0,0 @@
/*
* Copyright 2002-2022 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
*
* https://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.springframework.web.socket.sockjs.client;
import org.eclipse.jetty.client.HttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.JettyWebSocketTestServer;
import org.springframework.web.socket.server.RequestUpgradeStrategy;
import org.springframework.web.socket.server.jetty.JettyRequestUpgradeStrategy;
/**
* SockJS integration tests using Jetty for client and server.
*
* @author Rossen Stoyanchev
*/
class JettySockJsIntegrationTests extends AbstractSockJsIntegrationTests {
@Override
protected Class<?> upgradeStrategyConfigClass() {
return JettyTestConfig.class;
}
@Override
protected JettyWebSocketTestServer createWebSocketTestServer() {
return new JettyWebSocketTestServer();
}
@SuppressWarnings("removal")
@Override
protected Transport createWebSocketTransport() {
return new WebSocketTransport(new org.springframework.web.socket.client.jetty.JettyWebSocketClient());
}
@Override
protected AbstractXhrTransport createXhrTransport() {
return new JettyXhrTransport(new HttpClient());
}
@Configuration(proxyBeanMethods = false)
static class JettyTestConfig {
@Bean
RequestUpgradeStrategy upgradeStrategy() {
return new JettyRequestUpgradeStrategy();
}
}
}